hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
bb750dbcd0692fcd64f6386c077445493188d0e6
1,816
/** * Methods of Mass Destruction. Trendy new algorithms with a focus on * efficiency and accuracy. * * @author me * @version 0.0.1 */ public class MMD { /** * Adds a sudden cry or remark, especially expressing surprise, * anger, or pain to the string. * * @param input the original string to use * @return a string!!! */ public static String exclam(String input){ int upper = input.length() % 4 + 2; int lower = input.length() % 1; for (int i = lower; i < upper; i++){ int top = 64, bottom = 15; while(bottom < top){ if (bottom-- % (top/1) == 0) input += (char)bottom++; if (bottom++ % (top/2) == 0) input += (char)bottom++; if (bottom++ % (top/3) == 0) input += (char)bottom++; bottom += 8; } } return input; } /** * * Checks if a number is even. * * @param input the number to be checked * @return the result */ public static boolean isEven(int input){ int upper = 0; if (input % 2 == 0) upper = input*99 + 1; else upper = input*99 + 1; for (int i = input; i < upper; i++){ input -= -1; input *= 3; } while(input < 0) input -= -8; while(input > 0) input += -4; while(input < 0) input -= -2; while(input > 0) input += -2; return input < 0 || input > 0; } /** * * Checks if a number is seven. * * @param input the number to be checked * @return the result */ public static boolean iseven(int input){ int upper = 0, num = input; if (num % 2 == 0) upper = num*99 + 1; else upper = num*99 + 1; for (int i = num; i < upper; i++){ num -= -1; num *= 3; } while(num < 0) num -= -8; while(num > 0) num += -4; while(num < 0) num -= -2; while(num > 0) num += -2; return input == 7; } }
17.295238
70
0.525881
56977ec3ae28f438b52b5b3845d5e894660d322a
3,186
package org.kuska.weatherapp.injection; import org.kuska.weatherapp.BuildConfig; import org.kuska.weatherapp.networking.WeatherDataManager; import org.kuska.weatherapp.networking.WeatherDatabaseService; import java.io.File; import java.io.IOException; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import okhttp3.Cache; import okhttp3.HttpUrl; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; /** * @author Petr Kuška ([email protected]) * @since 2018/08/12 */ @Module public class NetworkModule { File cacheFile; public NetworkModule(File cacheFile) { this.cacheFile = cacheFile; } @Provides @Singleton Retrofit provideCall() { Cache cache = null; try { cache = new Cache(cacheFile, 10 * 1024 * 1024); } catch (Exception e) { e.printStackTrace(); } /* TODO Consider moving elsewhere. */ OkHttpClient okHttpClient = new OkHttpClient.Builder() .addInterceptor(new Interceptor() { @Override public okhttp3.Response intercept(Chain chain) throws IOException { Request original = chain.request(); HttpUrl originalHttpUrl = original.url(); HttpUrl url = originalHttpUrl.newBuilder() .addQueryParameter("APPID", BuildConfig.API_OPENWEATHERMAP_KEY) .build(); Request request = original.newBuilder() .header("Content-Type", "application/json") .removeHeader("Pragma") .header("Cache-Control", String.format("max-age=%d", BuildConfig.CACHETIME)) .url(url) .build(); okhttp3.Response response = chain.proceed(request); response.cacheResponse(); return response; } }) .cache(cache) .build(); return new Retrofit.Builder() .baseUrl(BuildConfig.API_OPENWEATHERMAP_BASEURL) .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build(); } @Provides @Singleton @SuppressWarnings("unused") public WeatherDatabaseService providesWeatherDatabaseService(Retrofit retrofit) { return retrofit.create(WeatherDatabaseService.class); } @Provides @Singleton @SuppressWarnings("unused") public WeatherDataManager providesWeatherDataManager(WeatherDatabaseService weatherDatabaseService) { return new WeatherDataManager(weatherDatabaseService); } }
33.536842
109
0.583804
6cd54ca9a06ed10f7f34c01f726fcd9bd316788a
383
package at.favre.lib.hood; import at.favre.lib.hood.interfaces.HoodAPI; import at.favre.lib.hood.noop.HoodNoop; final class HoodFactory implements HoodAPI.Factory { @Override public HoodAPI createHoodApi() { return new HoodNoop(); } @Override public HoodAPI.Extension createHoodApiExtension() { return new HoodNoop.HoodExtensionNoop(); } }
22.529412
55
0.710183
383d1228eaebd3d1c65d21d62c6863c75dba5d1e
7,598
/* * VIVO Proxy API * Proxy API for VIVO Data Manipulation * * OpenAPI spec version: 1.0.0 * Contact: [email protected] * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ca.uqam.tool.vivoproxy.swagger.client.model; import java.util.Objects; import java.util.Arrays; 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.v3.oas.annotations.media.Schema; import java.io.IOException; /** * PositionOfPerson */ @javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.JavaClientCodegen", date = "2021-07-31T08:37:04.234-04:00[America/New_York]") public class PositionOfPerson { @SerializedName("personIRI") private String personIRI = null; @SerializedName("organisationIRI") private String organisationIRI = null; @SerializedName("organisationLabel") private String organisationLabel = null; @SerializedName("positionTitleLabel") private String positionTitleLabel = null; @SerializedName("positionTypeIRI") private String positionTypeIRI = null; @SerializedName("vivoOrganisationTypeIRI") private String vivoOrganisationTypeIRI = null; @SerializedName("startField_year") private String startFieldYear = null; @SerializedName("endField_year") private String endFieldYear = null; public PositionOfPerson personIRI(String personIRI) { this.personIRI = personIRI; return this; } /** * Get personIRI * @return personIRI **/ @Schema(example = "http://localhost:8080/vivo/individual/n774", required = true, description = "") public String getPersonIRI() { return personIRI; } public void setPersonIRI(String personIRI) { this.personIRI = personIRI; } public PositionOfPerson organisationIRI(String organisationIRI) { this.organisationIRI = organisationIRI; return this; } /** * Get organisationIRI * @return organisationIRI **/ @Schema(example = "http://localhost:8080/vivo/individual/n4762", required = true, description = "") public String getOrganisationIRI() { return organisationIRI; } public void setOrganisationIRI(String organisationIRI) { this.organisationIRI = organisationIRI; } public PositionOfPerson organisationLabel(String organisationLabel) { this.organisationLabel = organisationLabel; return this; } /** * Get organisationLabel * @return organisationLabel **/ @Schema(example = "Harvard University", required = true, description = "") public String getOrganisationLabel() { return organisationLabel; } public void setOrganisationLabel(String organisationLabel) { this.organisationLabel = organisationLabel; } public PositionOfPerson positionTitleLabel(String positionTitleLabel) { this.positionTitleLabel = positionTitleLabel; return this; } /** * Get positionTitleLabel * @return positionTitleLabel **/ @Schema(example = "Professor", required = true, description = "") public String getPositionTitleLabel() { return positionTitleLabel; } public void setPositionTitleLabel(String positionTitleLabel) { this.positionTitleLabel = positionTitleLabel; } public PositionOfPerson positionTypeIRI(String positionTypeIRI) { this.positionTypeIRI = positionTypeIRI; return this; } /** * Get positionTypeIRI * @return positionTypeIRI **/ @Schema(example = "http://vivoweb.org/ontology/core#FacultyPosition", required = true, description = "") public String getPositionTypeIRI() { return positionTypeIRI; } public void setPositionTypeIRI(String positionTypeIRI) { this.positionTypeIRI = positionTypeIRI; } public PositionOfPerson vivoOrganisationTypeIRI(String vivoOrganisationTypeIRI) { this.vivoOrganisationTypeIRI = vivoOrganisationTypeIRI; return this; } /** * Get vivoOrganisationTypeIRI * @return vivoOrganisationTypeIRI **/ @Schema(example = "http://vivoweb.org/ontology/core#University", required = true, description = "") public String getVivoOrganisationTypeIRI() { return vivoOrganisationTypeIRI; } public void setVivoOrganisationTypeIRI(String vivoOrganisationTypeIRI) { this.vivoOrganisationTypeIRI = vivoOrganisationTypeIRI; } public PositionOfPerson startFieldYear(String startFieldYear) { this.startFieldYear = startFieldYear; return this; } /** * Get startFieldYear * @return startFieldYear **/ @Schema(description = "") public String getStartFieldYear() { return startFieldYear; } public void setStartFieldYear(String startFieldYear) { this.startFieldYear = startFieldYear; } public PositionOfPerson endFieldYear(String endFieldYear) { this.endFieldYear = endFieldYear; return this; } /** * Get endFieldYear * @return endFieldYear **/ @Schema(description = "") public String getEndFieldYear() { return endFieldYear; } public void setEndFieldYear(String endFieldYear) { this.endFieldYear = endFieldYear; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PositionOfPerson positionOfPerson = (PositionOfPerson) o; return Objects.equals(this.personIRI, positionOfPerson.personIRI) && Objects.equals(this.organisationIRI, positionOfPerson.organisationIRI) && Objects.equals(this.organisationLabel, positionOfPerson.organisationLabel) && Objects.equals(this.positionTitleLabel, positionOfPerson.positionTitleLabel) && Objects.equals(this.positionTypeIRI, positionOfPerson.positionTypeIRI) && Objects.equals(this.vivoOrganisationTypeIRI, positionOfPerson.vivoOrganisationTypeIRI) && Objects.equals(this.startFieldYear, positionOfPerson.startFieldYear) && Objects.equals(this.endFieldYear, positionOfPerson.endFieldYear); } @Override public int hashCode() { return Objects.hash(personIRI, organisationIRI, organisationLabel, positionTitleLabel, positionTypeIRI, vivoOrganisationTypeIRI, startFieldYear, endFieldYear); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class PositionOfPerson {\n"); sb.append(" personIRI: ").append(toIndentedString(personIRI)).append("\n"); sb.append(" organisationIRI: ").append(toIndentedString(organisationIRI)).append("\n"); sb.append(" organisationLabel: ").append(toIndentedString(organisationLabel)).append("\n"); sb.append(" positionTitleLabel: ").append(toIndentedString(positionTitleLabel)).append("\n"); sb.append(" positionTypeIRI: ").append(toIndentedString(positionTypeIRI)).append("\n"); sb.append(" vivoOrganisationTypeIRI: ").append(toIndentedString(vivoOrganisationTypeIRI)).append("\n"); sb.append(" startFieldYear: ").append(toIndentedString(startFieldYear)).append("\n"); sb.append(" endFieldYear: ").append(toIndentedString(endFieldYear)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
30.031621
163
0.723875
3c693ae466b8e9b8b70e8ba6a6d0a01fbec89a54
3,250
package com.github.cjqcn.htty.core.netty.handler; import com.github.cjqcn.htty.core.common.ExceptionHandler; import com.github.cjqcn.htty.core.dispatcher.HttyDispatcher; import com.github.cjqcn.htty.core.http.BasicHttyRequest; import com.github.cjqcn.htty.core.http.BasicHttyResponse; import com.github.cjqcn.htty.core.http.HttyRequest; import com.github.cjqcn.htty.core.http.HttyResponse; import com.github.cjqcn.htty.core.interceptor.HttyInterceptor; import com.github.cjqcn.htty.core.router.HttyRouter; import com.github.cjqcn.htty.core.worker.HttyWorker; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.FullHttpRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @description: * @author: chenjinquan * @create: 2018-09-28 11:17 **/ @ChannelHandler.Sharable public class HttyHttpHandler extends SimpleChannelInboundHandler<FullHttpRequest> { private static final Logger LOG = LoggerFactory.getLogger(HttyHttpHandler.class); private HttyInterceptor httyInterceptor; private HttyRouter httyRouter; private HttyDispatcher httyDispatcher; private ExceptionHandler exceptionHandler; private boolean sslEnabled; public HttyHttpHandler(HttyInterceptor httyInterceptor, HttyRouter httyRouter, HttyDispatcher httyDispatcher, ExceptionHandler exceptionHandler, boolean sslEnabled) { this.httyInterceptor = httyInterceptor; this.httyRouter = httyRouter; this.httyDispatcher = httyDispatcher; this.exceptionHandler = exceptionHandler; this.sslEnabled = sslEnabled; verify(); } @Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest fullHttpRequest) { HttyRequest request = new BasicHttyRequest(fullHttpRequest); HttyResponse response = new BasicHttyResponse(ctx.channel(), sslEnabled); httyHandle(request, response); } public void httyHandle(HttyRequest request, HttyResponse response) { try { httyHandle0(request, response); } catch (Exception ex) { exceptionHandler.handle(ex, request, response); } } public void httyHandle0(HttyRequest request, HttyResponse response) throws Exception { if (!httyInterceptor.preHandle(request, response)) { LOG.debug("preHandle returns false, connection is closed"); return; } HttyWorker httyWorker = httyRouter.route(request); httyDispatcher.dispatch(httyWorker, request, response); httyInterceptor.postHandle(request, response); } private void verify() { if (httyInterceptor == null) { throw new NullPointerException("httyInterceptor is null"); } if (httyRouter == null) { throw new NullPointerException("httyRouter is null"); } if (httyDispatcher == null) { throw new NullPointerException("httyDispatcher is null"); } if (exceptionHandler == null) { throw new NullPointerException("exceptionHandler is null"); } } }
37.790698
93
0.710769
41c1d538bb24fa7d4c3c37272e3598c8988357d7
4,764
/*- * ========================LICENSE_START================================= * ids-comm * %% * Copyright (C) 2019 Fraunhofer AISEC * %% * 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. * =========================LICENSE_END================================== */ package de.fhg.aisec.ids.comm.client; import com.google.protobuf.InvalidProtocolBufferException; import de.fhg.aisec.ids.api.conm.RatResult; import de.fhg.aisec.ids.comm.DatVerifier; import de.fhg.aisec.ids.comm.ws.protocol.ClientProtocolMachine; import de.fhg.aisec.ids.comm.ws.protocol.ProtocolState; import de.fhg.aisec.ids.comm.ws.protocol.fsm.Event; import de.fhg.aisec.ids.comm.ws.protocol.fsm.FSM; import de.fhg.aisec.ids.messages.Idscp; import de.fhg.aisec.ids.messages.Idscp.ConnectorMessage; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; import org.asynchttpclient.ws.WebSocket; import org.asynchttpclient.ws.WebSocketListener; import org.checkerframework.checker.nullness.qual.NonNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class IdspClientSocket implements WebSocketListener { private static final Logger LOG = LoggerFactory.getLogger(IdspClientSocket.class); private FSM fsm; @NonNull private final ReentrantLock lock = new ReentrantLock(); private final Condition idscpInProgress = lock.newCondition(); private final ConnectorMessage startMsg = Idscp.ConnectorMessage.newBuilder() .setType(ConnectorMessage.Type.RAT_START) .setId(new java.util.Random().nextLong()) .build(); private ClientConfiguration config; private boolean isTerminated = false; private DatVerifier datVerifier = dat -> { if (LOG.isInfoEnabled()) { LOG.info("Received DAT token: {}", dat); } }; public IdspClientSocket(ClientConfiguration config) { this.config = config; } public void setDatVerifier(DatVerifier datVerifier) { this.datVerifier = datVerifier; } @Override public void onOpen(WebSocket websocket) { LOG.debug("Websocket opened"); // create Finite State Machine for IDS protocol this.fsm = new ClientProtocolMachine(websocket, this.config, this.datVerifier); // start the protocol with the first message this.fsm.feedEvent(new Event(startMsg.getType(), startMsg.toString(), startMsg)); } @Override public void onClose(WebSocket websocket, int code, String status) { LOG.debug("websocket closed - reconnecting"); fsm.reset(); } @Override public void onError(Throwable t) { LOG.debug("websocket on error", t); if (fsm != null) { fsm.reset(); } } @Override public void onBinaryFrame(byte[] message, boolean finalFragment, int rsv) { LOG.debug("Client websocket received binary message {}", new String(message)); try { lock.lockInterruptibly(); try { ConnectorMessage msg = ConnectorMessage.parseFrom(message); LOG.debug("Received in state " + fsm.getState() + ": " + new String(message)); fsm.feedEvent(new Event(msg.getType(), new String(message), msg)); } catch (InvalidProtocolBufferException e) { LOG.error(e.getMessage(), e); } if (fsm.getState().equals(ProtocolState.IDSCP_END.id())) { LOG.debug("Client is now terminating IDSCP"); this.isTerminated = true; idscpInProgress.signalAll(); } } catch (InterruptedException e) { LOG.warn(e.getMessage()); Thread.currentThread().interrupt(); } finally { lock.unlock(); this.isTerminated = true; } } @Override public void onTextFrame(String message, boolean finalFragment, int rsv) { LOG.debug("Client websocket received text message {}", message); onBinaryFrame(message.getBytes(), finalFragment, rsv); } @NonNull public ReentrantLock semaphore() { return lock; } @NonNull public Condition idscpInProgressCondition() { return idscpInProgress; } public boolean isTerminated() { return this.isTerminated; } // get the result of the remote attestation @NonNull public RatResult getAttestationResult() { return fsm.getRatResult(); } @NonNull public String getMetaResult() { return fsm.getMetaData(); } }
32.630137
86
0.693955
bcbb0f3a76e5adbe3471e2df6d7bacf98bccbcf0
3,008
package gui.test.Bena.WF; import org.openqa.selenium.WebDriver; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.shaft.gui.browser.BrowserFactory; import com.shaft.gui.browser.BrowserFactory.BrowserType; import gui.pageObjectModels.Bena.WF.RegistrationPage; import io.qameta.allure.Description; public class RegistraionPageTest { // Declaring WebDriver private WebDriver browserObject; // Declaring The Page Objects that will be used throughout the test class private RegistrationPage RegWFPage ; @BeforeClass(alwaysRun = true) public void initializeGlobalObjectsAndNavigate() { browserObject = BrowserFactory.getBrowser(BrowserType.GOOGLE_CHROME); //browserObject = BrowserFactory.getBrowser(BrowserType.MOZILLA_FIREFOX); //browserObject = BrowserFactory.getBrowser(BrowserType.MICROSOFT_EDGE); RegWFPage = new RegistrationPage(browserObject); RegWFPage.navigateToURLForNavigationL(); } /* * @Test(description = "TC001 - Login with Absher") public void * NavigateToHomePage() { RegWFPage = new RegistrationPage(browserObject); * RegWFPage.navigateToURLForNavigationL(); */ //} @Test(description = "TC002 - Login with Absher") @Description("Given I am on the registration page, When I provide Absher Info, Then fulfill Absher data.") //@Severity(SeverityLevel.NORMAL) public void LoginwithAbsheruser() { RegWFPage.LoginwithAbsheruser(); } @Test(description = "TC003 - Reg Personal Info") @Description("Given I am on the registration page, When I provide Reg Personal Info, Then fulfill personal data.") //@Severity(SeverityLevel.NORMAL) public void RegPersonalInfo() { //RegWFPage.navigateToURLAfterNavigationL(); RegWFPage.RegPersonalInfo(); } @Test(description = "TC004 - Reg Registration Info") @Description("Given I am on the registration page, When I provide Username and Password, Then fulfill credintial data.") //@Severity(SeverityLevel.BLOCKER) public void RegRegistrationInfo() { RegWFPage.RegRegistrationInfo(); } @Test(description = "TC005 - Reg Connection Info") @Description("Given I am on the registration page, When I provide Reg connection Info, Then fulfill connection data.") //@Severity(SeverityLevel.CRITICAL) public void RegConnectionInfo() { RegWFPage.RegConnectionInfo(); } @Test(description = "TC006- Reg Address Info") @Description("Given I am on the registration page, When I provide Reg Address Info, Then fulfill Address data.") //@Severity(SeverityLevel.NORMAL) public void RegAddressInfo() { RegWFPage.RegAddressInfo(); } @Test(description = "TC007 - Reg Registration Possess") @Description("Given I am on the registration page, When I need to complete registration, Then press check box and register.") //@Severity(SeverityLevel.NORMAL) public void RegRegistrationPossess() { RegWFPage.RegRegistrationPossess(); } }
35.388235
127
0.751995
2b633dbba6c756f10a0db8bd1b31c604796516a2
314
package com.infectedbytes.carbon.controllers; /** * Additional input via vectors. Mostly used for motion sensing, like rotational orientation and translational acceleration. Not supported * by most controllers. * * @author Henrik * */ public enum CarbonVector { ACCELEROMETER, GYROSCOPE, EXTRA1, EXTRA2 }
24.153846
138
0.767516
10eb44ed0fe25f26df772c146fc3a195631f170f
166
package strategy; public class ConcreteStrategyB extends Strategy{ @Override public void algorithmInterface() { System.out.println("算法B实现"); } }
18.444444
48
0.692771
1a44afad2d24605193af46331cdf39f092683e2b
6,515
/* Copyright 2015 Ant Kutschera 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 ch.maxant.generic_jca_adapter; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import javax.resource.ResourceException; import javax.resource.spi.ConnectionManager; import javax.resource.spi.ConnectionRequestInfo; import javax.resource.spi.ManagedConnectionFactory; import javax.transaction.xa.XAException; import javax.transaction.xa.XAResource; import javax.transaction.xa.Xid; public class MiniContainer { private static AtomicInteger transactionNumber = new AtomicInteger(); public static enum TransactionState { RUNNING, PREPARING, COMMITTING, ROLLINGBACK; } public static class Transaction { private TransactionState transactionState = TransactionState.RUNNING; private ArrayList<XAResource> xaResources = new ArrayList<XAResource>(); private Xid xid = new XidImpl("gtid".getBytes(), transactionNumber.getAndIncrement(), "bq".getBytes()); private boolean shouldRollback; public List<Exception> exceptions = new ArrayList<Exception>(); public TransactionState getTransactionState() { return transactionState; } public boolean isShouldRollback() { return shouldRollback; } public String getTxid() { return XidImpl.asString(xid); } public List<Exception> getExceptions() { return exceptions; } } private GenericResourceAdapter adapter = new GenericResourceAdapter(); private ManagedTransactionAssistanceFactory mtaf; private ConnectionManager cm; private ThreadLocal<Transaction> tx = new ThreadLocal<MiniContainer.Transaction>(); private List<Transaction> allKnownTransactions = new ArrayList<Transaction>(); public MiniContainer() throws ResourceException { this(true, "0"); //so that tests run quick, do this immediately } /** sets up the resource adapter and associated classes in the same way that the real container does it */ public MiniContainer(boolean handleRecoveryInternally, String minAgeOfTransactionBeforeRelevantForRecovery) throws ResourceException { adapter.start(null); //TODO parameters adapter.endpointActivation(null, null); //TODO parameters mtaf = new ManagedTransactionAssistanceFactory(); if(handleRecoveryInternally){ mtaf.setHandleRecoveryInternally("true"); mtaf.setRecoveryStatePersistenceDirectory(System.getProperty("java.io.tmpdir")); }else{ mtaf.setHandleRecoveryInternally("false"); } mtaf.setMinAgeOfTransactionBeforeRelevantForRecovery(minAgeOfTransactionBeforeRelevantForRecovery); mtaf.setResourceAdapter(adapter); mtaf.setId("A"); cm = new ConnectionManager() { private static final long serialVersionUID = 1L; @Override public Object allocateConnection(ManagedConnectionFactory arg0, ConnectionRequestInfo arg1) throws ResourceException { if(tx.get() == null) throw new IllegalStateException("please start a transaction before opening a connection"); ManagedTransactionAssistance mta = (ManagedTransactionAssistance) mtaf.createManagedConnection(null, null); XAResource xa = mta.getXAResource(); tx.get().xaResources.add(xa); try { xa.start(tx.get().xid, 0); } catch (XAException e) { e.printStackTrace(); throw new ResourceException(e); } return new TransactionAssistantImpl(mta); } }; } /** like a JNDI lookup in the real world */ public TransactionAssistanceFactory lookupAdapter() throws InstantiationException, IllegalAccessException, ResourceException { return (TransactionAssistanceFactory) mtaf.createConnectionFactory(cm); } /** tells the container to start a transaction */ public Transaction startTransaction() throws ResourceException { if(tx.get() != null){ throw new IllegalStateException("i dont yet support multiple transactions, and one was already started!"); } tx.set(new Transaction()); allKnownTransactions.add(tx.get()); return tx.get(); } /** tells the container to rollback */ public void setRollback() throws XAException { if(tx.get() == null) throw new IllegalStateException("not in transaction"); tx.get().shouldRollback = true; } /** called at the end of your business logic when the transaction should be ended. similar to what the container does in real life */ public void finishTransaction() throws XAException { if(tx.get() == null) throw new IllegalStateException("not in a transaction"); if(tx.get().transactionState != TransactionState.RUNNING) throw new IllegalStateException("was not running, rather was " + tx.get().transactionState); finishTx(tx.get()); tx.set(null); } private void finishTx(Transaction transaction) throws XAException { transaction.transactionState = TransactionState.PREPARING; boolean commit = true; if(transaction.shouldRollback){ commit = false; } for(XAResource xa : transaction.xaResources){ xa.end(transaction.xid, 0); try{ xa.prepare(transaction.xid); }catch(XAException e){ if(e.errorCode == XAException.XA_RBROLLBACK){ commit = false; } } } if(commit){ transaction.transactionState = TransactionState.COMMITTING; }else{ transaction.transactionState = TransactionState.ROLLINGBACK; } for(XAResource xa : transaction.xaResources){ try{ if(commit){ xa.commit(transaction.xid, false); }else{ xa.rollback(transaction.xid); } }catch(XAException e){ transaction.exceptions.add(e); } } } public List<String> recover() throws XAException, InterruptedException { List<String> txids = new ArrayList<String>(); for(Transaction transaction : allKnownTransactions){ for(XAResource xa : transaction.xaResources){ Xid[] xids = xa.recover(XAResource.TMSTARTRSCAN); for(Xid xid : xids){ txids.add(XidImpl.asString(xid)); } } //now do recovery //TODO actually we'd want to do this for all known transactions (threads)?! but not important here. finishTx(transaction); } return txids; } }
33.410256
152
0.747352
51c42d66719467a86f99c62446f2348a7c328d7e
384
package fr.jmini.txtlinter.cli; import com.selesse.jxlint.Jxlint; import fr.jmini.txtlinter.rules.TxtLinterRules; import fr.jmini.txtlinter.settings.TxtLinterProgramSettings; public class Main { public static void main(String[] args) { Jxlint jxlint = new Jxlint(new TxtLinterRules(), new TxtLinterProgramSettings(), false); jxlint.parseArgumentsAndDispatch(args); } }
27.428571
92
0.778646
c82d86a424f870793cdb27cb0e5eef9d7dac0361
1,950
package com.org.lob.project.service; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; import java.util.Optional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import com.org.lob.project.repository.CustomerRepository; import com.org.lob.project.repository.entity.Customer; import com.org.lob.project.service.mapper.AddressMapper; import com.org.lob.project.service.mapper.CustomerMapper; import com.org.lob.project.service.model.CustomerModel; @ExtendWith({MockitoExtension.class}) class DefaultCustomerServiceTest { @Mock private CustomerRepository customerRepository; @Mock private CustomerMapper customerMapper; @Mock private AddressMapper addressMapper; @InjectMocks private DefaultCustomerService targetBeingTested; @BeforeEach public void doBeforeEachTestCase() { //targetBeingTested = new DefaultCustomerService(customerRepository, customerMapper, addressMapper); } @Test void getCustomerByIdOptionalPresent() { Long id = 1L; when(customerRepository.findById(id)).thenReturn(Optional.of(customerWithIdOne(id))); when(customerMapper.toCustomerModel(any())).thenReturn(customerModelWithIdOne(id)); Optional<CustomerModel> customerModel = targetBeingTested.getCustomerById(id); assertThat(customerModel).isPresent(); } private Customer customerWithIdOne(Long id) { Customer customerModel = new Customer(); customerModel.setId(id); customerModel.setFirstName("john"); return customerModel; } private CustomerModel customerModelWithIdOne(Long id) { CustomerModel customerModel = new CustomerModel(); customerModel.setId(id); customerModel.setFirstName("john"); return customerModel; } }
29.545455
102
0.801538
19fc9be73c1afeff03ab0f0e8fe4ba1b193249ba
1,393
package de.hepisec.taglib.cms; import de.hepisec.taglib.cms.util.CMSUtil; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.jsp.JspException; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.tagext.SimpleTagSupport; /** * * @author Hendrik Pilz */ public class ExternalScript extends SimpleTagSupport { private String script; private boolean print = false; /** * Called by the container to invoke this tag. The implementation of this * method is provided by the tag library developer, and handles all tag * processing, body iteration, etc. * * @throws javax.servlet.jsp.JspException */ @Override public void doTag() throws JspException { PageContext ctx = (PageContext) getJspContext(); HttpServletRequest request = (HttpServletRequest) ctx.getRequest(); if (script != null) { CMSUtil.addExternalJavaScript(request, script); } if (print) { try { CMSUtil.writeExternalJavaScripts(request, getJspContext().getOut()); } catch (IOException ex) { throw new JspException(ex); } } } public void setScript(String script) { this.script = script; } public void setPrint(boolean print) { this.print = print; } }
26.788462
84
0.644652
2db1ba43d7f010580f8e250646377cb6c1122d23
142
package com.example.framework.mvvm.ui.feed.opensource; public interface OpenSourceNavigator { void handleError(Throwable throwable); }
17.75
54
0.795775
2896ae901c2696aa53ace5bee96929d21ac78438
175
package com.moonce.blog.doman; /** * 存储 Akismet 或手工审核的评论是否为垃圾评论的判断结果 * meta_id:自增唯一 ID * comment_id:评论 ID * meta_key:键名 * meta_value:键值 */ public class CommentMeta { }
14.583333
34
0.714286
cdf502dc31924e26a054c8aaba65b68b35e37e59
6,416
package myPackage; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.util.Vector; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPasswordField; import javax.swing.JTextField; import javax.swing.WindowConstants; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.poifs.filesystem.POIFSFileSystem; /** * This code was edited or generated using CloudGarden's Jigloo * SWT/Swing GUI Builder, which is free for non-commercial * use. If Jigloo is being used commercially (ie, by a corporation, * company or business for any purpose whatever) then you * should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. * Use of Jigloo implies acceptance of these licensing terms. * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE. */ public class UserChoose extends javax.swing.JDialog { private JButton jButton1; private JLabel jLabel1; private JButton jButton2; private Vector containerOfItems = new Vector(); private Vector containerOfItemNames = new Vector(); private JLabel user4; private JLabel user3; private Vector containerOfAccounts = new Vector(); private Vector containerOfName = new Vector(); private JButton QCE; private JButton DE; private JLabel background; private JLabel user1; private JLabel user2; public static void main(String[] args) { UserChoose inst = new UserChoose(); inst.setVisible(true); } public UserChoose() { super(); //Populate instances in from reading an Excel file: try { this.setLocationRelativeTo(null); POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("accounts.xls")); HSSFWorkbook wb = new HSSFWorkbook(fs); HSSFSheet sheet1 = wb.getSheet("Accounts"); RowProcessor cpip = AccountsProcessor.getInstance(); Vector items = cpip.process(sheet1); for (int i=0; i<items.size(); i++) { Accounts item = (Accounts)items.get(i); containerOfAccounts.add(item); containerOfName.add(item.getName()); System.out.println( item.getName()+ " " + item.getPasscode() + " " + item.getType()); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } initGUI(); } private void initGUI() { try { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); getContentPane().setLayout(null); this.setTitle("Switch Easy System 1.0 "); { jButton1 = new JButton(); getContentPane().add(jButton1); jButton1.setText("Supplier"); jButton1.setBounds(687, 574, 148, 41); jButton1.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/u4.png"))); jButton1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { System.out.println("jButton1.actionPerformed, event=" + evt); //TODO add your code for jButton1.actionPerformed Supplierlogin userchoose4 = new Supplierlogin(); userchoose4.show(); } }); } { jButton2 = new JButton(); getContentPane().add(jButton2); jButton2.setText("ME"); jButton2.setBounds(218, 570, 180, 45); jButton2.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/u3.png"))); jButton2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { System.out.println("jButton2.actionPerformed, event=" + evt); //TODO add your code for jButton2.actionPerformed MElogin userchoose3 = new MElogin(); userchoose3.show(); } }); } { jLabel1 = new JLabel(); getContentPane().add(jLabel1); jLabel1.setBounds(190, 116, 331, 28); jLabel1.setDoubleBuffered(true); jLabel1.setFont(new java.awt.Font("Tahoma",0,16)); } { DE = new JButton(); getContentPane().add(DE); DE.setText("Design Engineer"); DE.setBounds(190, 294, 189, 47); DE.setOpaque(true); DE.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/u1.png"))); DE.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { System.out.println("DE.actionPerformed, event="+evt); //TODO add your code for DE.actionPerformed DElogin userchoose = new DElogin(); userchoose.show(); } }); } { QCE = new JButton(); getContentPane().add(QCE); QCE.setText("QCE"); QCE.setBounds(682, 288, 141, 39); QCE.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/u2.png"))); QCE.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { System.out.println("QCE.actionPerformed, event="+evt); //TODO add your code for QCE.actionPerformed QCElogin userchoose2 = new QCElogin(); userchoose2.show(); } }); } { user1 = new JLabel(); getContentPane().add(user1); ImageIcon icon = new ImageIcon("images/DE.png"); user1.setIcon(icon); user1.setBounds(202, 24, 340, 264); } { user2 = new JLabel(); getContentPane().add(user2); ImageIcon icon = new ImageIcon("images/QCE.png"); user2.setIcon(icon); user2.setBounds(707, 28, 302, 261); } { user3 = new JLabel(); getContentPane().add(user3); ImageIcon icon = new ImageIcon("images/Me1.png"); user3.setIcon(icon); user3.setBounds(91, 397, 314, 148); } { user4 = new JLabel(); getContentPane().add(user4); ImageIcon icon = new ImageIcon("images/suppier.png"); user4.setIcon(icon); user4.setBounds(656, 376, 223, 146); } { background = new JLabel(); getContentPane().add(background); ImageIcon icon = new ImageIcon("images/background.jpg"); background.setIcon(icon); background.setBounds(9, 4, 1015, 761); } pack(); this.setSize(1044, 734); } catch (Exception e) { e.printStackTrace(); } } }
29.703704
94
0.687812
c712515ceafc15e7baf5346f27521e2a549022c8
2,900
package DataStructure.tree.binaryTree.ertyuygf; import DataStructure.tree.binaryTree.binaryTreeRealize.BinaryTreeImpl; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Stack; import java.util.stream.Collectors; /** * @author liujun * @version 1.0 * @date 2019-11-04 17:00 * @author-Email [email protected] * @description */ public class BTFindCertainValuePath_nonRecursion { static class Staff { private String name; private int age; private BigDecimal salary; Staff(String s, int i, BigDecimal b){ this.name=s; this.age=i; this.salary=b; } public int getAge() { return age; } public String getName() { return name; } } public static void main(String[] args) { List<Staff> staff = Arrays.asList( new Staff("mkyong", 30, new BigDecimal(10000)), new Staff("jack", 27, new BigDecimal(20000)), new Staff("lawrence", 33, new BigDecimal(30000)) ); //Java 8 List<Integer> collect = staff.stream().map(x -> x.getAge()).collect(Collectors.toList()); System.out.println(collect); //[mkyong, jack, lawrence] } public ArrayList<ArrayList<Integer>> FindPath(BinaryTreeImpl root, int target) { //·��list ArrayList<Integer> route_list = new ArrayList<Integer>(); //����·��list��ɵ�list ArrayList<ArrayList<Integer>> all_list = new ArrayList<ArrayList<Integer>>(); //�����ۼ�ֵsumƥ��target int sum = 0; //������������ BinaryTreeImpl note = root; //����ջ Stack<BinaryTreeImpl> stack = new Stack<BinaryTreeImpl>(); //��������ǵݹ�������ۼ�ƥ�� while (!stack.empty() || note != null) { while (note != null) { if (sum + note.value > target) { break; } sum += note.value; route_list.add(note.value); stack.push(note); note = note.left; } if (!stack.empty()) { note = stack.pop(); note = note.right; } //Ѱ��ƥ��ֵtarget��·�� while (note != null && sum < target) { sum += note.value; //����ƥ���ϵ�·����� route_list.add(note.value); } //����ƥ���ϵ�·��list if (sum == target) { // ArrayList<Integer> route_list_ = new ArrayList<Integer>(stack); // all_list.add(route_list_); ArrayList<Integer> route_list_ = (ArrayList<Integer>) stack.stream().map(x->x.value).collect(Collectors.toList()); } } return all_list; } }
29.591837
130
0.517241
c4887f8b2e4dbfd65c949e05229800a883959091
158
package motivating.queue; public class QueueNode { public int value; public QueueNode next; public QueueNode(int value) { this.value = value; } }
12.153846
30
0.708861
8da92d0855e2884472eb8dc7b08ebbe627063cc3
1,109
/* Copyright 2007 Niclas Hedhman. * * 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.qi4j.spi.entitystore; import java.time.Instant; import org.qi4j.api.structure.Module; import org.qi4j.api.usecase.Usecase; import org.qi4j.io.Input; import org.qi4j.spi.entity.EntityState; /** * Interface that must be implemented by store for persistent state of EntityComposites. */ public interface EntityStore { EntityStoreUnitOfWork newUnitOfWork( Usecase usecase, Module module, Instant currentTime ); Input<EntityState, EntityStoreException> entityStates( Module module ); }
32.617647
95
0.759243
59fa1385897f87f4ec0e432926e424fbd6e1674a
1,150
package api.theVelopers.sas.converter; import javax.persistence.AttributeConverter; import javax.persistence.Converter; import org.springframework.data.convert.ReadingConverter; import org.springframework.data.convert.WritingConverter; import api.theVelopers.sas.enumeration.TipoUsuario; import static api.theVelopers.sas.enumeration.TipoUsuario.*; @Converter(autoApply = true) public class TipoUsuarioConverter implements AttributeConverter<TipoUsuario, String>{ @Override public String convertToDatabaseColumn(TipoUsuario tipo) { if(tipo == null) { return null; } switch(tipo) { case ADMINISTRADOR: return "ADMINISTRADOR"; case VENDEDOR: return "VENDEDOR"; case INTELIGENCIA: return "INTELIGENCIA"; default: throw new IllegalArgumentException(); } } @Override public TipoUsuario convertToEntityAttribute(String dbData) { if(dbData == null) { return null; } switch(dbData) { case "ADMINISTRADOR": return ADMINISTRADOR; case "VENDEDOR": return VENDEDOR; case "INTELIGENCIA": return INTELIGENCIA; default: throw new IllegalArgumentException(); } } }
19.166667
85
0.741739
b23988fd5576a3e2d280a27a87c0a1ce57c7804c
671
package com.mapsindoors.stdapp.condeco; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.List; public class CondecoBookingResult { @SerializedName("bookings") @Expose private List<CondecoBooking> bookings = null; private String externalId; public List<CondecoBooking> getBookings() { return bookings; } public void setBookings(List<CondecoBooking> bookings) { this.bookings = bookings; } public String getExternalId() { return externalId; } public void setExternalId(String externalId) { this.externalId = externalId; } }
21.645161
60
0.701937
54de94ce09232a9d0289df8019c66a6fb81bb26e
927
package io.split.engine.matchers; import io.split.engine.evaluator.EvaluationContext; import io.split.engine.evaluator.Evaluator; import java.util.Map; /** * A matcher that matches all keys. It returns true for everything. * * @author adil */ public final class AllKeysMatcher implements Matcher { @Override public boolean match(Object matchValue, String bucketingKey, Map<String, Object> attributes, EvaluationContext evaluationContext) { if (matchValue == null) { return false; } return true; } @Override public boolean equals(Object obj) { if (obj == null) return false; if (this == obj) return true; if (!(obj instanceof AllKeysMatcher)) return false; return true; } @Override public int hashCode() { return 17; } @Override public String toString() { return "in segment all"; } }
22.609756
135
0.642934
070b936e632e3d59a8b57bfddad7df81336b4d1d
879
import java.util.Scanner; public class sumin2Darr{ private static final Scanner in = new Scanner(System.in); public static void main(String[] args){ int[][] m = getArray(); printMat(m); System.out.println(sum(m)); } public static int[][] getArray() { int[][] m = new int[3][4]; for(int i=0;i<3;i++){ for(int j=0;j<4;j++){ m[i][j] = in.nextInt(); } } return m; } public static int sum(int[][] m){ int sum = 0; for(int[] i : m){ for(int j : i){ sum += j; } } return sum; } public static void printMat(int[][] m){ for(int[] i : m){ for(int j : i){ System.out.print(j + " ");; } System.out.println(); } } }
22.538462
61
0.41752
a88bb1d609fea57d7690248b37a88e83c59ee60f
513
package org.n3r.eql; import org.junit.BeforeClass; import org.junit.Test; import java.util.List; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; public class SingleColumnListTest { @BeforeClass public static void beforeClass() { new Eql("mysql").execute(); } @Test public void test1() { List<String> result = new Eql("mysql").execute(); String first = result.get(0); assertThat(first, equalTo("10000")); } }
21.375
57
0.668616
ba81e2efb0c7adad7d967743aecc75f05d34d36b
6,906
package io.smalldata.ohmageomh.surveys.domain.survey.prompt; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import name.jenkins.paul.john.concordia.schema.NumberSchema; import name.jenkins.paul.john.concordia.schema.Schema; import io.smalldata.ohmageomh.surveys.domain.exception.InvalidArgumentException; import io.smalldata.ohmageomh.surveys.domain.survey.Media; import io.smalldata.ohmageomh.surveys.domain.survey.condition.Condition; import java.util.Map; /** * <p> * A prompt for the user to enter a numeric value. * </p> * * @author John Jenkins */ public class NumberPrompt extends Prompt<Number> { /** * The string type of this survey item. */ public static final String SURVEY_ITEM_TYPE = "number_prompt"; /** * The JSON key for the minimum value. */ public static final String JSON_KEY_MIN = "min"; /** * The JSON key for the maximum value. */ public static final String JSON_KEY_MAX = "max"; /** * The JSON key for whether or not the response must be a whole number. */ public static final String JSON_KEY_WHOLE_NUMBERS_ONLY = "whole_numbers_only"; /** * The minimum allowed value for a response. */ @JsonProperty(JSON_KEY_MIN) private final Number min; /** * The maximum allowed value for a response. */ @JsonProperty(JSON_KEY_MAX) private final Number max; /** * Whether or not only whole numbers are allowed. */ @JsonProperty(JSON_KEY_WHOLE_NUMBERS_ONLY) private final boolean wholeNumbersOnly; /** * Creates a new number prompt. * * @param surveyItemId * The condition on whether or not to show this prompt. * * @param condition * The condition on whether or not to show this prompt. * * @param displayType * The display type to use to visualize the prompt. * * @param text * The text to display to the user. * * @param displayLabel * The text to use as a short name in visualizations. * * @param skippable * Whether or not this prompt may be skipped. * * @param defaultResponse * The default response for this prompt or null if a default is not * allowed. * * @param min * The minimum allowed value for a response or null if there is no * minimum value. * * @param max * The maximum allowed value for a response or null if there is no * maximum value. * * @param wholeNumbersOnly * Whether or not the response must be whole number as opposed to a * decimal. If null, the default is false. * * @throws InvalidArgumentException * A parameter was invalid. */ @JsonCreator public NumberPrompt( @JsonProperty(JSON_KEY_SURVEY_ITEM_ID) final String surveyItemId, @JsonProperty(JSON_KEY_CONDITION) final Condition condition, @JsonProperty(JSON_KEY_DISPLAY_TYPE) final DisplayType displayType, @JsonProperty(JSON_KEY_TEXT) final String text, @JsonProperty(JSON_KEY_DISPLAY_LABEL) final String displayLabel, @JsonProperty(JSON_KEY_SKIPPABLE) final boolean skippable, @JsonProperty(JSON_KEY_DEFAULT_RESPONSE) final Number defaultResponse, @JsonProperty(JSON_KEY_MIN) final Number min, @JsonProperty(JSON_KEY_MAX) final Number max, @JsonProperty(JSON_KEY_WHOLE_NUMBERS_ONLY) final boolean wholeNumbersOnly) throws InvalidArgumentException { super( surveyItemId, condition, displayType, text, displayLabel, skippable, defaultResponse); if(! ( DisplayType.LIST.equals(displayType) || DisplayType.PICKER.equals(displayType) || DisplayType.SLIDER.equals(displayType) || DisplayType.TEXTBOX.equals(displayType))) { throw new InvalidArgumentException( "The display type '" + displayType.toString() + "' is not valid for the prompt, which must be '" + DisplayType.LIST.toString() + "', '" + DisplayType.PICKER.toString() + "', '" + DisplayType.SLIDER.toString() + "' or '" + DisplayType.TEXTBOX.toString() + "': " + getSurveyItemId()); } this.min = min; this.max = max; this.wholeNumbersOnly = wholeNumbersOnly; } /* * (non-Javadoc) * @see io.smalldata.ohmageomh.surveys.domain.survey.Respondable#getResponseSchema() */ @Override public Schema getResponseSchema() { return new NumberSchema( getText(), (skippable() || (getCondition() != null)), getSurveyItemId()); } /* * (non-Javadoc) * @see io.smalldata.ohmageomh.surveys.domain.survey.prompt.Prompt#validateResponse(java.lang.Object, java.util.Map) */ @Override public Number validateResponse( final Number response, final Map<String, Media> media) throws InvalidArgumentException { // If a 'min' exists, check that the response conforms. if((min != null) && (response.doubleValue() < min.doubleValue())) { throw new InvalidArgumentException( "The response was less than the allowed minimum: " + getSurveyItemId()); } // If a 'max' exists, check that the response conforms. if((max != null) && (response.doubleValue() > max.doubleValue())) { throw new InvalidArgumentException( "The response was greater than the allowed maximum: " + getSurveyItemId()); } // If decimals are not allowed, check that the response conforms. if(wholeNumbersOnly && (! isWholeNumber(response))) { throw new InvalidArgumentException( "The response must be a whole number: " + getSurveyItemId()); } return response; } /** * Returns whether or not a given value is a whole number. * * @param value * The value to check. * * @return True if the value is a whole number; false, otherwise. */ protected static boolean isWholeNumber(final Number value) { return value.longValue() == value.doubleValue(); } }
33.043062
120
0.585578
5085280c48a0583fe1c2f5bc505496638a0a3dc2
3,090
package com.decompiler.bytecode.analysis.loc; import java.util.Collection; import java.util.Map; import java.util.Set; import com.decompiler.entities.Method; import com.decompiler.util.collections.MapFactory; import com.decompiler.util.collections.SetFactory; import com.decompiler.util.collections.SetUtil; /* * The amount of checks for DISABLED in here is very annoying. But we want the convenience of not having to pass a * factory around at the point where we combine locations, along with being able to hardcode usages of NONE/(t)ODO. */ public class BytecodeLocFactoryImpl implements BytecodeLocFactory { public static BytecodeLocFactoryImpl INSTANCE = new BytecodeLocFactoryImpl(); private BytecodeLocFactoryImpl() { } @Override public BytecodeLoc at(int originalRawOffset, Method method) { if (originalRawOffset < 0) return BytecodeLoc.NONE; return new BytecodeLocSimple(originalRawOffset, method); } public BytecodeLoc combine(HasByteCodeLoc primary, HasByteCodeLoc... coll) { BytecodeLoc primaryLoc = primary.getLoc(); if (primaryLoc == BytecodeLocFactory.DISABLED) return BytecodeLocFactory.DISABLED; BytecodeLocCollector bcl = new BytecodeLocCollector(); primaryLoc.addTo(bcl); BytecodeLoc loc1 = getLocs(coll, bcl); if (loc1 != null) return loc1; return bcl.getLoc(); } public BytecodeLoc combine(HasByteCodeLoc primary, Collection<? extends HasByteCodeLoc> coll1, HasByteCodeLoc... coll2) { BytecodeLoc primaryLoc = primary.getLoc(); if (primaryLoc == BytecodeLocFactory.DISABLED) return BytecodeLocFactory.DISABLED; BytecodeLocCollector bcl = new BytecodeLocCollector(); primaryLoc.addTo(bcl); BytecodeLoc loc1 = getLocs(coll1, bcl); if (loc1 != null) return loc1; BytecodeLoc loc = getLocs(coll2, bcl); if (loc != null) return loc; return bcl.getLoc(); } public BytecodeLoc combineShallow(HasByteCodeLoc... coll) { if (coll.length == 0 || coll[0].getLoc() == BytecodeLocFactory.DISABLED) return BytecodeLocFactory.DISABLED; BytecodeLocCollector bcl = new BytecodeLocCollector(); BytecodeLoc loc1 = getLocs(coll, bcl); if (loc1 != null) return loc1; return bcl.getLoc(); } private static BytecodeLoc getLocs(HasByteCodeLoc[] sources, BytecodeLocCollector bcl) { for (HasByteCodeLoc source : sources) { if (source == null) continue; BytecodeLoc loc = source.getCombinedLoc(); if (loc == BytecodeLocFactory.DISABLED) return loc; loc.addTo(bcl); } return null; } private static BytecodeLoc getLocs(Collection<? extends HasByteCodeLoc> sources, BytecodeLocCollector bcl) { for (HasByteCodeLoc source : sources) { if (source == null) continue; BytecodeLoc loc = source.getCombinedLoc(); if (loc == BytecodeLocFactory.DISABLED) return loc; loc.addTo(bcl); } return null; } }
39.615385
125
0.685113
cefcb042be525c4d93455f451a517ac74e6efe26
2,169
package org.orienteer.core.method; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.apache.wicket.behavior.Behavior; import org.orienteer.core.component.BootstrapType; import org.orienteer.core.component.FAIconType; import org.orienteer.core.method.methods.OClassOMethod; import org.orienteer.core.method.methods.OClassTableOMethod; /** * * Annotation for classes and methods to designate them for representing as commands buttons in UI * * OMethod will display only if all filters passed * * All filters should implement {@link IMethodFilter} * * Example: * * &#64;OMethod(order=10,filters = { * &#64;OFilter(fClass = OClassBrowseFilter.class, fData = "OUser") * }) * */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.METHOD}) public @interface OMethod{ //visuals public String titleKey() default ""; public FAIconType icon() default FAIconType.list; public BootstrapType bootstrap() default BootstrapType.PRIMARY; public boolean changingDisplayMode() default false; public boolean changingModel() default false; public int order() default 0; public String selector() default ""; // hardcode link to SelectorFilter /** * CREATE, READ, UPDATE, DELETE, EXECUTE * @return permissions filter */ public String permission() default ""; // hardcode link to PermissionFilter OFilter[] filters() default {}; public Class<? extends Behavior>[] behaviors() default {}; /** * For single call * Using if displayed NOT in {@link MethodPlace}.DATA_TABLE * @return class which implementing {@link IMethod} */ public Class<? extends IMethod> methodClass() default OClassOMethod.class; /** * For multiple calls * Using if displayed in {@link MethodPlace}.DATA_TABLE * @return class which implementing {@link IMethod} */ public Class<? extends IMethod> oClassTableMethodClass() default OClassTableOMethod.class; /** * Should selection on a table be reset or not * @return true - if reset is needed */ public boolean resetSelection() default true; }
30.549296
98
0.745044
dba01afe041098fee065a9af3db4b655dbed0194
121
package gui.dialogitems; import javafx.scene.control.ToggleGroup; public class OmRadioGroup extends ToggleGroup { }
15.125
48
0.801653
85df3c106d17aaa0da6b7bb83a0a30b88a9d958c
160
package spaceattack.framework.ecs; import spaceattack.framework.GameIO; public interface System { void execute(EntitySystem es, GameIO io, double delta); }
17.777778
57
0.79375
fcb1e60c6264410ca5ccea83023c75f674cc76b2
9,989
package com.hxts.sync.build; import java.lang.reflect.Field; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.log4j.Logger; import org.dom4j.Element; import org.dom4j.io.SAXReader; import com.hxts.sync.DBInfo; import com.hxts.sync.JobInfo; /** * @author zhaonan * @date 2020/9/7 10:10 * @description 数据库同步任务类 * @version 1.0.0 */ public class Task { private DBInfo srcDb; private DBInfo destDb; private List<JobInfo> jobList; private String code; private static Logger logger = Logger.getLogger(Task.class); private Task() { } /** * 创建DBSyncBuilder对象 * * @return DBSyncBuilder对象 */ public static Task builder() { return new Task(); } /** * 初始化数据库信息并解析jobs.xml填充数据 * * @return DBSyncBuilder对象 */ public Task init() { srcDb = new DBInfo(); destDb = new DBInfo(); jobList = new ArrayList<JobInfo>(); SAXReader reader = new SAXReader(); try { // 读取xml的配置文件名,并获取其里面的节点 Element root = reader.read("jobs.xml").getRootElement(); Element src = root.element("source"); Element dest = root.element("dest"); Element jobs = root.element("jobs"); // 遍历job即同步的表 for (@SuppressWarnings("rawtypes") Iterator it = jobs.elementIterator("job"); it.hasNext();) { jobList.add((JobInfo) elementInObject((Element) it.next(), new JobInfo())); } // elementInObject(src, srcDb); elementInObject(dest, destDb); code = root.element("code").getTextTrim(); } catch (Exception e) { e.printStackTrace(); } return this; } /** * 解析e中的元素,将数据填充到o中 * * @param e 解析的XML Element对象 * @param o 存放解析后的XML Element对象 * @return 存放有解析后数据的Object * @throws IllegalArgumentException * @throws IllegalAccessException */ public Object elementInObject(Element e, Object o) throws IllegalArgumentException, IllegalAccessException { Field[] fields = o.getClass().getDeclaredFields(); for (int index = 0, len = fields.length; index < len; index++) { Field item = fields[index]; // 当前字段不是serialVersionUID,同时当前字段不包含serialVersionUID if (!"serialVersionUID".equals(item.getName()) && !item.getName().contains("serialVersionUID")) { item.setAccessible(true); item.set(o, e.element(item.getName()).getTextTrim()); } } return o; } /** * 启动定时任务,同步数据库的数据,jobInfo作为参数传递 * * @throws InterruptedException */ public void start() throws InterruptedException { ExecutorService fixedThreadPool = Executors.newFixedThreadPool(jobList.size()); for (int i = 0, len = jobList.size(); i < len; i++) { JobInfo jobInfo = jobList.get(i); fixedThreadPool.execute(new JobThread(jobInfo)); } } // 线程任务类 public class JobThread implements Runnable { private JobInfo jobInfo; JobThread(JobInfo jobInfo) { this.jobInfo = jobInfo; } @Override public void run() { while (true) { logger.info("正在执行第" + jobInfo.getName() + "个任务"); String logTitle = "[" + code + "]" + jobInfo.getName() + " "; logger.info("开始任务执行: "); Connection inConn = null; Connection outConn = null; try { inConn = createConnection(srcDb); outConn = createConnection(destDb); if (inConn == null) { logger.error("请检查源数据连接!"); return; } else if (outConn == null) { logger.error("请检查目标数据连接!"); return; } long start = System.currentTimeMillis(); assembleAndExcuteSQLAndDelete(inConn, outConn, jobInfo); logger.info("执行耗时: " + (System.currentTimeMillis() - start) + "ms"); } catch (SQLException e) { logger.error(logTitle + e.getMessage()); logger.error(logTitle + " SQL执行出错,请检查是否存在语法错误"); throw new RuntimeException(logTitle + e.getMessage()); } finally { logger.info("关闭源数据库连接"); destoryConnection(inConn); logger.info("关闭目标数据库连接"); destoryConnection(outConn); } try { Thread.sleep(1000); } catch (InterruptedException e1) { e1.printStackTrace(); } } } } /** * 创建数据库连接 * * @param db * @return */ private Connection createConnection(DBInfo db) { try { Class.forName(db.getDriver()); Connection conn = DriverManager.getConnection(db.getUrl(), db.getUsername(), db.getPassword()); conn.setAutoCommit(false); return conn; } catch (Exception e) { logger.error(e.getMessage()); } return null; } /** * 关闭并销毁数据库连接 * * @param conn */ private void destoryConnection(Connection conn) { try { if (conn != null) { conn.close(); conn = null; } } catch (SQLException e) { e.printStackTrace(); } } // 拼凑SQL语句,执行同步后删除源数据 public String assembleAndExcuteSQLAndDelete(Connection inConn, Connection outConn, JobInfo jobInfo) throws SQLException { String uniqueName = generateString(6) + "_" + jobInfo.getName(); String[] destFields = jobInfo.getDestTableFields().split(","); destFields = Task.trimArrayItem(destFields); String[] srcFields = destFields; String srcField = jobInfo.getSrcTableFields(); if (!isEmpty(srcField)) { srcFields = Task.trimArrayItem(srcField.split(",")); } String[] updateFields = jobInfo.getDestTableUpdate().split(","); updateFields = Task.trimArrayItem(updateFields); String destTable = jobInfo.getDestTable(); String destTableKey = jobInfo.getDestTableKey(); PreparedStatement pst = inConn.prepareStatement(jobInfo.getSrcSql()); ResultSet rs = pst.executeQuery(); //预先分配sql语句的StringBuffer长度为300 StringBuffer sql = new StringBuffer(300); StringBuffer sqlDel = new StringBuffer(); StringBuffer delIds = new StringBuffer(); if (!rs.next()) return null; long count = 0; if ("insert".equals(rs.getString("action")) || "update".equals(rs.getString("action"))) { sql.append("insert into ").append(destTable).append(" (").append(jobInfo.getDestTableFields()) .append(") values "); sql.append(rs.getString("action_sql")).append(","); delIds.append(rs.getObject("ids")).append(","); count++; if (count > 0) { sql = sql.deleteCharAt(sql.length() - 1); if ((!isEmpty(jobInfo.getDestTableUpdate())) && (!isEmpty(jobInfo.getDestTableKey()))) { sql.append(" on duplicate key update "); for (int index = 0, len = updateFields.length; index < len; index++) { sql.append(updateFields[index]).append("= values(").append(updateFields[index]) .append(index == (updateFields.length - 1) ? ")" : "),"); } String newSql = new StringBuffer("alter table ").append(destTable).append(" add constraint ") .append(uniqueName).append(" unique (").append(destTableKey).append(");") .append(sql.toString()).append(";alter table ").append(destTable).append(" drop index ") .append(uniqueName).toString(); // 执行SQL语句,删除源数据 PreparedStatement pst1 = outConn.prepareStatement(""); Statement statement = inConn.createStatement(); String[] sqlList = newSql.split(";"); for (int index = 0, len = sqlList.length; index < len; index++) { pst1.addBatch(sqlList[index]); } pst1.executeBatch(); logger.info("目标数据表插入:" + sqlList[1]); delIds.deleteCharAt(delIds.length() - 1); statement.executeUpdate("delete from " + jobInfo.getSrcTable() + " where " + srcFields[0] + " in " + "(" + delIds.toString() + ")"); logger.info("删除源数据表数据: delete from " + jobInfo.getSrcTable() + " where " + srcFields[0] + " in " + " (" + delIds.toString() + ")"); statement.close(); outConn.commit(); inConn.commit(); pst1.close(); if (rs.next()) { if (!"insert".equals(rs.getString("action"))) { pst.close(); rs.close(); return newSql; } } else { pst.close(); rs.close(); return newSql; } } } logger.debug(sql.toString()); } else if ("delete".equals(rs.getString("action"))) { sqlDel.append("delete from ").append(jobInfo.getDestTable()).append(" where ") .append(jobInfo.getDestTableKey()).append(" in (").append(rs.getString("action_sql")).append(")"); StringBuffer sqlSrcDel = new StringBuffer(); sqlSrcDel.append("delete from ").append(jobInfo.getSrcTable()).append(" where ").append(srcFields[0]) .append(" in (").append(rs.getString("ids")).append(")"); Statement statementIn = inConn.createStatement(); Statement statementOut = outConn.createStatement(); // 删除之前要判断是否为空 statementOut.executeUpdate(sqlDel.toString()); logger.info("删除目标数据库数据: " + sqlDel.toString()); statementIn.executeUpdate(sqlSrcDel.toString()); logger.info("删除源数据库数据: " + sqlSrcDel.toString()); statementOut.close(); if (rs.next()) { if (!"delete".equals(rs.getNString("action"))) { pst.close(); rs.close(); outConn.commit(); inConn.commit(); return sqlDel.toString(); } } else { pst.close(); rs.close(); outConn.commit(); inConn.commit(); return sqlDel.toString(); } } return destTableKey; } /** * 去除String数组每个元素中的空格 * * @param src 需要去除空格的数组 * @return 去除空格后的数组 */ private static String[] trimArrayItem(String[] src) { if (src == null || src.length == 0) return src; String[] dest = new String[src.length]; for (int i = 0, len = src.length; i < len; i++) { dest[i] = src[i].trim(); } return dest; } /** * 产生随机字符串 * * @param length 字符串的长度 * @return 随机的字符串 */ public static String generateString(int length) { if (length < 1) length = 6; String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; String genStr = ""; for (int index = 0; index < length; index++) { genStr = genStr + str.charAt((int) ((Math.random() * 100) % 26)); } return genStr; } /** * @description 字符串工具类 */ public static boolean isEmpty(String str) { return str == null || "".equals(str.trim()); } }
28.621777
109
0.649715
bebe8de77b108dc8e377ec8c1bb999111f12458e
5,026
package com.techhounds.lib.hid; import java.util.ArrayList; import java.util.HashMap; import com.techhounds.Robot; import edu.wpi.first.wpilibj.GenericHID.RumbleType; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; public class ControllerMap { private HashMap<Integer, JoystickButton> buttons; private ArrayList<MultiButton> multiButtons; private Joystick joystick; private Type type; private int [] buttonPorts; private double DEADZONE = 0.05; public interface Key { // XBOX AND LOGITECH KEYS && UNIVERSAL AXIS KEYS int A = 0, B = 1, X = 2, Y = 3, RB = 4, RT = 5, LB = 6, LT = 7, START = 8, BACK = 9; // PLAYSTATION KEYS (START = 8 but already defined) int CROSS = 0, CIRCLE = 1, SQUARE = 2, TRIANGLE = 3, R1 = 4, R2 = 5, L1 = 6, L2 = 7, SELECT = 9, OPTIONS = 8, SHARE = 9; } public interface Direction { int LEFT_HORIZONTAL = 10, RIGHT_HORIZONTAL = 11, LEFT_VERTICAL = 12, RIGHT_VERTICAL = 13; } protected static final int[] logitech = { 2, 3, 1, 4, 6, 8, 5, 7, 10, 9, 0, 2, 1, 3}; protected static final int[] xbox360 = { 1, 2, 3, 4, 6, -1, 5, -1, 8, 7, 0, 4, 1, 5}; protected static final int[] ps4 = { 2, 3, 1, 4, 6, 8, 5, 7, 10, 9, 0, 2, 1, 5}; protected static final int[] xboxOne = { 1, 2, 3, 4, 6, 3, 5, 2, 8, 7, 0, 4, 1, 5}; public ControllerMap(Joystick joystick) { this(joystick, Type.LOGITECH); } public ControllerMap(Joystick joystick, Type type) { this.joystick = joystick; buttons = new HashMap<>(); multiButtons = new ArrayList<>(); setControllerType(type); } public void setControllerType(Type type) { this.type = type; switch(type){ case PS4: buttonPorts = ps4; break; case LOGITECH: buttonPorts = logitech; break; case XBOX_ONE: buttonPorts = xboxOne; break; case XBOX_360: buttonPorts = xbox360; break; default: buttonPorts = logitech; break; } // Iterate through all possible Joystick buttons to replace type for(int buttonID = 0; buttonID < 10; buttonID++) { JoystickButton button = buttons.get(buttonID); if(button != null) { button.setOff(true); if((type == Type.XBOX_ONE || type == Type.XBOX_360) && (buttonID == Key.LT || buttonID == Key.RT)) buttons.replace(buttonID, new TriggerButton(joystick, buttonID)); else buttons.replace(buttonID, new JoystickButton(joystick, buttonPorts[buttonID])); // SmartDashboard.putNumber("Button Selected " + buttonID, buttonPorts[buttonID]); } } for(MultiButton button : multiButtons) button.setOff(true); multiButtons.clear(); } public void clearButtons(){ for(int button = 0; button < buttons.size(); button ++){ if(buttons.get(button) != null){ buttons.get(button).setOff(true); } } for(MultiButton button : multiButtons) button.setOff(true); multiButtons.clear(); buttons.clear(); } public void clearButton(int id){ if(buttons.get(id) != null){ buttons.remove(id).setOff(true); } } public double getForwardsRightPower(){ return Robot.rangeCheck(getAxis(Direction.LEFT_VERTICAL) - getAxis(Direction.RIGHT_HORIZONTAL)); } public double getForwardsLeftPower(){ return Robot.rangeCheck(getAxis(Direction.LEFT_VERTICAL) + getAxis(Direction.RIGHT_HORIZONTAL)); } public double getBackwardsRightPower(){ return Robot.rangeCheck(-getAxis(Direction.LEFT_VERTICAL) - getAxis(Direction.RIGHT_HORIZONTAL) ); } public double getBackwardsLeftPower(){ return Robot.rangeCheck(-getAxis(Direction.LEFT_VERTICAL) + getAxis(Direction.RIGHT_HORIZONTAL)); } public Type getType() { return type; } public double getAxis(int direction) { return checkDeadZone(joystick.getRawAxis(buttonPorts[direction])); } public Button getButton(Integer buttonID) { if(buttons.get(buttonID) == null) { if(DPadButton.isDPADButton(buttonID)) buttons.put(buttonID, new DPadButton(joystick, buttonID)); else if((type == Type.XBOX_ONE || type == Type.XBOX_360) && (buttonID == Key.LT || buttonID == Key.RT)) buttons.put(buttonID, new TriggerButton(joystick, buttonID)); else buttons.put(buttonID, new JoystickButton(joystick, buttonPorts[buttonID])); } //if(!DPadButton.isDPADButton(buttonID)) // SmartDashboard.putNumber("Button Selected " + buttonID, buttonPorts[buttonID]); return buttons.get(buttonID); } public Button getMultiButton(Integer... buttonID) { MultiButton button = new MultiButton(this, buttonID); multiButtons.add(button); return button; } private double checkDeadZone(double value) { return Math.abs(value) < DEADZONE ? 0 : value; } public enum Type { PS4, LOGITECH, XBOX_ONE, XBOX_360 } public void startRumble() { joystick.setRumble(RumbleType.kLeftRumble, 1); joystick.setRumble(RumbleType.kRightRumble, 1); } public void stopRumble() { joystick.setRumble(RumbleType.kLeftRumble, 0); joystick.setRumble(RumbleType.kRightRumble, 1); } }
28.078212
103
0.682451
d6d1ecc85c3d635ae0fad7f6c422d4cfe7a0ba50
3,129
package com.bdp.tx.netty.service.impl; import com.alibaba.fastjson.JSONObject; import com.bdp.tx.commons.utils.task.ConditionUtils; import com.bdp.tx.commons.utils.task.IBack; import com.bdp.tx.commons.utils.task.Task; import com.bdp.tx.control.service.TransactionControlService; import com.bdp.tx.framework.utils.SocketManager; import com.bdp.tx.listener.service.ModelNameService; import com.bdp.tx.netty.service.MQTxManagerService; import com.bdp.tx.netty.service.NettyControlService; import com.bdp.tx.netty.service.NettyService; import com.bdp.tx.netty.utils.IpAddressUtils; import io.netty.channel.ChannelHandlerContext; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class NettyControlServiceImpl implements NettyControlService { @Autowired private NettyService nettyService; @Autowired private TransactionControlService transactionControlService; @Autowired private MQTxManagerService mqTxManagerService; @Autowired private ModelNameService modelNameService; @Override public void restart() { nettyService.close(); try { Thread.sleep(1000 * 3); } catch (InterruptedException e) { e.printStackTrace(); } nettyService.start(); } @Override public void uploadModelInfo() { new Thread(new Runnable() { @Override public void run() { while (!SocketManager.getInstance().isNetState() || !IpAddressUtils.isIpAddress(modelNameService.getIpAddress())) { try { Thread.sleep(1000 * 5); } catch (InterruptedException e) { e.printStackTrace(); } } mqTxManagerService.uploadModelInfo(); } }).start(); } @Override public void executeService(final ChannelHandlerContext ctx, final String json) { if (StringUtils.isNotEmpty(json)) { JSONObject resObj = JSONObject.parseObject(json); if (resObj.containsKey("a")) { // a表示action,是tm发送给tx模块的处理命令。即通过a值来做事务提交或补偿操作。 // a的取值为t或c,分别对应调用ActionTServiceImpl和ActionCServiceImpl。 transactionControlService.notifyTransactionMsg(ctx, resObj, json); } else { // tx发送数据给tm的响应返回数据 String key = resObj.getString("k"); responseMsg(key, resObj); } } } private void responseMsg(String key, JSONObject resObj) { if (!"h".equals(key)) {// 表示非心跳数据 // 获取具体的数据 final String data = resObj.getString("d"); // 通过key获取对应的Task Task task = ConditionUtils.getInstance().getTask(key); if (task != null) { if (task.isAwait()) { // 设置好接收返回消息的回调接口 task.setBack(new IBack() { @Override public Object doing(Object... objs) throws Throwable { return data; } }); // 唤醒正在等的线程,即当前响应对应的请求线程 task.signalTask(); } } } else { // 心跳数据 final String data = resObj.getString("d"); // 心跳正常,即设置网络状态为正常 SocketManager.getInstance().setNetState(true); if (StringUtils.isNotEmpty(data)) { try { // 可知消息接收超时时间是由心跳发过来的 SocketManager.getInstance().setDelay(Integer.parseInt(data)); } catch (Exception e) { SocketManager.getInstance().setDelay(1); } } } } }
27.208696
81
0.717482
4fa0637bb8e6e1d797a155f0b2f3e02642c90d99
2,622
// Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, Inc. licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.cloudera.api.model; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; /** * Config Details: The config can either have a value or ref or variable. */ public class ApiClusterTemplateConfig { /** * Config name */ private String name; /** * Config value */ @JsonInclude(Include.NON_NULL) private String value; /** * Name of the reference. If referring to a service then it will be replaced * with actual service name at import time. If referring to a role then it * will be replaced with the host name containing that role at import time. */ @JsonInclude(Include.NON_EMPTY) private String ref; /** * Referring a variable. The variable value will be provided by the user at * import time. Variable name for this config. At import time the value of * this variable will be provided by the * {@link #ApiClusterTemplateInstantiator.Variable} */ @JsonInclude(Include.NON_EMPTY) private String variable; /** * This indicates that the value was automatically configured. */ @JsonInclude(Include.NON_DEFAULT) private boolean autoConfig; public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getValue() { return this.value; } public void setValue(String value) { this.value = value; } public String getRef() { return this.ref; } public void setRef(String ref) { this.ref = ref; } public String getVariable() { return this.variable; } public void setVariable(String variable) { this.variable = variable; } public boolean isAutoConfig() { return this.autoConfig; } public void setAutoConfig(boolean autoConfig) { this.autoConfig = autoConfig; } }
27.3125
78
0.713577
483112d4c559359c57abc048cf248e194e119813
3,527
package com.ramostear.unaboot.web; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.ServletRequestDataBinder; import org.springframework.web.bind.ServletRequestUtils; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import java.text.SimpleDateFormat; import java.util.Date; /** * @ClassName UnaController * @Description 公共的控制器 * @Author ramostear * @Date 2019/11/12 0012 3:00 * @Version 1.0 **/ public class UnaController { @InitBinder public void initBinder(ServletRequestDataBinder dataBinder){ dataBinder.registerCustomEditor(Date.class,new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true)); } /** * 默认分页 * @return Pageable */ protected Pageable page(){ HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder .getRequestAttributes()).getRequest(); int size = ServletRequestUtils.getIntParameter(request,"size",15); int offset = ServletRequestUtils.getIntParameter(request,"offset",1); return PageRequest.of(offset-1,size); } /** * 根据排序字段降序排列分页数据 * @param field 排序字段 * @return Pageable */ protected Pageable pageByDesc(String field){ return initPage(field,0); } protected Pageable pageByDesc(String field,int size){ return initPage(field,0,size); } /** * 根据排序字段升序排列分页数据 * @param field 排序字段 * @return Pageable */ protected Pageable pageByAsc(String field){ return initPage(field,1); } protected Pageable pageByAsc(String field,int size){ return initPage(field,1,size); } /** * 路径跳转命令 * @param path 跳转路径 * @return String */ protected String redirect(String path){ return "redirect:"+path; } /** * 异步请求成功返回值 * @return */ protected ResponseEntity<Object> ok(){ return ResponseEntity.ok().build(); } protected ResponseEntity<Object> ok(String msg){ return new ResponseEntity<>(msg, HttpStatus.OK); } /** * 异步请求失败返回值 * @return */ protected ResponseEntity<Object> badRequest(){ return ResponseEntity.badRequest().build(); } protected ResponseEntity<Object> badRequest(String msg){ return new ResponseEntity<>(msg,HttpStatus.BAD_REQUEST); } private Pageable initPage(String field,int type){ return initPage(field,type,15); } private Pageable initPage(String field,int type,int _size){ HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest(); int size = ServletRequestUtils.getIntParameter(request,"size",_size); int offset = ServletRequestUtils.getIntParameter(request,"offset",1); if(type == 0){ return PageRequest.of(offset-1,size,new Sort(Sort.Direction.DESC,field)); }else{ return PageRequest.of(offset-1,size,new Sort(Sort.Direction.ASC,field)); } } }
30.669565
122
0.683584
4fd7182cd3f866f1911ad233c646d40bca038a12
39,298
/* * 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.serde.support.deserializers; import io.micronaut.core.annotation.NonNull; import io.micronaut.core.annotation.Nullable; import io.micronaut.core.reflect.exception.InstantiationException; import io.micronaut.core.type.Argument; import io.micronaut.core.util.ArrayUtils; import io.micronaut.serde.Decoder; import io.micronaut.serde.Deserializer; import io.micronaut.serde.UpdatingDeserializer; import io.micronaut.serde.config.annotation.SerdeConfig; import io.micronaut.serde.exceptions.InvalidFormatException; import io.micronaut.serde.exceptions.InvalidPropertyFormatException; import io.micronaut.serde.exceptions.SerdeException; import io.micronaut.serde.reference.PropertyReference; import java.io.IOException; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; /** * Implementation for deserialization of objects that uses introspection metadata. * * @author graemerocher * @since 1.0.0 */ class SpecificObjectDeserializer implements Deserializer<Object>, UpdatingDeserializer<Object> { private final boolean ignoreUnknown; private final DeserBean<? super Object> deserBean; public SpecificObjectDeserializer(boolean ignoreUnknown, DeserBean<? super Object> deserBean) { this.ignoreUnknown = ignoreUnknown && deserBean.ignoreUnknown; this.deserBean = deserBean; } @Override public Object deserialize(Decoder decoder, DecoderContext decoderContext, Argument<? super Object> type) throws IOException { if (decoder.decodeNull()) { return null; } deserBean.initialize(decoderContext); DeserBean<? super Object> deserBean = this.deserBean; Class<? super Object> objectType = deserBean.introspection.getBeanType(); if (deserBean.delegating) { if (deserBean.creatorParams != null) { final PropertiesBag<Object>.Consumer creatorParams = deserBean.creatorParams.newConsumer(); final DeserBean.DerProperty<Object, Object> creator = creatorParams.getNotConsumed().iterator().next(); final Object val = deserializeValue(decoderContext, decoder, creator, creator.argument, null); return deserBean.introspection.instantiate(val); } else { throw new IllegalStateException("At least one creator parameter expected"); } } else { PropertiesBag<Object>.Consumer readProperties = deserBean.readProperties != null ? deserBean.readProperties.newConsumer() : null; boolean hasProperties = readProperties != null; Decoder objectDecoder = decoder.decodeObject(type); TokenBuffer tokenBuffer = null; AnyValues<Object> anyValues = deserBean.anySetter != null ? new AnyValues<>(deserBean.anySetter) : null; Object obj; if (deserBean instanceof SubtypedDeserBean) { // subtyped binding required SubtypedDeserBean<? super Object> subtypedDeserBean = (SubtypedDeserBean) deserBean; final String discriminatorName = subtypedDeserBean.discriminatorName; final Map<String, DeserBean<?>> subtypes = subtypedDeserBean.subtypes; final SerdeConfig.Subtyped.DiscriminatorType discriminatorType = subtypedDeserBean.discriminatorType; if (discriminatorType == SerdeConfig.Subtyped.DiscriminatorType.PROPERTY) { while (true) { final String key = objectDecoder.decodeKey(); if (key == null) { break; } if (key.equals(discriminatorName)) { if (!objectDecoder.decodeNull()) { final String subtypeName = objectDecoder.decodeString(); final DeserBean<?> subtypeDeser = subtypes.get(subtypeName); if (subtypeDeser != null) { //noinspection unchecked deserBean = (DeserBean<? super Object>) subtypeDeser; deserBean.initialize(decoderContext); //noinspection unchecked objectType = (Class<? super Object>) subtypeDeser.introspection.getBeanType(); readProperties = deserBean.readProperties != null ? deserBean.readProperties.newConsumer() : null; hasProperties = readProperties != null; anyValues = deserBean.anySetter != null ? new AnyValues<>(deserBean.anySetter) : null; } } break; } else { tokenBuffer = initTokenBuffer(tokenBuffer, objectDecoder, key); } } } else { while (true) { final String key = objectDecoder.decodeKey(); if (key == null) { break; } final DeserBean<?> subtypeBean = subtypes.get(key); if (subtypeBean != null) { if (!objectDecoder.decodeNull()) { objectDecoder = objectDecoder.decodeObject(type); deserBean = (DeserBean<? super Object>) subtypeBean; deserBean.initialize(decoderContext); //noinspection unchecked objectType = (Class<? super Object>) subtypeBean.introspection.getBeanType(); readProperties = deserBean.readProperties != null ? deserBean.readProperties.newConsumer() : null; hasProperties = readProperties != null; } break; } else { if (anyValues != null) { tokenBuffer = initTokenBuffer(tokenBuffer, objectDecoder, key); } else { objectDecoder.skipValue(); } } } } } if (deserBean.creatorParams != null) { final PropertiesBag<Object>.Consumer creatorParameters = deserBean.creatorParams.newConsumer(); int creatorSize = deserBean.creatorSize; Object[] params = new Object[creatorSize]; PropertyBuffer buffer = initFromTokenBuffer( tokenBuffer, creatorParameters, readProperties, anyValues, decoderContext ); while (true) { final String prop = objectDecoder.decodeKey(); if (prop == null) { break; } final DeserBean.DerProperty<? super Object, ?> sp = creatorParameters.findNotConsumed(prop); if (sp != null) { if (sp.views != null && !decoderContext.hasView(sp.views)) { creatorParameters.consume(prop); objectDecoder.skipValue(); continue; } @SuppressWarnings("unchecked") final Argument<Object> propertyType = (Argument<Object>) sp.argument; final Object val = deserializeValue(decoderContext, objectDecoder, sp, propertyType, null); if (val == null) { // Skip consume continue; } creatorParameters.consume(prop); if (sp.instrospection.getBeanType() == objectType) { params[sp.index] = val; if (hasProperties && readProperties.isNotConsumed(prop)) { // will need binding to properties as well buffer = initBuffer(buffer, sp, prop, val); } } else { buffer = initBuffer(buffer, sp, prop, val); } if (creatorParameters.isAllConsumed()) { break; } } else if (hasProperties) { final DeserBean.DerProperty<? super Object, ?> rp = readProperties.findNotConsumed(prop); if (rp != null) { @SuppressWarnings("unchecked") final Argument<Object> argument = (Argument<Object>) rp.argument; final Object val = deserializeValue(decoderContext, objectDecoder, rp, argument, null); buffer = initBuffer(buffer, rp, prop, val); } else { skipOrSetAny( decoderContext, objectDecoder, prop, anyValues, ignoreUnknown, type ); } } else { skipOrSetAny( decoderContext, objectDecoder, prop, anyValues, ignoreUnknown, type ); } } if (buffer != null && !creatorParameters.isAllConsumed()) { for (PropertyBuffer propertyBuffer : buffer) { final DeserBean.DerProperty<? super Object, ?> derProperty = creatorParameters.consume(propertyBuffer.name); if (derProperty != null) { propertyBuffer.set( params, decoderContext ); } } } if (!creatorParameters.isAllConsumed()) { // set unsatisfied parameters to defaults or fail for (DeserBean.DerProperty<? super Object, ?> sp : creatorParameters.getNotConsumed()) { if (sp.backRef != null) { final PropertyReference<? super Object, ?> ref = decoderContext.resolveReference( new PropertyReference<>( sp.backRef, sp.instrospection, sp.argument, null ) ); if (ref != null) { final Object o = ref.getReference(); if (o == null) { sp.setDefault(decoderContext, params); } else { params[sp.index] = o; } continue; } } if (sp.unwrapped != null && buffer != null) { final Object o = materializeFromBuffer(sp, buffer, decoderContext); if (o == null) { sp.setDefault(decoderContext, params); } else { params[sp.index] = o; } } else { if (sp.isAnySetter && anyValues != null) { anyValues.bind(params); anyValues = null; } else { sp.setDefault(decoderContext, params); } } } } try { obj = deserBean.introspection.instantiate(params); } catch (InstantiationException e) { throw new SerdeException("Unable to deserialize type [" + type + "]: " + e.getMessage(), e); } if (hasProperties) { if (buffer != null) { for (PropertyBuffer propertyBuffer : buffer) { final DeserBean.DerProperty<? super Object, ?> derProperty = readProperties.consume(propertyBuffer.name); if (derProperty != null) { if (derProperty.instrospection.getBeanType() == objectType) { propertyBuffer.set(obj, decoderContext); } } } } if (!readProperties.isAllConsumed()) { // more properties still to be read buffer = decodeProperties( deserBean, decoderContext, obj, objectDecoder, readProperties, deserBean.unwrappedProperties, buffer, anyValues, ignoreUnknown, type ); } applyDefaultValuesOrFail( obj, readProperties, deserBean.unwrappedProperties, buffer, decoderContext ); } } else { try { obj = deserBean.introspection.instantiate(); } catch (InstantiationException e) { throw new SerdeException("Unable to deserialize type [" + type + "]: " + e.getMessage(), e); } if (hasProperties) { final PropertyBuffer existingBuffer = initFromTokenBuffer( tokenBuffer, null, readProperties, anyValues, decoderContext); final PropertyBuffer propertyBuffer = decodeProperties(deserBean, decoderContext, obj, objectDecoder, readProperties, deserBean.unwrappedProperties, existingBuffer, anyValues, ignoreUnknown, type); // the property buffer will be non-null if there were any unwrapped // properties in which case we need to go through and materialize unwrapped // from the buffer applyDefaultValuesOrFail( obj, readProperties, deserBean.unwrappedProperties, propertyBuffer, decoderContext ); } else if (anyValues != null && tokenBuffer != null) { for (TokenBuffer buffer : tokenBuffer) { anyValues.handle( buffer.name, buffer.decoder, decoderContext ); } } } // finish up finalizeObjectDecoder(decoderContext, type, ignoreUnknown, objectDecoder, anyValues, obj); return obj; } } private Object deserializeValue(DecoderContext decoderContext, Decoder objectDecoder, DeserBean.DerProperty<? super Object, ?> derProperty, Argument<Object> propertyType, Object constructedBean) throws IOException { final Object val; final boolean hasRef = constructedBean != null && derProperty.managedRef != null; try { if (hasRef) { decoderContext.pushManagedRef( new PropertyReference<>( derProperty.managedRef, derProperty.instrospection, derProperty.argument, constructedBean ) ); } val = derProperty.deserializer.deserialize( objectDecoder, decoderContext, propertyType ); } catch (InvalidFormatException e) { throw new InvalidPropertyFormatException( e, propertyType ); } finally { if (hasRef) { decoderContext.popManagedRef(); } } return val; } private void finalizeObjectDecoder(DecoderContext decoderContext, Argument<? super Object> type, boolean ignoreUnknown, Decoder objectDecoder, AnyValues<Object> anyValues, Object obj) throws IOException { while (true) { final String key = objectDecoder.decodeKey(); if (key == null) { break; } skipOrSetAny(decoderContext, objectDecoder, key, anyValues, ignoreUnknown, type); } if (anyValues != null) { anyValues.bind(obj); } objectDecoder.finishStructure(); } private TokenBuffer initTokenBuffer(TokenBuffer tokenBuffer, Decoder objectDecoder, String key) throws IOException { return tokenBuffer == null ? new TokenBuffer( key, objectDecoder.decodeBuffer(), null ) : tokenBuffer.next(key, objectDecoder.decodeBuffer()); } private @Nullable PropertyBuffer initFromTokenBuffer(@Nullable TokenBuffer tokenBuffer, @Nullable PropertiesBag<Object>.Consumer creatorParameters, @Nullable PropertiesBag<Object>.Consumer readProperties, @Nullable AnyValues<?> anyValues, DecoderContext decoderContext) throws IOException { if (tokenBuffer != null) { PropertyBuffer propertyBuffer = null; for (TokenBuffer buffer : tokenBuffer) { final String n = buffer.name; if (creatorParameters != null && creatorParameters.isNotConsumed(n)) { final DeserBean.DerProperty<? super Object, ?> derProperty = creatorParameters.findNotConsumed(n); propertyBuffer = initBuffer( propertyBuffer, derProperty, n, buffer.decoder ); } else if (readProperties != null && readProperties.isNotConsumed(n)) { final DeserBean.DerProperty<? super Object, ?> derProperty = readProperties.findNotConsumed(n); propertyBuffer = initBuffer( propertyBuffer, derProperty, n, buffer.decoder ); } else if (anyValues != null) { anyValues.handle( buffer.name, buffer.decoder, decoderContext ); } } return propertyBuffer; } return null; } private PropertyBuffer initBuffer(PropertyBuffer buffer, DeserBean.DerProperty<? super Object, ?> rp, String prop, Object val) { if (buffer == null) { buffer = new PropertyBuffer(rp, prop, val, null); } else { buffer = buffer.next(rp, prop, val); } return buffer; } @Override public boolean allowNull() { return true; } private PropertyBuffer decodeProperties( DeserBean<? super Object> introspection, DecoderContext decoderContext, Object obj, Decoder objectDecoder, PropertiesBag.Consumer readProperties, DeserBean.DerProperty<? super Object, Object>[] unwrappedProperties, PropertyBuffer propertyBuffer, @Nullable AnyValues<?> anyValues, boolean ignoreUnknown, Argument<?> beanType) throws IOException { while (true) { final String prop = objectDecoder.decodeKey(); if (prop == null) { break; } @SuppressWarnings("unchecked") final DeserBean.DerProperty<Object, Object> property = (DeserBean.DerProperty<Object, Object>) readProperties.consume(prop); if (property != null && (property.beanProperty != null || property.beanMethod != null)) { if (property.views != null && !decoderContext.hasView(property.views)) { objectDecoder.skipValue(); continue; } final Argument<Object> propertyType = property.argument; boolean isNull = objectDecoder.decodeNull(); if (isNull) { if (propertyType.isNullable()) { property.set(obj, null); } else { property.setDefault(decoderContext, obj); } continue; } final Object val = deserializeValue(decoderContext, objectDecoder, property, propertyType, obj); if (introspection.introspection == property.instrospection) { property.set(obj, val); } else { propertyBuffer = initBuffer(propertyBuffer, property, prop, val); } if (readProperties.isAllConsumed() && unwrappedProperties == null && introspection.anySetter == null) { break; } } else { skipOrSetAny( decoderContext, objectDecoder, prop, anyValues, ignoreUnknown, beanType ); } } return propertyBuffer; } private void skipOrSetAny(DecoderContext decoderContext, Decoder objectDecoder, String property, @Nullable AnyValues<?> anyValues, boolean ignoreUnknown, Argument<?> type) throws IOException { if (anyValues != null) { anyValues.handle( property, objectDecoder, decoderContext ); } else { if (ignoreUnknown) { objectDecoder.skipValue(); } else { throw new SerdeException("Unknown property [" + property + "] encountered during deserialization of type: " + type); } } } private void applyDefaultValuesOrFail( Object obj, PropertiesBag<? super Object>.Consumer readProperties, @Nullable DeserBean.DerProperty<? super Object, Object>[] unwrappedProperties, @Nullable PropertyBuffer buffer, DecoderContext decoderContext) throws IOException { if (ArrayUtils.isNotEmpty(unwrappedProperties)) { for (DeserBean.DerProperty<? super Object, Object> dp : unwrappedProperties) { if (dp.views != null && !decoderContext.hasView(dp.views)) { continue; } if (buffer == null) { dp.set(obj, null); } else { Object v = materializeFromBuffer(dp, buffer, decoderContext); dp.set(obj, v); } } } if (buffer != null && !readProperties.isAllConsumed()) { for (PropertyBuffer propertyBuffer : buffer) { final DeserBean.DerProperty<? super Object, ?> derProperty = readProperties.consume(propertyBuffer.name); if (derProperty != null) { propertyBuffer.set(obj, decoderContext); } } } if (!readProperties.isAllConsumed()) { for (DeserBean.DerProperty<? super Object, ?> dp : readProperties.getNotConsumed()) { if (dp.backRef != null) { final PropertyReference<? super Object, ?> ref = decoderContext.resolveReference( new PropertyReference<>( dp.backRef, dp.instrospection, dp.argument, null ) ); if (ref != null) { final Object o = ref.getReference(); if (o == null) { dp.setDefault(decoderContext, obj); } else { //noinspection unchecked ((DeserBean.DerProperty) dp).set(obj, o); } } } else { dp.setDefault(decoderContext, obj); } } } } private @Nullable Object materializeFromBuffer( DeserBean.DerProperty<? super Object, ?> property, PropertyBuffer buffer, DecoderContext decoderContext) throws IOException { @SuppressWarnings("unchecked") final DeserBean<Object> unwrapped = (DeserBean<Object>) property.unwrapped; if (unwrapped != null) { Object object; if (unwrapped.creatorParams != null) { final PropertiesBag<Object>.Consumer creatorParams = unwrapped.creatorParams.newConsumer(); Object[] params = new Object[unwrapped.creatorSize]; // handle construction for (DeserBean.DerProperty<?, ?> der : creatorParams.getNotConsumed()) { boolean satisfied = false; for (PropertyBuffer pb : buffer) { if (pb.property == der) { pb.set(params, decoderContext); satisfied = true; break; } } if (!satisfied) { if (der.defaultValue != null) { params[der.index] = der.defaultValue; } else if (der.required) { throw new SerdeException("Unable to deserialize type [" + unwrapped.introspection.getBeanType() + "]. Required constructor parameter [" + der.argument + "] at index [" + der.index + "] is not present in supplied data"); } } } object = unwrapped.introspection.instantiate(params); } else { object = unwrapped.introspection.instantiate(); } if (unwrapped.readProperties != null) { final PropertiesBag<Object>.Consumer readProperties = unwrapped.readProperties.newConsumer(); for (DeserBean.DerProperty<Object, Object> der : readProperties.getNotConsumed()) { boolean satisfied = false; for (PropertyBuffer pb : buffer) { if (pb.property == der) { pb.set(object, decoderContext); der.set(object, pb.value); satisfied = true; break; } } if (!satisfied) { der.setDefault(decoderContext, object); } } } return object; } return null; } @Override public void deserializeInto(Decoder decoder, DecoderContext decoderContext, Argument<? super Object> type, Object value) throws IOException { deserBean.initialize(decoderContext); PropertiesBag.Consumer readProperties = deserBean.readProperties != null ? deserBean.readProperties.newConsumer() : null; boolean hasProperties = readProperties != null; boolean ignoreUnknown = this.ignoreUnknown && deserBean.ignoreUnknown; AnyValues<Object> anyValues = deserBean.anySetter != null ? new AnyValues<>(deserBean.anySetter) : null; final Decoder objectDecoder = decoder.decodeObject(type); if (hasProperties) { final PropertyBuffer propertyBuffer = decodeProperties(deserBean, decoderContext, value, objectDecoder, readProperties, deserBean.unwrappedProperties, null, anyValues, ignoreUnknown, type); // the property buffer will be non-null if there were any unwrapped // properties in which case we need to go through and materialize unwrapped // from the buffer applyDefaultValuesOrFail( value, readProperties, deserBean.unwrappedProperties, propertyBuffer, decoderContext ); } finalizeObjectDecoder( decoderContext, type, ignoreUnknown, objectDecoder, anyValues, value ); } private static final class AnyValues<T> { Map<String, T> values; final DeserBean.AnySetter<T> anySetter; private AnyValues(DeserBean.AnySetter<T> anySetter) { this.anySetter = anySetter; } void handle(String property, Decoder objectDecoder, DecoderContext decoderContext) throws IOException { if (values == null) { values = new LinkedHashMap<>(); } if (objectDecoder.decodeNull()) { values.put(property, null); } else { if (anySetter.deserializer != null) { values.put(property, anySetter.deserializer.deserialize( objectDecoder, decoderContext, anySetter.valueType )); } else { //noinspection unchecked values.put(property, (T) objectDecoder.decodeArbitrary()); } } } void bind(Object obj) { if (values != null) { anySetter.bind(values, obj); } } } private static final class TokenBuffer implements Iterable<TokenBuffer> { final String name; final Decoder decoder; private final TokenBuffer next; private TokenBuffer(@NonNull String name, @NonNull Decoder decoder, @Nullable TokenBuffer next) { this.name = name; this.decoder = decoder; this.next = next; } TokenBuffer next(@NonNull String name, @NonNull Decoder decoder) { return new TokenBuffer(name, decoder, this); } @Override public Iterator<TokenBuffer> iterator() { return new Iterator<SpecificObjectDeserializer.TokenBuffer>() { SpecificObjectDeserializer.TokenBuffer thisBuffer = null; @Override public boolean hasNext() { return thisBuffer == null || thisBuffer.next != null; } @Override public SpecificObjectDeserializer.TokenBuffer next() { if (thisBuffer == null) { thisBuffer = SpecificObjectDeserializer.TokenBuffer.this; } else { thisBuffer = thisBuffer.next; } return thisBuffer; } }; } } private static final class PropertyBuffer implements Iterable<PropertyBuffer> { final DeserBean.DerProperty<Object, Object> property; final String name; private Object value; private final PropertyBuffer next; public PropertyBuffer(DeserBean.DerProperty<? super Object, ?> derProperty, String name, Object val, @Nullable PropertyBuffer next) { //noinspection unchecked this.property = (DeserBean.DerProperty<? super Object, Object>) derProperty; this.name = name; this.value = val; this.next = next; } PropertyBuffer next(DeserBean.DerProperty<? super Object, ?> rp, String property, Object val) { return new PropertyBuffer(rp, property, val, this); } @Override public Iterator<PropertyBuffer> iterator() { return new Iterator<SpecificObjectDeserializer.PropertyBuffer>() { SpecificObjectDeserializer.PropertyBuffer thisBuffer = null; @Override public boolean hasNext() { return thisBuffer == null || thisBuffer.next != null; } @Override public SpecificObjectDeserializer.PropertyBuffer next() { if (thisBuffer == null) { thisBuffer = SpecificObjectDeserializer.PropertyBuffer.this; } else { thisBuffer = thisBuffer.next; } return thisBuffer; } }; } public void set(Object obj, DecoderContext decoderContext) throws IOException { if (value instanceof Decoder) { if (property.managedRef != null) { decoderContext.pushManagedRef( new PropertyReference<>( property.managedRef, property.instrospection, property.argument, obj ) ); } try { value = property.deserializer.deserialize( (Decoder) value, decoderContext, property.argument ); } catch (InvalidFormatException e) { throw new InvalidPropertyFormatException( e, property.argument ); } finally { decoderContext.popManagedRef(); } } property.set(obj, value); } public void set(Object[] params, DecoderContext decoderContext) throws IOException { if (value instanceof Decoder) { try { value = property.deserializer.deserialize( (Decoder) value, decoderContext, property.argument ); } catch (InvalidFormatException e) { throw new InvalidPropertyFormatException( e, property.argument ); } } params[property.index] = value; } } }
44.505096
247
0.456028
24030ac728082951e2e9da183edd89ad4ac7b45e
1,634
package com.imageloader.adapter; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.imageloader.R; import java.util.List; /** * Created by wangzhiguo on 15/8/31. */ public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerViewHolder> { private String[] mList; private List<String> mStringList; public RecyclerAdapter(String[] array,List<String> list) { mList = array; mStringList = list; } @Override public RecyclerViewHolder onCreateViewHolder(ViewGroup viewGroup, int type) { if(type == ItemType.FIRSTITEM) { View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.empty_item,viewGroup,false); return new RecyclerViewHolder(view,type,viewGroup.getContext()); } else { View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recycler_item,viewGroup,false); return new RecyclerViewHolder(view,type,viewGroup.getContext()); } } @Override public void onBindViewHolder(RecyclerViewHolder recyclerViewHolder, int i) { if(i != 0) { recyclerViewHolder.setImage(mList[i - 1]); recyclerViewHolder.setText(mStringList.get(i - 1)); } } @Override public int getItemCount() { return mList.length + 1; } @Override public int getItemViewType(int position) { if(position == 0) { return ItemType.FIRSTITEM; } else { return ItemType.GENERAL; } } }
28.172414
116
0.659731
bee689eb337d495e414d551baae8ade39a5e1c7f
2,731
/** * Copyright 2005-2014 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * 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.kuali.rice.kew.xml.xstream; import java.util.List; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFunction; import javax.xml.xpath.XPathFunctionException; import org.w3c.dom.Node; /** * An XPathFunction which will run XStream safe XPath queries. * * @see XStreamSafeEvaluator * * @author Kuali Rice Team ([email protected]) */ public class XStreamSafeSearchFunction implements XPathFunction { private final Node rootNode; private XPath xpath; private static XStreamSafeEvaluator evaluator = new XStreamSafeEvaluator(); public XStreamSafeSearchFunction(Node rootNode, XPath xpath) { this.rootNode = rootNode; this.xpath = xpath; } public Object evaluate(List parameters) throws XPathFunctionException { String xPathExpression = getXPathExpressionParameter(parameters); evaluator.setXpath(xpath); //Node rootSearchNode = getRootSearchNodeParameter(parameters); try { return evaluator.evaluate(xPathExpression, rootNode); } catch (XPathExpressionException e) { throw new XPathFunctionException(e); } } private String getXPathExpressionParameter(List parameters) throws XPathFunctionException { if (parameters.size() < 1) { throw new XPathFunctionException("First parameter must be an XPath expression."); } if (!(parameters.get(0) instanceof String)) { throw new XPathFunctionException("First parameter must be an XPath expression String"); } return (String)parameters.get(0); } public XPath getXpath() { return xpath; } public void setXpath(XPath xpath) { this.xpath = xpath; } /*private Node getRootSearchNodeParameter(List parameters) throws XPathFunctionException { if (parameters.size() < 2) { throw new XPathFunctionException("Second parameter should be root node and is required"); } System.out.println(parameters.get(1)); if (!(parameters.get(1) instanceof Node)) { throw new XPathFunctionException("Second parameter should be an instance of Node (try using the root() XPath function)."); } return (Node)parameters.get(1); }*/ }
31.755814
125
0.755767
b0d1d1083a85947b58a5989194dfad0aa55da1e4
1,384
// // ======================================================================== // Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // All rights reserved. This program and the accompanying materials // are made available under the terms of the Eclipse Public License v1.0 // and Apache License v2.0 which accompanies this distribution. // // The Eclipse Public License is available at // http://www.eclipse.org/legal/epl-v10.html // // The Apache License v2.0 is available at // http://www.opensource.org/licenses/apache2.0.php // // You may elect to redistribute this code under either of these licenses. // ======================================================================== // package org.eclipse.jetty.jaas.callback; import javax.security.auth.callback.Callback; /** * ObjectCallback * <p> * Can be used as a LoginModule Callback to * obtain a user's credential as an Object, rather than * a char[], to which some credentials may not be able * to be converted */ public class ObjectCallback implements Callback { protected Object _object; public void setObject(Object o) { _object = o; } public Object getObject () { return _object; } public void clearObject () { _object = null; } }
27.68
76
0.565029
dfe46447ab0547c3ff5a5bf36c7b7b87d84bef9f
3,462
/* * Sleuth Kit Data Model * * Copyright 2013 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sleuthkit.datamodel; import java.util.HashMap; /** * Instances of this class are data transfer objects (DTOs) that represent the * names (and related properties) a user can select from to apply a tag to * content or a blackboard artifact. */ public class TagName implements Comparable<TagName> { public enum HTML_COLOR { NONE("None"), //NON-NLS WHITE("White"), //NON-NLS SILVER("Silver"), //NON-NLS GRAY("Gray"), //NON-NLS BLACK("Black"), //NON-NLS RED("Red"), //NON-NLS MAROON("Maron"), //NON-NLS YELLOW("Yellow"), //NON-NLS OLIVE("Olive"), //NON-NLS LIME("Lime"), //NON-NLS GREEN("Green"), //NON-NLS AQUA("Aqua"), //NON-NLS TEAL("Teal"), //NON-NLS BLUE("Blue"), //NON-NLS NAVY("Navy"), //NON-NLS FUCHSIA("Fuchsia"), //NON-NLS PURPLE("Purple"); //NON-NLS private final static HashMap<String, HTML_COLOR> colorMap = new HashMap<String, HTML_COLOR>(); private String name; static { for (HTML_COLOR color : HTML_COLOR.values()) { colorMap.put(color.name(), color); } } private HTML_COLOR(String name) { this.name = name; } String getName() { return name; } public static HTML_COLOR getColorByName(String colorName) { if (colorMap.containsKey(colorName)) { return colorMap.get(colorName); } else { return NONE; } } } static long ID_NOT_SET = -1; private long id = ID_NOT_SET; private final String displayName; private String description; private HTML_COLOR color; // Clients of the org.sleuthkit.datamodel package should not directly create these objects. TagName(long id, String displayName, String description, HTML_COLOR color) { this.id = id; this.displayName = displayName; this.description = description; this.color = color; } public long getId() { return id; } public String getDisplayName() { return displayName; } public String getDescription() { return description; } public HTML_COLOR getColor() { return color; } /** * Compares this TagName to the other TagName based on null null null null null {@link String#compareTo(java.lang.String) of the display names * * @param other The other TagName to compare this TagName to * @return -1 if this TagName's display name is before/less than the other * TagName's display name as determined by {@link String#compareTo(java.lang.String). * 0 if this TagName's display name is equal to the other TagName's * display name as determined by {@link String#compareTo(java.lang.String). * 1 if this TagName's display name is after/greater than the other TagName's * display name as determined by {@link String#compareTo(java.lang.String). */ @Override public int compareTo(TagName other) { return this.getDisplayName().compareTo(other.getDisplayName()); } }
28.85
144
0.703351
97c204d9b804876ca72682ed1714d7d62a570180
2,548
/** * Copyright (C) FuseSource, Inc. * http://fusesource.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.fusesource.gateway; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Collections; import java.util.List; /** */ public class ServiceDTO implements ServiceDetails { @JsonProperty private String id; @JsonProperty private String container; @JsonProperty private String version; @JsonProperty private String bundleName; @JsonProperty private String bundleVersion; @JsonProperty private List<String> services = Collections.EMPTY_LIST; @Override public String toString() { return "ServiceDTO{" + "id='" + id + '\'' + ", container='" + container + '\'' + ", version='" + version + '\'' + ", bundleName='" + bundleName + '\'' + ", bundleVersion='" + bundleVersion + '\'' + ", services=" + services + '}'; } public String getId() { return id; } public void setId(String id) { this.id = id; } @Override public String getContainer() { return container; } public void setContainer(String container) { this.container = container; } @Override public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public List<String> getServices() { return services; } public void setServices(List<String> services) { this.services = services; } @Override public String getBundleName() { return bundleName; } public void setBundleName(String bundleName) { this.bundleName = bundleName; } @Override public String getBundleVersion() { return bundleVersion; } public void setBundleVersion(String bundleVersion) { this.bundleVersion = bundleVersion; } }
23.163636
75
0.620879
a964cc31118e2ed6d148f956dc93a301dcbaed99
323
package com.github.ticherti.parser.repository; import com.github.ticherti.parser.model.ParsedPage; import java.util.List; public interface Repository { void create(ParsedPage page); ParsedPage read(String url); void update(ParsedPage page); void delete(String url); List<ParsedPage> getAll(); }
17.944444
51
0.733746
db737e09a5e95b8448e30df14383a55f1eb6fff0
13,158
/* * Copyright (c) 2011, The Broad Institute * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.broadinstitute.sting.jna.drmaa.v1_0; import com.sun.jna.Memory; import com.sun.jna.NativeLong; import com.sun.jna.Pointer; import com.sun.jna.StringArray; import com.sun.jna.ptr.IntByReference; import com.sun.jna.ptr.PointerByReference; import org.apache.commons.io.FileUtils; import org.broadinstitute.sting.BaseTest; import org.testng.Assert; import org.testng.annotations.Test; import java.io.File; import java.util.Arrays; import java.util.List; public class LibDrmaaIntegrationTest extends BaseTest { private String implementation = null; @Test public void testDrmaa() throws Exception { Memory error = new Memory(LibDrmaa.DRMAA_ERROR_STRING_BUFFER); int errnum; IntByReference major = new IntByReference(); IntByReference minor = new IntByReference(); Memory contact = new Memory(LibDrmaa.DRMAA_CONTACT_BUFFER); Memory drmSystem = new Memory(LibDrmaa.DRMAA_DRM_SYSTEM_BUFFER); Memory drmaaImplementation = new Memory(LibDrmaa.DRMAA_DRMAA_IMPLEMENTATION_BUFFER); errnum = LibDrmaa.drmaa_version(major, minor, error, LibDrmaa.DRMAA_ERROR_STRING_BUFFER_LEN); if (errnum != LibDrmaa.DRMAA_ERRNO.DRMAA_ERRNO_SUCCESS) Assert.fail(String.format("Could not get version from the DRMAA library: %s", error.getString(0))); System.out.println(String.format("DRMAA version: %d.%d", major.getValue(), minor.getValue())); errnum = LibDrmaa.drmaa_get_contact(contact, LibDrmaa.DRMAA_CONTACT_BUFFER_LEN, error, LibDrmaa.DRMAA_ERROR_STRING_BUFFER_LEN); if (errnum != LibDrmaa.DRMAA_ERRNO.DRMAA_ERRNO_SUCCESS) Assert.fail(String.format("Could not get contacts from the DRMAA library: %s", error.getString(0))); System.out.println(String.format("DRMAA contact(s): %s", contact.getString(0))); errnum = LibDrmaa.drmaa_get_DRM_system(drmSystem, LibDrmaa.DRMAA_DRM_SYSTEM_BUFFER_LEN, error, LibDrmaa.DRMAA_ERROR_STRING_BUFFER_LEN); if (errnum != LibDrmaa.DRMAA_ERRNO.DRMAA_ERRNO_SUCCESS) Assert.fail(String.format("Could not get DRM system from the DRMAA library: %s", error.getString(0))); System.out.println(String.format("DRM system(s): %s", drmSystem.getString(0))); errnum = LibDrmaa.drmaa_get_DRMAA_implementation(drmaaImplementation, LibDrmaa.DRMAA_DRMAA_IMPLEMENTATION_BUFFER_LEN, error, LibDrmaa.DRMAA_ERROR_STRING_BUFFER_LEN); if (errnum != LibDrmaa.DRMAA_ERRNO.DRMAA_ERRNO_SUCCESS) Assert.fail(String.format("Could not get DRMAA implementation from the DRMAA library: %s", error.getString(0))); System.out.println(String.format("DRMAA implementation(s): %s", drmaaImplementation.getString(0))); this.implementation = drmaaImplementation.getString(0); } @Test(dependsOnMethods = { "testDrmaa" }) public void testSubmitEcho() throws Exception { if (implementation.contains("LSF")) { System.err.println(" *********************************************************"); System.err.println(" ***********************************************************"); System.err.println(" **** ****"); System.err.println(" **** Skipping LibDrmaaIntegrationTest.testSubmitEcho() ****"); System.err.println(" **** Are you using the dotkit .combined_LSF_SGE? ****"); System.err.println(" **** ****"); System.err.println(" ***********************************************************"); System.err.println(" *********************************************************"); return; } Memory error = new Memory(LibDrmaa.DRMAA_ERROR_STRING_BUFFER); int errnum; File outFile = tryCreateNetworkTempFile("LibDrmaaIntegrationTest.out"); errnum = LibDrmaa.drmaa_init(null, error, LibDrmaa.DRMAA_ERROR_STRING_BUFFER_LEN); if (errnum != LibDrmaa.DRMAA_ERRNO.DRMAA_ERRNO_SUCCESS) Assert.fail(String.format("Could not initialize the DRMAA library: %s", error.getString(0))); try { PointerByReference jtRef = new PointerByReference(); Pointer jt; Memory jobIdMem = new Memory(LibDrmaa.DRMAA_JOBNAME_BUFFER); String jobId; IntByReference remotePs = new IntByReference(); IntByReference stat = new IntByReference(); PointerByReference rusage = new PointerByReference(); errnum = LibDrmaa.drmaa_allocate_job_template(jtRef, error, LibDrmaa.DRMAA_ERROR_STRING_BUFFER_LEN); if (errnum != LibDrmaa.DRMAA_ERRNO.DRMAA_ERRNO_SUCCESS) Assert.fail(String.format("Could not create job template: %s", error.getString(0))); jt = jtRef.getValue(); errnum = LibDrmaa.drmaa_set_attribute(jt, LibDrmaa.DRMAA_REMOTE_COMMAND, "sh", error, LibDrmaa.DRMAA_ERROR_STRING_BUFFER_LEN); if (errnum != LibDrmaa.DRMAA_ERRNO.DRMAA_ERRNO_SUCCESS) Assert.fail(String.format("Could not set attribute \"%s\": %s", LibDrmaa.DRMAA_REMOTE_COMMAND, error.getString(0))); errnum = LibDrmaa.drmaa_set_attribute(jt, LibDrmaa.DRMAA_OUTPUT_PATH, ":" + outFile.getAbsolutePath(), error, LibDrmaa.DRMAA_ERROR_STRING_BUFFER_LEN); if (errnum != LibDrmaa.DRMAA_ERRNO.DRMAA_ERRNO_SUCCESS) Assert.fail(String.format("Could not set attribute \"%s\": %s", LibDrmaa.DRMAA_OUTPUT_PATH, error.getString(0))); errnum = LibDrmaa.drmaa_set_attribute(jt, LibDrmaa.DRMAA_JOIN_FILES, "y", error, LibDrmaa.DRMAA_ERROR_STRING_BUFFER_LEN); if (errnum != LibDrmaa.DRMAA_ERRNO.DRMAA_ERRNO_SUCCESS) Assert.fail(String.format("Could not set attribute \"%s\": %s", LibDrmaa.DRMAA_JOIN_FILES, error.getString(0))); StringArray args = new StringArray(new String[] { "-c", "echo \"Hello world.\"" }); errnum = LibDrmaa.drmaa_set_vector_attribute(jt, LibDrmaa.DRMAA_V_ARGV, args, error, LibDrmaa.DRMAA_ERROR_STRING_BUFFER_LEN); if (errnum != LibDrmaa.DRMAA_ERRNO.DRMAA_ERRNO_SUCCESS) Assert.fail(String.format("Could not set attribute \"%s\": %s", LibDrmaa.DRMAA_V_ARGV, error.getString(0))); errnum = LibDrmaa.drmaa_run_job(jobIdMem, LibDrmaa.DRMAA_JOBNAME_BUFFER_LEN, jt, error, LibDrmaa.DRMAA_ERROR_STRING_BUFFER_LEN); if (errnum != LibDrmaa.DRMAA_ERRNO.DRMAA_ERRNO_SUCCESS) Assert.fail(String.format("Could not submit job: %s", error.getString(0))); jobId = jobIdMem.getString(0); System.out.println(String.format("Job id %s", jobId)); errnum = LibDrmaa.drmaa_delete_job_template(jt, error, LibDrmaa.DRMAA_ERROR_STRING_BUFFER_LEN); if (errnum != LibDrmaa.DRMAA_ERRNO.DRMAA_ERRNO_SUCCESS) Assert.fail(String.format("Could not delete job template: %s", error.getString(0))); System.out.println("Waiting for job to run: " + jobId); remotePs.setValue(LibDrmaa.DRMAA_PS.DRMAA_PS_QUEUED_ACTIVE); List<Integer> runningStatuses = Arrays.asList( LibDrmaa.DRMAA_PS.DRMAA_PS_QUEUED_ACTIVE, LibDrmaa.DRMAA_PS.DRMAA_PS_RUNNING); while (runningStatuses.contains(remotePs.getValue())) { Thread.sleep(30 * 1000L); errnum = LibDrmaa.drmaa_job_ps(jobId, remotePs, error, LibDrmaa.DRMAA_ERROR_STRING_BUFFER_LEN); if (errnum != LibDrmaa.DRMAA_ERRNO.DRMAA_ERRNO_SUCCESS) Assert.fail(String.format("Could not get status for jobId %s: %s", jobId, error.getString(0))); } Assert.assertEquals(remotePs.getValue(), LibDrmaa.DRMAA_PS.DRMAA_PS_DONE, "Job status is not DONE."); errnum = LibDrmaa.drmaa_wait(jobId, Pointer.NULL, new NativeLong(0), stat, LibDrmaa.DRMAA_TIMEOUT_NO_WAIT, rusage, error, LibDrmaa.DRMAA_ERROR_STRING_BUFFER_LEN); if (errnum != LibDrmaa.DRMAA_ERRNO.DRMAA_ERRNO_SUCCESS) Assert.fail(String.format("Wait failed for jobId %s: %s", jobId, error.getString(0))); IntByReference exited = new IntByReference(); IntByReference exitStatus = new IntByReference(); IntByReference signaled = new IntByReference(); Memory signal = new Memory(LibDrmaa.DRMAA_SIGNAL_BUFFER); IntByReference coreDumped = new IntByReference(); IntByReference aborted = new IntByReference(); errnum = LibDrmaa.drmaa_wifexited(exited, stat.getValue(), error, LibDrmaa.DRMAA_ERROR_STRING_BUFFER_LEN); if (errnum != LibDrmaa.DRMAA_ERRNO.DRMAA_ERRNO_SUCCESS) Assert.fail(String.format("Exit check failed for jobId %s: %s", jobId, error.getString(0))); Assert.assertTrue(exited.getValue() != 0, String.format("Job did not exit cleanly: %s", jobId)); errnum = LibDrmaa.drmaa_wexitstatus(exitStatus, stat.getValue(), error, LibDrmaa.DRMAA_ERROR_STRING_BUFFER_LEN); if (errnum != LibDrmaa.DRMAA_ERRNO.DRMAA_ERRNO_SUCCESS) Assert.fail(String.format("Exit status failed for jobId %s: %s", jobId, error.getString(0))); Assert.assertEquals(exitStatus.getValue(), 0, String.format("Exit status for jobId %s is non-zero", jobId)); errnum = LibDrmaa.drmaa_wifsignaled(signaled, stat.getValue(), error, LibDrmaa.DRMAA_ERROR_STRING_BUFFER_LEN); if (errnum != LibDrmaa.DRMAA_ERRNO.DRMAA_ERRNO_SUCCESS) Assert.fail(String.format("Signaled check failed for jobId %s: %s", jobId, error.getString(0))); if (signaled.getValue() != 0) { errnum = LibDrmaa.drmaa_wtermsig(signal, LibDrmaa.DRMAA_SIGNAL_BUFFER_LEN, stat.getValue(), error, LibDrmaa.DRMAA_ERROR_STRING_BUFFER_LEN); if (errnum != LibDrmaa.DRMAA_ERRNO.DRMAA_ERRNO_SUCCESS) Assert.fail(String.format("Signal lookup failed for jobId %s: %s", jobId, error.getString(0))); errnum = LibDrmaa.drmaa_wcoredump(coreDumped, stat.getValue(), error, LibDrmaa.DRMAA_ERROR_STRING_BUFFER_LEN); if (errnum != LibDrmaa.DRMAA_ERRNO.DRMAA_ERRNO_SUCCESS) Assert.fail(String.format("Core dump check failed for jobId %s: %s", jobId, error.getString(0))); Assert.fail(String.format("JobId %s exited with signal %s and core dump flag %d", jobId, signal.getString(0), coreDumped.getValue())); } errnum = LibDrmaa.drmaa_wifaborted(aborted, stat.getValue(), error, LibDrmaa.DRMAA_ERROR_STRING_BUFFER_LEN); if (errnum != LibDrmaa.DRMAA_ERRNO.DRMAA_ERRNO_SUCCESS) Assert.fail(String.format("Aborted check failed for jobId %s: %s", jobId, error.getString(0))); Assert.assertTrue(aborted.getValue() == 0, String.format("Job was aborted: %s", jobId)); } finally { if (errnum != LibDrmaa.DRMAA_ERRNO.DRMAA_ERRNO_SUCCESS) { LibDrmaa.drmaa_exit(error, LibDrmaa.DRMAA_ERROR_STRING_BUFFER_LEN); } else { errnum = LibDrmaa.drmaa_exit(error, LibDrmaa.DRMAA_ERROR_STRING_BUFFER_LEN); if (errnum != LibDrmaa.DRMAA_ERRNO.DRMAA_ERRNO_SUCCESS) Assert.fail(String.format("Could not shut down the DRMAA library: %s", error.getString(0))); } } Assert.assertTrue(FileUtils.waitFor(outFile, 120), "File not found: " + outFile.getAbsolutePath()); System.out.println("--- output ---"); System.out.println(FileUtils.readFileToString(outFile)); System.out.println("--- output ---"); Assert.assertTrue(outFile.delete(), "Unable to delete " + outFile.getAbsolutePath()); System.out.println("Validating that we reached the end of the test without exit."); } }
52.214286
173
0.662031
242aec0ca5802708743a8fda6b38ebe1bf2fc9a7
2,239
package com.myedu.project.system.domain; import com.myedu.framework.aspectj.lang.annotation.Excel; import com.myedu.framework.web.domain.BaseEntity; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; /** /** * 组合数据详情对象 yun_system_group_data * * @author myedu * @date 2020-06-20 */ public class YunSystemGroupData extends BaseEntity { private static final long serialVersionUID = 1L; /** 组合数据详情ID */ private Long id; /** 对应的数据名称 */ @Excel(name = "对应的数据名称") private String groupName; /** 数据组对应的数据值(json数据) */ @Excel(name = "数据组对应的数据值", readConverterExp = "j=son数据") private String value; /** 添加数据时间 */ @Excel(name = "添加数据时间") private Integer addTime; /** 数据排序 */ @Excel(name = "数据排序") private Integer sort; /** 状态(1:开启;2:关闭;) */ @Excel(name = "状态", readConverterExp = "1=:开启;2:关闭;") private Integer status; public void setId(Long id) { this.id = id; } public Long getId() { return id; } public void setGroupName(String groupName) { this.groupName = groupName; } public String getGroupName() { return groupName; } public Integer getSort() { return sort; } public void setSort(Integer sort) { this.sort = sort; } public void setValue(String value) { this.value = value; } public String getValue() { return value; } public void setAddTime(Integer addTime) { this.addTime = addTime; } public Integer getAddTime() { return addTime; } public void setStatus(Integer status) { this.status = status; } public Integer getStatus() { return status; } @Override public String toString() { return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) .append("id", getId()) .append("groupName", getGroupName()) .append("value", getValue()) .append("addTime", getAddTime()) .append("sort", getSort()) .append("status", getStatus()) .toString(); } }
20.171171
71
0.586423
c5dea1f9dba0bd88a98a0b7b78298abcdc632c29
7,182
package com.example.instagramtake2.fragments; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import com.example.instagramtake2.EndlessRecyclerViewScrollListener; import com.example.instagramtake2.LoginActivity; import com.example.instagramtake2.R; import com.example.instagramtake2.TimelineAdapter; import com.example.instagramtake2.model.Post; import com.parse.FindCallback; import com.parse.ParseException; import com.parse.ParseUser; import java.util.ArrayList; import java.util.List; public class PostsFragment extends Fragment { protected TimelineAdapter timelineAdapter; private ParseUser currentUser; private SwipeRefreshLayout swipeContainer; protected ArrayList<Post> posts; protected RecyclerView rvPosts; boolean mFirstLoad = true; private ImageButton logoutBtn; private EndlessRecyclerViewScrollListener scrollListener; public static int page_size = 25; // the onCreateView method is called when Fragment should create its View object hierarchy // either dynamically on via XML layout inflation @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_posts, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); logoutBtn = view.findViewById(R.id.logoutBtn); currentUser = ParseUser.getCurrentUser(); // find the RecyclerView rvPosts = (RecyclerView) view.findViewById(R.id.rvItems); // init the arraylist (data source) posts = new ArrayList<>(); // construct the adapter from this datasource timelineAdapter = new TimelineAdapter(posts); // RecyclerView setup (layout manager, use adapter) LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext()); rvPosts.setLayoutManager(linearLayoutManager); // Lookup the swipe container view swipeContainer = (SwipeRefreshLayout) view.findViewById(R.id.swipeContainer); // Setup refresh listener which triggers new data loading scrollListener = new EndlessRecyclerViewScrollListener(linearLayoutManager) { @Override public void onLoadMore(int page, int totalItemsCount, RecyclerView view) { loadNextDataFromParse(page); } }; swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { swipeContainer.setRefreshing(false); fetchTimelineAsync(0); } }); // Configure the refreshing colors swipeContainer.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light); // set the adapter rvPosts.setAdapter(timelineAdapter); Log.d("Timeline", "adapter set successfully"); loadPosts(); logoutBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (currentUser != null) { ParseUser.logOut(); currentUser = ParseUser.getCurrentUser(); // this will now be null final Intent intent = new Intent(getContext(), LoginActivity.class); startActivity(intent); getActivity().finish(); } else { final Intent intent = new Intent(getContext(), LoginActivity.class); startActivity(intent); getActivity().finish(); } } }); } // Query messages from Parse so we can load them into the chat adapter protected void loadPosts() { // Construct query to execute Post.Query query = new Post.Query(); // Configure limit and sort order query.withUser(); // get the latest 50 messages, order will show up newest to oldest of this group query.orderByDescending("createdAt"); // Execute query to fetch all messages from Parse asynchronously // This is equivalent to a SELECT query with SQL query.findInBackground(new FindCallback<Post>() { public void done(List<Post> messages, ParseException e) { if (e == null) { posts.clear(); posts.addAll(messages); timelineAdapter.notifyDataSetChanged(); // update adapter // Scroll to the bottom of the list on initial load if (mFirstLoad) { rvPosts.scrollToPosition(0); mFirstLoad = false; } } else { Log.e("message", "Error Loading Messages" + e); } } }); } public void fetchTimelineAsync(int page) { timelineAdapter.clear(); loadPosts(); swipeContainer.setRefreshing(false); } public void loadNextDataFromParse(final int page) { // Construct query to execute Post.Query query = new Post.Query(); // Configure limit and sort order query.withUser(); // get the latest 50 messages, order will show up newest to oldest of this group query.orderByDescending("createdAt"); // Execute query to fetch all messages from Parse asynchronously // This is equivalent to a SELECT query with SQL query.findInBackground(new FindCallback<Post>() { public void done(List<Post> posts, ParseException e) { if (e == null) { posts.clear(); for (int i = page_size * page; i < posts.size(); i++){ if (i >= (page_size*(page +1))) { break; } Post post = posts.get(i); posts.add(post); timelineAdapter.notifyDataSetChanged(); // update adapter } // Scroll to the bottom of the list on initial load if (mFirstLoad) { rvPosts.scrollToPosition(0); mFirstLoad = false; } } else { Log.e("message", "Error Loading Messages" + e); } } }); } }
39.245902
132
0.614731
bfaa3d45153d61eb9df37016cbf3c9292441934e
6,819
package com.stylefeng.guns.rest.modular.order.service; import com.alibaba.dubbo.config.annotation.Reference; import com.alibaba.dubbo.config.annotation.Service; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.mapper.EntityWrapper; import com.baomidou.mybatisplus.plugins.Page; import com.stylefeng.guns.api.cinema.CinemaService; import com.stylefeng.guns.api.cinema.vo.FilmInfoVO; import com.stylefeng.guns.api.cinema.vo.OrderQueryVO; import com.stylefeng.guns.api.order.OrderService; import com.stylefeng.guns.api.order.vo.OrderVO; import com.stylefeng.guns.rest.modular.order.util.FTPUtil; import com.stylefeng.guns.rest.persistence.dao.MtimeOrderTMapper; import com.stylefeng.guns.rest.persistence.model.MtimeOrderT; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.ArrayList; import java.util.List; import java.util.UUID; /** * @author Wang Xueyang * @create 2019-04-24 */ @Slf4j @Component @Service(interfaceClass = OrderService.class,group = "default") public class OrderServiceImpl implements OrderService { //需要cinemaService中的接口方法获取影片的信息,和影院的信息 //getFilmInfoByFieldId,getOrderNeed @Autowired private MtimeOrderTMapper mtimeOrderTMapper; @Autowired private FTPUtil ftpUtil; //需要cinemaService的接口 @Reference(interfaceClass = CinemaService.class, check = false) private CinemaService cinemaService; //求订单的总价 private static double getTotalPrice(int solds,double filmPrice){ BigDecimal soldDecimal = new BigDecimal(solds); BigDecimal filmPriceDecimal = new BigDecimal(filmPrice); BigDecimal result = soldDecimal.multiply(filmPriceDecimal); //四舍五入,小数点后保留两位 BigDecimal resultDecimal = result.setScale(2, RoundingMode.HALF_UP); return resultDecimal.doubleValue(); } @Override public boolean isTrueSeats(String fieldId, String seats) {//是否是真实的座位 //根据fieldId找到对应的座位的位置图 String seatPath = mtimeOrderTMapper.selectSeatsByField(fieldId); //找位置图,判断seats是否为真 String fileStrByAddress = ftpUtil.getFileStrByAddress(seatPath); //将位置图信息转换成json对象 JSONObject jsonObject = JSONObject.parseObject(fileStrByAddress); String ids = jsonObject.get("ids").toString(); //如果找的到,就给isTrue+1 String[] seatArrs = seats.split(","); String[] idArrs = ids.split(","); int isTrue =0; for (String idArr : idArrs) { for (String seatArr : seatArrs) { if (seatArr.equalsIgnoreCase(idArr)){ isTrue++; } } } if (seatArrs.length==isTrue){ return true; }else { return false; } } @Override public boolean isNotSoldSeats(String fieldId, String seats) {//判断是否是已售出的座位 EntityWrapper<MtimeOrderT> entityWrapper = new EntityWrapper<>(); entityWrapper.eq("field_id",fieldId); List<MtimeOrderT> list = mtimeOrderTMapper.selectList(entityWrapper); String[] seatArrs = seats.split(","); //有任何一个编号可以匹配,则直接返回失败 for (MtimeOrderT mtimeOrderT : list) { String[] ids = mtimeOrderT.getSeatsIds().split(","); for (String id : ids) { for (String seatArr : seatArrs) { if (id.equalsIgnoreCase(seatArr)){ return false; } } } } return true; } @Override public OrderVO saveOrderInfo(Integer fieldId, String soldSeats, String seatName, Integer userId) { //订单编号 String uuid = UUID.randomUUID().toString().replace("-", ""); //影片信息 FilmInfoVO filmInfoVO = cinemaService.getFilmInfoByFieldId(fieldId); Integer filmId = Integer.parseInt(filmInfoVO.getFilmId()); //获取影院信息 OrderQueryVO orderQuery = cinemaService.getOrderQuery(fieldId); Integer cinemaId = Integer.parseInt(orderQuery.getCinemaId()); double filmPrice = Double.parseDouble(orderQuery.getFilmPrice()); int solds = soldSeats.split(",").length; double totalPrice = getTotalPrice(solds, filmPrice); MtimeOrderT mtimeOrderT = new MtimeOrderT(); mtimeOrderT.setUuid(uuid); mtimeOrderT.setSeatsName(seatName); mtimeOrderT.setSeatsIds(soldSeats); mtimeOrderT.setOrderUser(userId); mtimeOrderT.setOrderPrice(totalPrice); mtimeOrderT.setFilmPrice(filmPrice); mtimeOrderT.setFilmId(filmId); mtimeOrderT.setFieldId(fieldId); mtimeOrderT.setCinemaId(cinemaId); Integer insert = mtimeOrderTMapper.insert(mtimeOrderT); if (insert>0){ OrderVO orderVO = mtimeOrderTMapper.selectOrderInfoById(uuid); if (orderVO==null||orderVO.getOrderId()==null){ log.error("订单详情查询失败,订单编号为:"+uuid); return null; }else{ return orderVO; } }else { log.error("新增订单失败。"); return null; } } @Override public Page<OrderVO> getOrderByUserId(Integer userId, Page<OrderVO> page) { Page<OrderVO> result = new Page<>(); if (userId==null){ log.error("用户信息找不到"); return null; }else{ List<OrderVO> orders = mtimeOrderTMapper.selectOrderByUserId(userId, page); if (orders==null&orders.size()==0){ result.setTotal(0); result.setRecords(new ArrayList<>()); return result; }else { //获取订单总数 EntityWrapper<MtimeOrderT> entityWrapper = new EntityWrapper<>(); entityWrapper.eq("order_user",userId); Integer counts = mtimeOrderTMapper.selectCount(entityWrapper); result.setTotal(counts); result.setRecords(orders); return result; } } } //获得所有的已售的座位 @Override public String getSoldSeatsByFieldId(Integer fieldId) { if(fieldId==null){ log.error("未找到场次信息。"); return ""; }else { String soldSeats = mtimeOrderTMapper.selectSoldSeatsByFieldId(fieldId); return soldSeats; } } @Override public OrderVO getOrderInfoById(String orderId) { OrderVO orderVO = mtimeOrderTMapper.selectOrderInfoById(orderId); return orderVO; } @Override public boolean paySuccess(String orderId) { return false; } @Override public boolean payFail(String orderId) { return false; } }
34.095
102
0.639097
13291f66949ff60b4357b9b021e1c6181289144c
7,763
package com.diozero.internal.provider.pi4j; /* * #%L * Organisation: mattjlewis * Project: Device I/O Zero - pi4j provider * Filename: RaspiGpioBcm.java * * This file is part of the diozero project. More information about this project * can be found at http://www.diozero.com/ * %% * Copyright (C) 2016 - 2017 mattjlewis * %% * 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. * #L% */ import java.util.HashMap; import java.util.Map; import com.pi4j.io.gpio.Pin; import com.pi4j.io.gpio.RaspiPin; /** * +-----+-----+---------+------+---+---Pi 2---+---+------+---------+-----+-----+ * | BCM | wPi | Name | Mode | V | Physical | V | Mode | Name | wPi | BCM | * +-----+-----+---------+------+---+----++----+---+------+---------+-----+-----+ * | | | 3.3v | | | 1 || 2 | | | 5v | | | * | 2 | 8 | SDA.1 | ALT0 | 1 | 3 || 4 | | | 5V | | | * | 3 | 9 | SCL.1 | ALT0 | 1 | 5 || 6 | | | 0v | | | * | 4 | 7 | GPIO. 7 | IN | 1 | 7 || 8 | 1 | ALT0 | TxD | 15 | 14 | * | | | 0v | | | 9 || 10 | 1 | ALT0 | RxD | 16 | 15 | * | 17 | 0 | GPIO. 0 | IN | 0 | 11 || 12 | 1 | IN | GPIO. 1 | 1 | 18 | * | 27 | 2 | GPIO. 2 | IN | 0 | 13 || 14 | | | 0v | | | * | 22 | 3 | GPIO. 3 | IN | 0 | 15 || 16 | 0 | IN | GPIO. 4 | 4 | 23 | * | | | 3.3v | | | 17 || 18 | 0 | IN | GPIO. 5 | 5 | 24 | * | 10 | 12 | MOSI | ALT0 | 0 | 19 || 20 | | | 0v | | | * | 9 | 13 | MISO | ALT0 | 0 | 21 || 22 | 0 | IN | GPIO. 6 | 6 | 25 | * | 11 | 14 | SCLK | ALT0 | 0 | 23 || 24 | 1 | OUT | CE0 | 10 | 8 | * | | | 0v | | | 25 || 26 | 1 | OUT | CE1 | 11 | 7 | * | 0 | 30 | SDA.0 | IN | 1 | 27 || 28 | 1 | IN | SCL.0 | 31 | 1 | * | 5 | 21 | GPIO.21 | IN | 1 | 29 || 30 | | | 0v | | | * | 6 | 22 | GPIO.22 | IN | 1 | 31 || 32 | 0 | IN | GPIO.26 | 26 | 12 | * | 13 | 23 | GPIO.23 | IN | 0 | 33 || 34 | | | 0v | | | * | 19 | 24 | GPIO.24 | IN | 0 | 35 || 36 | 0 | IN | GPIO.27 | 27 | 16 | * | 26 | 25 | GPIO.25 | IN | 0 | 37 || 38 | 0 | IN | GPIO.28 | 28 | 20 | * | | | 0v | | | 39 || 40 | 0 | IN | GPIO.29 | 29 | 21 | * +-----+-----+---------+------+---+----++----+---+------+---------+-----+-----+ * | BCM | wPi | Name | Mode | V | Physical | V | Mode | Name | wPi | BCM | * +-----+-----+---------+------+---+---Pi 2---+---+------+---------+-----+-----+ */ public class RaspiGpioBcm { private static final Pin BCM_GPIO_2 = RaspiPin.GPIO_08; private static final Pin BCM_GPIO_3 = RaspiPin.GPIO_09; private static final Pin BCM_GPIO_4 = RaspiPin.GPIO_07; private static final Pin BCM_GPIO_5 = RaspiPin.GPIO_21; private static final Pin BCM_GPIO_6 = RaspiPin.GPIO_22; private static final Pin BCM_GPIO_7 = RaspiPin.GPIO_11; private static final Pin BCM_GPIO_8 = RaspiPin.GPIO_10; private static final Pin BCM_GPIO_9 = RaspiPin.GPIO_13; private static final Pin BCM_GPIO_10 = RaspiPin.GPIO_12; private static final Pin BCM_GPIO_11 = RaspiPin.GPIO_14; private static final Pin BCM_GPIO_12 = RaspiPin.GPIO_26; private static final Pin BCM_GPIO_13 = RaspiPin.GPIO_23; private static final Pin BCM_GPIO_14 = RaspiPin.GPIO_15; private static final Pin BCM_GPIO_15 = RaspiPin.GPIO_16; private static final Pin BCM_GPIO_16 = RaspiPin.GPIO_27; private static final Pin BCM_GPIO_17 = RaspiPin.GPIO_00; private static final Pin BCM_GPIO_18 = RaspiPin.GPIO_01; private static final Pin BCM_GPIO_19 = RaspiPin.GPIO_24; private static final Pin BCM_GPIO_20 = RaspiPin.GPIO_28; private static final Pin BCM_GPIO_21 = RaspiPin.GPIO_29; private static final Pin BCM_GPIO_22 = RaspiPin.GPIO_03; private static final Pin BCM_GPIO_23 = RaspiPin.GPIO_04; private static final Pin BCM_GPIO_24 = RaspiPin.GPIO_05; private static final Pin BCM_GPIO_25 = RaspiPin.GPIO_06; private static final Pin BCM_GPIO_26 = RaspiPin.GPIO_25; private static final Pin BCM_GPIO_27 = RaspiPin.GPIO_02; private static final Pin BCM_GPIO_28 = RaspiPin.GPIO_17; private static final Pin BCM_GPIO_29 = RaspiPin.GPIO_18; private static final Pin BCM_GPIO_30 = RaspiPin.GPIO_19; private static final Pin BCM_GPIO_31 = RaspiPin.GPIO_20; private static final Map<Integer, Pin> BCM_TO_WIRINGPI_MAPPING = new HashMap<>(); static { BCM_TO_WIRINGPI_MAPPING.put(Integer.valueOf(2), BCM_GPIO_2); BCM_TO_WIRINGPI_MAPPING.put(Integer.valueOf(3), BCM_GPIO_3); BCM_TO_WIRINGPI_MAPPING.put(Integer.valueOf(4), BCM_GPIO_4); BCM_TO_WIRINGPI_MAPPING.put(Integer.valueOf(5), BCM_GPIO_5); BCM_TO_WIRINGPI_MAPPING.put(Integer.valueOf(6), BCM_GPIO_6); BCM_TO_WIRINGPI_MAPPING.put(Integer.valueOf(7), BCM_GPIO_7); BCM_TO_WIRINGPI_MAPPING.put(Integer.valueOf(8), BCM_GPIO_8); BCM_TO_WIRINGPI_MAPPING.put(Integer.valueOf(9), BCM_GPIO_9); BCM_TO_WIRINGPI_MAPPING.put(Integer.valueOf(10), BCM_GPIO_10); BCM_TO_WIRINGPI_MAPPING.put(Integer.valueOf(11), BCM_GPIO_11); BCM_TO_WIRINGPI_MAPPING.put(Integer.valueOf(12), BCM_GPIO_12); BCM_TO_WIRINGPI_MAPPING.put(Integer.valueOf(13), BCM_GPIO_13); BCM_TO_WIRINGPI_MAPPING.put(Integer.valueOf(14), BCM_GPIO_14); BCM_TO_WIRINGPI_MAPPING.put(Integer.valueOf(15), BCM_GPIO_15); BCM_TO_WIRINGPI_MAPPING.put(Integer.valueOf(16), BCM_GPIO_16); BCM_TO_WIRINGPI_MAPPING.put(Integer.valueOf(17), BCM_GPIO_17); BCM_TO_WIRINGPI_MAPPING.put(Integer.valueOf(18), BCM_GPIO_18); BCM_TO_WIRINGPI_MAPPING.put(Integer.valueOf(19), BCM_GPIO_19); BCM_TO_WIRINGPI_MAPPING.put(Integer.valueOf(20), BCM_GPIO_20); BCM_TO_WIRINGPI_MAPPING.put(Integer.valueOf(21), BCM_GPIO_21); BCM_TO_WIRINGPI_MAPPING.put(Integer.valueOf(22), BCM_GPIO_22); BCM_TO_WIRINGPI_MAPPING.put(Integer.valueOf(23), BCM_GPIO_23); BCM_TO_WIRINGPI_MAPPING.put(Integer.valueOf(24), BCM_GPIO_24); BCM_TO_WIRINGPI_MAPPING.put(Integer.valueOf(25), BCM_GPIO_25); BCM_TO_WIRINGPI_MAPPING.put(Integer.valueOf(26), BCM_GPIO_26); BCM_TO_WIRINGPI_MAPPING.put(Integer.valueOf(27), BCM_GPIO_27); BCM_TO_WIRINGPI_MAPPING.put(Integer.valueOf(28), BCM_GPIO_28); BCM_TO_WIRINGPI_MAPPING.put(Integer.valueOf(29), BCM_GPIO_29); BCM_TO_WIRINGPI_MAPPING.put(Integer.valueOf(30), BCM_GPIO_30); BCM_TO_WIRINGPI_MAPPING.put(Integer.valueOf(31), BCM_GPIO_31); } /*public static Pin getPin(int pinNumer) { return BCM_TO_WIRINGPI_MAPPING.get(Integer.valueOf(pinNumer)); }*/ }
55.848921
83
0.619606
054842fc1a588ac777b9cbcb2c9bd8f6e1934ed6
2,622
package com.zx.sms.common; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.util.concurrent.*; /** * A skeletal {@link ChannelFuture} implementation which represents a * {@link ChannelFuture} which channel is error,such as : not connected,channel writable is false,and so on. */ public class ErrorChannelFuture extends CompleteFuture<Void> implements ChannelFuture { /** * 错误信息描述 */ private String errorMsg; /** * Creates a new instance. */ public ErrorChannelFuture(EventExecutor executor) { super(executor); } /** * Creates a new instance. */ public ErrorChannelFuture(String errorMsg) { super(GlobalEventExecutor.INSTANCE); this.errorMsg = errorMsg; } @Override protected EventExecutor executor() { EventExecutor e = super.executor(); if (e == null) { return GlobalEventExecutor.INSTANCE; } else { return e; } } @Override public boolean isSuccess() { return false; } @Override public Throwable cause() { return new SendFailException(errorMsg); } public String getErrorMsg() { return errorMsg; } @Override public Channel channel() { return null; } @Override public ChannelFuture addListener(GenericFutureListener<? extends Future<? super Void>> listener) { super.addListener(listener); return this; } @Override public ChannelFuture addListeners(GenericFutureListener<? extends Future<? super Void>>... listeners) { super.addListeners(listeners); return this; } @Override public ChannelFuture removeListener(GenericFutureListener<? extends Future<? super Void>> listener) { super.removeListener(listener); return this; } @Override public ChannelFuture removeListeners(GenericFutureListener<? extends Future<? super Void>>... listeners) { super.removeListeners(listeners); return this; } @Override public ChannelFuture syncUninterruptibly() { return this; } @Override public ChannelFuture sync() throws InterruptedException { return this; } @Override public ChannelFuture await() throws InterruptedException { return this; } @Override public ChannelFuture awaitUninterruptibly() { return this; } @Override public Void getNow() { return null; } @Override public boolean isVoid() { return false; } }
22.603448
110
0.634249
678729a8de8d2229171eddb2ed656fe4c3a862cb
11,814
package com.armueller.fluxytodo.models; import com.armueller.fluxytodo.actions.DataBundle; import com.armueller.fluxytodo.actions.TodoAction; import com.armueller.fluxytodo.actions.ViewAction; import com.armueller.fluxytodo.busses.ActionBus; import com.armueller.fluxytodo.busses.DataBus; import com.armueller.fluxytodo.data.RawTodoList; import com.squareup.otto.Subscribe; import com.squareup.otto.ThreadEnforcer; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import java.util.ArrayList; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import static org.fest.assertions.api.Assertions.assertThat; /** * Created by armueller on 3/14/15. */ @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class TodoListManagerTest { private ActionBus actionBus; private DataBus dataBus; private TodoListManager list; @Before public void setup() { actionBus = new ActionBus(); dataBus = new DataBus(ThreadEnforcer.ANY); list = new TodoListManager(actionBus, dataBus); } @Test(timeout = 100) public void createTodoTest() throws InterruptedException { final AtomicBoolean testDone = new AtomicBoolean(false); createTodos(1); dataBus.register(new Object() { @Subscribe public void onListUpdated(RawTodoList rawTodoList) { assertThat(rawTodoList.list.size()).isEqualTo(1); assertThat(rawTodoList.list.get(0).getDescription()).isEqualTo("Testing 0"); assertThat(rawTodoList.list.get(0).isComplete()).isFalse(); testDone.set(true); } }); // Wait for test to finish or timeout while (!testDone.get()) ; } private void createTodos(final int numberOfTodos) throws InterruptedException { for (int i = 0; i < numberOfTodos; i++) { DataBundle<TodoAction.DataKeys> bundle = new DataBundle<>(); bundle.put(TodoAction.DataKeys.DESCRIPTION, "Testing " + i); actionBus.post(new TodoAction(TodoAction.ActionTypes.ADD, bundle)); Thread.sleep(10); } } @Test(timeout = 100) public void createMultipleTodosTest() throws InterruptedException { final AtomicBoolean testDone = new AtomicBoolean(false); createTodos(4); dataBus.register(new Object() { @Subscribe public void onListUpdated(RawTodoList rawTodoList) { assertThat(rawTodoList.list.size()).isEqualTo(4); testDone.set(true); } }); // Wait for test to finish or timeout while (!testDone.get()) ; } @Test(timeout = 100) public void completeTodoTest() throws InterruptedException { final AtomicBoolean testDone = new AtomicBoolean(false); final ArrayList<TodoItem> todoItems = new ArrayList<TodoItem>(); createTodos(2); dataBus.register(new Object() { @Subscribe public void onListUpdated(RawTodoList rawTodoList) { todoItems.clear(); todoItems.addAll(rawTodoList.list); if (!todoItems.get(1).isComplete()) { DataBundle<TodoAction.DataKeys> bundle = new DataBundle<>(); bundle.put(TodoAction.DataKeys.ID, todoItems.get(1).getId()); actionBus.post(new TodoAction(TodoAction.ActionTypes.TOGGLE, bundle)); } else { assertThat(todoItems.get(0).isComplete()).isFalse(); assertThat(todoItems.get(1).isComplete()).isTrue(); testDone.set(true); } } }); // Wait for test to finish or timeout while (!testDone.get()) ; } @Test(timeout = 100) public void completeAllTodosTest() throws InterruptedException { final AtomicBoolean testDone = new AtomicBoolean(false); final ArrayList<TodoItem> todoItems = new ArrayList<TodoItem>(); createTodos(3); dataBus.register(new Object() { @Subscribe public void onListUpdated(RawTodoList rawTodoList) { todoItems.clear(); todoItems.addAll(rawTodoList.list); if (!todoItems.get(0).isComplete()) { actionBus.post(new TodoAction(TodoAction.ActionTypes.TOGGLE_ALL)); } else { assertThat(todoItems.get(0).isComplete()).isTrue(); assertThat(todoItems.get(1).isComplete()).isTrue(); assertThat(todoItems.get(2).isComplete()).isTrue(); testDone.set(true); } } }); // Wait for test to finish or timeout while (!testDone.get()) ; } @Test(timeout = 100) public void editTodoTest() throws InterruptedException { final AtomicBoolean testDone = new AtomicBoolean(false); final ArrayList<TodoItem> todoItems = new ArrayList<TodoItem>(); createTodos(1); dataBus.register(new Object() { @Subscribe public void onListUpdated(RawTodoList rawTodoList) { todoItems.clear(); todoItems.addAll(rawTodoList.list); if (todoItems.get(0).getDescription().equals("Testing 0")) { DataBundle<TodoAction.DataKeys> bundle = new DataBundle<>(); bundle.put(TodoAction.DataKeys.ID, todoItems.get(0).getId()); bundle.put(TodoAction.DataKeys.DESCRIPTION, "New Todo Description"); actionBus.post(new TodoAction(TodoAction.ActionTypes.EDIT, bundle)); } else { assertThat(todoItems.get(0).getDescription()).isEqualTo("New Todo Description"); testDone.set(true); } } }); // Wait for test to finish or timeout while (!testDone.get()) ; } @Test(timeout = 100) public void deleteTodoTest() throws InterruptedException { final AtomicBoolean testDone = new AtomicBoolean(false); final AtomicLong deletedId = new AtomicLong(-1); final ArrayList<TodoItem> todoItems = new ArrayList<TodoItem>(); createTodos(3); dataBus.register(new Object() { @Subscribe public void onListUpdated(RawTodoList rawTodoList) { todoItems.clear(); todoItems.addAll(rawTodoList.list); if (todoItems.size() == 3) { deletedId.set(todoItems.get(1).getId()); DataBundle<TodoAction.DataKeys> bundle = new DataBundle<>(); bundle.put(TodoAction.DataKeys.ID, todoItems.get(1).getId()); actionBus.post(new TodoAction(TodoAction.ActionTypes.DELETE, bundle)); } else { assertThat(todoItems.size()).isEqualTo(2); assertThat(todoItems.get(0).getId()).isNotEqualTo(deletedId.get()); assertThat(todoItems.get(1).getId()).isNotEqualTo(deletedId.get()); testDone.set(true); } } }); // Wait for test to finish or timeout while (!testDone.get()) ; } @Test(timeout = 100) public void deleteAllCompleteTodosTest() throws InterruptedException { final AtomicBoolean testDone = new AtomicBoolean(false); final AtomicBoolean checkedTodo1 = new AtomicBoolean(false); final AtomicBoolean checkedTodo3 = new AtomicBoolean(false); final AtomicBoolean deleted = new AtomicBoolean(false); final ArrayList<TodoItem> todoItems = new ArrayList<TodoItem>(); createTodos(4); dataBus.register(new Object() { @Subscribe public void onListUpdated(RawTodoList rawTodoList) { todoItems.clear(); todoItems.addAll(rawTodoList.list); if (!checkedTodo1.get()) { checkedTodo1.set(true); DataBundle<TodoAction.DataKeys> bundle = new DataBundle<>(); bundle.put(TodoAction.DataKeys.ID, todoItems.get(1).getId()); actionBus.post(new TodoAction(TodoAction.ActionTypes.TOGGLE, bundle)); return; } if (!checkedTodo3.get()) { checkedTodo3.set(true); DataBundle<TodoAction.DataKeys> bundle = new DataBundle<>(); bundle.put(TodoAction.DataKeys.ID, todoItems.get(3).getId()); actionBus.post(new TodoAction(TodoAction.ActionTypes.TOGGLE, bundle)); return; } if (!deleted.get() && checkedTodo1.get() && checkedTodo3.get()) { deleted.set(true); actionBus.post(new TodoAction(TodoAction.ActionTypes.DELETE_ALL)); return; } if (deleted.get()) { assertThat(todoItems.size()).isEqualTo(2); testDone.set(true); } } }); // Wait for test to finish or timeout while (!testDone.get()) ; } @Test(timeout = 100) public void undoDeleteAllCompleteTodosTest() throws InterruptedException { final AtomicBoolean testDone = new AtomicBoolean(false); final AtomicBoolean checkedTodo1 = new AtomicBoolean(false); final AtomicBoolean checkedTodo3 = new AtomicBoolean(false); final AtomicBoolean deletedTodos = new AtomicBoolean(false); final AtomicBoolean undidDelete = new AtomicBoolean(false); final ArrayList<TodoItem> todoItems = new ArrayList<TodoItem>(); createTodos(4); dataBus.register(new Object() { @Subscribe public void onListUpdated(RawTodoList rawTodoList) { todoItems.clear(); todoItems.addAll(rawTodoList.list); if (!checkedTodo1.get()) { checkedTodo1.set(true); DataBundle<TodoAction.DataKeys> bundle = new DataBundle<>(); bundle.put(TodoAction.DataKeys.ID, todoItems.get(1).getId()); actionBus.post(new TodoAction(TodoAction.ActionTypes.TOGGLE, bundle)); return; } if (!checkedTodo3.get()) { checkedTodo3.set(true); DataBundle<TodoAction.DataKeys> bundle = new DataBundle<>(); bundle.put(TodoAction.DataKeys.ID, todoItems.get(3).getId()); actionBus.post(new TodoAction(TodoAction.ActionTypes.TOGGLE, bundle)); return; } if (!deletedTodos.get() && checkedTodo1.get() && checkedTodo3.get()) { deletedTodos.set(true); actionBus.post(new TodoAction(TodoAction.ActionTypes.DELETE_ALL)); return; } if (!undidDelete.get() && deletedTodos.get()) { undidDelete.set(true); actionBus.post(new TodoAction(TodoAction.ActionTypes.UNDO_DELETE_ALL)); return; } if (undidDelete.get() && deletedTodos.get()) { assertThat(todoItems.size()).isEqualTo(4); testDone.set(true); } } }); // Wait for test to finish or timeout while (!testDone.get()) ; } }
38.990099
100
0.579736
761eaa14abb308b397a49b6a9c0be9fbe4d54646
5,198
package com.liux.android.util; import org.junit.Test; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import com.liux.android.test.RobolectricTest; public class TextUtilTest extends RobolectricTest { @Test public void MD5() { assertEquals("d41d8cd98f00b204e9800998ecf8427e", TextUtil.MD5("")); assertEquals("033bd94b1168d7e4f0d644c3c95e35bf", TextUtil.MD5("TEST")); } @Test public void SHA1() { assertEquals("da39a3ee5e6b4b0d3255bfef95601890afd80709", TextUtil.SHA1("")); assertEquals("984816fd329622876e14907634264e6f332e9fb3", TextUtil.SHA1("TEST")); } @Test public void SHA224() { assertEquals("917ecca24f3e6ceaf52375d8083381f1f80a21e6e49fbadc40afeb8e", TextUtil.SHA224("TEST")); } @Test public void SHA256() { assertEquals("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", TextUtil.SHA256("")); assertEquals("94ee059335e587e501cc4bf90613e0814f00a7b08bc7c648fd865a2af6a22cc2", TextUtil.SHA256("TEST")); } @Test public void SHA384() { assertEquals("4f37c49c0024445f91977dbc47bd4da9c4de8d173d03379ee19c2bb15435c2c7e624ea42f7cc1689961cb7aca50c7d17", TextUtil.SHA384("TEST")); } @Test public void SHA512() { assertEquals("7bfa95a688924c47c7d22381f20cc926f524beacb13f84e203d4bd8cb6ba2fce81c57a5f059bf3d509926487bde925b3bcee0635e4f7baeba054e5dba696b2bf", TextUtil.SHA512("TEST")); } @Test public void crc32() { assertEquals("00000000", TextUtil.crc32("")); assertEquals("83dcefb7", TextUtil.crc32("1")); assertEquals("9ae0daaf", TextUtil.crc32("12345678")); } @Test public void crc64() { assertEquals("0000000000000000", TextUtil.crc64("")); assertEquals("2a2f0e859495caed", TextUtil.crc64("1")); assertEquals("5c8b80482bac7809", TextUtil.crc64("12345678")); } //@Test public void hmacMD5() { assertEquals("1aee732e9c1d3faa20775d1438af9472", TextUtil.HmacMD5("TEST", "KEY")); } //@Test public void hmacSHA1() { assertEquals("7403a7476a1758ff716b8bd405d0ef5574e9cd0a", TextUtil.HmacSHA1("TEST", "KEY")); } //@Test public void hmacSHA224() { assertEquals("e802b12b9dbfca2785fb1d93864eb984494e110acefe468fea6a3f79", TextUtil.HmacSHA224("TEST", "KEY")); } //@Test public void hmacSHA256() { assertEquals("615dac1c53c9396d8f69a419a0b2d9393a0461d7ad5f7f3d9beb57264129ef12", TextUtil.HmacSHA256("TEST", "KEY")); } //@Test public void hmacSHA384() { assertEquals("03ae3f1ba7a6626b24de55db51dbaa498c2baaa58b4a2617f48c8f7eae58a31e70f2d9f82241e1bbb287d89902f2fe3a", TextUtil.HmacSHA384("TEST", "KEY")); } //@Test public void hmacSHA512() { assertEquals("c0fcb3918e49a7f5af5af7881b9b89951efa39ae1f276237f483d19e0dbc504aaf6febe7e3af4a1dd3bd06ba9de8737b61b903b584d50b78a549a65fa0806100", TextUtil.HmacSHA512("TEST", "KEY")); } @Test public void encodeURL() { assertEquals("https%3A%2F%2F6xyun.cn%2Fapi%3Fkey%3D%E6%B5%8B%E8%AF%95", TextUtil.encodeURL("https://6xyun.cn/api?key=测试", null)); } @Test public void decodeURL() { assertEquals("https://6xyun.cn/api?key=测试", TextUtil.decodeURL("https%3a%2f%2f6xyun.cn%2fapi%3fkey%3d%e6%b5%8b%e8%af%95", null)); } @Test public void string2Unicode() { assertEquals("\\u0054\\u0045\\u0053\\u0054", TextUtil.string2Unicode("TEST")); } @Test public void unicode2String() { assertEquals("TEST", TextUtil.unicode2String("\\u0054\\u0045\\u0053\\u0054")); } @Test public void formetByteLength() { assertEquals("1.00KB", TextUtil.formetByteLength(1024)); assertEquals("1.00MB", TextUtil.formetByteLength(1024 * 1024)); assertEquals("1.00GB", TextUtil.formetByteLength(1024 * 1024 * 1024)); assertEquals("1.05GB", TextUtil.formetByteLength(1024 * 1024 * 1024 + (1024 * 1024 * 50))); } @Test public void money2Chinese() { assertEquals("一亿零二百四十万零九十元整", TextUtil.money2Chinese(102400090)); } @Test public void money2ChineseTraditional() { assertEquals("壹亿零贰佰肆拾万零玖拾元整", TextUtil.money2ChineseTraditional(102400090)); } @Test public void number2Chinese() { assertEquals("一亿零二百四十万零九十", TextUtil.number2Chinese(102400090)); } @Test public void bytes2Hex() { assertEquals("54455354", TextUtil.bytes2Hex("TEST".getBytes())); assertEquals("54455354", TextUtil.bytes2Hex("TEST".getBytes(), false)); assertEquals("54 45 53 54", TextUtil.bytes2Hex("TEST".getBytes(), true)); } @Test public void hex2Bytes() { assertEquals("TEST", new String(TextUtil.hex2Bytes("54455354"))); assertEquals("TEST", new String(TextUtil.hex2Bytes("54 45 53 54"))); } @Test public void encodeBase64() { assertEquals("VEVTVA==", TextUtil.encodeBase64("TEST".getBytes())); } @Test public void decodeBase64() { assertArrayEquals(TextUtil.hex2Bytes("54 45 53 54"), TextUtil.decodeBase64("VEVTVA==")); } }
33.753247
189
0.685071
531373b63c29c34af73e042bbc345b88d5ee7b9d
1,874
// SPDX-FileCopyrightText: 2022 RTE FRANCE // // SPDX-License-Identifier: Apache-2.0 package org.lfenergy.compas.sct.commons.dto; import org.junit.jupiter.api.Test; import org.lfenergy.compas.scl2007b4.model.THitem; import java.time.LocalDateTime; import java.util.UUID; import static org.junit.jupiter.api.Assertions.*; class HeaderDTOTest { @Test void testConstructor(){ UUID id = UUID.randomUUID(); HeaderDTO headerDTO = DTO.createHeaderDTO(id); assertEquals(id,headerDTO.getId()); assertEquals("1.0",headerDTO.getVersion()); assertEquals("1.0",headerDTO.getRevision()); assertFalse(headerDTO.getHistoryItems().isEmpty()); HeaderDTO.HistoryItem historyItem = headerDTO.getHistoryItems().get(0); assertEquals("1.0",historyItem.getRevision()); assertEquals("1.0",historyItem.getVersion()); assertEquals("what",historyItem.getWhat()); assertEquals("why",historyItem.getWhy()); assertEquals("who",historyItem.getWho()); assertEquals(DTO.NOW_STR,historyItem.getWhen()); headerDTO = new HeaderDTO(id,"1.0","1.0"); assertEquals("1.0",headerDTO.getVersion()); assertEquals("1.0",headerDTO.getRevision()); } @Test void testHItemFrom(){ THitem tHitem = new THitem(); tHitem.setRevision("1.0"); tHitem.setVersion("1.0"); tHitem.setWhat("what"); tHitem.setWho("who"); tHitem.setWhy("why"); tHitem.setWhen(DTO.NOW_STR); HeaderDTO.HistoryItem historyItem = HeaderDTO.HistoryItem.from(tHitem); assertEquals("1.0",historyItem.getRevision()); assertEquals("1.0",historyItem.getVersion()); assertEquals("what",historyItem.getWhat()); assertEquals("why",historyItem.getWhy()); assertEquals("who",historyItem.getWho()); } }
32.310345
79
0.657951
091ab876e7545ba501fd91757916dcd18a6ce089
7,644
/* * Copyright 2021 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.keycloak.quarkus.runtime.storage.database.liquibase; import java.lang.reflect.Method; import java.sql.Connection; import javax.xml.parsers.SAXParserFactory; import liquibase.database.core.MariaDBDatabase; import liquibase.database.core.MySQLDatabase; import org.jboss.logging.Logger; import org.keycloak.Config; import org.keycloak.connections.jpa.JpaConnectionProvider; import org.keycloak.connections.jpa.JpaConnectionProviderFactory; import org.keycloak.connections.jpa.updater.liquibase.MySQL8VarcharType; import org.keycloak.connections.jpa.updater.liquibase.PostgresPlusDatabase; import org.keycloak.connections.jpa.updater.liquibase.UpdatedMariaDBDatabase; import org.keycloak.connections.jpa.updater.liquibase.UpdatedMySqlDatabase; import org.keycloak.connections.jpa.updater.liquibase.conn.CustomChangeLogHistoryService; import org.keycloak.connections.jpa.updater.liquibase.conn.LiquibaseConnectionProvider; import org.keycloak.connections.jpa.updater.liquibase.conn.LiquibaseConnectionProviderFactory; import org.keycloak.models.KeycloakSession; import org.keycloak.models.KeycloakSessionFactory; import liquibase.Liquibase; import liquibase.changelog.ChangeLogHistoryServiceFactory; import liquibase.database.Database; import liquibase.database.DatabaseFactory; import liquibase.database.jvm.JdbcConnection; import liquibase.datatype.DataTypeFactory; import liquibase.exception.LiquibaseException; import liquibase.parser.ChangeLogParser; import liquibase.parser.ChangeLogParserFactory; import liquibase.parser.core.xml.XMLChangeLogSAXParser; import liquibase.resource.ClassLoaderResourceAccessor; import liquibase.resource.ResourceAccessor; import liquibase.servicelocator.ServiceLocator; public class QuarkusLiquibaseConnectionProvider implements LiquibaseConnectionProviderFactory, LiquibaseConnectionProvider { private static final Logger logger = Logger.getLogger(QuarkusLiquibaseConnectionProvider.class); private volatile boolean initialized = false; private ClassLoaderResourceAccessor resourceAccessor; @Override public LiquibaseConnectionProvider create(KeycloakSession session) { if (!initialized) { synchronized (this) { if (!initialized) { baseLiquibaseInitialization(session); initialized = true; } } } return this; } protected void baseLiquibaseInitialization(KeycloakSession session) { resourceAccessor = new ClassLoaderResourceAccessor(getClass().getClassLoader()); FastServiceLocator locator = (FastServiceLocator) ServiceLocator.getInstance(); JpaConnectionProviderFactory jpaConnectionProvider = (JpaConnectionProviderFactory) session .getKeycloakSessionFactory().getProviderFactory(JpaConnectionProvider.class); // register our custom databases locator.register(new PostgresPlusDatabase()); locator.register(new UpdatedMySqlDatabase()); locator.register(new UpdatedMariaDBDatabase()); // registers only the database we are using try (Connection connection = jpaConnectionProvider.getConnection()) { Database database = DatabaseFactory.getInstance() .findCorrectDatabaseImplementation(new JdbcConnection(connection)); if (database.getDatabaseProductName().equals(MySQLDatabase.PRODUCT_NAME)) { // Adding CustomVarcharType for MySQL 8 and newer DataTypeFactory.getInstance().register(MySQL8VarcharType.class); ChangeLogHistoryServiceFactory.getInstance().register(new CustomChangeLogHistoryService()); } else if (database.getDatabaseProductName().equals(MariaDBDatabase.PRODUCT_NAME)) { // Adding CustomVarcharType for MySQL 8 and newer DataTypeFactory.getInstance().register(MySQL8VarcharType.class); } DatabaseFactory.getInstance().clearRegistry(); locator.register(database); } catch (Exception cause) { throw new RuntimeException("Failed to configure Liquibase database", cause); } // disables XML validation for (ChangeLogParser parser : ChangeLogParserFactory.getInstance().getParsers()) { if (parser instanceof XMLChangeLogSAXParser) { Method getSaxParserFactory = null; try { getSaxParserFactory = XMLChangeLogSAXParser.class.getDeclaredMethod("getSaxParserFactory"); getSaxParserFactory.setAccessible(true); SAXParserFactory saxParserFactory = (SAXParserFactory) getSaxParserFactory.invoke(parser); saxParserFactory.setValidating(false); saxParserFactory.setSchema(null); } catch (Exception e) { logger.warnf("Failed to disable liquibase XML validations"); } finally { if (getSaxParserFactory != null) { getSaxParserFactory.setAccessible(false); } } } } } @Override public void init(Config.Scope config) { } @Override public void postInit(KeycloakSessionFactory factory) { } @Override public void close() { } @Override public String getId() { return "quarkus"; } @Override public Liquibase getLiquibase(Connection connection, String defaultSchema) throws LiquibaseException { Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection)); if (defaultSchema != null) { database.setDefaultSchemaName(defaultSchema); } String changelog = QuarkusJpaUpdaterProvider.CHANGELOG; logger.debugf("Using changelog file %s and changelogTableName %s", changelog, database.getDatabaseChangeLogTableName()); return new Liquibase(changelog, resourceAccessor, database); } @Override public Liquibase getLiquibaseForCustomUpdate(Connection connection, String defaultSchema, String changelogLocation, ClassLoader classloader, String changelogTableName) throws LiquibaseException { Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection)); if (defaultSchema != null) { database.setDefaultSchemaName(defaultSchema); } ResourceAccessor resourceAccessor = new ClassLoaderResourceAccessor(classloader); database.setDatabaseChangeLogTableName(changelogTableName); logger.debugf("Using changelog file %s and changelogTableName %s", changelogLocation, database.getDatabaseChangeLogTableName()); return new Liquibase(changelogLocation, resourceAccessor, database); } @Override public int order() { return 100; } }
42.466667
199
0.724097
a31ed037feb224b75ed61237d9354247246331b4
16,957
/* 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.griffin.core.job; import com.fasterxml.jackson.core.type.TypeReference; import org.apache.commons.lang.StringUtils; import org.apache.griffin.core.error.exception.GriffinException.GetHealthInfoFailureException; import org.apache.griffin.core.error.exception.GriffinException.GetJobsFailureException; import org.apache.griffin.core.job.entity.JobHealth; import org.apache.griffin.core.job.entity.JobInstance; import org.apache.griffin.core.job.entity.JobRequestBody; import org.apache.griffin.core.job.entity.LivySessionStates; import org.apache.griffin.core.job.repo.JobInstanceRepo; import org.apache.griffin.core.measure.entity.Measure; import org.apache.griffin.core.util.GriffinOperationMessage; import org.apache.griffin.core.util.GriffinUtil; import org.quartz.*; import org.quartz.impl.matchers.GroupMatcher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.quartz.SchedulerFactoryBean; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import java.io.IOException; import java.io.Serializable; import java.util.*; import static org.apache.griffin.core.util.GriffinOperationMessage.*; import static org.quartz.JobBuilder.newJob; import static org.quartz.JobKey.jobKey; import static org.quartz.TriggerBuilder.newTrigger; import static org.quartz.TriggerKey.triggerKey; @Service public class JobServiceImpl implements JobService { private static final Logger LOGGER = LoggerFactory.getLogger(JobServiceImpl.class); @Autowired private SchedulerFactoryBean factory; @Autowired private JobInstanceRepo jobInstanceRepo; @Autowired private Properties sparkJobProps; public JobServiceImpl() { } @Override public List<Map<String, Serializable>> getAliveJobs() { Scheduler scheduler = factory.getObject(); List<Map<String, Serializable>> list = new ArrayList<>(); try { for (String groupName : scheduler.getJobGroupNames()) { for (JobKey jobKey : scheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName))) { Map jobInfoMap = getJobInfoMap(scheduler, jobKey); if (jobInfoMap.size() != 0 && !isJobDeleted(scheduler, jobKey)) { list.add(jobInfoMap); } } } } catch (SchedulerException e) { LOGGER.error("failed to get running jobs.{}", e.getMessage()); throw new GetJobsFailureException(); } return list; } private boolean isJobDeleted(Scheduler scheduler, JobKey jobKey) throws SchedulerException { JobDataMap jobDataMap = scheduler.getJobDetail(jobKey).getJobDataMap(); return jobDataMap.getBooleanFromString("deleted"); } private Map getJobInfoMap(Scheduler scheduler, JobKey jobKey) throws SchedulerException { List<Trigger> triggers = (List<Trigger>) scheduler.getTriggersOfJob(jobKey); Map<String, Serializable> jobInfoMap = new HashMap<>(); if (triggers == null || triggers.size() == 0) { return jobInfoMap; } JobDetail jd = scheduler.getJobDetail(jobKey); Date nextFireTime = triggers.get(0).getNextFireTime(); Date previousFireTime = triggers.get(0).getPreviousFireTime(); Trigger.TriggerState triggerState = scheduler.getTriggerState(triggers.get(0).getKey()); jobInfoMap.put("jobName", jobKey.getName()); jobInfoMap.put("groupName", jobKey.getGroup()); if (nextFireTime != null) { jobInfoMap.put("nextFireTime", nextFireTime.getTime()); } else { jobInfoMap.put("nextFireTime", -1); } if (previousFireTime != null) { jobInfoMap.put("previousFireTime", previousFireTime.getTime()); } else { jobInfoMap.put("previousFireTime", -1); } jobInfoMap.put("triggerState", triggerState); jobInfoMap.put("measureId", jd.getJobDataMap().getString("measureId")); jobInfoMap.put("sourcePattern", jd.getJobDataMap().getString("sourcePattern")); jobInfoMap.put("targetPattern", jd.getJobDataMap().getString("targetPattern")); if (StringUtils.isNotEmpty(jd.getJobDataMap().getString("blockStartTimestamp"))) { jobInfoMap.put("blockStartTimestamp", jd.getJobDataMap().getString("blockStartTimestamp")); } jobInfoMap.put("jobStartTime", jd.getJobDataMap().getString("jobStartTime")); jobInfoMap.put("interval", jd.getJobDataMap().getString("interval")); return jobInfoMap; } @Override public GriffinOperationMessage addJob(String groupName, String jobName, Long measureId, JobRequestBody jobRequestBody) { int interval; Date jobStartTime; try { interval = Integer.parseInt(jobRequestBody.getInterval()); jobStartTime = new Date(Long.parseLong(jobRequestBody.getJobStartTime())); setJobStartTime(jobStartTime, interval); } catch (Exception e) { LOGGER.info("jobStartTime or interval format error! {}", e.getMessage()); return CREATE_JOB_FAIL; } try { Scheduler scheduler = factory.getObject(); TriggerKey triggerKey = triggerKey(jobName, groupName); if (scheduler.checkExists(triggerKey)) { LOGGER.error("the triggerKey(jobName,groupName) {} has been used.", jobName); return CREATE_JOB_FAIL; } JobKey jobKey = jobKey(jobName, groupName); JobDetail jobDetail; if (scheduler.checkExists(jobKey)) { jobDetail = scheduler.getJobDetail(jobKey); setJobData(jobDetail, jobRequestBody, measureId, groupName, jobName); scheduler.addJob(jobDetail, true); } else { jobDetail = newJob(SparkSubmitJob.class) .storeDurably() .withIdentity(jobKey) .build(); //set JobData setJobData(jobDetail, jobRequestBody, measureId, groupName, jobName); scheduler.addJob(jobDetail, false); } Trigger trigger = newTrigger() .withIdentity(triggerKey) .forJob(jobDetail) .withSchedule(SimpleScheduleBuilder.simpleSchedule() .withIntervalInSeconds(interval) .repeatForever()) .startAt(jobStartTime) .build(); scheduler.scheduleJob(trigger); return GriffinOperationMessage.CREATE_JOB_SUCCESS; } catch (SchedulerException e) { LOGGER.error("SchedulerException when add job. {}", e.getMessage()); return CREATE_JOB_FAIL; } } private void setJobStartTime(Date jobStartTime, int interval) { long currentTimestamp = System.currentTimeMillis(); long jobStartTimestamp = jobStartTime.getTime(); //if jobStartTime is before currentTimestamp, reset it with a future time if (jobStartTime.before(new Date(currentTimestamp))) { long n = (currentTimestamp - jobStartTimestamp) / (long) (interval * 1000); jobStartTimestamp = jobStartTimestamp + (n + 1) * (long) (interval * 1000); jobStartTime.setTime(jobStartTimestamp); } } private void setJobData(JobDetail jobDetail, JobRequestBody jobRequestBody, Long measureId, String groupName, String jobName) { jobDetail.getJobDataMap().put("groupName", groupName); jobDetail.getJobDataMap().put("jobName", jobName); jobDetail.getJobDataMap().put("measureId", measureId.toString()); jobDetail.getJobDataMap().put("sourcePattern", jobRequestBody.getSourcePattern()); jobDetail.getJobDataMap().put("targetPattern", jobRequestBody.getTargetPattern()); jobDetail.getJobDataMap().put("blockStartTimestamp", jobRequestBody.getBlockStartTimestamp()); jobDetail.getJobDataMap().put("jobStartTime", jobRequestBody.getJobStartTime()); jobDetail.getJobDataMap().put("interval", jobRequestBody.getInterval()); jobDetail.getJobDataMap().put("lastBlockStartTimestamp", ""); jobDetail.getJobDataMap().putAsString("deleted", false); } @Override public GriffinOperationMessage pauseJob(String group, String name) { try { Scheduler scheduler = factory.getObject(); scheduler.pauseJob(new JobKey(name, group)); return GriffinOperationMessage.PAUSE_JOB_SUCCESS; } catch (SchedulerException | NullPointerException e) { LOGGER.error("{} {}", GriffinOperationMessage.PAUSE_JOB_FAIL, e.getMessage()); return GriffinOperationMessage.PAUSE_JOB_FAIL; } } private GriffinOperationMessage setJobDeleted(String group, String name) { try { Scheduler scheduler = factory.getObject(); JobDetail jobDetail = scheduler.getJobDetail(new JobKey(name, group)); jobDetail.getJobDataMap().putAsString("deleted", true); scheduler.addJob(jobDetail, true); return GriffinOperationMessage.SET_JOB_DELETED_STATUS_SUCCESS; } catch (SchedulerException | NullPointerException e) { LOGGER.error("{} {}", GriffinOperationMessage.PAUSE_JOB_FAIL, e.getMessage()); return GriffinOperationMessage.SET_JOB_DELETED_STATUS_FAIL; } } /** * logically delete * 1. pause these jobs * 2. set these jobs as deleted status * * @param group * @param name * @return */ @Override public GriffinOperationMessage deleteJob(String group, String name) { //logically delete if (pauseJob(group, name).equals(PAUSE_JOB_SUCCESS) && setJobDeleted(group, name).equals(SET_JOB_DELETED_STATUS_SUCCESS)) { return GriffinOperationMessage.DELETE_JOB_SUCCESS; } return GriffinOperationMessage.DELETE_JOB_FAIL; } /** * deleteJobsRelateToMeasure * 1. search jobs related to measure * 2. deleteJob * * @param measure */ //TODO public void deleteJobsRelateToMeasure(Measure measure) throws SchedulerException { Scheduler scheduler = factory.getObject(); for (JobKey jobKey : scheduler.getJobKeys(GroupMatcher.anyGroup())) {//get all jobs JobDetail jobDetail = scheduler.getJobDetail(jobKey); JobDataMap jobDataMap = jobDetail.getJobDataMap(); if (jobDataMap.getString("measureId").equals(measure.getId().toString())) { //select jobs related to measureId, deleteJob(jobKey.getGroup(), jobKey.getName()); LOGGER.info("{} {} is paused and logically deleted.", jobKey.getGroup(), jobKey.getName()); } } } @Override public List<JobInstance> findInstancesOfJob(String group, String jobName, int page, int size) { //query and return instances Pageable pageRequest = new PageRequest(page, size, Sort.Direction.DESC, "timestamp"); return jobInstanceRepo.findByGroupNameAndJobName(group, jobName, pageRequest); } @Scheduled(fixedDelayString = "${jobInstance.fixedDelay.in.milliseconds}") public void syncInstancesOfAllJobs() { List<Object> groupJobList = jobInstanceRepo.findGroupWithJobName(); for (Object groupJobObj : groupJobList) { try { Object[] groupJob = (Object[]) groupJobObj; if (groupJob != null && groupJob.length == 2) { syncInstancesOfJob(groupJob[0].toString(), groupJob[1].toString()); } } catch (Exception e) { LOGGER.error("schedule update instances of all jobs failed. {}", e.getMessage()); } } } /** * call livy to update jobInstance table in mysql. * * @param group * @param jobName */ private void syncInstancesOfJob(String group, String jobName) { //update all instance info belongs to this group and job. List<JobInstance> jobInstanceList = jobInstanceRepo.findByGroupNameAndJobName(group, jobName); for (JobInstance jobInstance : jobInstanceList) { if (!LivySessionStates.isActive(jobInstance.getState())) { continue; } String uri = sparkJobProps.getProperty("livy.uri") + "/" + jobInstance.getSessionId(); RestTemplate restTemplate = new RestTemplate(); String resultStr; try { resultStr = restTemplate.getForObject(uri, String.class); } catch (Exception e) { LOGGER.error("spark session {} has overdue, set state as unknown!\n {}", jobInstance.getSessionId(), e.getMessage()); //if server cannot get session from Livy, set State as unknown. jobInstance.setState(LivySessionStates.State.unknown); jobInstanceRepo.save(jobInstance); continue; } TypeReference<HashMap<String, Object>> type = new TypeReference<HashMap<String, Object>>() { }; HashMap<String, Object> resultMap; try { resultMap = GriffinUtil.toEntity(resultStr, type); } catch (IOException e) { LOGGER.error("jobInstance jsonStr convert to map failed. {}", e.getMessage()); continue; } try { if (resultMap != null && resultMap.size() != 0) { jobInstance.setState(LivySessionStates.State.valueOf(resultMap.get("state").toString())); jobInstance.setAppId(resultMap.get("appId").toString()); jobInstance.setAppUri(sparkJobProps.getProperty("spark.uri") + "/cluster/app/" + resultMap.get("appId").toString()); } } catch (Exception e) { LOGGER.warn("{},{} job Instance has some null field (state or appId). {}", group, jobName, e.getMessage()); continue; } jobInstanceRepo.save(jobInstance); } } /** * a job is regard as healthy job when its latest instance is in healthy state. * * @return */ @Override public JobHealth getHealthInfo() { Scheduler scheduler = factory.getObject(); int jobCount = 0; int notHealthyCount = 0; try { for (String groupName : scheduler.getJobGroupNames()) { for (JobKey jobKey : scheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName))) { jobCount++; String jobName = jobKey.getName(); String jobGroup = jobKey.getGroup(); Pageable pageRequest = new PageRequest(0, 1, Sort.Direction.DESC, "timestamp"); JobInstance latestJobInstance; if (jobInstanceRepo.findByGroupNameAndJobName(jobGroup, jobName, pageRequest) != null && jobInstanceRepo.findByGroupNameAndJobName(jobGroup, jobName, pageRequest).size() > 0) { latestJobInstance = jobInstanceRepo.findByGroupNameAndJobName(jobGroup, jobName, pageRequest).get(0); if (!LivySessionStates.isHeathy(latestJobInstance.getState())) { notHealthyCount++; } } } } } catch (SchedulerException e) { LOGGER.error(e.getMessage()); throw new GetHealthInfoFailureException(); } return new JobHealth(jobCount - notHealthyCount, jobCount); } }
45.339572
136
0.643156
bae35118b1fd3c0468e1d206ecbd0e382dbde40b
15,100
/** * Copyright 2007-2015, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaazing.k3po.driver.internal.behavior.visitor; import org.kaazing.k3po.lang.internal.ast.AstAcceptNode; import org.kaazing.k3po.lang.internal.ast.AstAcceptableNode; import org.kaazing.k3po.lang.internal.ast.AstAcceptedNode; import org.kaazing.k3po.lang.internal.ast.AstBoundNode; import org.kaazing.k3po.lang.internal.ast.AstChildClosedNode; import org.kaazing.k3po.lang.internal.ast.AstChildOpenedNode; import org.kaazing.k3po.lang.internal.ast.AstCloseNode; import org.kaazing.k3po.lang.internal.ast.AstClosedNode; import org.kaazing.k3po.lang.internal.ast.AstCommandNode; import org.kaazing.k3po.lang.internal.ast.AstConnectAbortNode; import org.kaazing.k3po.lang.internal.ast.AstConnectAbortedNode; import org.kaazing.k3po.lang.internal.ast.AstConnectNode; import org.kaazing.k3po.lang.internal.ast.AstConnectedNode; import org.kaazing.k3po.lang.internal.ast.AstDisconnectNode; import org.kaazing.k3po.lang.internal.ast.AstDisconnectedNode; import org.kaazing.k3po.lang.internal.ast.AstEventNode; import org.kaazing.k3po.lang.internal.ast.AstNode; import org.kaazing.k3po.lang.internal.ast.AstOpenedNode; import org.kaazing.k3po.lang.internal.ast.AstPropertyNode; import org.kaazing.k3po.lang.internal.ast.AstReadAbortNode; import org.kaazing.k3po.lang.internal.ast.AstReadAbortedNode; import org.kaazing.k3po.lang.internal.ast.AstReadAdviseNode; import org.kaazing.k3po.lang.internal.ast.AstReadAdvisedNode; import org.kaazing.k3po.lang.internal.ast.AstReadAwaitNode; import org.kaazing.k3po.lang.internal.ast.AstReadClosedNode; import org.kaazing.k3po.lang.internal.ast.AstReadConfigNode; import org.kaazing.k3po.lang.internal.ast.AstReadNotifyNode; import org.kaazing.k3po.lang.internal.ast.AstReadOptionNode; import org.kaazing.k3po.lang.internal.ast.AstReadValueNode; import org.kaazing.k3po.lang.internal.ast.AstRejectedNode; import org.kaazing.k3po.lang.internal.ast.AstScriptNode; import org.kaazing.k3po.lang.internal.ast.AstStreamNode; import org.kaazing.k3po.lang.internal.ast.AstStreamableNode; import org.kaazing.k3po.lang.internal.ast.AstUnbindNode; import org.kaazing.k3po.lang.internal.ast.AstUnboundNode; import org.kaazing.k3po.lang.internal.ast.AstWriteAbortNode; import org.kaazing.k3po.lang.internal.ast.AstWriteAbortedNode; import org.kaazing.k3po.lang.internal.ast.AstWriteAdviseNode; import org.kaazing.k3po.lang.internal.ast.AstWriteAdvisedNode; import org.kaazing.k3po.lang.internal.ast.AstWriteAwaitNode; import org.kaazing.k3po.lang.internal.ast.AstWriteCloseNode; import org.kaazing.k3po.lang.internal.ast.AstWriteConfigNode; import org.kaazing.k3po.lang.internal.ast.AstWriteFlushNode; import org.kaazing.k3po.lang.internal.ast.AstWriteNotifyNode; import org.kaazing.k3po.lang.internal.ast.AstWriteOptionNode; import org.kaazing.k3po.lang.internal.ast.AstWriteValueNode; // Note: this is no longer injecting, just validating, as injection is now generalized public class ValidateStreamsVisitor implements AstNode.Visitor<AstScriptNode, ValidateStreamsVisitor.State> { public enum StreamState { // @formatter:off OPEN, CLOSED, // @formatter:on } public static final class State { private StreamState readState; private StreamState writeState; public State() { readState = StreamState.OPEN; writeState = StreamState.OPEN; } } @Override public AstScriptNode visit(AstScriptNode script, State state) { for (AstStreamNode stream : script.getStreams()) { stream.accept(this, state); } return null; } @Override public AstScriptNode visit(AstPropertyNode propertyNode, State state) { return null; } @Override public AstScriptNode visit(AstAcceptNode acceptNode, State state) { for (AstStreamableNode streamable : acceptNode.getStreamables()) { streamable.accept(this, state); } for (AstAcceptableNode acceptable : acceptNode.getAcceptables()) { state.readState = StreamState.OPEN; state.writeState = StreamState.OPEN; acceptable.accept(this, state); } return null; } @Override public AstScriptNode visit(AstConnectNode connectNode, State state) { state.writeState = StreamState.OPEN; state.readState = StreamState.OPEN; for (AstStreamableNode streamable : connectNode.getStreamables()) { streamable.accept(this, state); } return null; } @Override public AstScriptNode visit(AstConnectAbortNode node, State state) { switch (state.writeState) { case OPEN: state.readState = StreamState.CLOSED; break; default: throw new IllegalStateException(unexpectedInWriteState(node, state)); } return null; } @Override public AstScriptNode visit(AstConnectAbortedNode node, State state) { switch (state.writeState) { case OPEN: state.readState = StreamState.CLOSED; break; default: throw new IllegalStateException(unexpectedInWriteState(node, state)); } return null; } @Override public AstScriptNode visit(AstReadConfigNode node, State state) { switch (state.readState) { case OPEN: case CLOSED: break; default: throw new IllegalStateException(String.format("Unexpected read config event (%s) while reading in state %s", node .toString().trim(), state.readState)); } return null; } @Override public AstScriptNode visit(AstWriteConfigNode node, State state) { switch (state.writeState) { case OPEN: case CLOSED: break; default: throw new IllegalStateException(String.format("Unexpected write config command (%s) while writing in state %s", node .toString().trim(), state.writeState)); } return null; } @Override public AstScriptNode visit(AstReadAdviseNode node, State state) { switch (state.readState) { case OPEN: case CLOSED: break; default: throw new IllegalStateException(String.format("Unexpected read advise command (%s) while writing in state %s", node .toString().trim(), state.writeState)); } return null; } @Override public AstScriptNode visit(AstReadAdvisedNode node, State state) { switch (state.readState) { case OPEN: case CLOSED: break; default: throw new IllegalStateException(String.format("Unexpected read advised event (%s) while writing in state %s", node .toString().trim(), state.writeState)); } return null; } @Override public AstScriptNode visit(AstWriteAdviseNode node, State state) { switch (state.writeState) { case OPEN: case CLOSED: break; default: throw new IllegalStateException(String.format("Unexpected write advise command (%s) while writing in state %s", node .toString().trim(), state.writeState)); } return null; } @Override public AstScriptNode visit(AstWriteAdvisedNode node, State state) { switch (state.writeState) { case OPEN: case CLOSED: break; default: throw new IllegalStateException(String.format("Unexpected write advised event (%s) while writing in state %s", node .toString().trim(), state.writeState)); } return null; } @Override public AstScriptNode visit(AstReadClosedNode node, State state) { switch (state.readState) { case OPEN: state.readState = StreamState.CLOSED; break; default: throw new IllegalStateException(unexpectedInReadState(node, state)); } return null; } @Override public AstScriptNode visit(AstWriteCloseNode node, State state) { switch (state.writeState) { case OPEN: state.writeState = StreamState.CLOSED; break; default: throw new IllegalStateException(unexpectedInWriteState(node, state)); } return null; } @Override public AstScriptNode visit(AstWriteAbortNode node, State state) { switch (state.readState) { case OPEN: case CLOSED: state.writeState = StreamState.CLOSED; break; default: throw new IllegalStateException(unexpectedInReadState(node, state)); } return null; } @Override public AstScriptNode visit(AstReadAbortNode node, State state) { switch (state.readState) { case OPEN: case CLOSED: state.readState = StreamState.CLOSED; break; default: throw new IllegalStateException(unexpectedInReadState(node, state)); } return null; } @Override public AstScriptNode visit(AstReadAbortedNode node, State state) { switch (state.writeState) { case OPEN: case CLOSED: state.readState = StreamState.CLOSED; break; default: throw new IllegalStateException(unexpectedInWriteState(node, state)); } return null; } @Override public AstScriptNode visit(AstWriteAbortedNode node, State state) { switch (state.writeState) { case OPEN: case CLOSED: state.writeState = StreamState.CLOSED; break; default: throw new IllegalStateException(unexpectedInWriteState(node, state)); } return null; } @Override public AstScriptNode visit(AstReadValueNode node, State state) { switch (state.readState) { case OPEN: break; default: throw new IllegalStateException(unexpectedInReadState(node, state)); } return null; } @Override public AstScriptNode visit(AstWriteValueNode node, State state) { switch (state.writeState) { case OPEN: break; default: throw new IllegalStateException(unexpectedInWriteState(node, state)); } return null; } @Override public AstScriptNode visit(AstWriteFlushNode node, State state) { switch (state.writeState) { case OPEN: break; default: throw new IllegalStateException(unexpectedInWriteState(node, state)); } return null; } @Override public AstScriptNode visit(AstAcceptedNode node, State state) { for (AstStreamableNode streamable : node.getStreamables()) { streamable.accept(this, state); } return null; } @Override public AstScriptNode visit(AstRejectedNode node, State state) { for (AstStreamableNode streamable : node.getStreamables()) { streamable.accept(this, state); } return null; } @Override public AstScriptNode visit(AstDisconnectNode node, State state) { return null; } @Override public AstScriptNode visit(AstUnbindNode node, State state) { return null; } @Override public AstScriptNode visit(AstCloseNode node, State state) { return null; } @Override public AstScriptNode visit(AstChildOpenedNode node, State state) { return null; } @Override public AstScriptNode visit(AstChildClosedNode node, State state) { return null; } @Override public AstScriptNode visit(AstOpenedNode node, State state) { return null; } @Override public AstScriptNode visit(AstBoundNode node, State state) { return null; } @Override public AstScriptNode visit(AstConnectedNode node, State state) { return null; } @Override public AstScriptNode visit(AstDisconnectedNode node, State state) { return null; } @Override public AstScriptNode visit(AstUnboundNode node, State state) { return null; } @Override public AstScriptNode visit(AstClosedNode node, State state) { switch (state.readState) { case OPEN: state.readState = StreamState.CLOSED; break; case CLOSED: break; default: throw new IllegalStateException(unexpectedInReadState(node, state)); } switch (state.writeState) { case OPEN: state.writeState = StreamState.CLOSED; break; case CLOSED: break; default: throw new IllegalStateException(unexpectedInWriteState(node, state)); } return null; } @Override public AstScriptNode visit(AstReadAwaitNode node, State state) { return null; } @Override public AstScriptNode visit(AstWriteAwaitNode node, State state) { return null; } @Override public AstScriptNode visit(AstReadNotifyNode node, State state) { return null; } @Override public AstScriptNode visit(AstWriteNotifyNode node, State state) { return null; } @Override public AstScriptNode visit(AstReadOptionNode node, State state) { return null; } @Override public AstScriptNode visit(AstWriteOptionNode node, State state) { return null; } private String unexpectedInReadState(AstNode node, State state) { return String.format("Unexpected %s while reading in state %s", description(node), state.readState); } private String unexpectedInWriteState(AstNode node, State state) { return String.format("Unexpected %s while writing in state %s", description(node), state.writeState); } private String description(AstNode node) { String description = node.toString().trim(); if (node instanceof AstEventNode) { description = String.format("event (%s)", description); } else if (node instanceof AstCommandNode) { description = String.format("command (%s)", description); } return description; } }
30.139721
128
0.656026
c1ba2b6a3b2f82872f9477f2b388adf3175b1ec7
7,112
// ============================================================================ // Copyright (C) 2006-2018 Talend Inc. - www.talend.com // // This source code is available under agreement available at // https://github.com/Talend/data-prep/blob/master/LICENSE // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // // ============================================================================ package org.talend.dataprep.transformation.pipeline.model; import static org.talend.dataprep.transformation.pipeline.Signal.END_OF_STREAM; import java.io.IOException; import java.util.concurrent.atomic.AtomicBoolean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.talend.dataprep.api.dataset.RowMetadata; import org.talend.dataprep.api.dataset.row.DataSetRow; import org.talend.dataprep.cache.ContentCacheKey; import org.talend.dataprep.transformation.api.transformer.ConfiguredCacheWriter; import org.talend.dataprep.transformation.api.transformer.TransformerWriter; import org.talend.dataprep.transformation.pipeline.*; import org.talend.dataprep.transformation.pipeline.node.BasicNode; public class WriterNode extends BasicNode implements Monitored { private static final Logger LOGGER = LoggerFactory.getLogger(WriterNode.class); private final TransformerWriter writer; private final ConfiguredCacheWriter metadataCacheWriter; private final ContentCacheKey metadataKey; private static final long DATASET_RECORDS_LIMIT = 10000; private long nbRowsReceived = 0; /** Fall back raw metadata when no row (hence row metadata) is received. */ private RowMetadata fallBackRowMetadata; private RowMetadata lastRowMetadata; private boolean metaDataWrote = false; private boolean startRecords = false; private long totalTime; private int count; /** True if the writer is stopped. */ private AtomicBoolean isStopped = new AtomicBoolean(false); /** * Constructor. * * @param writer the transformer writer. * @param metadataCacheWriter the metadata cache writer. * @param metadataKey the transformation metadata cache key to use. * @param fallBackRowMetadata fallback raw metadata to be able to write an empty content even if no row/rowMetadata id * received. */ public WriterNode(final TransformerWriter writer, final ConfiguredCacheWriter metadataCacheWriter, final ContentCacheKey metadataKey, RowMetadata fallBackRowMetadata) { this.writer = writer; this.metadataCacheWriter = metadataCacheWriter; this.metadataKey = metadataKey; this.fallBackRowMetadata = fallBackRowMetadata; } /** * Synchronized method not to clash with the signal method. * * @see WriterNode#signal(Signal) * @see RuntimeNode#receive(DataSetRow, RowMetadata) */ @Override public synchronized void receive(DataSetRow row, RowMetadata metadata) { // do not write this row if the writer is stopped if (isStopped.get()) { LOGGER.debug("already finished or canceled, let's skip this row"); return; } final long start = System.currentTimeMillis(); try { if (!startRecords) { writer.startObject(); writer.fieldName("records"); writer.startArray(); startRecords = true; } lastRowMetadata = metadata; if (row.shouldWrite()) { writer.write(row); super.receive(row, metadata); if (!metaDataWrote && ++nbRowsReceived > DATASET_RECORDS_LIMIT) { writer.setHeader(lastRowMetadata); metaDataWrote = true; } } } catch (IOException e) { LOGGER.error("Unable to write record.", e); } finally { totalTime += System.currentTimeMillis() - start; count++; } } /** * Synchronized method not to clash with the receive method. * * @see WriterNode#receive(DataSetRow, RowMetadata) * @see RuntimeNode#signal(Signal) */ @Override public synchronized void signal(Signal signal) { LOGGER.debug("receive {}", signal); switch (signal) { case END_OF_STREAM: endOfStream(); break; case CANCEL: cancel(); break; default: LOGGER.debug("Unhandled signal {}.", signal); } super.signal(signal); } /** * Deal with the cancel signal. */ private void cancel() { // just set stopped flag to true so that the writer is not used anymore this.isStopped.set(true); } /** * Deal with end of stream signal. */ private void endOfStream() { if (isStopped.get()) { LOGGER.debug("cannot process {} because WriterNode is already finished or canceled", END_OF_STREAM); return; } // set this writer to stopped this.isStopped.set(true); final long start = System.currentTimeMillis(); try { // no row received, let's switch to the fallback row metadata if (!startRecords) { writer.startObject(); writer.fieldName("records"); writer.startArray(); lastRowMetadata = fallBackRowMetadata; } writer.endArray(); // <- end records writer.fieldName("metadata"); // <- start metadata writer.startObject(); writer.fieldName("columns"); writer.write(lastRowMetadata); writer.endObject(); writer.endObject(); // <- end data set writer.flush(); } catch (IOException e) { LOGGER.error("Unable to end writer.", e); } finally { totalTime += System.currentTimeMillis() - start; } // Cache computed metadata for later reuse try { metadataCacheWriter.write(metadataKey, lastRowMetadata); } catch (IOException e) { LOGGER.error("Unable to cache metadata for preparation #{} @ step #{}", metadataKey.getKey()); LOGGER.debug("Unable to cache metadata due to exception.", e); } finally { try { writer.close(); } catch (IOException e) { LOGGER.error("unable to close writer", e); } } } @Override public void accept(Visitor visitor) { visitor.visitNode(this); } @Override public Node copyShallow() { return new WriterNode(writer, metadataCacheWriter, metadataKey, fallBackRowMetadata); } @Override public long getTotalTime() { return totalTime; } @Override public long getCount() { return count; } public TransformerWriter getWriter() { return writer; } }
31.056769
122
0.607705
44721f6af2159aebefaf231c2c9c2ea0d47c2ef2
16,817
/* * JBoss, Home of Professional Open Source * Copyright 2009, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. * See the copyright.txt in the distribution for a * full listing of individual contributors. * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * 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, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. * * (C) 2009, * @author JBoss Inc. */ package org.jboss.jbossts.qa.junit.testgroup; import org.jboss.jbossts.qa.junit.*; import org.junit.*; // Automatically generated by XML2JUnit public class TestGroup_perfprofile01_e extends TestGroupBase { public String getTestGroupName() { return "perfprofile01_e_ait01_explicitobject_notran"; } protected Task server0 = null; @Before public void setUp() { super.setUp(); server0 = createTask("server0", com.arjuna.ats.arjuna.recovery.RecoveryManager.class, Task.TaskType.EXPECT_READY, 480); server0.start("-test"); } @After public void tearDown() { try { server0.terminate(); Task task0 = createTask("task0", org.jboss.jbossts.qa.Utils.RemoveServerIORStore.class, Task.TaskType.EXPECT_PASS_FAIL, 480); task0.perform("$(1)"); } finally { super.tearDown(); } } @Test public void PerfProfile01_E_AIT01_ExplicitObject_NoTran_NoTranNullOper() { setTestName("AIT01_ExplicitObject_NoTran_NoTranNullOper"); Task server1 = createTask("server1", org.jboss.jbossts.qa.PerfProfile01Servers.Server_AIT01_ExplicitObject.class, Task.TaskType.EXPECT_READY, 480); server1.start("$(1)"); Task client0 = createTask("client0", org.jboss.jbossts.qa.PerfProfile01Clients.Client_ExplicitObject_NoTran_NoTranNullOper.class, Task.TaskType.EXPECT_PASS_FAIL, 480); client0.start("AIT01", "10000", "$(1)"); client0.waitFor(); server1.terminate(); } @Test public void PerfProfile01_E_AIT01_ExplicitObject_NoTran_TranCommitNullOper() { setTestName("AIT01_ExplicitObject_NoTran_TranCommitNullOper"); Task server1 = createTask("server1", org.jboss.jbossts.qa.PerfProfile01Servers.Server_AIT01_ExplicitObject.class, Task.TaskType.EXPECT_READY, 480); server1.start("$(1)"); Task client0 = createTask("client0", org.jboss.jbossts.qa.PerfProfile01Clients.Client_ExplicitObject_NoTran_TranCommitNullOper.class, Task.TaskType.EXPECT_PASS_FAIL, 480); client0.start("AIT01", "1000", "$(1)"); client0.waitFor(); server1.terminate(); } @Test public void PerfProfile01_E_AIT01_ExplicitObject_NoTran_TranCommitReadLock() { setTestName("AIT01_ExplicitObject_NoTran_TranCommitReadLock"); Task server1 = createTask("server1", org.jboss.jbossts.qa.PerfProfile01Servers.Server_AIT01_ExplicitObject.class, Task.TaskType.EXPECT_READY, 480); server1.start("$(1)"); Task client0 = createTask("client0", org.jboss.jbossts.qa.PerfProfile01Clients.Client_ExplicitObject_NoTran_TranCommitReadLock.class, Task.TaskType.EXPECT_PASS_FAIL, 480); client0.start("AIT01", "1000", "$(1)"); client0.waitFor(); server1.terminate(); } @Test public void PerfProfile01_E_AIT01_ExplicitObject_NoTran_TranCommitWriteLock() { setTestName("AIT01_ExplicitObject_NoTran_TranCommitWriteLock"); Task server1 = createTask("server1", org.jboss.jbossts.qa.PerfProfile01Servers.Server_AIT01_ExplicitObject.class, Task.TaskType.EXPECT_READY, 480); server1.start("$(1)"); Task client0 = createTask("client0", org.jboss.jbossts.qa.PerfProfile01Clients.Client_ExplicitObject_NoTran_TranCommitWriteLock.class, Task.TaskType.EXPECT_PASS_FAIL, 480); client0.start("AIT01", "1000", "$(1)"); client0.waitFor(); server1.terminate(); } @Test public void PerfProfile01_E_AIT01_ExplicitObject_NoTran_TranRollbackNullOper() { setTestName("AIT01_ExplicitObject_NoTran_TranRollbackNullOper"); Task server1 = createTask("server1", org.jboss.jbossts.qa.PerfProfile01Servers.Server_AIT01_ExplicitObject.class, Task.TaskType.EXPECT_READY, 480); server1.start("$(1)"); Task client0 = createTask("client0", org.jboss.jbossts.qa.PerfProfile01Clients.Client_ExplicitObject_NoTran_TranRollbackNullOper.class, Task.TaskType.EXPECT_PASS_FAIL, 480); client0.start("AIT01", "1000", "$(1)"); client0.waitFor(); server1.terminate(); } @Test public void PerfProfile01_E_AIT01_ExplicitObject_NoTran_TranRollbackReadLock() { setTestName("AIT01_ExplicitObject_NoTran_TranRollbackReadLock"); Task server1 = createTask("server1", org.jboss.jbossts.qa.PerfProfile01Servers.Server_AIT01_ExplicitObject.class, Task.TaskType.EXPECT_READY, 480); server1.start("$(1)"); Task client0 = createTask("client0", org.jboss.jbossts.qa.PerfProfile01Clients.Client_ExplicitObject_NoTran_TranRollbackReadLock.class, Task.TaskType.EXPECT_PASS_FAIL, 480); client0.start("AIT01", "1000", "$(1)"); client0.waitFor(); server1.terminate(); } @Test public void PerfProfile01_E_AIT01_ExplicitObject_NoTran_TranRollbackWriteLock() { setTestName("AIT01_ExplicitObject_NoTran_TranRollbackWriteLock"); Task server1 = createTask("server1", org.jboss.jbossts.qa.PerfProfile01Servers.Server_AIT01_ExplicitObject.class, Task.TaskType.EXPECT_READY, 480); server1.start("$(1)"); Task client0 = createTask("client0", org.jboss.jbossts.qa.PerfProfile01Clients.Client_ExplicitObject_NoTran_TranRollbackWriteLock.class, Task.TaskType.EXPECT_PASS_FAIL, 480); client0.start("AIT01", "1000", "$(1)"); client0.waitFor(); server1.terminate(); } @Test public void PerfProfile01_E_AIT01_ExplicitObject_TranCommit_NoTranNullOper() { setTestName("AIT01_ExplicitObject_TranCommit_NoTranNullOper"); Task server1 = createTask("server1", org.jboss.jbossts.qa.PerfProfile01Servers.Server_AIT01_ExplicitObject.class, Task.TaskType.EXPECT_READY, 480); server1.start("$(1)"); Task client0 = createTask("client0", org.jboss.jbossts.qa.PerfProfile01Clients.Client_ExplicitObject_TranCommit_NoTranNullOper.class, Task.TaskType.EXPECT_PASS_FAIL, 480); client0.start("AIT01", "1000", "$(1)"); client0.waitFor(); server1.terminate(); } @Test public void PerfProfile01_E_AIT01_ExplicitObject_TranCommit_NoTranReadLock() { setTestName("AIT01_ExplicitObject_TranCommit_NoTranReadLock"); Task server1 = createTask("server1", org.jboss.jbossts.qa.PerfProfile01Servers.Server_AIT01_ExplicitObject.class, Task.TaskType.EXPECT_READY, 480); server1.start("$(1)"); Task client0 = createTask("client0", org.jboss.jbossts.qa.PerfProfile01Clients.Client_ExplicitObject_TranCommit_NoTranReadLock.class, Task.TaskType.EXPECT_PASS_FAIL, 480); client0.start("AIT01", "1000", "$(1)"); client0.waitFor(); server1.terminate(); } @Test public void PerfProfile01_E_AIT01_ExplicitObject_TranCommit_NoTranWriteLock() { setTestName("AIT01_ExplicitObject_TranCommit_NoTranWriteLock"); Task server1 = createTask("server1", org.jboss.jbossts.qa.PerfProfile01Servers.Server_AIT01_ExplicitObject.class, Task.TaskType.EXPECT_READY, 480); server1.start("$(1)"); Task client0 = createTask("client0", org.jboss.jbossts.qa.PerfProfile01Clients.Client_ExplicitObject_TranCommit_NoTranWriteLock.class, Task.TaskType.EXPECT_PASS_FAIL, 480); client0.start("AIT01", "1000", "$(1)"); client0.waitFor(); server1.terminate(); } @Test public void PerfProfile01_E_AIT01_ExplicitObject_TranCommit_TranCommitNullOper() { setTestName("AIT01_ExplicitObject_TranCommit_TranCommitNullOper"); Task server1 = createTask("server1", org.jboss.jbossts.qa.PerfProfile01Servers.Server_AIT01_ExplicitObject.class, Task.TaskType.EXPECT_READY, 480); server1.start("$(1)"); Task client0 = createTask("client0", org.jboss.jbossts.qa.PerfProfile01Clients.Client_ExplicitObject_TranCommit_TranCommitNullOper.class, Task.TaskType.EXPECT_PASS_FAIL, 480); client0.start("AIT01", "1000", "$(1)"); client0.waitFor(); server1.terminate(); } @Test public void PerfProfile01_E_AIT01_ExplicitObject_TranCommit_TranCommitReadLock() { setTestName("AIT01_ExplicitObject_TranCommit_TranCommitReadLock"); Task server1 = createTask("server1", org.jboss.jbossts.qa.PerfProfile01Servers.Server_AIT01_ExplicitObject.class, Task.TaskType.EXPECT_READY, 480); server1.start("$(1)"); Task client0 = createTask("client0", org.jboss.jbossts.qa.PerfProfile01Clients.Client_ExplicitObject_TranCommit_TranCommitReadLock.class, Task.TaskType.EXPECT_PASS_FAIL, 480); client0.start("AIT01", "1000", "$(1)"); client0.waitFor(); server1.terminate(); } @Test public void PerfProfile01_E_AIT01_ExplicitObject_TranCommit_TranCommitWriteLock() { setTestName("AIT01_ExplicitObject_TranCommit_TranCommitWriteLock"); Task server1 = createTask("server1", org.jboss.jbossts.qa.PerfProfile01Servers.Server_AIT01_ExplicitObject.class, Task.TaskType.EXPECT_READY, 480); server1.start("$(1)"); Task client0 = createTask("client0", org.jboss.jbossts.qa.PerfProfile01Clients.Client_ExplicitObject_TranCommit_TranCommitWriteLock.class, Task.TaskType.EXPECT_PASS_FAIL, 480); client0.start("AIT01", "1000", "$(1)"); client0.waitFor(); server1.terminate(); } @Test public void PerfProfile01_E_AIT01_ExplicitObject_TranCommit_TranRollbackNullOper() { setTestName("AIT01_ExplicitObject_TranCommit_TranRollbackNullOper"); Task server1 = createTask("server1", org.jboss.jbossts.qa.PerfProfile01Servers.Server_AIT01_ExplicitObject.class, Task.TaskType.EXPECT_READY, 480); server1.start("$(1)"); Task client0 = createTask("client0", org.jboss.jbossts.qa.PerfProfile01Clients.Client_ExplicitObject_TranCommit_TranRollbackNullOper.class, Task.TaskType.EXPECT_PASS_FAIL, 480); client0.start("AIT01", "1000", "$(1)"); client0.waitFor(); server1.terminate(); } @Test public void PerfProfile01_E_AIT01_ExplicitObject_TranCommit_TranRollbackReadLock() { setTestName("AIT01_ExplicitObject_TranCommit_TranRollbackReadLock"); Task server1 = createTask("server1", org.jboss.jbossts.qa.PerfProfile01Servers.Server_AIT01_ExplicitObject.class, Task.TaskType.EXPECT_READY, 480); server1.start("$(1)"); Task client0 = createTask("client0", org.jboss.jbossts.qa.PerfProfile01Clients.Client_ExplicitObject_TranCommit_TranRollbackReadLock.class, Task.TaskType.EXPECT_PASS_FAIL, 480); client0.start("AIT01", "1000", "$(1)"); client0.waitFor(); server1.terminate(); } @Test public void PerfProfile01_E_AIT01_ExplicitObject_TranCommit_TranRollbackWriteLock() { setTestName("AIT01_ExplicitObject_TranCommit_TranRollbackWriteLock"); Task server1 = createTask("server1", org.jboss.jbossts.qa.PerfProfile01Servers.Server_AIT01_ExplicitObject.class, Task.TaskType.EXPECT_READY, 480); server1.start("$(1)"); Task client0 = createTask("client0", org.jboss.jbossts.qa.PerfProfile01Clients.Client_ExplicitObject_TranCommit_TranRollbackWriteLock.class, Task.TaskType.EXPECT_PASS_FAIL, 480); client0.start("AIT01", "1000", "$(1)"); client0.waitFor(); server1.terminate(); } @Test public void PerfProfile01_E_AIT01_ExplicitObject_TranRollback_NoTranNullOper() { setTestName("AIT01_ExplicitObject_TranRollback_NoTranNullOper"); Task server1 = createTask("server1", org.jboss.jbossts.qa.PerfProfile01Servers.Server_AIT01_ExplicitObject.class, Task.TaskType.EXPECT_READY, 480); server1.start("$(1)"); Task client0 = createTask("client0", org.jboss.jbossts.qa.PerfProfile01Clients.Client_ExplicitObject_TranRollback_NoTranNullOper.class, Task.TaskType.EXPECT_PASS_FAIL, 480); client0.start("AIT01", "1000", "$(1)"); client0.waitFor(); server1.terminate(); } @Test public void PerfProfile01_E_AIT01_ExplicitObject_TranRollback_NoTranReadLock() { setTestName("AIT01_ExplicitObject_TranRollback_NoTranReadLock"); Task server1 = createTask("server1", org.jboss.jbossts.qa.PerfProfile01Servers.Server_AIT01_ExplicitObject.class, Task.TaskType.EXPECT_READY, 480); server1.start("$(1)"); Task client0 = createTask("client0", org.jboss.jbossts.qa.PerfProfile01Clients.Client_ExplicitObject_TranRollback_NoTranReadLock.class, Task.TaskType.EXPECT_PASS_FAIL, 480); client0.start("AIT01", "1000", "$(1)"); client0.waitFor(); server1.terminate(); } @Test public void PerfProfile01_E_AIT01_ExplicitObject_TranRollback_NoTranWriteLock() { setTestName("AIT01_ExplicitObject_TranRollback_NoTranWriteLock"); Task server1 = createTask("server1", org.jboss.jbossts.qa.PerfProfile01Servers.Server_AIT01_ExplicitObject.class, Task.TaskType.EXPECT_READY, 480); server1.start("$(1)"); Task client0 = createTask("client0", org.jboss.jbossts.qa.PerfProfile01Clients.Client_ExplicitObject_TranRollback_NoTranWriteLock.class, Task.TaskType.EXPECT_PASS_FAIL, 480); client0.start("AIT01", "1000", "$(1)"); client0.waitFor(); server1.terminate(); } @Test public void PerfProfile01_E_AIT01_ExplicitObject_TranRollback_TranCommitNullOper() { setTestName("AIT01_ExplicitObject_TranRollback_TranCommitNullOper"); Task server1 = createTask("server1", org.jboss.jbossts.qa.PerfProfile01Servers.Server_AIT01_ExplicitObject.class, Task.TaskType.EXPECT_READY, 480); server1.start("$(1)"); Task client0 = createTask("client0", org.jboss.jbossts.qa.PerfProfile01Clients.Client_ExplicitObject_TranRollback_TranCommitNullOper.class, Task.TaskType.EXPECT_PASS_FAIL, 480); client0.start("AIT01", "1000", "$(1)"); client0.waitFor(); server1.terminate(); } @Test public void PerfProfile01_E_AIT01_ExplicitObject_TranRollback_TranCommitReadLock() { setTestName("AIT01_ExplicitObject_TranRollback_TranCommitReadLock"); Task server1 = createTask("server1", org.jboss.jbossts.qa.PerfProfile01Servers.Server_AIT01_ExplicitObject.class, Task.TaskType.EXPECT_READY, 480); server1.start("$(1)"); Task client0 = createTask("client0", org.jboss.jbossts.qa.PerfProfile01Clients.Client_ExplicitObject_TranRollback_TranCommitReadLock.class, Task.TaskType.EXPECT_PASS_FAIL, 480); client0.start("AIT01", "1000", "$(1)"); client0.waitFor(); server1.terminate(); } @Test public void PerfProfile01_E_AIT01_ExplicitObject_TranRollback_TranCommitWriteLock() { setTestName("AIT01_ExplicitObject_TranRollback_TranCommitWriteLock"); Task server1 = createTask("server1", org.jboss.jbossts.qa.PerfProfile01Servers.Server_AIT01_ExplicitObject.class, Task.TaskType.EXPECT_READY, 480); server1.start("$(1)"); Task client0 = createTask("client0", org.jboss.jbossts.qa.PerfProfile01Clients.Client_ExplicitObject_TranRollback_TranCommitWriteLock.class, Task.TaskType.EXPECT_PASS_FAIL, 480); client0.start("AIT01", "1000", "$(1)"); client0.waitFor(); server1.terminate(); } @Test public void PerfProfile01_E_AIT01_ExplicitObject_TranRollback_TranRollbackNullOper() { setTestName("AIT01_ExplicitObject_TranRollback_TranRollbackNullOper"); Task server1 = createTask("server1", org.jboss.jbossts.qa.PerfProfile01Servers.Server_AIT01_ExplicitObject.class, Task.TaskType.EXPECT_READY, 480); server1.start("$(1)"); Task client0 = createTask("client0", org.jboss.jbossts.qa.PerfProfile01Clients.Client_ExplicitObject_TranRollback_TranRollbackNullOper.class, Task.TaskType.EXPECT_PASS_FAIL, 480); client0.start("AIT01", "1000", "$(1)"); client0.waitFor(); server1.terminate(); } @Test public void PerfProfile01_E_AIT01_ExplicitObject_TranRollback_TranRollbackReadLock() { setTestName("AIT01_ExplicitObject_TranRollback_TranRollbackReadLock"); Task server1 = createTask("server1", org.jboss.jbossts.qa.PerfProfile01Servers.Server_AIT01_ExplicitObject.class, Task.TaskType.EXPECT_READY, 480); server1.start("$(1)"); Task client0 = createTask("client0", org.jboss.jbossts.qa.PerfProfile01Clients.Client_ExplicitObject_TranRollback_TranRollbackReadLock.class, Task.TaskType.EXPECT_PASS_FAIL, 480); client0.start("AIT01", "1000", "$(1)"); client0.waitFor(); server1.terminate(); } @Test public void PerfProfile01_E_AIT01_ExplicitObject_TranRollback_TranRollbackWriteLock() { setTestName("AIT01_ExplicitObject_TranRollback_TranRollbackWriteLock"); Task server1 = createTask("server1", org.jboss.jbossts.qa.PerfProfile01Servers.Server_AIT01_ExplicitObject.class, Task.TaskType.EXPECT_READY, 480); server1.start("$(1)"); Task client0 = createTask("client0", org.jboss.jbossts.qa.PerfProfile01Clients.Client_ExplicitObject_TranRollback_TranRollbackWriteLock.class, Task.TaskType.EXPECT_PASS_FAIL, 480); client0.start("AIT01", "1000", "$(1)"); client0.waitFor(); server1.terminate(); } }
50.960606
182
0.792948
946633605648e5edf5b18122ee7ae87329ff2670
40,703
/* * USE - UML based specification environment * Copyright (C) 1999-2010 Mark Richters, University of Bremen * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ // $Id: StatementEffectTest.java 5036 2014-06-13 10:54:47Z lhamann $ package org.tzi.use.uml.sys.soil; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import junit.framework.TestCase; import org.junit.Before; import org.junit.Test; import org.tzi.use.TestSystem; import org.tzi.use.api.UseSystemApi; import org.tzi.use.parser.shell.ShellCommandCompiler; import org.tzi.use.uml.mm.MInvalidModelException; import org.tzi.use.uml.ocl.expr.ExpInvalidException; import org.tzi.use.uml.ocl.value.IntegerValue; import org.tzi.use.uml.ocl.value.ObjectValue; import org.tzi.use.uml.ocl.value.Value; import org.tzi.use.uml.sys.MLink; import org.tzi.use.uml.sys.MLinkObject; import org.tzi.use.uml.sys.MObject; import org.tzi.use.uml.sys.MOperationCall; import org.tzi.use.uml.sys.MSystemException; import org.tzi.use.uml.sys.MSystemState; import org.tzi.use.uml.sys.ppcHandling.SoilPPCHandler; import org.tzi.use.util.NullPrintWriter; import org.tzi.use.util.soil.VariableEnvironment; /** * Test cases to test the effects of different statements. * @author Daniel Gent * */ public class StatementEffectTest extends TestCase { private TestSystem fTestSystem; private UseSystemApi systemApi; private MSystemState fState; private MSystemState fOldState; private VariableEnvironment fOldVarEnv; @Before @Override public void setUp() throws MInvalidModelException, MSystemException, ExpInvalidException { fTestSystem = new TestSystem(); systemApi = UseSystemApi.create(fTestSystem.getSystem(), false); fState = fTestSystem.getState(); fOldState = new MSystemState("oldState", fState); fOldVarEnv = new VariableEnvironment(fTestSystem.getVarEnv()); } private void reset() throws MSystemException { fTestSystem.reset(); fState = fTestSystem.getState(); fOldState = new MSystemState("oldState", fState); fOldVarEnv = new VariableEnvironment(fTestSystem.getVarEnv()); } @Test public void testVariableAssignment() throws MSystemException { //////////////////////////////// // simple variable assignment // //////////////////////////////// String statement; IntegerValue val1 = IntegerValue.valueOf(42); String varName = "x"; // variable not existent before assertNull(lookUpVar(varName)); statement = varName + " := " + val1; evaluateStatement(statement); // 1 new variable List<String> newVars = getNewVars(); assertEquals(1, newVars.size()); assertTrue(getNewVars().contains(varName)); // with the desired value assertEquals(lookUpVar(varName), val1); ////////// // undo // ////////// IntegerValue val2 = IntegerValue.valueOf(43); // overwrite variable statement = varName + " := " + val2; evaluateStatement(statement); // variable has new value assertEquals(lookUpVar(varName), val2); undo(); // old value should be restored assertEquals(lookUpVar(varName), val1); ////////// // redo // ////////// redo(); // new value should be restored assertEquals(lookUpVar(varName), val2); ////////////////////////////// // assignment of new object // ////////////////////////////// String className = "C1"; MObject newObject; Value varVal; reset(); // variable not existent assertNull(lookUpVar(varName)); statement = varName + " := new " + className; evaluateStatement(statement); // 2 new variables assertEquals(1, getNewVars().size()); // explicit variable refers to object assertNotNull(lookUpVar(varName)); varVal = lookUpVar(varName); assertTrue(varVal instanceof ObjectValue); newObject = ((ObjectValue)varVal).value(); // new object did not exist before assertFalse(fOldState.hasObjectWithName(newObject.name())); // new object is of desired class assertEquals(newObject.cls().name(), className); /////////////////////////////////// // assignment of new link object // /////////////////////////////////// String assocClassName = "AC1"; MLinkObject newLinkObject; String objName1 = "o1"; String objName2 = "o2"; reset(); // variable not existent assertNull(lookUpVar(varName)); statement = varName + " := new " + assocClassName + " between (" + objName1 + ", " + objName2 + ")"; evaluateStatement(statement); // 1 new variable assertEquals(1, getNewVars().size()); // explicit variable referring to the new link object varVal = lookUpVar(varName); assertNotNull(varVal); assertTrue(varVal instanceof ObjectValue); assertTrue(((ObjectValue)varVal).value() instanceof MLinkObject); newLinkObject = (MLinkObject)((ObjectValue)varVal).value(); assertEquals(newLinkObject.cls().name(), assocClassName); // object did not exist before assertFalse(fOldState.hasObjectWithName(newLinkObject.name())); //////////////////////////////// // assignment of return value // //////////////////////////////// String opCallObjectName = "o1"; String opName = "s1"; String paramString = "0"; int expectedResultValue = 42; reset(); assertNull(lookUpVar(varName)); statement = varName + " := " + opCallObjectName + "." + opName + "(" + paramString + ")"; evaluateStatement(statement); // 1 new variable with the expected value assertEquals(getNewVars().size(), 1); assertNotNull(lookUpVar(varName)); varVal = lookUpVar(varName); assertTrue(varVal instanceof IntegerValue); assertEquals(((IntegerValue)varVal).value(), expectedResultValue); } @Test public void testAttributeAssignment() throws MSystemException { //////////////////////////////// // basic attribute assignment // //////////////////////////////// String objVarName = "o1"; String attName = "int"; int attVal = 42; String statement = objVarName + "." + attName + " := " + attVal; MObject object = getObjectByVarName(objVarName); assertNotNull(object); evaluateStatement(statement); Value newAttVal = getAttVal(object, attName); assertEquals(newAttVal, IntegerValue.valueOf(attVal)); int attVal2 = 43; statement = objVarName + "." + attName + " := " + attVal2; evaluateStatement(statement); newAttVal = getAttVal(object, attName); assertEquals(newAttVal, IntegerValue.valueOf(attVal2)); ////////// // undo // ////////// undo(); newAttVal = getAttVal(object, attName); assertEquals(newAttVal, IntegerValue.valueOf(attVal)); ////////// // redo // ////////// redo(); newAttVal = getAttVal(object, attName); assertEquals(newAttVal, IntegerValue.valueOf(attVal2)); } @Test public void testObjectCreation() throws MSystemException { /////////////////////////// // basic object creation // /////////////////////////// String statement; String className = "C1"; statement = "new " + className; evaluateStatement(statement); // 1 new object of expected class List<MObject> newObjects = getNewObjects(); assertEquals(newObjects.size(), 1); MObject newObject = newObjects.get(0); assertEquals(newObject.cls().name(), className); // there is a variable with the same name as the object name assertEquals(0, getNewVars().size()); String objectName = newObject.name(); Value varVal = lookUpVar(objectName); assertNotNull(varVal); // and it points to the new object assertEquals(varVal, newObject.value()); ////////// // undo // ////////// undo(); // new object is gone assertTrue(getNewObjects().isEmpty()); // variable is gone assertNull(lookUpVar(objectName)); ////////// // redo // ////////// redo(); assertEquals(newObjects.size(), 1); newObject = newObjects.get(0); // object is of class C1 assertEquals(newObject.cls().name(), className); // and has the same name as in the previous run assertEquals(newObject.name(), objectName); // the variable should be back varVal = lookUpVar(objectName); assertNotNull(varVal); // and it points to the new object assertEquals(varVal, newObject.value()); //////////////////////////////////////////////// // object creation with mandatory object name // //////////////////////////////////////////////// String name1 = "a"; reset(); statement = "new " + className + "('" + name1 + "')"; evaluateStatement(statement); // 1 new variable assertEquals(0, getNewVars().size()); newObjects = getNewObjects(); // 1 new object assertEquals(newObjects.size(), 1); newObject = newObjects.get(0); // object is of class C1 assertEquals(newObject.cls().name(), className); // objects name is the mandatory name assertEquals(newObject.name(), name1); // new variable with that name exists varVal = lookUpVar(name1); assertNotNull(varVal); // and it points to the new object assertEquals(varVal, newObject.value()); //////////////////////// // variable shadowing // //////////////////////// int intVal = 42; reset(); // 2 consecutive statements statement = "new " + className + "('" + name1 + "')" + "; " + name1 + " := " + intVal; evaluateStatement(statement); // 1 new variable assertEquals(getNewVars().size(), 1); newObjects = getNewObjects(); // 1 new object assertEquals(newObjects.size(), 1); newObject = newObjects.get(0); // of the declared class assertEquals(newObject.cls().name(), className); // with the mandatory name assertEquals(newObject.name(), name1); // but its variable is shadowed varVal = lookUpVar(name1); assertEquals(((IntegerValue)varVal).value(), intVal); // order of the sequence should not matter reset(); // 2 consecutive statements statement = name1 + " := " + intVal + "; " + "new " + className + "('" + name1 + "')"; evaluateStatement(statement); // 1 new variable assertEquals(getNewVars().size(), 1); newObjects = getNewObjects(); // 1 new object assertEquals(newObjects.size(), 1); newObject = newObjects.get(0); // of the declared class assertEquals(newObject.cls().name(), className); // with the mandatory name assertEquals(newObject.name(), name1); // but its variable is shadowed varVal = lookUpVar(name1); assertEquals(((IntegerValue)varVal).value(), 42); } @Test public void testLinkObjectCreation() throws MSystemException { //////////////////////////////// // basic link object creation // //////////////////////////////// String statement; String assClassName = "AC1"; String pName1 = "o1"; String pName2 = "o2"; // the objects we're about to link should exist... assertNotNull(lookUpVar(pName1)); assertTrue(lookUpVar(pName1) instanceof ObjectValue); MObject linkedObject1 = ((ObjectValue)lookUpVar(pName1)).value(); assertNotNull(lookUpVar(pName2)); assertTrue(lookUpVar(pName2) instanceof ObjectValue); MObject linkedObject2 = ((ObjectValue)lookUpVar(pName2)).value(); statement = "new " + assClassName + " between " + "(" + pName1 + "," + pName2 + ")"; evaluateStatement(statement); assertEquals(0, getNewVars().size()); List<MObject> newObjects = getNewObjects(); // 1 new object assertEquals(1, newObjects.size()); MObject newObject = newObjects.get(0); // must be a link object assertTrue(newObject instanceof MLinkObject); MLinkObject newLinkObject = (MLinkObject)newObject; // association must be AC1 assertEquals(newLinkObject.association().name(), assClassName); // 1 new link List<MLink> newLinks = getNewLinks(); assertEquals(newLinks.size(), 1); MLink newLink = newLinks.get(0); // must be the link object assertSame(newLink, newObject); // o1 and o2 must be the linked object assertEquals(newLinkObject.linkedObjects().size(), 2); assertTrue(newLinkObject.linkedObjects().contains(linkedObject1)); assertTrue(newLinkObject.linkedObjects().contains(linkedObject2)); String linkObjectName = newLinkObject.name(); // there must be a variable with the same name as the link object Value varVal = lookUpVar(linkObjectName); assertNotNull(varVal); // which refers to the new link object assertEquals(varVal, newLinkObject.value()); undo(); // should remove the new object, the new link and the variable assertTrue(getNewObjects().isEmpty()); assertTrue(getNewLinks().isEmpty()); assertNull(lookUpVar(linkObjectName)); ////////// // redo // ////////// redo(); assertEquals(0, getNewVars().size()); newObjects = getNewObjects(); assertEquals(1, newObjects.size()); newObject = newObjects.get(0); // must have the same name again assertEquals(newObject.name(), linkObjectName); // must be a link object assertTrue(newObject instanceof MLinkObject); newLinkObject = (MLinkObject)newObject; // association must be AC1 assertEquals(newLinkObject.association().name(), assClassName); // 1 new link newLinks = getNewLinks(); assertEquals(newLinks.size(), 1); newLink = newLinks.get(0); // must be the link object assertSame(newLink, newObject); // o1 and o2 must be the linked object assertEquals(newLinkObject.linkedObjects().size(), 2); assertTrue(newLinkObject.linkedObjects().contains(linkedObject1)); assertTrue(newLinkObject.linkedObjects().contains(linkedObject2)); // there must be a variable with the same name as the link object varVal = lookUpVar(linkObjectName); assertNotNull(varVal); // which refers to the new link object assertEquals(varVal, newLinkObject.value()); ////////////////////////////////////////////////////////// // link object creation with mandatory link object name // ////////////////////////////////////////////////////////// reset(); String mandatoryName = "a"; statement = "new " + assClassName + "('" + mandatoryName + "') " + "between (" + pName1 + "," + pName2 + ")"; evaluateStatement(statement); assertEquals(0, getNewVars().size()); newObjects = getNewObjects(); assertEquals(newObjects.size(), 1); newObject = newObjects.get(0); // must be a link object assertTrue(newObject instanceof MLinkObject); newLinkObject = (MLinkObject)newObject; // name must be the mandatory name assertEquals(newLinkObject.name(), mandatoryName); // association must be AC1 assertEquals(newLinkObject.association().name(), assClassName); // 1 new link newLinks = getNewLinks(); assertEquals(newLinks.size(), 1); newLink = newLinks.get(0); // must be the link object assertSame(newLink, newObject); // o1 and o2 must be the linked object assertEquals(newLinkObject.linkedObjects().size(), 2); assertTrue(newLinkObject.linkedObjects().contains(linkedObject1)); assertTrue(newLinkObject.linkedObjects().contains(linkedObject2)); // there must be a variable with the mandatory name varVal = lookUpVar(mandatoryName); assertNotNull(varVal); // which refers to the new link object assertEquals(varVal, newLinkObject.value()); ////////////////////////////////////////////////// // link object creation between two new objects // ////////////////////////////////////////////////// reset(); String pClass1 = "C1"; String pClass2 = "C2"; String pMName1 = "b"; String pMName2 = "c"; statement = "new " + assClassName + "('" + mandatoryName + "') " + "between (" + "new " + pClass1 + "('" + pMName1 + "'), " + "new " + pClass2 + "('" + pMName2 + "')" + ")"; // variable names should be free assertNull(lookUpVar(pMName1)); assertNull(lookUpVar(pMName2)); evaluateStatement(statement); // no new variables List<String> newVars = getNewVars(); assertEquals(0, newVars.size()); assertFalse(newVars.contains(mandatoryName)); assertFalse(newVars.contains(pMName1)); assertFalse(newVars.contains(pMName2)); // 3 new objects newObjects = getNewObjects(); assertEquals(3, newObjects.size()); linkedObject1 = getObject(pMName1); assertTrue(newObjects.contains(linkedObject1)); assertEquals(linkedObject1.cls().name(), pClass1); linkedObject2 = getObject(pMName2); assertTrue(newObjects.contains(linkedObject2)); assertEquals(linkedObject2.cls().name(), pClass2); newObject = getObject(mandatoryName); assertTrue(newObject instanceof MLinkObject); newLinkObject = (MLinkObject)newObject; assertEquals(newLinkObject.association().name(), assClassName); assertEquals(newLinkObject.linkedObjects().size(), 2); assertTrue(newLinkObject.linkedObjects().contains(linkedObject1)); assertTrue(newLinkObject.linkedObjects().contains(linkedObject2)); // 1 new link newLinks = getNewLinks(); assertEquals(newLinks.size(), 1); newLinks = getNewLinks(); assertEquals(newLinks.size(), 1); newLink = newLinks.get(0); // must be the link object assertSame(newLink, newObject); // variables are assigned correctly assertEquals(linkedObject1.value(), lookUpVar(pMName1)); assertEquals(linkedObject2.value(), lookUpVar(pMName2)); assertEquals(newLinkObject.value(), lookUpVar(mandatoryName)); ////////// // undo // ////////// undo(); // no new variables assertTrue(getNewVars().isEmpty()); // no new objects assertTrue(getNewObjects().isEmpty()); // no new links assertTrue(getNewLinks().isEmpty()); ////////// // redo // ////////// redo(); // everything should be the same again // 3 new variables newVars = getNewVars(); assertEquals(0, newVars.size()); assertFalse(newVars.contains(mandatoryName)); assertFalse(newVars.contains(pMName1)); assertFalse(newVars.contains(pMName2)); // 3 new objects newObjects = getNewObjects(); assertEquals(newObjects.size(), 3); linkedObject1 = getObject(pMName1); assertTrue(newObjects.contains(linkedObject1)); assertEquals(linkedObject1.cls().name(), pClass1); linkedObject2 = getObject(pMName2); assertTrue(newObjects.contains(linkedObject2)); assertEquals(linkedObject2.cls().name(), pClass2); newObject = getObject(mandatoryName); assertTrue(newObject instanceof MLinkObject); newLinkObject = (MLinkObject)newObject; assertEquals(newLinkObject.association().name(), assClassName); assertEquals(newLinkObject.linkedObjects().size(), 2); assertTrue(newLinkObject.linkedObjects().contains(linkedObject1)); assertTrue(newLinkObject.linkedObjects().contains(linkedObject2)); // 1 new link newLinks = getNewLinks(); assertEquals(newLinks.size(), 1); newLinks = getNewLinks(); assertEquals(newLinks.size(), 1); newLink = newLinks.get(0); // must be the link object assertSame(newLink, newObject); // variables are assigned correctly assertEquals(linkedObject1.value(), lookUpVar(pMName1)); assertEquals(linkedObject2.value(), lookUpVar(pMName2)); assertEquals(newLinkObject.value(), lookUpVar(mandatoryName)); } @Test public void testObjectDestruction() throws MSystemException { ////////////////////////////// // basic object destruction // ////////////////////////////// String vNameObj1 = "o1"; assertNotNull(lookUpVar(vNameObj1)); MObject object1 = getObjectByVarName(vNameObj1); String oNameObj1 = object1.name(); assertNotNull(object1); String statement = "destroy " + vNameObj1; evaluateStatement(statement); // object should be gone assertNull(getObject(oNameObj1)); // variable should be undefined, but still exist Value varVal1 = lookUpVar(vNameObj1); assertNotNull(varVal1); assertTrue(varVal1.type().isSubtypeOf(fOldVarEnv.lookUp(vNameObj1).type())); assertTrue(varVal1.isUndefined()); ////////// // undo // ////////// undo(); // object should be back MObject restoredObject = getObjectByVarName(vNameObj1); assertNotNull(restoredObject); assertSame(object1, restoredObject); // variable should be restored varVal1 = lookUpVar(vNameObj1); assertNotNull(varVal1); assertEquals(varVal1, restoredObject.value()); ////////// // redo // ////////// redo(); // object should be gone assertNull(getObjectByVarName(vNameObj1)); // variable should be undefined, but still exist varVal1 = lookUpVar(vNameObj1); assertNotNull(varVal1); assertTrue(varVal1.type().isSubtypeOf(fOldVarEnv.lookUp(vNameObj1).type())); assertTrue(varVal1.isUndefined()); ///////////////////////////////////// // destruction of multiple objects // ///////////////////////////////////// reset(); String vNameObj2 = "o2"; assertNotNull(lookUpVar(vNameObj1)); assertNotNull(lookUpVar(vNameObj2)); object1 = getObjectByVarName(vNameObj1); oNameObj1 = object1.name(); assertNotNull(object1); MObject object2 = getObjectByVarName(vNameObj2); String oNameObj2 = object2.name(); assertNotNull(object2); statement = "destroy " + vNameObj1 + ", " + vNameObj2; evaluateStatement(statement); // both objects should be gone assertNull(getObject(oNameObj1)); assertNull(getObject(oNameObj2)); // variables should undefined varVal1 = lookUpVar(vNameObj1); assertNotNull(varVal1); assertTrue(varVal1.type().isSubtypeOf(fOldVarEnv.lookUp(vNameObj1).type())); assertTrue(varVal1.isUndefined()); Value varVal2 = lookUpVar(vNameObj2); assertNotNull(varVal2); assertTrue(varVal2.type().isSubtypeOf(fOldVarEnv.lookUp(vNameObj2).type())); assertTrue(varVal2.isUndefined()); /////////////////////////////////////////////// // destruction of a static object collection // /////////////////////////////////////////////// reset(); statement = "destroy " + "Set{" + vNameObj1 + ", " + vNameObj2 + "}"; evaluateStatement(statement); // both objects should be gone assertNull(getObject(oNameObj1)); assertNull(getObject(oNameObj2)); // variables should undefined varVal1 = lookUpVar(vNameObj1); assertNotNull(varVal1); assertTrue(varVal1.type().isSubtypeOf(fOldVarEnv.lookUp(vNameObj1).type())); assertTrue(varVal1.isUndefined()); varVal2 = lookUpVar(vNameObj2); assertNotNull(varVal2); assertTrue(varVal2.type().isSubtypeOf(fOldVarEnv.lookUp(vNameObj2).type())); assertTrue(varVal2.isUndefined()); ////////////////////////////////////////////// // destruction of dynamic object collection // ////////////////////////////////////////////// reset(); String objClassName = "C1"; List<MObject> objectsToDestroy = new ArrayList<MObject>(); for (MObject o : fState.allObjects()) { if (o.cls().name().equals(objClassName)) { objectsToDestroy.add(o); } } assertFalse(objectsToDestroy.isEmpty()); statement = "destroy " + objClassName + ".allInstances"; evaluateStatement(statement); // all objects of chosen class destroyed for (MObject o : objectsToDestroy) { assertFalse(fState.hasObjectWithName(o.name())); } ////////// // undo // ////////// undo(); // all destroyed objects restored for (MObject o : objectsToDestroy) { assertTrue(fState.hasObjectWithName(o.name())); } // TODO: link object destruction? } @Test public void testLinkInsertion() throws MSystemException { ////////////////////////// // basic link insertion // ////////////////////////// String statement; String assocName = "A1"; String pName1 = "o1"; String pName2 = "o2"; statement = "insert (" + pName1 + ", " + pName2 + ") into " + assocName; // objects we want to link should exist... MObject linkedObject1 = getObjectByVarName(pName1); assertNotNull(linkedObject1); MObject linkedObject2 = getObjectByVarName(pName2); assertNotNull(linkedObject2); assertFalse(fState.hasLinkBetweenObjects( fTestSystem.getSystem().model().getAssociation(assocName), linkedObject1, linkedObject2)); evaluateStatement(statement); // 1 new link List<MLink> newLinks = getNewLinks(); assertEquals(newLinks.size(), 1); MLink newLink = newLinks.get(0); // of the correct association assertEquals(newLink.association().name(), assocName); // linking the correct objects List<MObject> linkedObjects = newLink.linkedObjects(); assertEquals(linkedObjects.size(), 2); assertTrue(linkedObjects.contains(linkedObject1)); assertTrue(linkedObjects.contains(linkedObject2)); ////////// // undo // ////////// undo(); // link is gone newLinks = getNewLinks(); assertTrue(newLinks.isEmpty()); assertFalse(fState.allLinks().contains(newLink)); ////////// // redo // ////////// redo(); // 1 new link newLinks = getNewLinks(); assertEquals(newLinks.size(), 1); newLink = newLinks.get(0); // of the correct association assertEquals(newLink.association().name(), assocName); // linking the correct objects linkedObjects = newLink.linkedObjects(); assertEquals(linkedObjects.size(), 2); assertTrue(linkedObjects.contains(linkedObject1)); assertTrue(linkedObjects.contains(linkedObject2)); ///////////////////////////////////////////// // link object creation via link insertion // ///////////////////////////////////////////// reset(); String assocClassName = "AC1"; statement = "insert (" + pName1 + ", " + pName2 + ") into " + assocClassName; // objects we want to link should exist... linkedObject1 = getObjectByVarName(pName1); assertNotNull(linkedObject1); linkedObject2 = getObjectByVarName(pName2); assertNotNull(linkedObject2); assertFalse(fState.hasLinkBetweenObjects( fTestSystem.getSystem().model().getAssociation(assocClassName), linkedObject1, linkedObject2)); evaluateStatement(statement); // 1 new link newLinks = getNewLinks(); assertEquals(newLinks.size(), 1); newLink = newLinks.get(0); // link object! assertTrue(newLink instanceof MLinkObject); assertEquals(getNewObjects().size(), 1); // of the correct association assertEquals(newLink.association().name(), assocClassName); // linking the correct objects linkedObjects = newLink.linkedObjects(); assertEquals(linkedObjects.size(), 2); assertTrue(linkedObjects.contains(linkedObject1)); assertTrue(linkedObjects.contains(linkedObject2)); } @Test public void testLinkDeletion() throws MSystemException { ///////////////////////// // basic link deletion // ///////////////////////// String statement; String assocName = "A1"; String pName1 = "o3"; String pName2 = "o4"; statement = "delete (" + pName1 + ", " + pName2 + ") from " + assocName; // objects we want to link should exist... MObject linkedObject1 = getObjectByVarName(pName1); assertNotNull(linkedObject1); MObject linkedObject2 = getObjectByVarName(pName2); assertNotNull(linkedObject2); // link should exist assertNotNull(getLink(assocName, linkedObject1, linkedObject2)); evaluateStatement(statement); // 1 less link assertEquals(fState.allLinks().size() + 1, fOldState.allLinks().size()); assertNull(getLink(assocName, linkedObject1, linkedObject2)); ////////// // undo // ////////// undo(); // link is back assertEquals(fState.allLinks().size(), fOldState.allLinks().size()); assertNotNull(getLink(assocName, linkedObject1, linkedObject2)); ////////// // redo // ////////// redo(); // and gone again assertEquals(fState.allLinks().size() + 1, fOldState.allLinks().size()); assertNull(getLink(assocName, linkedObject1, linkedObject2)); /////////////////////////////////////////////// // link object destruction via link deletion // /////////////////////////////////////////////// reset(); String assocClassName = "AC1"; pName1 = "o5"; pName2 = "o6"; linkedObject1 = getObjectByVarName(pName1); assertNotNull(linkedObject1); linkedObject2 = getObjectByVarName(pName2); assertNotNull(linkedObject1); MObject linkObject = getObjectByVarName("lo1"); assertNotNull(linkObject); MLink link = getLink(assocClassName, linkedObject1, linkedObject2); assertSame(linkObject, link); statement = "delete " + "(" + pName1 + ", " + pName2 + ") from " + assocClassName; evaluateStatement(statement); // link + link object gone assertFalse(fState.allLinks().contains(link)); assertFalse(fState.allObjects().contains(linkObject)); } @Test public void testConditional() throws MSystemException { ////////////////////// // condition = true // ////////////////////// String varName = "v"; int thenVal = 41; int elseVal = 43; String condition = "true"; String statement = "if " + condition + " then " + varName + " := " + thenVal + " else " + varName + " := " + elseVal + " end"; // there is a variable "v" of type integer with value 42 Value varVal = lookUpVar(varName); assertNotNull(varVal); assertTrue(varVal instanceof IntegerValue); assertEquals(((IntegerValue)varVal).value(), 42); evaluateStatement(statement); // value should now be the then value varVal = lookUpVar(varName); assertNotNull(varVal); assertTrue(varVal instanceof IntegerValue); assertEquals(((IntegerValue)varVal).value(), thenVal); ////////// // undo // ////////// undo(); varVal = lookUpVar(varName); assertNotNull(varVal); assertTrue(varVal instanceof IntegerValue); assertEquals(((IntegerValue)varVal).value(), 42); ////////// // redo // ////////// redo(); varVal = lookUpVar(varName); assertNotNull(varVal); assertTrue(varVal instanceof IntegerValue); assertEquals(((IntegerValue)varVal).value(), thenVal); /////////////////////// // condition = false // /////////////////////// reset(); condition = "false"; statement = "if " + condition + " then " + varName + " := " + thenVal + " else " + varName + " := " + elseVal + " end"; // there is a variable "v" of type integer with value 42 varVal = lookUpVar(varName); assertNotNull(varVal); assertTrue(varVal instanceof IntegerValue); assertEquals(((IntegerValue)varVal).value(), 42); evaluateStatement(statement); // value should now be the else value varVal = lookUpVar(varName); assertNotNull(varVal); assertTrue(varVal instanceof IntegerValue); assertEquals(((IntegerValue)varVal).value(), elseVal); /////////////////////////////////////// // condition = oclUndefined(Boolean) // /////////////////////////////////////// reset(); condition = "oclUndefined(Boolean)"; statement = "if " + condition + " then " + varName + " := " + thenVal + " else " + varName + " := " + elseVal + " end"; // there is a variable "v" of type integer with value 42 varVal = lookUpVar(varName); assertNotNull(varVal); assertTrue(varVal instanceof IntegerValue); assertEquals(((IntegerValue)varVal).value(), 42); evaluateStatement(statement); // value should now be the else value varVal = lookUpVar(varName); assertNotNull(varVal); assertTrue(varVal instanceof IntegerValue); assertEquals(((IntegerValue)varVal).value(), elseVal); ////////////////////////////////////////////////// // variables created inside conditionals vanish // ////////////////////////////////////////////////// reset(); varName = "asdf"; statement = "if true then " + varName + " := 12 end"; assertNull(lookUpVar(varName)); evaluateStatement(statement); assertNotNull(lookUpVar(varName)); } @Test public void testIteration() throws MSystemException { /////////////////// // silly example // /////////////////// String statement = "sum := 0; " + "for x in Sequence{1..10} do sum := sum + x end;"; evaluateStatement(statement); // java equivalent of soil code int sum = 0; for (int x = 1; x <= 10; ++x) { sum += x; } assertEquals(IntegerValue.valueOf(sum), lookUpVar("sum")); /////////////////////////////////////////////////// // iteration variable shadows existing variables // /////////////////////////////////////////////////// reset(); statement = "x := 12; y := 13; for x in Set{0} do y := x end"; evaluateStatement(statement); assertEquals(lookUpVar("y"), IntegerValue.valueOf(0)); //////////////////////////////////////////////// // variables created inside iterations vanish // //////////////////////////////////////////////// reset(); statement = "for x in Set{0} do y := x end"; assertNull(lookUpVar("y")); evaluateStatement(statement); assertNotNull(lookUpVar("y")); } @Test public void testOperationCall() throws MSystemException { ///////////////////////// // failed precondition // ///////////////////////// String objVarName = "o1"; // this operation fails to fulfill the pre conditions String opName = "failEnter"; String statement = objVarName + "." + opName + "()"; // hide output fTestSystem.getSystem().registerPPCHandlerOverride( new SoilPPCHandler( NullPrintWriter.getInstance())); boolean caughtException = false; try { evaluateStatement(statement); } catch (MSystemException e) { caughtException = true; } assertTrue(caughtException); // call stack should be empty assertTrue(fTestSystem.getSystem().getCallStack().isEmpty()); ////////////////////////// // failed postcondition // ////////////////////////// // this operation fails to fulfill the post conditions opName = "failExit"; statement = objVarName + "." + opName + "()"; caughtException = false; try { evaluateStatement(statement); } catch (MSystemException e) { caughtException = true; } assertTrue(caughtException); // call stack should be empty assertTrue(fTestSystem.getSystem().getCallStack().isEmpty()); //////////////// // proxy fail // //////////////// // this operation does not violate pre- or post conditions itself, // but calls another operation which does opName = "proxyFail"; statement = objVarName + "." + opName + "()"; caughtException = false; try { evaluateStatement(statement); } catch (MSystemException e) { caughtException = true; } assertTrue(caughtException); // call stack should be empty assertTrue(fTestSystem.getSystem().getCallStack().isEmpty()); } @Test public void testOpEnterOpExit() throws MSystemException { ///////////// // openter // ///////////// String objVarName = "o1"; String opName = "u1"; String statement = "openter " + objVarName + " " + opName + "()"; // object exists MObject object = getObjectByVarName(objVarName); assertNotNull(object); // call stack is empty assertTrue(fTestSystem.getSystem().getCallStack().isEmpty()); evaluateStatement(statement); // one item on the call stack now assertEquals(fTestSystem.getSystem().getCallStack().size(), 1); // which happens to be the called operation MOperationCall opCall = fTestSystem.getSystem().getCurrentOperation(); MObject self = opCall.getSelf(); assertSame(self, object); assertEquals(opCall.getOperation().name(), opName); ////////// // undo // ////////// undo(); // undo should result in the call stack being empty assertTrue(fTestSystem.getSystem().getCallStack().isEmpty()); ////////// // redo // ////////// redo(); // redo should have the original effect again assertEquals(fTestSystem.getSystem().getCallStack().size(), 1); opCall = fTestSystem.getSystem().getCurrentOperation(); self = opCall.getSelf(); assertSame(self, object); assertEquals(opCall.getOperation().name(), opName); ////////////////////////////////////// // opexit with missing result value // ////////////////////////////////////// statement = "opexit"; // opexit with improper result value should result in the operation // still being on the stack boolean exceptionCaught = false; try { evaluateStatement(statement); } catch (MSystemException e) { exceptionCaught = true; } assertTrue(exceptionCaught); assertEquals(fTestSystem.getSystem().getCallStack().size(), 1); opCall = fTestSystem.getSystem().getCurrentOperation(); self = opCall.getSelf(); assertSame(self, object); assertEquals(opCall.getOperation().name(), opName); ////////////////////////////////////// // opexit with correct result value // ////////////////////////////////////// statement = "opexit 'asdf'"; evaluateStatement(statement); // a proper opexit should result in an empty call stack assertTrue(fTestSystem.getSystem().getCallStack().isEmpty()); ////////// // undo // ////////// undo(); assertEquals(fTestSystem.getSystem().getCallStack().size(), 1); opCall = fTestSystem.getSystem().getCurrentOperation(); self = opCall.getSelf(); assertSame(self, object); assertEquals(opCall.getOperation().name(), opName); ////////// // redo // ////////// redo(); assertTrue(fTestSystem.getSystem().getCallStack().isEmpty()); } private Value lookUpVar( String varName, VariableEnvironment varEnv) { return varEnv.lookUp(varName); } private Value lookUpVar(String varName) { return lookUpVar(varName, fTestSystem.getVarEnv()); } private MObject getObject(String objectName, MSystemState state) { return state.objectByName(objectName); } private MObject getObject(String objectName) { return getObject(objectName, fTestSystem.getState()); } private MObject getObjectByVarName(String varName, VariableEnvironment varEnv) { Value varVal = lookUpVar(varName, varEnv); if (varVal == null) { return null; } if (varVal instanceof ObjectValue) { return ((ObjectValue)varVal).value(); } return null; } private MObject getObjectByVarName(String varName) { return getObjectByVarName(varName, fTestSystem.getVarEnv()); } private Value getAttVal(MObject object, String attName) { if (fState.allObjects().contains(object)) { return object.state(fState).attributeValue(attName); } return null; } private List<String> getNewVars() { List<String> result = new ArrayList<String>(fTestSystem.getVarEnv().getCurrentMappings().keySet()); result.removeAll(fOldVarEnv.getCurrentMappings().keySet()); return result; } private List<MObject> getNewObjects() { List<MObject> result = new ArrayList<MObject>(fTestSystem.getState().allObjects()); result.removeAll(fOldState.allObjects()); return result; } private List<MLink> getNewLinks() { List<MLink> result = new ArrayList<MLink>(fTestSystem.getState().allLinks()); result.removeAll(fOldState.allLinks()); return result; } private MLink getLink(String assocName, MObject... participants) { List<MObject> partList = Arrays.asList(participants); for (MLink link : fTestSystem.getState().allLinks()) { if ((link.association().name().equals(assocName)) && (link.linkedObjects().containsAll(partList)) && (partList.containsAll(link.linkedObjects()))) { return link; } } return null; } private void undo() throws MSystemException { fTestSystem.getSystem().undoLastStatement(); } private void redo() throws MSystemException { fTestSystem.getSystem().redoStatement(); } public void evaluateStatement(String statement) throws MSystemException { systemApi.getSystem().execute(generateStatement(statement)); } private MStatement generateStatement(String input) { return ShellCommandCompiler.compileShellCommand( systemApi.getSystem().model(), systemApi.getSystem().state(), systemApi.getSystem().getVariableEnvironment(), input, "<input>", NullPrintWriter.getInstance(), false); } }
26.14194
91
0.640346
bf9070add54ff7943b115a8b136dbeee0a42af47
5,981
package net.ims.jcms.extras; import net.ims.jcms.*; import java.io.FileNotFoundException; import java.sql.ResultSet; import java.sql.SQLException; import java.text.SimpleDateFormat; import javax.naming.NamingException; import javax.servlet.ServletContext; /** * Extends Record to contain the data for a single paymentoptions record. * Provides methods for inserting, updating, deleting, validation, and implements the Comparable interface for sorting. * * @author Sam Hokin <[email protected]> */ public class PaymentOption extends Record { /** the name of the database table, used by audit method */ private static String tablename = "paymentoptions"; /** paymentoptions.paymentoption_id: the primary key for this record */ public int paymentoption_id = 0; /** paymentoptions.payment_id: primary key of parent payments record */ public int payment_id = 0; /** paymentoptions.num: used for sorting paymentoptions on the same day */ public int num = 0; /** paymentoptions.amount */ public double amount = 0.00; /** paymentoptions.name: the paymentoption name */ public String name = null; /** paymentoptions.description */ public String description = null; /** * Construct a default paymentoptions object */ public PaymentOption() { setDefaults(); } /** * Construct given DB connection and an int primary key */ public PaymentOption(DB db, int key) throws SQLException { select(db, key); } /** * Construct given a Servlet context and primary key */ public PaymentOption(ServletContext context, int key) throws SQLException, FileNotFoundException, NamingException, ClassNotFoundException { DB db = null; try { db = new DB(context); select(db, key); } finally { if (db!=null) db.close(); } } /** * Construct from a populated ResultSet */ public PaymentOption(ResultSet rs) throws SQLException { populate(rs); } /** * Populate this instance from the given ResultSet */ protected void populate(ResultSet rs) throws SQLException { paymentoption_id = rs.getInt("paymentoption_id"); num = rs.getInt("num"); amount = rs.getDouble("amount"); name = rs.getString("name"); description = rs.getString("description"); } /** * Refresh this instance with values from the database record */ protected void refresh(DB db) throws SQLException { select(db, paymentoption_id); } /** * Throw a ValidationException of the instance variables fail validation rules. */ protected void validate() throws ValidationException { String error = ""; if (num<=0) error += "Payment option num must be a positive number. "; if (Util.nullOrEmpty(name)) error += "Payment option name is required. "; if (error.length()>0) throw new ValidationException(error); } /** * Do a SELECT query and set instance variables given a DB connection and a primary key */ protected void select(DB db, int key) throws SQLException { db.executeQuery("SELECT * FROM paymentoptions WHERE paymentoption_id="+key); if (db.rs.next()) populate(db.rs); } /** * Insert a new paymentoption record into the database and retrieve/set the resulting paymentoption_id. */ protected void insert(DB db) throws SQLException, ValidationException { validate(); description = Util.replaceLineBreaks(description); String query = "INSERT INTO paymentoptions (" + "payment_id,num,amount,name,description" + ") VALUES (" + intOrNull(payment_id)+"," + intOrNull(num)+"," + amount+"," + charsOrNull(name)+"," + charsOrNull(description) + ")"; db.executeUpdate(query); db.executeQuery("SELECT max(paymentoption_id) AS paymentoption_id FROM paymentoptions"); db.rs.next(); paymentoption_id = db.rs.getInt("paymentoption_id"); // refresh record to reflect current state select(db, paymentoption_id); } /** * Update the paymentoptions record. */ protected void update(DB db) throws SQLException, ValidationException { validate(); description = Util.replaceLineBreaks(description); String query = "UPDATE paymentoptions SET " + "num="+intOrNull(num)+"," + "amount="+amount+"," + "name="+charsOrNull(name)+"," + "description="+charsOrNull(description)+" " + "WHERE paymentoption_id="+paymentoption_id; db.executeUpdate(query); // refresh record to reflect current state select(db, paymentoption_id); } /** * Delete the current record, and reset to defaults. */ protected void delete(DB db) throws SQLException, ValidationException { db.executeUpdate("DELETE FROM paymentoptions WHERE paymentoption_id="+paymentoption_id); setDefaults(); } /** * Set default values when instance does not correspond to a database record (such as after delete() is called */ protected void setDefaults() { paymentoption_id = 0; num = 0; amount = 0.00; name = null; description = null; } /** * Return true if this is a default, uninstantiated instance */ public boolean isDefault() { return paymentoption_id==0; } /** * Insert an audit record for the given action */ protected void audit(DB db, char action, String username) throws SQLException { Audit a = new Audit(); a.tablename = tablename; a.record_id = paymentoption_id; a.action = action; a.username = username; a.description = name; a.insert(db); } /** * Compare two records based on date, num, name */ public int compareTo(Object o) { PaymentOption that = (PaymentOption)o; if (this.num==that.num) { return this.name.compareTo(that.name); } else { return this.num - that.num; } } /** * Return true if same primary key */ public boolean equals(Object o) { PaymentOption that = (PaymentOption) o; return this.paymentoption_id==that.paymentoption_id; } }
28.079812
141
0.676476
064323608e74cd392ccb88abadc9b93a6d0213bc
4,926
/* * Copyright (c) 2021 The lambda4j 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.lambda4j.runnable; import java.util.Objects; import javax.annotation.CheckForNull; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.lambda4j.Lambda; /** * The {@link Runnable} interface should be implemented by any class whose instances are intended to be executed by a * thread. The class must define a method of no arguments called {@link #run()}. This extension is able to throw any * {@link Throwable}. * <p> * This interface is designed to provide a common protocol for objects that wish to execute code while they are active. * For example, {@code Runnable} is implemented by class {@link Thread}. Being active simply means that a thread has * been started and has not yet been stopped. * <p> * In addition, {@code Runnable} provides the means for a class to be active while not subclassing {@code Thread}. A * class that implements {@code Runnable} can run without subclassing {@code Thread} by instantiating a {@code Thread} * instance and passing itself in as the target. In most cases, the {@code Runnable} interface should be used if you are * only planning to override the {@link #run()} method and no other {@code Thread} methods. This is important because * classes should not be subclassed unless the programmer intends on modifying or enhancing the fundamental behavior of * the class. * <p> * This is a {@link FunctionalInterface} whose functional method is {@link #run()}. * * @apiNote This is a JDK lambda. * @see Runnable */ @SuppressWarnings("unused") @FunctionalInterface public interface Runnable2 extends Lambda, Runnable { /** * Constructs a {@link Runnable2} based on a lambda expression or a method reference. Thereby the given lambda * expression or method reference is returned on an as-is basis to implicitly transform it to the desired type. With * this method, it is possible to ensure that correct type is used from lambda expression or method reference. * * @param expression A lambda expression or (typically) a method reference, e.g. {@code this::method} * @return A {@code Runnable2} from given lambda expression or method reference. * @implNote This implementation allows the given argument to be {@code null}, but only if {@code null} given, * {@code null} will be returned. * @see <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html#syntax">Lambda * Expression</a> * @see <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html">Method Reference</a> */ @CheckForNull @Nullable static Runnable2 of(@Nullable Runnable2 expression) { return expression; } /** * Calls the given {@link Runnable} with the given argument and returns its result. * * @param runnable The runnable to be called * @throws NullPointerException If given argument is {@code null} */ static void call(@Nonnull Runnable runnable) { Objects.requireNonNull(runnable); runnable.run(); } /** * Applies this runnable to the given argument. */ @Override void run(); /** * Returns the number of arguments for this runnable. * * @return The number of arguments for this runnable. * @implSpec The default implementation always returns {@code 0}. */ @Nonnegative default int arity() { return 0; } /** * Returns a composed {@link Runnable2} that performs, in sequence, this runnable followed by the {@code after} * runnable. If evaluation of either operation throws an exception, it is relayed to the caller of the composed * operation. If performing this runnable throws an exception, the {@code after} runnable will not be performed. * * @param after The runnable to apply after this runnable is applied * @return A composed {@link Runnable2} that performs, in sequence, this runnable followed by the {@code after} * runnable. * @throws NullPointerException If given argument is {@code null} */ @Nonnull default Runnable2 andThen(@Nonnull Runnable after) { Objects.requireNonNull(after); return () -> { run(); after.run(); }; } }
41.394958
120
0.703004
5a4168248b828015bbcac13a70fcf0f14d3dda01
414
public class ForLoops { /* * For loops work just like while loops, but with everything * you need to manage the loop all in one place */ public static void main(String[] args) { // i = i + 1 can be written as i++ // i = i - 1 can be written as i-- for( int i = 0; i < 100; i--){ if(i % 2 == 0){ System.out.println(i + " - even"); } else { System.out.println(i + " - odd"); } } } }
20.7
60
0.555556
cae9dd2bf8be863d930bd7f89ade4c0f2baf8c38
220
package com.todo.client; /** * A routing function that matches all todo items. */ public class ToDoRoutingAll implements ToDoRoutingFunction { @Override public boolean matches(ToDoItem item) { return true; } }
15.714286
60
0.740909
21776137f479d27834d5b86030c102991f20fb9c
2,817
package org.tahom.repository.dao; import java.util.List; import org.sqlproc.engine.SqlControl; import org.sqlproc.engine.SqlRowProcessor; import org.sqlproc.engine.SqlSession; import org.tahom.repository.model.Player; @SuppressWarnings("all") public interface PlayerDao { public Player insert(final SqlSession sqlSession, final Player player, SqlControl sqlControl); public Player insert(final Player player, SqlControl sqlControl); public Player insert(final SqlSession sqlSession, final Player player); public Player insert(final Player player); public Player get(final SqlSession sqlSession, final Player player, SqlControl sqlControl); public Player get(final Player player, SqlControl sqlControl); public Player get(final SqlSession sqlSession, final Player player); public Player get(final Player player); public int update(final SqlSession sqlSession, final Player player, SqlControl sqlControl); public int update(final Player player, SqlControl sqlControl); public int update(final SqlSession sqlSession, final Player player); public int update(final Player player); public int delete(final SqlSession sqlSession, final Player player, SqlControl sqlControl); public int delete(final Player player, SqlControl sqlControl); public int delete(final SqlSession sqlSession, final Player player); public int delete(final Player player); public List<Player> list(final SqlSession sqlSession, final Player player, SqlControl sqlControl); public List<Player> list(final Player player, SqlControl sqlControl); public List<Player> list(final SqlSession sqlSession, final Player player); public List<Player> list(final Player player); public int query(final SqlSession sqlSession, final Player player, SqlControl sqlControl, final SqlRowProcessor<Player> sqlRowProcessor); public int query(final Player player, SqlControl sqlControl, final SqlRowProcessor<Player> sqlRowProcessor); public int query(final SqlSession sqlSession, final Player player, final SqlRowProcessor<Player> sqlRowProcessor); public int query(final Player player, final SqlRowProcessor<Player> sqlRowProcessor); public List<Player> listFromTo(final SqlSession sqlSession, final Player player, SqlControl sqlControl); public List<Player> listFromTo(final Player player, SqlControl sqlControl); public List<Player> listFromTo(final SqlSession sqlSession, final Player player); public List<Player> listFromTo(final Player player); public int count(final SqlSession sqlSession, final Player player, SqlControl sqlControl); public int count(final Player player, SqlControl sqlControl); public int count(final SqlSession sqlSession, final Player player); public int count(final Player player); }
37.56
139
0.781328
edcf3131515b26fc882a7c704d81b3a9557adefb
9,584
package com.gameplaycoder.thunderjack.players; import android.support.constraint.Guideline; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.gameplaycoder.thunderjack.cards.Card; import com.gameplaycoder.thunderjack.utils.cardsTweener.CardsTweener; import java.util.ArrayList; import java.util.HashMap; public class BasePlayerData { //========================================================================= // members //========================================================================= private final PlayerIds m_playerId; private ArrayList<String>m_cardKeys; private BaseHandData m_handData; private boolean m_hasBlackjack; private boolean m_isBust; private int m_score; //========================================================================= // public //========================================================================= //------------------------------------------------------------------------- // ctor //------------------------------------------------------------------------- public BasePlayerData(ViewGroup viewGroup, PlayerIds playerId, float xDeck, float yDeck, int maxCardsPerHand, Guideline guideCardsLeft, Guideline guideCardsRight, Guideline guideCardsTop, Guideline guideCardsBottom, Guideline guideCardsUi, int cardImageWidth, TextView scoreText, ImageView resultImage, HashMap<String, Object> extraParams) { m_cardKeys = new ArrayList<>(); m_playerId = playerId; m_handData = onCreateHandData(viewGroup, xDeck, yDeck, maxCardsPerHand, guideCardsLeft, guideCardsRight, guideCardsTop, guideCardsBottom, guideCardsUi, cardImageWidth, scoreText, resultImage, extraParams); m_score = 0; resetStatus(); } //------------------------------------------------------------------------- // addCard //------------------------------------------------------------------------- public void addCard(Card card, CardsTweener cardsTweener, long startDelay, long moveDuration, boolean startAnimation, int cardImageIndex, boolean isCardBeingDealt) { if (card == null || cardsTweener == null) { return; //sanity check } m_cardKeys.add(card.getKey()); m_handData.addCard(card, cardsTweener, startDelay, moveDuration, startAnimation, cardImageIndex, isCardBeingDealt); } //------------------------------------------------------------------------- // fadeOutAllCards //------------------------------------------------------------------------- public void fadeOutAllCards(CardsTweener cardsTweener, long fadeOutDelay, boolean startAnimation) { m_handData.fadeOutAllCards(cardsTweener, fadeOutDelay, startAnimation); } //------------------------------------------------------------------------- // getCardKetAt //------------------------------------------------------------------------- public String getCardKetAt(int index) { return(0 <= index && index < m_cardKeys.size() ? m_cardKeys.get(index) : null); } //------------------------------------------------------------------------- // getCardKeys //------------------------------------------------------------------------- public ArrayList<String> getCardKeys() { int size = m_cardKeys.size(); ArrayList<String> out_keys = new ArrayList<String>(size); for (int index = 0; index < size; index++) { out_keys.add(m_cardKeys.get(index)); } return(out_keys); } //------------------------------------------------------------------------- // getCardFaceUp //------------------------------------------------------------------------- public boolean getCardFaceUp(int cardIndex) { return(m_handData.getCardFaceUp(cardIndex)); } //------------------------------------------------------------------------- // getFaceUpCardKeys //------------------------------------------------------------------------- public ArrayList<String> getFaceUpCardKeys(boolean isFaceUp) { ArrayList<String> out_keys = new ArrayList<>(); int size = m_cardKeys.size(); for (int index = 0; index < size; index++) { if (m_handData.getCardFaceUp(index) == isFaceUp) { out_keys.add(m_cardKeys.get(index)); } } return(out_keys); } //------------------------------------------------------------------------- // getHasBlackjack //------------------------------------------------------------------------- public boolean getHasBlackjack() { return(m_hasBlackjack); } //------------------------------------------------------------------------- // getId //------------------------------------------------------------------------- public PlayerIds getId() { return(m_playerId); } //------------------------------------------------------------------------- // getIsBust //------------------------------------------------------------------------- public boolean getIsBust() { return(m_isBust); } //------------------------------------------------------------------------- // getNumCards //------------------------------------------------------------------------- public int getNumCards() { return(m_cardKeys.size()); } //------------------------------------------------------------------------- // getScore //------------------------------------------------------------------------- public int getScore() { return(m_score); } //------------------------------------------------------------------------- // removeAllCards //------------------------------------------------------------------------- public void removeAllCards() { m_cardKeys.clear(); m_handData.removeAllCards(); } //------------------------------------------------------------------------- // popTopCard //------------------------------------------------------------------------- public Card popTopCard(CardsTweener cardsTweener, long startDelay, long moveDuration, boolean startAnimation) { if (cardsTweener == null) { return(null); //sanity check } if (m_cardKeys.size() == 0) { return(null); //nothing to remove } m_cardKeys.remove(m_cardKeys.size() - 1); return(m_handData.popTopCard(cardsTweener, startDelay, moveDuration, startAnimation)); } //------------------------------------------------------------------------- // resetStatus //------------------------------------------------------------------------- public void resetStatus() { m_hasBlackjack = m_isBust = false; } //------------------------------------------------------------------------- // setBlackjack //------------------------------------------------------------------------- public void setBlackjack() { m_hasBlackjack = true; } //------------------------------------------------------------------------- // setBust //------------------------------------------------------------------------- public void setBust() { m_isBust = true; } //------------------------------------------------------------------------- // setCardFaceUp //------------------------------------------------------------------------- public void setCardFaceUp(int cardIndex, boolean isFaceUp) { m_handData.setCardFaceUp(cardIndex, isFaceUp); } //------------------------------------------------------------------------- // setResultImage //------------------------------------------------------------------------- public void setResultImage(int drawableResourceId) { m_handData.setResultImage(drawableResourceId); } //------------------------------------------------------------------------- // setResultImageVisible //------------------------------------------------------------------------- public void setResultImageVisible(boolean isVisible) { m_handData.setResultImageVisible(isVisible); } //------------------------------------------------------------------------- // setScore //------------------------------------------------------------------------- public void setScore(int value) { m_score = value; m_handData.setScoreText(m_score); } //------------------------------------------------------------------------- // setScoreTextVisible //------------------------------------------------------------------------- public void setScoreTextVisible(boolean isVisible) { m_handData.setScoreTextVisible(isVisible); } //========================================================================= // protected //========================================================================= //------------------------------------------------------------------------- // getHandData //------------------------------------------------------------------------- protected BaseHandData getHandData() { return(m_handData); } //------------------------------------------------------------------------- // onCreateHandData //------------------------------------------------------------------------- protected BaseHandData onCreateHandData(ViewGroup viewGroup, float xDeck, float yDeck, int maxCardsPerHand, Guideline guideCardsLeft, Guideline guideCardsRight, Guideline guideCardsTop, Guideline guideCardsBottom, Guideline guideCardsUi, int cardImageWidth, TextView textView, ImageView resultImage, HashMap<String, Object> extraParams) { return(new BaseHandData(viewGroup, xDeck, yDeck, maxCardsPerHand, guideCardsLeft, guideCardsRight, guideCardsTop, guideCardsBottom, guideCardsUi, cardImageWidth, textView, resultImage, extraParams)); } }
38.645161
102
0.406407
be821e8d8e3557317a6ffc712ce74f4a54d6dcb5
2,078
/* * Copyright (c) 2020 Dario Lucia (https://www.dariolucia.eu) * * 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 eu.dariolucia.reatmetric.driver.automation.definition; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.bind.annotation.*; import java.io.IOException; import java.io.InputStream; @XmlRootElement(name = "automation", namespace = "http://dariolucia.eu/reatmetric/driver/automation") @XmlAccessorType(XmlAccessType.FIELD) public class AutomationConfiguration { public static AutomationConfiguration load(InputStream is) throws IOException { try { JAXBContext jc = JAXBContext.newInstance(AutomationConfiguration.class); Unmarshaller u = jc.createUnmarshaller(); AutomationConfiguration o = (AutomationConfiguration) u.unmarshal(is); return o; } catch (JAXBException e) { throw new IOException(e); } } @XmlElement(name = "max-parallel-scripts") private int maxParallelScripts = 1; @XmlElement(name = "script-folder", required = true) private String scriptFolder; public int getMaxParallelScripts() { return maxParallelScripts; } public void setMaxParallelScripts(int maxParallelScripts) { this.maxParallelScripts = maxParallelScripts; } public String getScriptFolder() { return scriptFolder; } public void setScriptFolder(String scriptFolder) { this.scriptFolder = scriptFolder; } }
32.984127
101
0.714148
32d19404d3b9197eb236d10bc85a105cc2afc974
4,561
/* * Created on Wed Sep 30 2020 * * Copyright (c) storycraft. Licensed under the MIT Licence. */ package sh.pancake.launcher; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.net.URL; import java.util.Optional; import java.util.ServiceLoader; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.spongepowered.asm.launch.MixinBootstrap; import org.spongepowered.asm.mixin.MixinEnvironment; import sh.pancake.launcher.classloader.DynamicURLClassLoader; import sh.pancake.launcher.classloader.ModdedClassLoader; import sh.pancake.launcher.classloader.ServerClassLoader; import sh.pancake.launcher.mod.MixinClassModder; import sh.pancake.sauce.RemapInfo; public class PancakeLauncher { private static final Logger LOGGER = LogManager.getLogger("PancakeLauncher"); private static PancakeLauncher launcher; public static PancakeLauncher getLauncher() { return launcher; } private IPancakeServer server; private ServerClassLoader serverClassLoader; private PancakeLauncher(IPancakeServer server, ServerClassLoader serverClassLoader) { this.server = server; this.serverClassLoader = serverClassLoader; } public ServerClassLoader getServerClassLoader() { return serverClassLoader; } public IPancakeServer getServer() { return server; } private void finishMixin() { try { Method m = MixinEnvironment.class.getDeclaredMethod("gotoPhase", MixinEnvironment.Phase.class); m.setAccessible(true); m.invoke(null, MixinEnvironment.Phase.INIT); m.invoke(null, MixinEnvironment.Phase.DEFAULT); } catch (Exception e) { throw new RuntimeException(e); } } private static String findTargetVersion(ClassLoader loader) throws IOException { try (InputStream stream = loader.getResourceAsStream("target_version")) { return new String(stream.readAllBytes()); } } private static DynamicURLClassLoader prepareServerClassLoader(File serverFile) throws Exception { DynamicURLClassLoader loader = new DynamicURLClassLoader(new URL[] { serverFile.toURI().toURL() }, PancakeLauncher.class.getClassLoader()); String version; try { version = findTargetVersion(loader); } catch (IOException e) { loader.close(); throw new Exception("Failed to read required server version from server file. File may be corrupted or invalid.", e); } LOGGER.info("Waiting Minecraft server " + version + " to be provided..."); Logger patchLogger = LogManager.getLogger("ServerRemapper"); MappedServerProvider provider = new MappedServerProvider(version, new File("patches")); File mcServerFile; try { mcServerFile = provider.provideServer( false, (RemapInfo info) -> patchLogger.info("PATCHING " + info.getFromName() + " -> " + info.getToName()) ); } catch (Exception e) { loader.close(); throw new Exception("Server preparing process failed with error. Server cannot be started.", e); } loader.addURL(mcServerFile.toURI().toURL()); MixinBootstrap.init(); return loader; } public static PancakeLauncher launch(File serverFile, String[] args) throws Exception { if (launcher != null) throw new RuntimeException("Launcher already created"); DynamicURLClassLoader innerClassLoader = prepareServerClassLoader(serverFile); ServerClassLoader serverClassLoader = new ServerClassLoader(new ModdedClassLoader(innerClassLoader, new MixinClassModder())); Thread.currentThread().setContextClassLoader(serverClassLoader); ServiceLoader<IPancakeServer> serverLoader = ServiceLoader.load(IPancakeServer.class); Optional<IPancakeServer> serverOptional = serverLoader.findFirst(); if (!serverOptional.isPresent()) throw new Exception("Cannot find IPancakeServer instance. Server cannot be started."); IPancakeServer server = serverOptional.get(); PancakeLauncher launcher = PancakeLauncher.launcher = new PancakeLauncher(server, serverClassLoader); LOGGER.info("Launching " + server.getClass().getSimpleName() + "..."); server.start(args, innerClassLoader::addURL, launcher::finishMixin); return launcher; } }
35.632813
147
0.696558
39f9774c3934b22949b3d5c70fe73a1e3fa8154a
746
package com.applicaster.plugin.player.dirtvision; import android.content.Context; import android.content.Intent; import android.os.Bundle; import com.applicaster.jwplayerplugin.JWPlayerActivity; import com.applicaster.plugin_manager.playersmanager.Playable; public class DIRTVisionPlayerActivity extends JWPlayerActivity { private static final String PLAYABLE_KEY = "playable"; public static void startPlayerActivity(Context context, Playable playable) { Intent intent = new Intent(context, DIRTVisionPlayerActivity.class); Bundle bundle = new Bundle(); bundle.putSerializable(DIRTVisionPlayerActivity.PLAYABLE_KEY, playable); intent.putExtras(bundle); context.startActivity(intent); } }
32.434783
80
0.77748
e2f0e4e8a42f002d58b4e28a813fcd51b77cb9b1
6,302
/******************************************************************************* * Copyright 2016 Elix_x * * 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 code.elix_x.excore.utils.net.packets; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import java.util.function.Function; import code.elix_x.excore.utils.net.packets.runnable.ClientRunnableMessageHandler; import code.elix_x.excore.utils.net.packets.runnable.RunnableMessageHandler; import code.elix_x.excore.utils.net.packets.runnable.ServerRunnableMessageHandler; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.network.NetworkRegistry; import net.minecraftforge.fml.common.network.simpleimpl.IMessage; import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper; import net.minecraftforge.fml.relauncher.Side; public class SmartNetworkWrapper { private final String name; private SimpleNetworkWrapper channel; private int nextPacketId = 0; private Map<Class<? extends IMessage>, Side> packetsReceivingSide = new HashMap<Class<? extends IMessage>, Side>(); public SmartNetworkWrapper(String name){ this.name = name; channel = NetworkRegistry.INSTANCE.newSimpleChannel(name); } /* * Getters */ public String getName(){ return name; } public SimpleNetworkWrapper getChannel(){ return channel; } public int getNextPacketId(){ return nextPacketId; } public Side getPacketReceivingSide(Class<? extends IMessage> clazz){ return packetsReceivingSide.get(clazz); } /* * Register */ public <REQ extends IMessage, REPLY extends IMessage> void registerMessage(Class<? extends IMessageHandler<REQ, REPLY>> messageHandler, Class<REQ> requestMessageType, Side side){ channel.registerMessage(messageHandler, requestMessageType, nextPacketId, side); packetsReceivingSide.put(requestMessageType, side); nextPacketId++; } public <REQ extends IMessage, REPLY extends IMessage> void registerMessage(IMessageHandler<? super REQ, ? extends REPLY> messageHandler, Class<REQ> requestMessageType, Side side){ channel.registerMessage(messageHandler, requestMessageType, nextPacketId, side); packetsReceivingSide.put(requestMessageType, side); nextPacketId++; } /* * Runnable */ public <REQ extends IMessage, REPLY extends IMessage> void registerMessage(Function<Pair<REQ, MessageContext>, Pair<Runnable, REPLY>> onReceive, Class<REQ> requestMessageType, Side side){ RunnableMessageHandler<REQ, REPLY> handler = new ServerRunnableMessageHandler<REQ, REPLY>(onReceive); if(side == Side.CLIENT && FMLCommonHandler.instance().getSide() == Side.CLIENT){ handler = new ClientRunnableMessageHandler<REQ, REPLY>(onReceive); } registerMessage(handler, requestMessageType, side); } public <REQ extends IMessage> void registerMessage1(final Function<Pair<REQ, MessageContext>, Runnable> onReceive, Class<REQ> requestMessageType, Side side){ registerMessage(new Function<Pair<REQ, MessageContext>, Pair<Runnable, IMessage>>(){ @Override public Pair<Runnable, IMessage> apply(Pair<REQ, MessageContext> t){ return new ImmutablePair<Runnable, IMessage>(onReceive.apply(t), null); } }, requestMessageType, side); } public <REQ extends IMessage, REPLY extends IMessage> void registerMessage2(final Function<REQ, Pair<Runnable, REPLY>> onReceive, Class<REQ> requestMessageType, Side side){ registerMessage(new Function<Pair<REQ, MessageContext>, Pair<Runnable, REPLY>>(){ @Override public Pair<Runnable, REPLY> apply(Pair<REQ, MessageContext> t){ return onReceive.apply(t.getKey()); } }, requestMessageType, side); } public <REQ extends IMessage> void registerMessage3(final Function<REQ, Runnable> onReceive, Class<REQ> requestMessageType, Side side){ registerMessage(new Function<Pair<REQ, MessageContext>, Pair<Runnable, IMessage>>(){ @Override public Pair<Runnable, IMessage> apply(Pair<REQ, MessageContext> t){ return new ImmutablePair<Runnable, IMessage>(onReceive.apply(t.getKey()), null); } }, requestMessageType, side); } public <REQ extends IMessage> void registerMessage(final Runnable onReceive, Class<REQ> requestMessageType, Side side){ registerMessage(new Function<Pair<REQ, MessageContext>, Pair<Runnable, IMessage>>(){ @Override public Pair<Runnable, IMessage> apply(Pair<REQ, MessageContext> t){ return new ImmutablePair<Runnable, IMessage>(onReceive, null); } }, requestMessageType, side); } /* * Sending */ public void sendToAll(IMessage message){ if(packetsReceivingSide.get(message.getClass()) == Side.CLIENT){ channel.sendToAll(message); } } public void sendTo(IMessage message, EntityPlayerMP player){ if(packetsReceivingSide.get(message.getClass()) == Side.CLIENT){ channel.sendTo(message, player); } } public void sendToAllAround(IMessage message, NetworkRegistry.TargetPoint point){ if(packetsReceivingSide.get(message.getClass()) == Side.CLIENT){ channel.sendToAllAround(message, point); } } public void sendToDimension(IMessage message, int dimensionId){ if(packetsReceivingSide.get(message.getClass()) == Side.CLIENT){ channel.sendToDimension(message, dimensionId); } } public void sendToServer(IMessage message){ if(packetsReceivingSide.get(message.getClass()) == Side.SERVER && FMLCommonHandler.instance().getSide() == Side.CLIENT){ channel.sendToServer(message); } } }
35.011111
188
0.746747
896052dfa79a4ddcf30d42f43636112a7def4235
447
package cn.ubuilding.dolphin.servlet.security; import org.springframework.stereotype.Service; /** * @author Wu Jianfeng * @since 16/3/2 08:36 * // TODO 登录模块接入SSO */ @Service public class DolphinUserCas { public User getUser(String account, String password) { if ("parker".equals(account) || "wjf".equals(account)) // TODO 登录逻辑后续实现 return new User(1001, account, "吴建峰-" + account); else return null; } }
22.35
79
0.662192
3d52ace0f84b5786182c94313c41c64c810b5d52
700
package com.snowcattle.game.service.net.http; import com.snowcattle.game.service.net.SdNetConfig; import org.jdom2.DataConversionException; import org.jdom2.Element; /** * Created by jiangwenping on 2017/7/3. */ public class SdHttpServerConfig extends SdNetConfig{ private int handleThreadSize; public void load(Element element) throws DataConversionException { super.load(element); handleThreadSize = Integer.valueOf(element.getChildTextTrim("handleThreadSize")); } public int getHandleThreadSize() { return handleThreadSize; } public void setHandleThreadSize(int handleThreadSize) { this.handleThreadSize = handleThreadSize; } }
25.925926
89
0.74
065cff36eb4cd365eb9c1122fe2586e05c34c339
556
package com.l1.service; import java.util.List; import java.util.Map; import com.l1.entity.Inventory; public interface InventoryService { public List<Inventory> find(Map<String, Object> map); public Inventory findById(Integer id); public Long getTotal(Map<String, Object> map); public Integer update(Inventory inventory); public Integer deleteById(Integer id); public void save(Inventory inventory); public Integer delete(String[] ids); public Inventory findBySkuAndWarehouse(Map<String, Object> params); }
22.24
70
0.730216
7f9cbee3276d4e3351dff0032aff2cdac1ac5676
13,147
package club.map.core.model; import club.map.core.util.BeanUtil; import club.map.core.util.StringUtil; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import java.io.*; import java.util.*; /** * TODO:此处继承了HashMap后无法自动注入了 * Created by zero-mac on 16/6/29. */ public class DAOFilter extends HashMap { protected Class persistentClass; protected String entityName; public DAOFilter() { } public DAOFilter(Class clazz) { setClass(clazz); } public void setClass(Class clazz) { this.persistentClass = clazz; this.entityName = persistentClass.getSimpleName(); } private boolean distinct = true; public boolean isDistinct() { return distinct; } public Class getPersistentClass() { return persistentClass; } public String getEntityName() { return entityName; } /** * 绑定查询条件的值到map属性中. * * @param key * @param val */ public void bindProperties(String key, Object val) { super.put(key, val); } /** * 自定义 select 语句, TODO:完成select语句的封装. * <p/> * 使用obj.*的原因是因为可以直接将结果转换为对象. 而使用obj.id, obj.name时只能返回为map,不是对象. */ private List<String> selectList = null; public List<String> getSelect() { return selectList; } public void setSelect(List<String> selectList) { this.selectList = selectList; } public DAOFilter addSelect(String... arr) { if (this.selectList == null) { this.selectList = new ArrayList<String>(); } for (String s : arr) { this.selectList.add(s); } return this; } /** * 单一查询. * <p/> * LIKE.0 * <p/> * <pre> * < input type="hidden" name="p['fieldName'].value" value="查询内容" /> * 或者 * < input type="hidden" name="p['fieldName_LK'].value" value="查询内容" /> * </pre> * <p/> * EQUAL.1 * <p/> * <pre> * < input type="hidden" name="p['fieldName_EQ'].value" value="查询内容" /> * </pre> * <p/> * NOTEQUAL.2 * <p/> * <pre> * < input type="hidden" name="p['fieldName_NE'].value" value="查询内容" /> * </pre> * <p/> * ISNULL.3 * <p/> * <pre> * < input type="hidden" name="p['fieldName_IN'].value" value="0" /> * </pre> * <p/> * NOTNULL.4 * <p/> * <pre> * < input type="hidden" name="p['fieldName_NN'].value" value="0" /> * </pre> */ private Map<String, Parameter> s; private List<Parameter> pl = new ArrayList<Parameter>(); public void setS(Map<String, Parameter> s) { this.s = s; } public List<Parameter> getPl() { return pl; } public void setPl(List<Parameter> pl) { this.pl = pl; } /** * 增加单一查询条件,支持大多数运算符. * <p/> * * @param value 字段值 * @param op 查询运算 {@code com.asd.model.DAOFilter.Operate } operate * @param fieldName 字段名 * @return {@code DAOFilter} DAOFilter */ public DAOFilter addSearch(Object value, Operate op, String fieldName) { if (!validateSearchValue(value, op)) { return this; } Parameter pm = new Parameter(fieldName, value, op); String bindName = "P" + pl.size(); pm.setBindName(bindName); bindProperties(bindName, pm.getValue()); pl.add(pm); return this; } private boolean validateSearchValue(Object val, Operate op) { if (val == null) { switch (op) { case LIKE: case LOWERLIKE: case EQUAL: case NOTEQUAL: case IN: case NOTIN: case LESSEQUAL: case GREAT: case GREATEQUAL: return false; case ISNULL: case NOTNULL: return true; default: return false; } } if (val instanceof String) { String v = (String) val; if ("".equals(v) || "%".equals(v) || "%%".equals(v)) { return false; } } return true; } private List<List<Parameter>> por = null; public List<List<Parameter>> getPor() { return por; } public void setPor(List<List<Parameter>> por) { this.por = por; } /** * 或查询,支持类似 (field1 = value or field2 = value or ...)或条件的查询操作. * <p/> * 注:不支持页面直接封装. * * @param value 需要匹配的值 * @param op 统一的查询运算符 * @param fieldName 各个字段 * @return {@code DAOFilter} DAOFilter */ public DAOFilter addOrSearch(Object value, Operate op, String... fieldName) { if (value == null || (value instanceof String && ((String) value).trim().length() == 0)) { return this; } List<Parameter> porl = new ArrayList<Parameter>(); if (por == null) { por = new ArrayList<List<Parameter>>(); } int index = 0; for (String field : fieldName) { index++; String bindName = "OR" + por.size() + index; Parameter p = new Parameter(field, value, op, "OR" + por.size() + index); p.setOrSearch(true); bindProperties(bindName, p.getValue()); porl.add(p); } por.add(porl); return this; } public DAOFilter addOrSearchSameKey(String fieldName, Operate op, Object... values) { List<Parameter> porl = new ArrayList<Parameter>(); if (por == null) { por = new ArrayList<List<Parameter>>(); } int index = 0; for (Object val : values) { index++; String bindName = "OR" + por.size() + index; Parameter p = new Parameter(fieldName, val, op, bindName); p.setOrSearch(true); bindProperties(bindName, p.getValue()); porl.add(p); } por.add(porl); return this; } public DAOFilter addOrSearchSameKey(List<Object> values, Operate op, String fieldName) { return addOrSearchSameKey(fieldName, op, values.toArray()); } /** * or高级查询. * * @param porl * @return */ public DAOFilter addOrSearch(List<Parameter> porl) { if (por == null) { por = new ArrayList<List<Parameter>>(); } int index = 0; for (Parameter p : porl) { index++; String bindName = "OR" + por.size() + index; p.setBindName(bindName); bindProperties(bindName, p.getValue()); } por.add(porl); return this; } /** * addOrSearch使用方法方法. */ @SuppressWarnings("unused") private void addOrSearchTest() { Parameter p1 = new Parameter("fieldName1", "v1", Operate.EQUAL); Parameter p2 = new Parameter("fieldName2", "v2", Operate.NOTEQUAL); Parameter p3 = new Parameter("fieldName3", "v3", Operate.LIKE); List<Parameter> pl = new ArrayList<Parameter>(); pl.add(p1); pl.add(p2); pl.add(p3); addOrSearch(pl); } /** * 清空已有or查询条件. * * @return */ public DAOFilter clearOrSearch() { por = new ArrayList<List<Parameter>>();// 清空OrSearch条件 return this; } /** * 清空所有已有or查询后再添加新的or查询条件. * * @param value * @param op * @param fieldName * @return */ public DAOFilter setOrSearch(Object value, Operate op, String... fieldName) { if (value == null || (value instanceof String && ((String) value).trim().length() == 0)) { return this; } por = new ArrayList<List<Parameter>>();// 清空OrSearch条件 List<Parameter> porl = new ArrayList<Parameter>(); int index = 0; for (String field : fieldName) { index++; String bindName = "OR" + por.size() + index; Parameter p = new Parameter(field, value, op, bindName); porl.add(p); bindProperties(bindName, p.getValue()); } por.add(porl); return this; } public DAOFilter setPaoSearch(Parameter pm) { bindAllPao(pm, "", 0); pl.add(pm); return this; } public void bindAllPao(Parameter pm, String pre, int index) { if (pm.isLink()) { List<Parameter> aol = pm.getAoList(); for (int i = 0; i < aol.size(); i++) { bindAllPao(aol.get(i), pre + index, i); } } else { // System.out.println("P" + pl.size() + "_" + pre + "_" + index); String bindName = "P" + pl.size() + "_" + pre + "_" + index; pm.setBindName(bindName); bindProperties(bindName, pm.getValue()); } } public static void main(String[] args) { // DAOFilter filter = new DAOFilter(); // Parameter p1 = new Parameter("sMonth", 3, Operate.LESSEQUAL); // Parameter p2 = new Parameter("bMonth", 3 + 1, Operate.GREATEQUAL); // // Parameter p3 = new Parameter("sMonth", 7 - 1, Operate.LESSEQUAL); // Parameter p4 = new Parameter("bMonth", 7, Operate.GREATEQUAL); // Parameter p5 = new Parameter("bMonth", 7, Operate.GREATEQUAL); // // // 组成 (p1 & p2) or (p3 & p4) // Parameter pa1 = new Parameter(false, p1, p2); // Parameter pa2 = new Parameter(false, p3, p4, p5); // // Parameter po = new Parameter(true, pa1, pa2); // filter.setPaoSearch(po); } /** * 区间查询.对between运算符的支持. * <p/> * 若begin为空,则自动转为小于end;若end为空则自动转为大于begin. * <p/> * 支持页面的封装.封装在名为"r"的map中. * <p/> * <pre> * < input type="hidden" name="r['fieldName'].begin" value="开始值" /> * </pre> * <p/> * <pre> * < input type="hidden" name="r['fieldName'].end" value="结束值" /> * </pre> */ public DAOFilter addRegion(String fieldName, Object begin, Object end) { Parameter pm = new Parameter(fieldName, begin, end, Operate.BETWEEN); String bindName = "P" + pl.size(); pm.setBindName(bindName); bindProperties(bindName + "lo", pm.getBegin()); bindProperties(bindName + "hi", pm.getEnd()); pl.add(pm); return this; } /** * sortList */ private List<Sort> sl = new LinkedList<Sort>(); public List<Sort> getSl() { return sl; } public void setSl(List<Sort> sl) { this.sl = sl; } /** * 添加排序条件,支持多字段排序,排序优先级同添加的先后顺序. * * @param field 字段名 * @param desc 是否降序 * @return */ public DAOFilter addSort(String field, boolean desc) { sl.add(new Sort(field, desc)); return this; } /** * 排序字段名.只用于页面分页时; * <p/> * 升序.ascend * <p/> * <pre> * < input type="hidden" name="sort['fieldName'].desc" value="false" /> * </pre> * <p/> * 降序.descend * <p/> * <pre> * < input type="hidden" name="sort['fieldName'].desc" value="true" /> * </pre> */ private String sortField; private boolean sortDesc; public String getSortField() { return sortField; } public String getSortFieldUnderLine() { if (StringUtil.isNull(sortField)) { return null; } return BeanUtil.camel2underline(sortField); } public void setSortField(String sortField) { this.sortField = sortField; } public boolean isSortDesc() { return sortDesc; } public void setSortDesc(boolean sortDesc) { this.sortDesc = sortDesc; } @Override public String toString() { ToStringBuilder sb = new ToStringBuilder(this, ToStringStyle.DEFAULT_STYLE); for (Parameter p : pl) { sb.append("key", p.getKeyUnderLine()).append("begin", p.getBegin()).append("end", p.getEnd()); } sb.append(" || map: " + super.toString()); return sb.toString(); } @Override public boolean equals(Object o) { // TODO Auto-generated method stub return false; } @Override public int hashCode() { // TODO Auto-generated method stub return 0; } public DAOFilter deepClone() { try { // 将对象写到流里 ByteArrayOutputStream bo = new ByteArrayOutputStream(); ObjectOutputStream oo; oo = new ObjectOutputStream(bo); oo.writeObject(this); // 从流里读出来 ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray()); ObjectInputStream oi = new ObjectInputStream(bi); return (DAOFilter) (oi.readObject()); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return null; } public boolean hasPAndOrs() { return false; } }
25.982213
106
0.529246
4a5bd7448ad5f9e08dd596cfdc31964504b21968
1,101
public class HW10 {//내 풀이 public static void main(String[] args) { /* 2개의 배열을 만든다. 하나는 과일을 담는 장바구니 배열 하나는 해당 과일의 개수가 들어있는 배열이다. 사과 5, 귤 3, 오렌지 5, 수박 2, 메론 3, 포도 4개를 배열로 표현하고 적당한 값을 매겨서 합산 가격을 출력하도록 프로그래밍 하시오. */ //1.2개의 배열을 만든다 //2.과일 담는 배열, 갯수 배열 //3.랜덤으로 가격 생성 final int TOTAL = 6; String[] fruit = new String[TOTAL]; //과일, 갯수, 가격 배열 int[] num = new int[TOTAL]; int[] price = new int[TOTAL]; fruit[0] = "사과"; fruit[1] = "귤"; fruit[2] = "오렌지"; fruit[3] = "수박"; fruit[4] = "메론"; fruit[5] = "포도"; num[0] = 5; num[1] = 3; num[2] = 5; num[3] = 2; num[4] = 3; num[5] = 4; price[0] = 1000; price[1] = 2000; price[2] = 1000; price[3] = 5000; price[4] = 6000; price[5] = 5000; int sum = 0; for (int i = 0; i < TOTAL; i++) { sum+= num[i] * price[i]; System.out.printf("%s합계=%d\n", fruit[i], sum); } } }
21.588235
59
0.415985
82206844133cdd747e094ede8b9bbff09997fd6e
286
package app.ccb.services; import javax.xml.bind.JAXBException; import java.io.IOException; public interface BankAccountService { Boolean bankAccountsAreImported(); String readBankAccountsXmlFile() throws IOException; String importBankAccounts() throws JAXBException; }
20.428571
56
0.793706
7f33dcd3751ff22175e0ca6605ca5b8865361ffb
1,923
package com.adaptris.core.json.jslt; import static org.apache.commons.lang3.StringUtils.isEmpty; import java.util.Collections; import java.util.Map; import java.util.regex.Pattern; import java.util.stream.Collectors; import com.adaptris.core.AdaptrisMessage; import com.fasterxml.jackson.databind.JsonNode; import com.thoughtworks.xstream.annotations.XStreamAlias; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; /** * Builds a map of variables for JSLT from object metadata. * <p> * This allows you to use object metadata that is already of the type {@code JsonNode}; possibly via * a previous execution of {@link JsltMetadataService} with a {@link JsltQueryToObjectMetadata}. If * the key exists, but is not a JsonNode then an exception is likely. * </p> * * @config jslt-object-variable */ @XStreamAlias("jslt-object-variable") @NoArgsConstructor public class JsltObjectVariables implements JsltVariableBuilder { /** * The filter you wish to apply to for object metadata * <p> * The regular expression should only match object metadata that is of the type {@code JsonNode}. * If not specified then no object metadata is included. * </p> * */ @Getter @Setter private String objectMetadataKeyRegexp; @Override public Map<String, JsonNode> build(AdaptrisMessage msg) { if (isEmpty(getObjectMetadataKeyRegexp())) { return Collections.EMPTY_MAP; } Pattern pattern = Pattern.compile(getObjectMetadataKeyRegexp()); Map<Object, Object> objMetadata = msg.getObjectHeaders(); return objMetadata.entrySet().stream() .filter((e) -> pattern.matcher(e.getKey().toString()).matches()) .collect(Collectors.toMap((e) -> e.getKey().toString(), (e) -> (JsonNode) e.getValue())); } public JsltObjectVariables withObjectMetadataKeyRegexp(String regexp) { setObjectMetadataKeyRegexp(regexp); return this; } }
32.59322
100
0.73843
a3e6bf51a391dc50c6e224355f13cd3b9e6c2f68
1,739
package com.lostagain.JamGwt.InventoryObjectTypes; import com.google.gwt.user.client.ui.PopupPanel; import com.lostagain.Jam.Interfaces.hasCloseDefault; import com.lostagain.Jam.Interfaces.PopupTypes.IsInventoryItemPopupContent; import com.lostagain.JamGwt.JargScene.SceneObjects.Interfaces.isInventoryItemImplementation; /** a dummy object is simply one that does not popup and purely exists in the inventory for mixing and examineing **/ public class DummyPopUp extends PopupPanel implements hasCloseDefault, isInventoryItemImplementation,IsInventoryItemPopupContent { // Type flag static final String POPUPTYPE = "Dummy"; //title static String TITLE = ""; public DummyPopUp(String Title) { TITLE = Title; //contains nothing at all! } public void CloseDefault(){ } public String POPUPTYPE() { return "Dummy"; } public boolean POPUPONCLICK() { return true; } public boolean MAGNIFYABLE() { return false; } public boolean DRAGABLE() { return true; } public String getSourceURL() { return null; } public int sourcesizeX() { return 0; } public int sourcesizeY() { return 0; } @Override public void RecheckSize() { } @Override public String getState() { return null; } @Override public void loadState(String state) { //no state needed } @Override public Object getVisualRepresentation() { return this.asWidget(); } @Override public int getExpectedZIndex() { return 1; } @Override public void OpenDefault() { // TODO Auto-generated method stub } }
19.10989
133
0.649224
b8585f6627c7b27c8972b3bc0f34687d036d90e6
258
package br.com.zupacademy.gabriel.proposta.biometry; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface BiometryRepository extends JpaRepository<Biometry, Long> { }
25.8
75
0.844961
f74c93c3144cff42481f83708a6c85495a45a5a9
286
/* * */ package com.synectiks.process.common.plugins.cef.parser; public class ParserException extends Exception { public ParserException(String msg) { super(msg); } public ParserException(String msg, Throwable throwable) { super(msg, throwable); } }
19.066667
61
0.674825
45866336df79882f64f45601a7da67ddb21756a3
183
package org.aksw.dcat_suite.service; import com.google.common.util.concurrent.Service; public interface ServiceInstance { Service getService(); ServiceConfig getConfig(); }
20.333333
49
0.775956
a58514ed38c8d2fc0311f91865c4c4975d65fa72
3,515
package br.com.zupacademy.proposta.model; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import br.com.zupacademy.proposta.consumer.CartaoClient; import br.com.zupacademy.proposta.consumer.request.CartaoBloqueioRequest; import br.com.zupacademy.proposta.consumer.request.CartaoCarteiraRequest; import br.com.zupacademy.proposta.consumer.request.CartaoViagemRequest; import br.com.zupacademy.proposta.model.enums.StatusBloqueioCartao; import br.com.zupacademy.proposta.repository.BiometriaRepository; import br.com.zupacademy.proposta.repository.CartaoRepository; import br.com.zupacademy.proposta.repository.CarteiraRepository; import br.com.zupacademy.proposta.repository.ViagemRepository; @Entity public class Cartao { @Id @NotBlank private String numero; @NotNull private Long limite; @OneToMany(cascade = CascadeType.MERGE) private List<Biometria> biometrias = new ArrayList<>(); @OneToOne(cascade = CascadeType.MERGE) private Bloqueio bloqueio = null; @Enumerated(EnumType.STRING) private StatusBloqueioCartao bloqueado = StatusBloqueioCartao.ATIVO; @OneToMany(mappedBy = "cartao") private List<Carteira> carteiras = new ArrayList<>(); @OneToOne(mappedBy = "cartao") private Proposta proposta; @Deprecated public Cartao() { } public Cartao(@NotBlank String numero, @NotNull Long limite) { this.numero = numero; this.limite = limite; } public Proposta getProposta() { return proposta; } public String getNumero() { return numero; } public Long getLimite() { return limite; } public List<Biometria> getBiometrias() { return biometrias; } public Bloqueio getBloqueio() { return bloqueio; } public StatusBloqueioCartao getBloqueado() { return bloqueado; } public List<Carteira> getCarteiras() { return carteiras; } public void adicionaBiometria(Biometria biometria, BiometriaRepository biometriaRepository) { biometriaRepository.save(biometria); this.biometrias.add(biometria); } public void adicionaBloqueio(Bloqueio bloqueio, CartaoRepository cartaoRepository) { this.bloqueio = bloqueio; cartaoRepository.save(this); } // public void removeBloqueio(BloqueioRepository bloqueioRepository) { // bloqueioRepository.delete(this.bloqueio); // this.bloqueio = null; // } public void notificarSistemaBloqueio(CartaoClient cartaoClient, CartaoRepository cartaoRepository) { StatusBloqueioCartao status = cartaoClient.bloquear(this.numero, new CartaoBloqueioRequest("Propostas_API")).getResultado(); if(status.equals(StatusBloqueioCartao.BLOQUEADO)) { this.bloqueado = StatusBloqueioCartao.BLOQUEADO; cartaoRepository.save(this); } } public void notificarSistemaViagem(CartaoClient cartaoClient, Viagem viagem, ViagemRepository viagemRepository) { cartaoClient.viagem(numero, new CartaoViagemRequest(viagem.getDestino(), viagem.getDataTermino())); viagemRepository.save(viagem); } public void notificarSistemaCarteira(CartaoClient cartaoClient, Carteira carteira, CarteiraRepository carteiraRepository) { cartaoClient.carteira(this.numero, new CartaoCarteiraRequest(carteira.getEmail(), carteira.getNomeCarteira())); carteiraRepository.save(carteira); } }
30.301724
128
0.795733
fb19c7dc1050751a458ad75fff7dc5e3c600192b
341
package me.ilvc.all.novel.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * <p> * 前端控制器 * </p> * * @author iLvc * @since 2019-11-12 */ @RestController @RequestMapping("/spider-novel-model") public class SpiderNovelModelController { }
16.238095
62
0.739003
594cbe0531bfbd9215345393dd1c6404fef1592c
406
package usa.cactuspuppy.PVNBot.utils.discord; import net.dv8tion.jda.core.EmbedBuilder; import net.dv8tion.jda.core.entities.Message; public class DiscordLogger { public static boolean logTextCommand(long guildID, String logChannel, String msg) { return true; } public static boolean logTextCommand(long guildID, String logChannel, EmbedBuilder embed) { return true; } }
27.066667
95
0.743842
c6772aeebe27dd270073cde0f1951705f8e3ef66
766
package com.hankz.util.dbutil; public class URLInformationModel { public String url; public String mainwords; public int total_frequence; public int different_DC_frequence; public int different_APK_frequence; public String DCs; public String APKs; public URLInformationModel(String url, String mainwords, int total_frequence, int different_DC_frequence, int different_APK_frequence, String DCs, String APKs){ this.url = url; this.mainwords = mainwords; this.total_frequence = total_frequence; this.different_DC_frequence = different_DC_frequence; this.different_APK_frequence = different_APK_frequence; this.DCs = DCs; this.APKs = APKs; } }
33.304348
109
0.694517
30a8ba77998a43bfb723f0a90cf9cf1dda9778fe
2,960
/* * 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.zeppelin.display; import java.io.Serializable; import java.util.*; import org.apache.zeppelin.display.Input.ParamOption; /** * Settings of a form. */ public class GUI implements Serializable { Map<String, Object> params = new HashMap<>(); // form parameters from client LinkedHashMap<String, Input> forms = new LinkedHashMap<>(); // form configuration public GUI() { } public void setParams(Map<String, Object> values) { this.params = values; } public Map<String, Object> getParams() { return params; } public LinkedHashMap<String, Input> getForms() { return forms; } public void setForms(LinkedHashMap<String, Input> forms) { this.forms = forms; } public Object input(String id, Object defaultValue) { // first find values from client and then use default Object value = params.get(id); if (value == null) { value = defaultValue; } forms.put(id, new Input(id, defaultValue, "input")); return value; } public Object input(String id) { return input(id, ""); } public Object select(String id, Object defaultValue, ParamOption[] options) { Object value = params.get(id); if (value == null) { value = defaultValue; } forms.put(id, new Input(id, defaultValue, "select", options)); return value; } public Collection<Object> checkbox(String id, Collection<Object> defaultChecked, ParamOption[] options) { Collection<Object> checked = (Collection<Object>) params.get(id); if (checked == null) { checked = defaultChecked; } forms.put(id, new Input(id, defaultChecked, "checkbox", options)); Collection<Object> filtered = new LinkedList<>(); for (Object o : checked) { if (isValidOption(o, options)) { filtered.add(o); } } return filtered; } private boolean isValidOption(Object o, ParamOption[] options) { for (ParamOption option : options) { if (o.equals(option.getValue())) { return true; } } return false; } public void clear() { this.forms = new LinkedHashMap<>(); } }
27.663551
83
0.669257
1e39ee272bdacd7780297d33bbbdb02d490f649e
2,108
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * 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.appium.uiautomator2.model; import androidx.test.platform.app.InstrumentationRegistry; import static android.content.res.Configuration.ORIENTATION_LANDSCAPE; import static android.content.res.Configuration.ORIENTATION_PORTRAIT; public enum ScreenOrientation { LANDSCAPE, PORTRAIT; public static ScreenOrientation ofString(String abbr) { try { return ScreenOrientation.valueOf(abbr.toUpperCase()); } catch (IllegalArgumentException e) { throw new IllegalArgumentException( String.format("Orientation value '%s' is not supported. " + "Only '%s' and '%s' values could be translated into " + "a valid screen orientation", abbr, LANDSCAPE.name(), PORTRAIT.name())); } } public static ScreenOrientation current() { int orientation = asInteger(); switch (orientation) { case ORIENTATION_PORTRAIT: return PORTRAIT; case ORIENTATION_LANDSCAPE: return LANDSCAPE; default: throw new IllegalStateException("The current screen orientation cannot be retrieved from resources"); } } private static int asInteger() { return InstrumentationRegistry.getInstrumentation() .getContext().getResources().getConfiguration().orientation; } }
38.327273
117
0.671252
d38692018bc6770c158c34c7d06074ae25701cc1
6,037
package fr.insee.rmes.persistance.service.sesame.concepts.collections; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.commons.httpclient.HttpStatus; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.json.JSONArray; import org.openrdf.model.Model; import org.openrdf.model.URI; import org.openrdf.model.impl.LinkedHashModel; import org.openrdf.model.vocabulary.DC; import org.openrdf.model.vocabulary.DCTERMS; import org.openrdf.model.vocabulary.RDF; import org.openrdf.model.vocabulary.SKOS; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import fr.insee.rmes.config.Config; import fr.insee.rmes.config.auth.security.restrictions.StampsRestrictionsService; import fr.insee.rmes.exceptions.RmesException; import fr.insee.rmes.exceptions.RmesUnauthorizedException; import fr.insee.rmes.persistance.service.sesame.concepts.collections.Collection; import fr.insee.rmes.persistance.service.sesame.concepts.publication.ConceptsPublication; import fr.insee.rmes.persistance.service.sesame.ontologies.INSEE; import fr.insee.rmes.persistance.service.sesame.utils.RepositoryGestion; import fr.insee.rmes.persistance.service.sesame.utils.SesameUtils; @Component public class CollectionsUtils { final static Logger logger = LogManager.getLogger(CollectionsUtils.class); @Autowired StampsRestrictionsService stampsRestrictionsService; /** * Collections * @throws RmesException */ public void setCollection(String body) throws RmesException { ObjectMapper mapper = new ObjectMapper(); mapper.configure( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); Collection collection = new Collection(); try { collection = mapper.readValue(body, Collection.class); } catch (IOException e) { throw new RmesException(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage(), "IOException"); } setRdfCollection(collection); logger.info("Create collection : " + collection.getId() + " - " + collection.getPrefLabelLg1()); } public void setCollection(String id, String body) throws RmesUnauthorizedException, RmesException { URI collectionURI = SesameUtils.collectionIRI(id); ObjectMapper mapper = new ObjectMapper(); if (!stampsRestrictionsService.isConceptOrCollectionOwner(collectionURI)) throw new RmesUnauthorizedException(); mapper.configure( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); Collection collection = new Collection(id); try { collection = mapper.readerForUpdating(collection).readValue(body); } catch (IOException e) { throw new RmesException(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage(), "IOException"); } setRdfCollection(collection); logger.info("Update collection : " + collection.getId() + " - " + collection.getPrefLabelLg1()); } public void collectionsValidation(String body) throws RmesUnauthorizedException, RmesException { JSONArray collectionsToValidate = new JSONArray(body); collectionsValidation(collectionsToValidate); } /** * Collections to sesame * @throws RmesException */ public static void setRdfCollection(Collection collection) throws RmesException { Model model = new LinkedHashModel(); URI collectionURI = SesameUtils.collectionIRI(collection.getId().replaceAll(" ", "-").toLowerCase()); /*Required*/ model.add(collectionURI, RDF.TYPE, SKOS.COLLECTION, SesameUtils.conceptGraph()); model.add(collectionURI, INSEE.IS_VALIDATED, SesameUtils.setLiteralBoolean(collection.getIsValidated()), SesameUtils.conceptGraph()); model.add(collectionURI, DCTERMS.TITLE, SesameUtils.setLiteralString(collection.getPrefLabelLg1(), Config.LG1), SesameUtils.conceptGraph()); model.add(collectionURI, DCTERMS.CREATED, SesameUtils.setLiteralDateTime(collection.getCreated()), SesameUtils.conceptGraph()); model.add(collectionURI, DC.CONTRIBUTOR, SesameUtils.setLiteralString(collection.getContributor()), SesameUtils.conceptGraph()); model.add(collectionURI, DC.CREATOR, SesameUtils.setLiteralString(collection.getCreator()), SesameUtils.conceptGraph()); /*Optional*/ SesameUtils.addTripleDateTime(collectionURI, DCTERMS.MODIFIED, collection.getModified(), model, SesameUtils.conceptGraph()); SesameUtils.addTripleString(collectionURI, DCTERMS.TITLE, collection.getPrefLabelLg2(), Config.LG2, model, SesameUtils.conceptGraph()); SesameUtils.addTripleString(collectionURI, DCTERMS.DESCRIPTION, collection.getDescriptionLg1(), Config.LG1, model, SesameUtils.conceptGraph()); SesameUtils.addTripleString(collectionURI, DCTERMS.DESCRIPTION, collection.getDescriptionLg2(), Config.LG2, model, SesameUtils.conceptGraph()); /*Members*/ collection.getMembers().forEach(member->{ URI memberIRI = SesameUtils.conceptIRI(member); model.add(collectionURI, SKOS.MEMBER, memberIRI, SesameUtils.conceptGraph()); }); RepositoryGestion.loadSimpleObject(collectionURI, model, null); } public void collectionsValidation(JSONArray collectionsToValidate) throws RmesUnauthorizedException, RmesException { Model model = new LinkedHashModel(); List<URI> collectionsToValidateList = new ArrayList<URI>(); for (int i = 0; i < collectionsToValidate.length(); i++) { URI collectionURI = SesameUtils.collectionIRI(collectionsToValidate.getString(i).replaceAll(" ", "").toLowerCase()); collectionsToValidateList.add(collectionURI); model.add(collectionURI, INSEE.IS_VALIDATED, SesameUtils.setLiteralBoolean(true), SesameUtils.conceptGraph()); logger.info("Validate collection : " + collectionURI); } if (!stampsRestrictionsService.isConceptsOrCollectionsOwner(collectionsToValidateList)) throw new RmesUnauthorizedException(); RepositoryGestion.objectsValidation(collectionsToValidateList, model); ConceptsPublication.publishCollection(collectionsToValidate); } }
46.438462
145
0.796091
b22313f17f4c320b6504583518b229fc6dcee47a
3,337
package com.goldenlife.android.presenter; import android.util.Log; import com.goldenlife.android.gson.News; import com.goldenlife.android.gson.Result; import com.goldenlife.android.model.ModelImp; import com.goldenlife.android.model.ModelInt; import com.goldenlife.android.util.HttpUtil; import com.goldenlife.android.util.Utility; import com.goldenlife.android.view.ViewInt; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; import okhttp3.internal.Util; /** * Created by 森宇 on 2018/5/8. */ public class MyPresenter { ModelInt mmodelInt; ViewInt mViewInt; public MyPresenter(ViewInt mViewInt){ this.mViewInt = mViewInt; mmodelInt = new ModelImp();//*****曾因此句话丢失导致空指针错误!!!! } public void parseJson(){ new Thread(new Runnable() { @Override public void run() { String path="http://web.juhe.cn:8080/finance/gold/bankgold?key=99b453c9cb68117ae21c0ef536ac1e68"; HttpUtil.sendOkHttpRequest(path, new Callback() { @Override public void onFailure(Call call, IOException e) { if(mViewInt != null){ mViewInt.showError(); } } @Override public void onResponse(Call call, Response response) throws IOException { final String responseText = response.body().string(); final Result result = Utility.handleResultResponse(responseText); Log.d("onResponse","刚好获取完result"); if(result != null){ //将解析回来的JSon对象转化成的Result对象对应一一赋值给各种Actual tellmodlesave(result); if(mViewInt!=null) { tellviewshowsuccess(); } }else if(result == null){ Log.d("onResponse","result是空"); } } }); } }).start(); } public void parseNewsJson(){ /*new Thread(new Runnable() { @Override public void run() {*/ String path = "http://api.jisuapi.com/news/get?channel=财经&start=0&num=20&appkey=4e51586fe92728b8"; HttpUtil.sendOkHttpRequest(path, new Callback() { @Override public void onFailure(Call call, IOException e) { Log.d("parseNewsJson","onFailure被调用"); } @Override public void onResponse(Call call, Response response) throws IOException { final String responseText = response.body().string(); final News news = Utility.handleNewsResponse(responseText);//这里也返回空 mViewInt.setNews(news); Log.d("MyPresenter","news:"+news.thenewslist.get(0).newstitle); } }); /* } }).start();*/ } private void tellviewshowsuccess() { if(mViewInt !=null){ mViewInt.showSuccess(); } } private void tellmodlesave(Result result) { Log.d("tellmodlesave","准备开始调用savetodb"); mmodelInt.savetoDB(result); } }
35.5
114
0.546599
93351a845dbdb8054f10be43521ae7bad2f33319
1,312
package io.skysail.server.app; import io.skysail.api.text.TranslationRenderService; import java.lang.ref.WeakReference; import java.util.*; import lombok.*; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang.StringUtils; import org.osgi.framework.Constants; /** * Holds a weak reference to a translationRenderService and its service * properties. * */ @Getter @Slf4j @EqualsAndHashCode(of = {"name"})// NO_UCD @ToString(of = {"name"}) public class TranslationRenderServiceHolder { private WeakReference<TranslationRenderService> service; private WeakHashMap<String, String> props; private String name; public TranslationRenderServiceHolder(TranslationRenderService service, Map<String, String> props) { this.service = new WeakReference<TranslationRenderService>(service); this.props = new WeakHashMap<>(props); this.name = service.getClass().getName(); } public Integer getServiceRanking() { String serviceRanking = props.get(Constants.SERVICE_RANKING); if (StringUtils.isEmpty(serviceRanking)) { return 0; } try { return Integer.valueOf(serviceRanking); } catch (NumberFormatException e) { log.error(e.getMessage(), e); return 0; } } }
26.77551
104
0.691311
4e0ac1d910ca7f47c0d62814ab116b0d296e2133
1,112
package im.dlg.botsdk.domain; public class Group { private String shortname; private String title; private Peer peer; private GroupType type; public Group(String shortname, String title, Peer peer, GroupType type) { this.shortname = shortname; this.title = title; this.peer = peer; this.type = type; } /** * @return The peer, related to group */ public Peer getPeer() { return peer; } /** * @return The title of group */ public String getTitle() { return title; } /** * @return Shortname */ public String getShortname() { return shortname; } /** * @return About string info */ public GroupType getType() { return type; } /** * @return user sex */ @Override public String toString() { return "Group{" + "peer=" + peer + ", title='" + title + '\'' + ", shortname='" + shortname + '\'' + ", type='" + type + '}'; } }
19.172414
77
0.48741
22fa6a641e631591e037739ba788bf2900d252f8
7,830
package com.tcmj.custjar; import com.tcmj.custjar.mrg.impl.JarFileMerger; import com.tcmj.custjar.mrg.Merger; import com.tcmj.custjar.mrg.impl.LightJarFileMerger; import java.io.File; import java.net.InetAddress; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /** * CustJar - Custom Jar Generator * @author Thomas Deutsch * @contact Thomas-Deutsch [at] tcmj [dot] de (2005 - 2009) */ public class CustJar { /** Version. */ public static final String VERSION = "2.00 / 2009"; /** Creates a new instance of CustJar. */ public CustJar() { } /** * @param args the command line arguments */ public static void main(String[] args) { Parameters params = new Parameters(); try { if (args.length < 4) { throw new Exception(getUsage()); } Set setLibs = new HashSet(); for (int i = 0; i < args.length; i++) { // System.out.println("o--> "+args[i]); String param = args[i]; if ("-out".equals(param) || "-output".equals(param)) { params.setOutput(args[++i]); } else if ("-m".equals(param) || "-manifest".equals(param)) { if (params.getMainclass() != null) { throw new Exception("You cannot use both options 'manifest' and 'mainclass'!"); } else { params.setManifest(args[++i]); } } else if ("-mc".equals(param) || "-mainclass".equals(param)) { if (params.getManifest() != null) { throw new Exception("You cannot use both options 'manifest' and 'mainclass'!"); } else { params.setMainclass(args[++i]); } } else if ("-l".equals(param) || "-light".equals(param)) { params.setOnlyneeded(true); } else if ("-lib".equals(param) || "-libs".equals(param) || "-libraries".equals(param)) { while (i < args.length - 1) { setLibs.add(args[++i]); } params.setSetInputLibraries(setLibs); } else if ("-v".equals(param) || "-verbose".equals(param)) { JarFileMerger.VERBOSE = true; } else { throw new Exception(getUsage()); } } System.out.println("** * * * * * * * * * * * * * * * * * * * * * * * * * *"); System.out.println("** Starting CustJar Version " + VERSION + " *"); System.out.println("** Author: Thomas Deutsch ([email protected]) *"); System.out.println("** * * * * * * * * * * * * * * * * * * * * * * * * * *"); //check availability of parameters: if (params.getOutput() == null) { throw new Exception("Output file not given!"); } if (params.getManifest() == null && params.getMainclass() == null) { throw new Exception("Manifest/MainClass not given!"); } if (setLibs.size() < 1) { throw new Exception("No jarfiles found to merge!"); } File fileOutput = new File(params.getOutput()); System.out.println("** outputfile : " + fileOutput.getCanonicalPath()); Merger jfe; if (params.isOnlyneeded()) { jfe = new JarFileMerger(fileOutput); System.out.println("** build light jar : true"); } else { jfe = new LightJarFileMerger(fileOutput); System.out.println("** build light jar : false"); } if (params.getManifest() != null) { File fileManifest = params.getManifestFile(); jfe.setManifest(fileManifest); System.out.println("** manifest : " + fileManifest.getCanonicalPath()); } else { jfe.setMainClass(params.getMainclass()); jfe.putManifestAttribute("Created-By", "CustJar " + VERSION + " by Thomas Deutsch"); jfe.putManifestAttribute("Built-By", System.getProperty("user.name") + "@" + InetAddress.getLocalHost().getCanonicalHostName()); System.out.println("** mainclass : " + params.getMainclass()); } System.out.println("** libs/paths : " + setLibs.size()); // System.out.println("** build light jar : "+onlyneeded); System.out.println("** verbose : " + JarFileMerger.VERBOSE); System.out.println("** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"); Iterator itLibs = setLibs.iterator(); while (itLibs.hasNext()) { String lib = (String) itLibs.next(); jfe.addJar(new File(lib)); } jfe.create(); System.out.println("*** JarFile successfully created! ***"); // jfe.extract(new File("jdom.jar"),"tempjar/"); } catch (Exception ex) { System.out.println(ex.getMessage()); } } private static final String getUsage() { String LINE = System.getProperty("line.separator"); StringBuffer s = new StringBuffer(300); s.append("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * "); s.append(LINE); s.append("** CustJar - Custom Jar - Version " + VERSION); s.append(LINE); s.append("** Author: Thomas Deutsch ([email protected])"); s.append(LINE); s.append("**"); s.append(LINE); s.append("** Merges some java jarfiles to a single big one!"); s.append(LINE); s.append("**"); s.append(LINE); s.append("** Usage:"); s.append(LINE); s.append("**\tcustjar [-out outputfile] [-m manifest || -mc mainclass] [-l] [-v] [-lib libraries]"); s.append(LINE); s.append("**"); s.append(LINE); s.append("** Mandatory Options:"); s.append(LINE); s.append("** \t-out output\t\tName of the output jarfile to create"); s.append(LINE); s.append("** \t-m manifest\t\tName of the manifest to be used"); s.append(LINE); s.append("** \t-lib libraries\t\tList of single jarfiles and/or directories with jarfiles"); s.append(LINE); s.append("** \t\t\t\tto merge (space as separator)"); s.append(LINE); s.append("**"); s.append(LINE); s.append("** Extended Options:"); s.append(LINE); s.append("** \t-v verbose\t\tOutputs all entries with state (optional)"); s.append(LINE); // s.append("** \t-l light\t\tOnly include needed classes (optional)"); // s.append(LINE); s.append("** \t-mc mainclass\t\tSpecifiy the Main-Class instead of a manifest file"); s.append(LINE); s.append("**"); s.append(LINE); s.append("**"); s.append(LINE); s.append("** Examples:"); s.append(LINE); s.append("**\tjava -jar CustJar.jar -out out.jar -m manifest.mf -lib lib1.jar lib2.jar lib3.jar"); s.append(LINE); s.append("**\tjava -jar CustJar.jar -out out.jar -mc inteco.MainFrame -lib \"C:\\Project\\dist\\libs\" .\\dist\\abc.jar"); s.append(LINE); s.append("**"); s.append(LINE); s.append("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * "); s.append(LINE); return s.toString(); } }
35.753425
144
0.487484
f683aa82b005dc18ff858d165f16997c4ba8dea4
2,601
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Licensed under the Zeebe Community License 1.1. You may not use this file * except in compliance with the Zeebe Community License 1.1. */ package io.camunda.zeebe.engine.state.variable; import io.camunda.zeebe.msgpack.spec.MsgPackReader; import java.util.Iterator; import java.util.NoSuchElementException; import org.agrona.DirectBuffer; import org.agrona.collections.Int2IntHashMap.EntryIterator; import org.agrona.concurrent.UnsafeBuffer; /** * Iterates of a document by reading the offsets directly from the associated {@code * offsetIterator}. Expected usage only through {@link IndexedDocument#iterator()}. * * <p>Note that keys are expected to be strings, and as such the length is removed from the MsgPack * representation before being added as the name in the {@link DocumentEntry}. String values are * kept as is, as values can be any kind of object. */ final class DocumentEntryIterator implements Iterator<DocumentEntry> { private final MsgPackReader reader; private final DocumentEntry entry = new DocumentEntry(); private final DirectBuffer document = new UnsafeBuffer(); private EntryIterator offsetIterator; private int documentLength; DocumentEntryIterator() { this(new MsgPackReader()); } DocumentEntryIterator(final MsgPackReader reader) { this.reader = reader; } @Override public boolean hasNext() { return offsetIterator.hasNext(); } @Override public DocumentEntry next() { if (!hasNext()) { throw new NoSuchElementException(); } offsetIterator.next(); final int keyOffset = offsetIterator.getIntKey(); final int valueOffset = offsetIterator.getIntValue(); reader.wrap(document, keyOffset, documentLength - keyOffset); final int nameLength = reader.readStringLength(); final int nameOffset = keyOffset + reader.getOffset(); reader.wrap(document, valueOffset, documentLength - valueOffset); reader.skipValue(); final int valueLength = reader.getOffset(); entry.wrap(document, nameOffset, nameLength, valueOffset, valueLength); return entry; } @Override public void remove() { offsetIterator.remove(); } void wrap(final DirectBuffer document, final EntryIterator offsetIterator) { this.document.wrap(document); this.offsetIterator = offsetIterator; documentLength = document.capacity(); } }
32.5125
99
0.750865
1aec2edcae27cc0acf656fd03877c5c510ef04ac
15,593
/* * Copyright 2019, Perfect Sense, 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 gyro.azure.sql; import com.microsoft.azure.management.sql.SqlDatabaseStandardStorage; import com.microsoft.azure.management.sql.SqlElasticPoolOperations; import com.microsoft.azure.management.sql.SqlServer; import com.psddev.dari.util.ObjectUtils; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.core.GyroException; import gyro.core.GyroUI; import gyro.core.resource.Id; import gyro.core.resource.Resource; import gyro.core.resource.Output; import gyro.core.Type; import gyro.core.resource.Updatable; import com.microsoft.azure.management.Azure; import com.microsoft.azure.management.sql.SqlElasticPool; import com.microsoft.azure.management.sql.SqlElasticPoolBasicEDTUs; import com.microsoft.azure.management.sql.SqlElasticPoolBasicMaxEDTUs; import com.microsoft.azure.management.sql.SqlElasticPoolBasicMinEDTUs; import com.microsoft.azure.management.sql.SqlElasticPoolPremiumEDTUs; import com.microsoft.azure.management.sql.SqlElasticPoolPremiumMaxEDTUs; import com.microsoft.azure.management.sql.SqlElasticPoolPremiumMinEDTUs; import com.microsoft.azure.management.sql.SqlElasticPoolPremiumSorage; import com.microsoft.azure.management.sql.SqlElasticPoolStandardEDTUs; import com.microsoft.azure.management.sql.SqlElasticPoolStandardMaxEDTUs; import com.microsoft.azure.management.sql.SqlElasticPoolStandardMinEDTUs; import com.microsoft.azure.management.sql.SqlElasticPoolStandardStorage; import com.microsoft.azure.management.sql.SqlElasticPoolOperations.DefinitionStages.WithEdition; import gyro.core.scope.State; import gyro.core.validation.Required; import gyro.core.validation.ValidStrings; import gyro.core.validation.ValidationError; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; /** * Creates a sql elastic pool. * * Example * ------- * * .. code-block:: gyro * * azure::sql-elastic-pool sql-elastic-pool-example * name: "sql-elastic-pool" * edition: "Basic" * dtu-min: "eDTU_0" * dtu-max: "eDTU_5" * dtu-reserved: "eDTU_50" * sql-server: $(azure::sql-server sql-server-example) * tags: { * Name: "sql-elastic-pool-example" * } * end */ @Type("sql-elastic-pool") public class SqlElasticPoolResource extends AzureResource implements Copyable<SqlElasticPool> { private static final String EDITION_BASIC = "Basic"; private static final String EDITION_PREMIUM = "Premium"; private static final String EDITION_STANDARD = "Standard"; private Set<String> databaseNames; private String dtuMax; private String dtuMin; private String dtuReserved; private String edition; private String id; private String name; private SqlServerResource sqlServer; private String storageCapacity; private Map<String, String> tags; /** * The databases within the elastic pool. */ @Updatable public Set<String> getDatabaseNames() { if (databaseNames == null) { databaseNames = new HashSet<>(); } return databaseNames; } public void setDatabaseNames(Set<String> databaseNames) { this.databaseNames = databaseNames; } /** * The maximum eDTU for the each database in the elastic pool. */ @Required @Updatable public String getDtuMax() { return dtuMax; } public void setDtuMax(String dtuMax) { this.dtuMax = dtuMax; } /** * The minimum of eDTU for each database in the elastic pool. */ @Required @Updatable public String getDtuMin() { return dtuMin; } public void setDtuMin(String dtuMin) { this.dtuMin = dtuMin; } /** * The total shared eDTU for the elastic pool. */ @Required @Updatable public String getDtuReserved() { return dtuReserved; } public void setDtuReserved(String dtuReserved) { this.dtuReserved = dtuReserved; } /** * The edition of the elastic pool. Valid values are ``Basic``, ``Premium``, or ``Standard`` */ @Required @ValidStrings({"Basic", "Premium", "Standard"}) @Updatable public String getEdition() { return edition; } public void setEdition(String edition) { this.edition = edition; } /** * The ID of the elastic pool. */ @Output public String getId() { return id; } public void setId(String id) { this.id = id; } /** * The name of the elastic pool. */ @Required @Id public String getName() { return name; } public void setName(String name) { this.name = name; } /** * The storage limit for the database elastic pool. Required when used with ``Standard`` or ``Premium`` editions. */ @Updatable public String getStorageCapacity() { return storageCapacity; } public void setStorageCapacity(String storageCapacity) { this.storageCapacity = storageCapacity; } /** * The SQL Server where the elastic pool is found. */ @Required public SqlServerResource getSqlServer() { return sqlServer; } public void setSqlServer(SqlServerResource sqlServer) { this.sqlServer = sqlServer; } /** * The tags associated with the elastic pool. */ @Updatable public Map<String, String> getTags() { if (tags == null) { tags = new HashMap<>(); } return tags; } public void setTags(Map<String, String> tags) { this.tags = tags; } @Override public void copyFrom(SqlElasticPool elasticPool) { getDatabaseNames().clear(); elasticPool.listDatabases().forEach(db -> getDatabaseNames().add(db.name())); setDtuMax("eDTU_" + elasticPool.databaseDtuMax()); setDtuMin("eDTU_" + elasticPool.databaseDtuMin()); setDtuReserved("eDTU_" + elasticPool.dtu()); setEdition(elasticPool.edition().toString()); setId(elasticPool.id()); setName(elasticPool.name()); setStorageCapacity(!getEdition().equals(EDITION_BASIC) ? Integer.toString(elasticPool.storageCapacityInMB()) : null); setTags(elasticPool.inner().getTags()); } @Override public boolean refresh() { Azure client = createClient(); SqlElasticPool elasticPool = getSqlElasticPool(client); if (elasticPool == null) { return false; } copyFrom(elasticPool); return true; } @Override public void create(GyroUI ui, State state) { if (getSqlServer() == null) { throw new GyroException("You must provide a sql server resource."); } Azure client = createClient(); WithEdition buildPool = client.sqlServers().getById(getSqlServer().getId()).elasticPools().define(getName()); SqlElasticPoolOperations.DefinitionStages.WithCreate elasticPool; if (EDITION_BASIC.equalsIgnoreCase(getEdition())) { elasticPool = buildPool.withBasicPool() .withDatabaseDtuMax(SqlElasticPoolBasicMaxEDTUs.valueOf(getDtuMax())) .withDatabaseDtuMin(SqlElasticPoolBasicMinEDTUs.valueOf(getDtuMin())) .withReservedDtu(SqlElasticPoolBasicEDTUs.valueOf(getDtuReserved())); } else if (EDITION_PREMIUM.equalsIgnoreCase(getEdition())) { elasticPool = buildPool.withPremiumPool() .withDatabaseDtuMax(SqlElasticPoolPremiumMaxEDTUs.valueOf(getDtuMax())) .withDatabaseDtuMin(SqlElasticPoolPremiumMinEDTUs.valueOf(getDtuMin())) .withReservedDtu(SqlElasticPoolPremiumEDTUs.valueOf(getDtuReserved())) .withStorageCapacity(SqlElasticPoolPremiumSorage.valueOf(getStorageCapacity())); } else if (EDITION_STANDARD.equalsIgnoreCase(getEdition())) { elasticPool = buildPool.withStandardPool() .withDatabaseDtuMax(SqlElasticPoolStandardMaxEDTUs.valueOf(getDtuMax())) .withDatabaseDtuMin(SqlElasticPoolStandardMinEDTUs.valueOf(getDtuMin())) .withReservedDtu(SqlElasticPoolStandardEDTUs.valueOf(getDtuReserved())) .withStorageCapacity(SqlElasticPoolStandardStorage.valueOf(getStorageCapacity())); } else { throw new GyroException("Invalid edition. Valid values are Basic, Standard, and Premium"); } for (String database : getDatabaseNames()) { elasticPool.withExistingDatabase(database); } elasticPool.withTags(getTags()); SqlElasticPool pool = elasticPool.create(); setId(pool.id()); copyFrom(pool); } @Override public void update(GyroUI ui, State state, Resource current, Set<String> changedProperties) { Azure client = createClient(); SqlElasticPool.Update update = getSqlElasticPool(client).update(); if (EDITION_BASIC.equalsIgnoreCase(getEdition())) { update.withDatabaseDtuMax(SqlElasticPoolBasicMaxEDTUs.valueOf(getDtuMax())) .withDatabaseDtuMin(SqlElasticPoolBasicMinEDTUs.valueOf(getDtuMin())) .withReservedDtu(SqlElasticPoolBasicEDTUs.valueOf(getDtuReserved())); } else if (EDITION_PREMIUM.equalsIgnoreCase(getEdition())) { update.withDatabaseDtuMax(SqlElasticPoolPremiumMaxEDTUs.valueOf(getDtuMax())) .withDatabaseDtuMin(SqlElasticPoolPremiumMinEDTUs.valueOf(getDtuMin())) .withReservedDtu(SqlElasticPoolPremiumEDTUs.valueOf(getDtuReserved())) .withStorageCapacity(SqlElasticPoolPremiumSorage.valueOf(getStorageCapacity())); } else if (EDITION_STANDARD.equalsIgnoreCase(getEdition())) { update.withDatabaseDtuMax(SqlElasticPoolStandardMaxEDTUs.valueOf(getDtuMax())) .withDatabaseDtuMin(SqlElasticPoolStandardMinEDTUs.valueOf(getDtuMin())) .withReservedDtu(SqlElasticPoolStandardEDTUs.valueOf(getDtuReserved())) .withStorageCapacity(SqlElasticPoolStandardStorage.valueOf(getStorageCapacity())); } for (String database : getDatabaseNames()) { update.withNewDatabase(database); } update.withTags(getTags()).apply(); } @Override public void delete(GyroUI ui, State state) { Azure client = createClient(); SqlElasticPool sqlElasticPool = getSqlElasticPool(client); if (sqlElasticPool != null) { sqlElasticPool.delete(); } } private SqlElasticPool getSqlElasticPool(Azure client) { SqlElasticPool sqlElasticPool = null; SqlServer sqlServer = client.sqlServers().getById(getSqlServer().getId()); if (sqlServer != null) { sqlElasticPool = sqlServer.elasticPools().get(getName()); } return sqlElasticPool; } @Override public List<ValidationError> validate() { List<ValidationError> errors = new ArrayList<>(); if (EDITION_PREMIUM.equalsIgnoreCase(getEdition())) { if (!Arrays.stream(SqlElasticPoolPremiumMaxEDTUs.values()).map(Enum::toString).collect(Collectors.toSet()).contains(getDtuMax())) { errors.add(new ValidationError(this, "dtu-max", "Invalid value for 'dtu-max' when 'edition' set to 'Premium'.")); } if (!Arrays.stream(SqlElasticPoolPremiumMinEDTUs.values()).map(Enum::toString).collect(Collectors.toSet()).contains(getDtuMin())) { errors.add(new ValidationError(this, "dtu-min", "Invalid value for 'dtu-min' when 'edition' set to 'Premium'.")); } if (!Arrays.stream(SqlElasticPoolPremiumEDTUs.values()).map(Enum::toString).collect(Collectors.toSet()).contains(getDtuReserved())) { errors.add(new ValidationError(this, "dtu-reserved", "Invalid value for 'dtu-reserved' when 'edition' set to 'Premium'.")); } if (!Arrays.stream(SqlElasticPoolPremiumSorage.values()).map(Enum::toString).collect(Collectors.toSet()).contains(getStorageCapacity())) { errors.add(new ValidationError(this, "storage-capacity", "Invalid value for 'storage-capacity' when 'edition' set to 'Premium'.")); } } else if (EDITION_STANDARD.equalsIgnoreCase(getEdition())) { if (!Arrays.stream(SqlElasticPoolStandardMaxEDTUs.values()).map(Enum::toString).collect(Collectors.toSet()).contains(getDtuMax())) { errors.add(new ValidationError(this, "dtu-max", "Invalid value for 'dtu-max' when 'edition' set to 'Standard'.")); } if (!Arrays.stream(SqlElasticPoolStandardMinEDTUs.values()).map(Enum::toString).collect(Collectors.toSet()).contains(getDtuMin())) { errors.add(new ValidationError(this, "dtu-min", "Invalid value for 'dtu-min' when 'edition' set to 'Standard'.")); } if (!Arrays.stream(SqlElasticPoolStandardEDTUs.values()).map(Enum::toString).collect(Collectors.toSet()).contains(getDtuReserved())) { errors.add(new ValidationError(this, "dtu-reserved", "Invalid value for 'dtu-reserved' when 'edition' set to 'Standard'.")); } if (!Arrays.stream(SqlDatabaseStandardStorage.values()).map(Enum::toString).collect(Collectors.toSet()).contains(getStorageCapacity())) { errors.add(new ValidationError(this, "storage-capacity", "Invalid value for 'storage-capacity' when 'edition' set to 'Standard'.")); } } else if (EDITION_BASIC.equalsIgnoreCase(getEdition())) { if (!Arrays.stream(SqlElasticPoolBasicMaxEDTUs.values()).map(Enum::toString).collect(Collectors.toSet()).contains(getDtuMax())) { errors.add(new ValidationError(this, "dtu-max", "Invalid value for 'dtu-max' when 'edition' set to 'Basic'.")); } if (!Arrays.stream(SqlElasticPoolBasicMinEDTUs.values()).map(Enum::toString).collect(Collectors.toSet()).contains(getDtuMin())) { errors.add(new ValidationError(this, "dtu-min", "Invalid value for 'dtu-min' when 'edition' set to 'Basic'.")); } if (!Arrays.stream(SqlElasticPoolBasicEDTUs.values()).map(Enum::toString).collect(Collectors.toSet()).contains(getDtuReserved())) { errors.add(new ValidationError(this, "dtu-reserved", "Invalid value for 'dtu-reserved' when 'edition' set to 'Basic'.")); } if (!ObjectUtils.isBlank(getStorageCapacity())) { errors.add(new ValidationError(this, "storage-capacity", "Cannot set 'storage-capacity' when 'edition' set to 'Basic'.")); } } return errors; } }
37.573494
150
0.663888
4bba9cc3b79bb3fcd5c8bd51f283b638c32f0432
5,961
package com.douglaswhitehead.controller; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.UUID; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mobile.device.Device; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.util.UriUtils; import com.douglaswhitehead.datalayer.OrderDataLayer; import com.douglaswhitehead.model.Address; import com.douglaswhitehead.model.Order; import com.douglaswhitehead.model.OrderForm; import com.douglaswhitehead.model.ShoppingCart; import com.douglaswhitehead.model.ShoppingCartItem; import com.douglaswhitehead.model.User; @Controller @RequestMapping("/orders") public class OrderControllerImpl extends AbstractController implements OrderController { @Autowired private OrderDataLayer dataLayer; @RequestMapping(value = "/checkout", method = RequestMethod.GET) @Override public String checkout(@ModelAttribute("orderForm") final OrderForm orderForm, final HttpServletRequest request, final Device device, final HttpServletResponse response, final Model model) { boolean auth = isAuthenticated(); String cartId; if (!checkCartIdCookie(request)) { String error = ""; try { error = UriUtils.encodeQueryParam("No cartId cookie.", "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return "redirect:/error?error="+error; } else { Cookie cookie = getCartIdCookie(request); cartId = cookie.getValue(); } ShoppingCart cart = cartService.get(UUID.fromString(cartId)); if (cart.getCartItems() == null || cart.getCartItems().size() == 0) { String error = ""; try { error = UriUtils.encodeQueryParam("No items in cart to checkout.", "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return "redirect:/error?error="+error; } User user = null; if (auth) { user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal(); } String digitalData = digitalDataAdapter.adapt(dataLayer.checkout(request, response, device, model, cart, user)); model.addAttribute("ensManAccountId", properties.getAccountId()); model.addAttribute("ensManPublishPath", properties.getPublishPath()); model.addAttribute("isAuthenticated", auth); model.addAttribute("cartId", cart.getId().toString()); model.addAttribute("cartSize", calculateCartSize(cart)); model.addAttribute("digitalData", digitalData); return "orders/checkout"; } @RequestMapping(value = "/complete", method = RequestMethod.POST) @Override public String complete(@ModelAttribute("orderForm") final OrderForm orderForm, final HttpServletRequest request, final Device device, final HttpServletResponse response, final Model model) { boolean auth = isAuthenticated(); String cartId; if (!checkCartIdCookie(request)) { String error = ""; try { error = UriUtils.encodeQueryParam("Order error. No cartId cookie.", "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return "redirect:/error?error="+error; } else { Cookie cookie = getCartIdCookie(request); cartId = cookie.getValue(); } // in a prod env, we would validate shipping address info here // validateShippingAddress(); Address shippingAddress = new Address(orderForm.getRecipientName(), orderForm.getLine1(), orderForm.getLine2(), orderForm.getCity(), orderForm.getStateProvince(), orderForm.getPostalCode(), orderForm.getCountry()); // in a prod env, we would validate payment info here (or maybe in a separate form step) // validatePaymentInfo(); ShoppingCart cart = cartService.get(UUID.fromString(cartId)); User user = null; if (auth) { user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal(); } // simulates placing an order // in a prod env, this would be replaced with a real order service and back end try { // remove items from shopping cart, since they are being purchased List<ShoppingCartItem> itemsToRemove = new ArrayList<ShoppingCartItem>(); if (cart != null) { for (ShoppingCartItem item: cart.getCartItems()) { for (int i=1;i<=item.getQuantity();i++) { itemsToRemove.add(item); } } } for (ShoppingCartItem item: itemsToRemove) { cartService.removeFromCart(cart.getId(), item.getId()); } Thread.sleep(5000); // simulate long-running purchase transaction } catch(InterruptedException ex) { Thread.currentThread().interrupt(); } // simulate order service response, which would return an order Order order = new Order(UUID.randomUUID(), cart.getBasePrice(), cart.getVoucherCode(), cart.getVoucherDiscount(), cart.getCurrency(), cart.getTaxRate(), cart.getShipping(), cart.getShippingMethod(), cart.getPriceWithTax(), cart.getCartTotal(), cart.getCartItems(), shippingAddress); String digitalData = digitalDataAdapter.adapt(dataLayer.complete(request, response, device, model, cart, order, user)); model.addAttribute("ensManAccountId", properties.getAccountId()); model.addAttribute("ensManPublishPath", properties.getPublishPath()); model.addAttribute("isAuthenticated", auth); model.addAttribute("cartId", cart.getId().toString()); model.addAttribute("cartSize", 0); // cart items is now 0 model.addAttribute("order", order); model.addAttribute("digitalData", digitalData); return "orders/complete"; } }
37.968153
191
0.741654
176ac98f393f0169b1d2a6796ce6be084b2a18dc
320
package org.sparqpoc.apprespository; import org.sparqpoc.appmodel.LoanMaster; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface LoanRepository extends JpaRepository<LoanMaster, Long> { LoanMaster findById(long loanid); }
22.857143
73
0.83125
362f10ada90fcc3a3227a7409d4467de3c1cf8f6
167
package com.elead.viewpagerutils; public interface PagerAssist { public boolean hasInit(); public void setInit(boolean hasInit); public void initPager(); }
13.916667
38
0.748503
aec60ffb40a20feb9fa705ea3d3764a19aab6668
1,011
package com.reynke.sloud.databaseutilities.dependencyinjection; import com.google.inject.Injector; import com.reynke.sloud.databaseutilities.configuration.DatabaseType; import com.reynke.sloud.databaseutilities.configuration.IDatabaseConfiguration; import com.reynke.sloud.databaseutilities.database.IDatabase; import javax.inject.Inject; import javax.inject.Provider; /** * @author Nicklas Reincke ([email protected]) */ public class DatabaseProvider implements Provider<IDatabase> { private final IDatabaseConfiguration databaseConfiguration; private final Injector injector; @Inject public DatabaseProvider(IDatabaseConfiguration databaseConfiguration, Injector injector) { this.databaseConfiguration = databaseConfiguration; this.injector = injector; } @Override public IDatabase get() { DatabaseType databaseType = this.databaseConfiguration.getDatabaseType(); return this.injector.getInstance(databaseType.getDatabaseClass()); } }
31.59375
94
0.78635
6f3a5fa900a872b8427b510ec8cc58f37f904ca1
1,497
package com.vaguehope.onosendai.util; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import com.vaguehope.onosendai.C; public final class LogcatHelper { private LogcatHelper () { throw new AssertionError(); } public static void dumpLog (final File file) throws IOException, InterruptedException { final List<String> args = new ArrayList<String>(); args.add("logcat"); args.add("-b"); args.add("main"); args.add("-t"); args.add("20000"); args.add("-f"); args.add(file.getAbsolutePath()); args.add("-v"); args.add("time"); args.add("-s"); args.add(C.TAG + ":I"); final Process proc = Runtime.getRuntime().exec(args.toArray(new String[args.size()])); eatStream(proc.getInputStream()); eatStream(proc.getErrorStream()); final int code = proc.waitFor(); if (code != 0) throw new IOException("Logcat exit code: " + code); if (!file.exists()) throw new IOException("Logcat did not write file: " + file.getAbsolutePath()); } private static void eatStream (final InputStream is) { new Thread(new Runnable() { @Override public void run () { try { try { final byte[] dummy = new byte[1024]; // NOSONAR not a magic number. while (is.read(dummy) >= 0) {/* Unwanted. */} // NOSONAR do not care about content. } catch (final IOException e) {/* Unwanted. */} } finally { IoHelper.closeQuietly(is); } } }).start(); } }
25.372881
100
0.653975
4be414f71280cd928817daaba07a53525a56e379
1,814
package stack; import java.util.Stack; public class LC844BackspaceStringCompare { public boolean backspaceCompare(String S, String T) { Stack<Character> stack1 = new Stack<>(); Stack<Character> stack2 = new Stack<>(); for (char c : S.toCharArray()) { if (c == '#') { if (!stack1.empty()) { stack1.pop(); } } else { stack1.push(c); } } for (Character c : T.toCharArray()) { if (c == '#') { if (!stack2.empty()) { stack2.pop(); } } else { stack2.push(c); } } boolean result = true; while (!stack1.empty() && !stack2.empty()) { if (stack1.pop() != stack2.pop()) { result = false; break; } } if (result) { if (stack1.empty() && stack2.empty()) { result = true; } else { result = false; } } return result; } public static void main(String[] args) { LC844BackspaceStringCompare test = new LC844BackspaceStringCompare(); boolean result; result = test.backspaceCompare("ab#c", "ad#c"); System.out.println(result); assert result; result = test.backspaceCompare("ab##", "c#d#"); System.out.println(result); assert result; result = test.backspaceCompare("a##c", "#a#c"); System.out.println(result); assert result; result = test.backspaceCompare("a#c", "b"); System.out.println(result); assert !result; System.out.println(" ====== Success! ====="); } }
26.676471
77
0.455347
c6367b8faa1002f833ae303f45069606a131a682
382
package no.fdk.acat.common.model.apispecification.info; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.Data; @Data @JsonInclude(JsonInclude.Include.NON_NULL) public class Info { private String title; private String description; private String termsOfService; private Contact contact; private License license; private String version; }
22.470588
55
0.774869
2d14e59f73009dd16f9dd443ca8d66817fb4b10a
4,048
package com.example.xiaojin20135.imagebrowsepro; import android.content.Intent; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.WindowManager; import android.widget.ProgressBar; import android.widget.TextView; import com.example.xiaojin20135.imagebrowsepro.adapter.ImageBrowseAdapter; import com.example.xiaojin20135.imagebrowsepro.inter.ImageLongClick; import java.lang.reflect.Array; import java.util.ArrayList; public class ImageBrowserActivity extends AppCompatActivity implements ImageLongClick { private ProgressBar loading_progress; private TextView mNumberTextView; private ArrayList<String> imageList = new ArrayList<>(); private ViewPager imageBrowserViewPager; private ImageBrowseAdapter imageBrowseAdapter; private int currentIndex = 0; //是否是网络图片 private boolean fromNet = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_image_browser); //加载动画 overridePendingTransition(R.anim.fade_in,R.anim.fade_out); //全屏 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); loadData(); initView(); initEvents(); //展示数据 showData(); } private void loadData(){ Intent intent = getIntent (); if(intent != null){ currentIndex = intent.getIntExtra("index", 0); fromNet = intent.getBooleanExtra("fromNet",false); imageList = (ArrayList<String>) intent.getStringArrayListExtra("imageList"); } } private void initView(){ loading_progress = (ProgressBar)findViewById(R.id.loading_progress); mNumberTextView = (TextView)findViewById(R.id.number_textview); imageBrowserViewPager = (ViewPager)findViewById (R.id.imageBrowseViewPager); imageBrowseAdapter = new ImageBrowseAdapter (this,imageList,this); imageBrowserViewPager.setAdapter (imageBrowseAdapter); imageBrowserViewPager.setCurrentItem (currentIndex); } private void initEvents(){ imageBrowserViewPager.addOnPageChangeListener (new ViewPager.OnPageChangeListener () { @Override public void onPageScrolled (int position, float positionOffset, int positionOffsetPixels) { currentIndex = position; updateBottomIndex(position + 1); } @Override public void onPageSelected (int position) { updateBottomIndex(position + 1); } @Override public void onPageScrollStateChanged (int state) { } }); } /* * @author lixiaojin * create on 2019/8/1 16:17 * description: 展示数据 */ private void showData(){ if(imageList.size() > 0) { updateBottomIndex(currentIndex + 1); } } /* * @author lixiaojin * create on 2019/8/1 16:13 * description: 底部数字索引 */ private void updateBottomIndex(int count){ mNumberTextView.setText(count + "/" + imageList.size()); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(KeyEvent.KEYCODE_BACK == keyCode){ back(); return true; } return super.onKeyDown(keyCode, event); } private void back(){ Intent intent = new Intent (); intent.putStringArrayListExtra ("imageList",imageList); setResult (RESULT_OK,intent); this.finish (); } @Override public void finish() { super.finish(); overridePendingTransition(R.anim.fade_in_disappear,R.anim.fade_out_disappear); } @Override public void longClickImage(int position) { //如果是网络图片 if(fromNet){ }else{//如果是本地图片预览 } } }
30.208955
116
0.657115
849203d3b1664faa80310cfe340023a822bb6d50
12,353
/* Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.api.codegen.transformer.java; import com.google.api.codegen.config.DiscoveryField; import com.google.api.codegen.config.FieldConfig; import com.google.api.codegen.config.FieldModel; import com.google.api.codegen.config.TypeModel; import com.google.api.codegen.discogapic.transformer.DiscoGapicNamer; import com.google.api.codegen.discovery.Schema; import com.google.api.codegen.discovery.Schema.Type; import com.google.api.codegen.transformer.SchemaTypeNameConverter; import com.google.api.codegen.transformer.SurfaceNamer; import com.google.api.codegen.util.Name; import com.google.api.codegen.util.TypeName; import com.google.api.codegen.util.TypeNameConverter; import com.google.api.codegen.util.TypedValue; import com.google.api.codegen.util.java.JavaNameFormatter; import com.google.api.codegen.util.java.JavaTypeTable; import com.google.common.base.Strings; /** The Schema TypeName converter for Java. */ public class JavaSchemaTypeNameConverter extends SchemaTypeNameConverter { /** The package prefix protoc uses if no java package option was provided. */ private static final String DEFAULT_JAVA_PACKAGE_PREFIX = "com.google.discovery"; private final TypeNameConverter typeNameConverter; private final JavaNameFormatter nameFormatter; private final String implicitPackageName; private final DiscoGapicNamer discoGapicNamer = new DiscoGapicNamer(); private final JavaSurfaceNamer namer; public JavaSchemaTypeNameConverter(String implicitPackageName, JavaNameFormatter nameFormatter) { this.typeNameConverter = new JavaTypeTable(implicitPackageName); this.nameFormatter = nameFormatter; this.implicitPackageName = implicitPackageName; this.namer = new JavaSurfaceNamer(implicitPackageName, implicitPackageName); } private static String getPrimitiveTypeName(Schema schema) { if (schema == null) { return "java.lang.Void"; } switch (schema.type()) { case INTEGER: return "int"; case NUMBER: switch (schema.format()) { case FLOAT: return "float"; case DOUBLE: default: return "double"; } case BOOLEAN: return "boolean"; case STRING: return "java.lang.String"; default: return null; } } /** * A map from primitive types in proto to zero values in Java. Returns 'Void' if input is null. */ private static String getPrimitiveZeroValue(Schema schema) { String primitiveType = getPrimitiveTypeName(schema); if (primitiveType == null) { return null; } if (primitiveType.equals("boolean")) { return "false"; } if (primitiveType.equals("int") || primitiveType.equals("long") || primitiveType.equals("double") || primitiveType.equals("float")) { return "0"; } if (primitiveType.equals("java.lang.String")) { return "\"\""; } if (primitiveType.equals("java.lang.Void")) { return "null"; } throw new IllegalArgumentException("Schema is of unknown type."); } @Override public DiscoGapicNamer getDiscoGapicNamer() { return discoGapicNamer; } @Override public SurfaceNamer getNamer() { return namer; } @Override public TypeName getTypeNameInImplicitPackage(String shortName) { return typeNameConverter.getTypeNameInImplicitPackage(shortName); } @Override public TypeName getTypeName(DiscoveryField field) { return getTypeName(field, BoxingBehavior.NO_BOX_PRIMITIVES); } @Override public TypedValue getEnumValue(DiscoveryField field, String value) { return TypedValue.create(getTypeName(field), "%s." + value); } @Override public TypeName getTypeNameForElementType(TypeModel type) { if (type.isStringType()) { return typeNameConverter.getTypeName("java.lang.String"); } else if (type.isEmptyType()) { return typeNameConverter.getTypeName("java.lang.Void"); } return getTypeNameForElementType((DiscoveryField) type); } /** * Returns the Java representation of a type, without cardinality. If the type is a Java * primitive, basicTypeName returns it in unboxed form. * * @param fieldModel The Schema to generate a TypeName from. * <p>This method will be recursively called on the given schema's children. */ private TypeName getTypeNameForElementType( DiscoveryField fieldModel, BoxingBehavior boxingBehavior) { if (fieldModel == null) { return new TypeName("java.lang.Void", "Void"); } Schema schema = fieldModel.getOriginalDiscoveryField(); String primitiveTypeName = getPrimitiveTypeName(schema); if (primitiveTypeName != null) { if (primitiveTypeName.contains(".")) { // Fully qualified type name, use regular type name resolver. Can skip boxing logic // because those types are already boxed. return typeNameConverter.getTypeName(primitiveTypeName); } else { switch (boxingBehavior) { case BOX_PRIMITIVES: return new TypeName(JavaTypeTable.getBoxedTypeName(primitiveTypeName)); case NO_BOX_PRIMITIVES: return new TypeName(primitiveTypeName); default: throw new IllegalArgumentException( String.format("Unhandled boxing behavior: %s", boxingBehavior.name())); } } } if (schema.type().equals(Type.ARRAY)) { return getTypeName( DiscoveryField.create(schema.dereference().items(), fieldModel.getDiscoApiModel()), BoxingBehavior.BOX_PRIMITIVES); } else { String packageName = !implicitPackageName.isEmpty() ? implicitPackageName : DEFAULT_JAVA_PACKAGE_PREFIX; String shortName = ""; if (schema.additionalProperties() != null && !Strings.isNullOrEmpty(schema.additionalProperties().reference())) { shortName = schema.additionalProperties().reference(); } else { shortName = namer.publicClassName(Name.anyCamel(fieldModel.getSimpleName())); } String longName = packageName + "." + shortName; return new TypeName(longName, shortName); } } /** * Returns the Java representation of a type, with cardinality. If the type is a Java primitive, * basicTypeName returns it in unboxed form. * * @param field The Schema to generate a TypeName from. * <p>This method will be recursively called on the given schema's children. */ @Override public TypeName getTypeName(DiscoveryField field, BoxingBehavior boxingBehavior) { TypeName elementTypeName = getTypeNameForElementType(field, BoxingBehavior.BOX_PRIMITIVES); if (field == null) { return elementTypeName; } Schema schema = field.getDiscoveryField(); if (schema.isMap()) { TypeName mapTypeName = typeNameConverter.getTypeName("java.util.Map"); TypeName keyTypeName = typeNameConverter.getTypeName("java.lang.String"); TypeName valueTypeName = getTypeNameForElementType( DiscoveryField.create(schema.additionalProperties(), field.getDiscoApiModel()), BoxingBehavior.BOX_PRIMITIVES); return new TypeName( mapTypeName.getFullName(), mapTypeName.getNickname(), "%s<%i, %i>", keyTypeName, valueTypeName); } if (schema.repeated() || schema.type().equals(Type.ARRAY)) { TypeName listTypeName = typeNameConverter.getTypeName("java.util.List"); return new TypeName( listTypeName.getFullName(), listTypeName.getNickname(), "%s<%i>", elementTypeName); } else { return elementTypeName; } } @Override public TypeName getTypeNameForElementType(DiscoveryField type) { return getTypeNameForElementType(type, BoxingBehavior.BOX_PRIMITIVES); } @Override public String renderPrimitiveValue(Schema schema, String value) { String primitiveType = getPrimitiveTypeName(schema); if (primitiveType == null) { throw new IllegalArgumentException( "Initial values are only supported for primitive types, got type " + schema + ", with value " + value); } if (primitiveType.equals("boolean")) { return value.toLowerCase(); } else if (primitiveType.equals("long")) { return value + "L"; } else if (primitiveType.equals("float")) { return value + "F"; } if (primitiveType.equals("int") || primitiveType.equals("double")) { return value; } if (primitiveType.equals("java.lang.String")) { return "\"" + value + "\""; } throw new IllegalArgumentException("Schema is of unknown type."); } @Override public String renderPrimitiveValue(TypeModel type, String value) { if (type.isStringType()) { return "\"" + value + "\""; } return renderPrimitiveValue(((DiscoveryField) type).getDiscoveryField(), value); } @Override public String renderValueAsString(String value) { return "\"" + value + "\""; } /** * Returns the Java representation of a zero value for that type, to be used in code sample doc. * * <p>Parametric types may use the diamond operator, since the return value will be used only in * initialization. */ @Override public TypedValue getSnippetZeroValue(DiscoveryField field) { Schema schema = field.getDiscoveryField(); if (getPrimitiveTypeName(schema) != null) { return TypedValue.create(getTypeName(field), getPrimitiveZeroValue(schema)); } if (field.isMap()) { return TypedValue.create(typeNameConverter.getTypeName("java.util.HashMap"), "new %s<>()"); } if (field.isRepeated()) { return TypedValue.create(typeNameConverter.getTypeName("java.util.ArrayList"), "new %s<>()"); } if (schema.type() == Type.OBJECT) { return TypedValue.create(getTypeNameForElementType(field), "%s.newBuilder().build()"); } return TypedValue.create(getTypeName(field), "null"); } /** * Returns the Java representation of a zero value for that type, to be used in code sample doc. * * <p>Parametric types may use the diamond operator, since the return value will be used only in * initialization. */ @Override public TypedValue getSnippetZeroValue(TypeModel typeModel) { if (typeModel.isEmptyType()) { return TypedValue.create(getTypeName((DiscoveryField) null), "null"); } return getSnippetZeroValue((DiscoveryField) typeModel); } @Override public TypedValue getImplZeroValue(DiscoveryField type) { return getSnippetZeroValue(type); } private TypeName getTypeNameForTypedResourceName(FieldModel type, String typedResourceShortName) { String packageName = implicitPackageName; String longName = packageName + "." + typedResourceShortName; TypeName simpleTypeName = new TypeName(longName, typedResourceShortName); if (type.isMap()) { throw new IllegalArgumentException("Map type not supported for typed resource name"); } else if (type.isRepeated()) { TypeName listTypeName = typeNameConverter.getTypeName("java.util.List"); return new TypeName( listTypeName.getFullName(), listTypeName.getNickname(), "%s<%i>", simpleTypeName); } else { return simpleTypeName; } } @Override public TypeName getTypeNameForTypedResourceName( FieldConfig fieldConfig, String typedResourceShortName) { return getTypeNameForTypedResourceName(fieldConfig.getField(), typedResourceShortName); } @Override public TypeName getTypeNameForResourceNameElementType( FieldConfig fieldConfig, String typedResourceShortName) { return getTypeNameForTypedResourceName(fieldConfig.getField(), typedResourceShortName); } }
35.909884
100
0.696754
b08e91e1d457bcfc12d89abf00df0383f3689b07
3,159
/* * Copyright (c) 2008, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ package com.sun.hotspot.igv.filter; import com.sun.hotspot.igv.graph.Diagram; import com.sun.hotspot.igv.graph.Figure; import com.sun.hotspot.igv.graph.Selector; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * * @author Thomas Wuerthinger */ public class RemoveFilter extends AbstractFilter { private List<RemoveRule> rules; private String name; public RemoveFilter(String name) { this.name = name; rules = new ArrayList<>(); } @Override public String getName() { return name; } @Override public void apply(Diagram diagram) { for (RemoveRule r : rules) { List<Figure> selected = r.getSelector().selected(diagram); Set<Figure> toRemove = new HashSet<>(selected); if (r.getRemoveOrphans()) { boolean changed; do { changed = false; for (Figure f : diagram.getFigures()) { if (!toRemove.contains(f)) { if (toRemove.containsAll(f.getPredecessors()) && toRemove.containsAll(f.getSuccessors())) { toRemove.add(f); changed = true; } } } } while (changed); } diagram.removeAllFigures(toRemove); } } public void addRule(RemoveRule rule) { rules.add(rule); } public static class RemoveRule { private Selector selector; private boolean removeOrphans; public RemoveRule(Selector selector) { this(selector, false); } public RemoveRule(Selector selector, boolean removeOrphans) { this.selector = selector; this.removeOrphans = removeOrphans; } public Selector getSelector() { return selector; } public boolean getRemoveOrphans() { return removeOrphans; } } }
30.085714
119
0.61032