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
efbbef43efe23a8312844c4924ff5a8cab56b07d
150
package epicsquid.mysticallib.particle; public interface IParticle { boolean alive(); boolean isAdditive(); boolean renderThroughBlocks(); }
15
39
0.76
0ff6dc9c0b899beb349334d4adda2b13c30c3cec
4,282
/* * Copyright (c) 2010-2018. Axon Framework * * 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.axonframework.eventhandling.interceptors; import org.axonframework.eventhandling.EventMessage; import org.axonframework.messaging.ExecutionException; import org.axonframework.messaging.Message; import org.axonframework.messaging.MessageDispatchInterceptor; import org.axonframework.messaging.unitofwork.CurrentUnitOfWork; import org.axonframework.messaging.unitofwork.ExecutionResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.function.BiFunction; import java.util.stream.Collectors; /** * Message Dispatch Interceptor that logs published events to a SLF4J logger. It does not alter or reject events. * <p/> * The interceptor also logs the cause of the published events. E.g. if the cause of the events is a command, the * interceptor also logs the command and the execution result of the command. * <p/> * The interceptor allows for configuration of the name under which the logger should log the statements. All logging * is done at the {@code INFO} level. * * @author Rene de Waele * @since 3.0 */ public class EventLoggingInterceptor implements MessageDispatchInterceptor<EventMessage<?>> { private final Logger logger; /** * Initialize the LoggingInterceptor with the default logger name, which is the fully qualified class name of this * logger. * * @see EventLoggingInterceptor#EventLoggingInterceptor(String) */ public EventLoggingInterceptor() { this(EventLoggingInterceptor.class.getName()); } /** * Initialize the interceptor with the given {@code loggerName}. The actual logging implementation will * use this name to decide the appropriate log level and location. See the documentation of your logging * implementation for more information. * * @param loggerName the name of the logger */ public EventLoggingInterceptor(String loggerName) { this.logger = LoggerFactory.getLogger(loggerName); } @Override public BiFunction<Integer, EventMessage<?>, EventMessage<?>> handle(List<? extends EventMessage<?>> messages) { StringBuilder sb = new StringBuilder(String.format("Events published: [%s]", messages.stream().map(m -> m.getPayloadType().getSimpleName()).collect(Collectors.joining(", ")))); CurrentUnitOfWork.ifStarted(unitOfWork -> { Message<?> message = unitOfWork.getMessage(); if (message == null) { sb.append(" while processing an operation not tied to an incoming message"); } else { sb.append(String.format(" while processing a [%s]", message.getPayloadType().getSimpleName())); } ExecutionResult executionResult = unitOfWork.getExecutionResult(); if (executionResult != null) { if (executionResult.isExceptionResult()) { @SuppressWarnings("ThrowableResultOfMethodCallIgnored") Throwable exception = executionResult.getExceptionResult(); exception = exception instanceof ExecutionException ? exception.getCause() : exception; sb.append(String.format(" which failed with a [%s]", exception.getClass().getSimpleName())); } else if (executionResult.getResult() != null) { sb.append(String.format(" which yielded a [%s] return value", executionResult.getResult().getClass().getSimpleName())); } } }); logger.info(sb.toString()); return (i, m) -> m; } }
44.14433
158
0.678655
3caebdc6fcad8bb5661214336c6264586f75929f
772
package xyz.upperlevel.uppercore.storage; public enum DuplicatePolicy { /** * If another entry is already in the database then the one that is already present will be kept * and the database will not be changed. */ KEEP_OLD, /** * The entry inserted will replace any older entries if present, so the database will always be modified. */ REPLACE, /** * If a data row is already present updates the existing data with the given one. * If a parameter is found in both, the one from the new entry will take precedence. * If a parameter is present only in the given entry, it'll be added. * This is not a deep operation hence this will treat map values like normal objects, replacing them. */ MERGE, }
36.761905
109
0.685233
c5fc77df239ea4602ef1ac0ac5c566083f0b8eca
1,968
package com.softicar.platform.core.module.email.buffer; import com.softicar.platform.core.module.CoreImages; import com.softicar.platform.core.module.CorePermissions; import com.softicar.platform.core.module.email.buffer.attachment.BufferedEmailAttachmentSectionDiv; import com.softicar.platform.core.module.module.instance.system.SystemModuleInstance; import com.softicar.platform.db.runtime.object.IDbObjectTableBuilder; import com.softicar.platform.emf.attribute.IEmfAttributeList; import com.softicar.platform.emf.authorizer.EmfAuthorizer; import com.softicar.platform.emf.form.section.EmfFormSectionConfiguration; import com.softicar.platform.emf.object.table.EmfObjectTable; import com.softicar.platform.emf.permission.EmfPermissions; import com.softicar.platform.emf.table.configuration.EmfTableConfiguration; public class AGBufferedEmailTable extends EmfObjectTable<AGBufferedEmail, SystemModuleInstance> { public AGBufferedEmailTable(IDbObjectTableBuilder<AGBufferedEmail> builder) { super(builder); } @Override public void customizeEmfTableConfiguration(EmfTableConfiguration<AGBufferedEmail, Integer, SystemModuleInstance> configuration) { configuration.setIcon(CoreImages.EMAIL_BUFFER); } @Override public void customizeAuthorizer(EmfAuthorizer<AGBufferedEmail, SystemModuleInstance> authorizer) { authorizer.setViewPermission(CorePermissions.SUPER_USER.toOtherEntityPermission()); authorizer.setEditPermission(EmfPermissions.never()); authorizer.setCreationPermission(EmfPermissions.never()); } @Override public void customizeAttributeProperties(IEmfAttributeList<AGBufferedEmail> attributes) { attributes.editAttribute(AGBufferedEmail.CONTENT).setConcealed(true); attributes.editAttribute(AGBufferedEmail.SUBJECT).setConcealed(true); } @Override public void customizeFormSections(EmfFormSectionConfiguration<AGBufferedEmail> configuration) { configuration.addSection(BufferedEmailAttachmentSectionDiv::new); } }
40.163265
130
0.850102
4d5f22dec0b0d3da93c051b3a47307bf9ebb9be1
6,095
package org.firealm; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import io.realm.RealmAsyncTask; import io.realm.RealmConfiguration; import io.realm.RealmObject; /** * Created by Vinoth on 28-5-16. */ public class Firealm { public static class Builder { protected Firealm firealm; public Builder(Context context, Object defaultRealmModule) { firealm = new Firealm(context, defaultRealmModule); } public Builder addFirebaseReferencePath(Class<? extends FirealmModel> cls, String firebaseReferencePath) { firealm.getMap().put(cls, firebaseReferencePath); return this; } /*public Builder addRealmModules() { return this; }*/ public Firealm build() { firealm.setRealmInstance(); return firealm; } } private Firealm(Context context, Object defaultRealmModule) { setAndroidContext(context); setDefaultRealmModule(defaultRealmModule); setMap(new FirealmMap()); } private FirealmMap map; public FirealmMap getMap() { return map; } public void setMap(FirealmMap map) { this.map = map; } public DatabaseReference getDatabaseReference(Class<? extends FirealmModel> cls) { return getFirebaseInstance().getReference(getMap().get(cls)); } private Context androidContext; protected Context getAndroidContext() { return androidContext; } private void setAndroidContext(Context context) { androidContext = context; } private Object defaultRealmModule; protected Object getDefaultRealmModule() { return defaultRealmModule; } protected void setDefaultRealmModule(Object defaultRealmModule) { this.defaultRealmModule = defaultRealmModule; } private io.realm.Realm realmInstance; public io.realm.Realm getRealmInstance() { return realmInstance; } protected void setRealmInstance() { RealmConfiguration configuration = new RealmConfiguration.Builder(getAndroidContext()) .name("firealm.realm") .modules(getDefaultRealmModule(), new FirealmModule()) .build(); realmInstance = io.realm.Realm.getInstance(configuration); } public FirebaseDatabase getFirebaseInstance() { return FirebaseDatabase.getInstance(); } public RealmAsyncTask writeAsync(@NonNull final FirealmModel model, @Nullable final WriteListener listener) { Realm realm = new Realm(model); final Firebase firebase = new Firebase(model); return realm.writeAsync(new org.firealm.realm.WriteListener() { @Override public void writtenOnRealm() { if (listener != null) listener.writtenOnRealm(); if (firebase.getDatabaseReference() == null) { if (listener != null) listener.errorOnFirebase(DatabaseError.fromException(new Throwable("Firebase reference path not exist"))); } else firebase.write(listener); } @Override public void errorOnRealm(Throwable error) { listener.errorOnRealm(error); } }); } public class Realm extends AbstractFirealm implements io.realm.Realm.Transaction { public Realm(FirealmModel model) { super(model); } @Override public void execute(io.realm.Realm realm) { RealmObject object = (RealmObject) getModel(); realm.copyToRealmOrUpdate(object); } public void write() { getRealmInstance().executeTransaction(this); } public RealmAsyncTask writeAsync(final org.firealm.realm.WriteListener listener) { return getRealmInstance().executeTransactionAsync(this, new OnSuccess() { @Override public void onSuccess() { listener.writtenOnRealm(); } }, new OnError() { @Override public void onError(Throwable error) { listener.errorOnRealm(error); } }); } } public class Firebase extends AbstractFirealm { public Firebase(FirealmModel model) { super(model); setDatabaseReference(Firealm.this.getDatabaseReference(getModel().getClass()).child(getProperty().getKey())); } private DatabaseReference databaseReference; public DatabaseReference getDatabaseReference() { return databaseReference; } public void setDatabaseReference(DatabaseReference databaseReference) { this.databaseReference = databaseReference; } protected void write(DatabaseReference.CompletionListener listener) { if (getProperty().getPriority() == null) getDatabaseReference().setValue(getModel(), getProperty().getPriority(), listener); else getDatabaseReference().setValue(getModel(), listener); } public void write(final org.firealm.firebase.WriteListener listener) { write(new DatabaseReference.CompletionListener() { @Override public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) { if (databaseError == null) { if (listener != null) listener.writtenOnFirebase(); } else { if (listener != null) listener.errorOnFirebase(databaseError); } } }); } } }
30.939086
130
0.610664
0869127507e7ef229a6507589edbc80ec66e7ec7
565
package cz.tefek.pluto.engine.graphics.spritesheet; public abstract class SpriteSheet<T> { protected T spriteSheet; public SpriteSheet(T sourceImage) { this.spriteSheet = sourceImage; } public SpriteSheet() { } public void setSpriteSheetImage(T sourceImage) { this.spriteSheet = sourceImage; } public T getSpriteSheetImage() { return this.spriteSheet; } public abstract int getWidthInPixels(); public abstract int getHeightInPixels(); public abstract void delete(); }
17.121212
51
0.660177
dd07cb45eff2865bf97b90e215f057947273d177
9,831
/* * Copyright © 2017-2020 factcast.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.factcast.store.pgsql.internal; import com.google.common.collect.Lists; import java.sql.ResultSet; import java.sql.SQLException; import java.util.*; import java.util.concurrent.atomic.AtomicLong; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; import lombok.val; import org.factcast.core.Fact; import org.factcast.core.snap.Snapshot; import org.factcast.core.snap.SnapshotId; import org.factcast.core.spec.FactSpec; import org.factcast.core.store.AbstractFactStore; import org.factcast.core.store.State; import org.factcast.core.store.StateToken; import org.factcast.core.store.TokenStore; import org.factcast.core.subscription.FactTransformerService; import org.factcast.core.subscription.Subscription; import org.factcast.core.subscription.SubscriptionRequestTO; import org.factcast.core.subscription.TransformationException; import org.factcast.core.subscription.observer.FactObserver; import org.factcast.store.pgsql.internal.StoreMetrics.OP; import org.factcast.store.pgsql.internal.lock.FactTableWriteLock; import org.factcast.store.pgsql.internal.query.PgQueryBuilder; import org.factcast.store.pgsql.internal.snapcache.PgSnapshotCache; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.dao.DuplicateKeyException; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementSetter; import org.springframework.jdbc.core.ResultSetExtractor; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; /** * A PostgreSQL based FactStore implementation * * @author uwe.schaefer@prisma-capacity.eu */ @Slf4j public class PgFactStore extends AbstractFactStore { // is that interesting to configure? private static final int BATCH_SIZE = 500; @NonNull private final JdbcTemplate jdbcTemplate; @NonNull private final PgSubscriptionFactory subscriptionFactory; @NonNull private final FactTableWriteLock lock; @NonNull private final FactTransformerService factTransformerService; @NonNull private final PgMetrics metrics; @NonNull private final PgSnapshotCache snapCache; @Autowired public PgFactStore( @NonNull JdbcTemplate jdbcTemplate, @NonNull PgSubscriptionFactory subscriptionFactory, @NonNull TokenStore tokenStore, @NonNull FactTableWriteLock lock, @NonNull FactTransformerService factTransformerService, @NonNull PgSnapshotCache snapCache, @NonNull PgMetrics metrics) { super(tokenStore); this.jdbcTemplate = jdbcTemplate; this.subscriptionFactory = subscriptionFactory; this.lock = lock; this.snapCache = snapCache; this.metrics = metrics; this.factTransformerService = factTransformerService; } @Override public @NonNull Optional<Fact> fetchById(@NonNull UUID id) { return metrics.time( OP.FETCH_BY_ID, () -> jdbcTemplate .query( PgConstants.SELECT_BY_ID, new Object[] {"{\"id\":\"" + id + "\"}"}, this::extractFactFromResultSet) .stream() .findFirst()); } @Override public @NonNull Optional<Fact> fetchByIdAndVersion(@NonNull UUID id, int version) throws TransformationException { val fact = fetchById(id); // map does not work here due to checked exception if (fact.isPresent()) { return Optional.of(factTransformerService.transformIfNecessary(fact.get(), version)); } else { return fact; } } @Override @Transactional(propagation = Propagation.REQUIRED) public void publish(@NonNull List<? extends Fact> factsToPublish) { metrics.time( OP.PUBLISH, () -> { try { lock.aquireExclusiveTXLock(); List<Fact> copiedListOfFacts = Lists.newArrayList(factsToPublish); int numberOfFactsToPublish = factsToPublish.size(); log.trace( "Inserting {} fact(s){}", numberOfFactsToPublish, numberOfFactsToPublish > BATCH_SIZE ? " in batches of " + BATCH_SIZE : ""); jdbcTemplate.batchUpdate( PgConstants.INSERT_FACT, copiedListOfFacts, BATCH_SIZE, (statement, fact) -> { statement.setString(1, fact.jsonHeader()); statement.setString(2, fact.jsonPayload()); }); // add serials to headers jdbcTemplate.batchUpdate( PgConstants.UPDATE_FACT_SERIALS, copiedListOfFacts, BATCH_SIZE, (statement, fact) -> { String idMatch = "{\"id\":\"" + fact.id() + "\"}"; statement.setString(1, idMatch); }); } catch (DuplicateKeyException dupkey) { throw new IllegalArgumentException(dupkey.getMessage()); } }); } private Fact extractFactFromResultSet(ResultSet resultSet, @SuppressWarnings("unused") int rowNum) throws SQLException { return PgFact.from(resultSet); } @NonNull private String extractStringFromResultSet( ResultSet resultSet, @SuppressWarnings("unused") int rowNum) throws SQLException { return resultSet.getString(1); } @Override public @NonNull Subscription subscribe( @NonNull SubscriptionRequestTO request, @NonNull FactObserver observer) { OP operation = request.continuous() ? OP.SUBSCRIBE_FOLLOW : OP.SUBSCRIBE_CATCHUP; return metrics.time(operation, () -> subscriptionFactory.subscribe(request, observer)); } @Override public @NonNull OptionalLong serialOf(@NonNull UUID l) { return metrics.time( OP.SERIAL_OF, () -> { try { Long res = jdbcTemplate.queryForObject( PgConstants.SELECT_SER_BY_ID, new Object[] {"{\"id\":\"" + l + "\"}"}, Long.class); if (res != null && res > 0) { return OptionalLong.of(res); } } catch (EmptyResultDataAccessException ignore) { // ignore } return OptionalLong.empty(); }); } @Override public @NonNull Set<String> enumerateNamespaces() { return metrics.time( OP.ENUMERATE_NAMESPACES, () -> new HashSet<>( jdbcTemplate.query( PgConstants.SELECT_DISTINCT_NAMESPACE, this::extractStringFromResultSet))); } @Override public @NonNull Set<String> enumerateTypes(@NonNull String ns) { return metrics.time( OP.ENUMERATE_TYPES, () -> new HashSet<>( jdbcTemplate.query( PgConstants.SELECT_DISTINCT_TYPE_IN_NAMESPACE, new Object[] {ns}, this::extractStringFromResultSet))); } @Override @Transactional(propagation = Propagation.REQUIRED) public boolean publishIfUnchanged( @NonNull List<? extends Fact> factsToPublish, @NonNull Optional<StateToken> optionalToken) { return metrics.time( OP.PUBLISH_IF_UNCHANGED, () -> { lock.aquireExclusiveTXLock(); return super.publishIfUnchanged(factsToPublish, optionalToken); }); } @Override protected State getStateFor(@NonNull List<FactSpec> specs) { return metrics.time( OP.GET_STATE_FOR, () -> { PgQueryBuilder pgQueryBuilder = new PgQueryBuilder(specs); String stateSQL = pgQueryBuilder.createStateSQL(); PreparedStatementSetter statementSetter = pgQueryBuilder.createStatementSetter(new AtomicLong(0)); try { ResultSetExtractor<Long> rch = new ResultSetExtractor<Long>() { @Override public Long extractData(ResultSet resultSet) throws SQLException, DataAccessException { if (!resultSet.next()) { return 0L; } else { return resultSet.getLong(1); } } }; long lastSerial = jdbcTemplate.query(stateSQL, statementSetter, rch); return State.of(specs, lastSerial); } catch (EmptyResultDataAccessException lastSerialIs0Then) { return State.of(specs, 0); } }); } @Override public long currentTime() { return jdbcTemplate.queryForObject(PgConstants.CURRENT_TIME_MILLIS, Long.class); } @Override public @NonNull Optional<Snapshot> getSnapshot(@NonNull SnapshotId id) { return metrics.time(OP.GET_SNAPSHOT, () -> snapCache.getSnapshot(id)); } @Override public void setSnapshot(@NonNull Snapshot snapshot) { metrics.time(OP.SET_SNAPSHOT, () -> snapCache.setSnapshot(snapshot)); } @Override public void clearSnapshot(@NonNull SnapshotId id) { metrics.time(OP.CLEAR_SNAPSHOT, () -> snapCache.clearSnapshot(id)); } }
34.254355
100
0.658427
c7bf5debbe031e6e1beba390b69880db97d638ef
1,800
package org.pollbox.poll.managers; import org.pollbox.poll.accounts.AccountsService; import org.pollbox.poll.owners.OwnersService; import org.pollbox.poll.projects.ProjectsService; import org.pollbox.poll.signup.SignupService; import org.pollbox.poll.statuses.StatusesService; import org.springframework.beans.factory.annotation.Autowired; /** * Provides access to service classes that implements business logic. */ public class ServiceManager { @Autowired private SignupService signupService; @Autowired private OwnersService ownersService; @Autowired private AccountsService accountsService; @Autowired private StatusesService statusesService; @Autowired private ProjectsService projectsService; public StatusesService getStatusesService() { return statusesService; } public void setStatusesService(StatusesService statusesService) { this.statusesService = statusesService; } public AccountsService getAccountsService() { return accountsService; } public void setAccountsService(AccountsService accountsService) { this.accountsService = accountsService; } public OwnersService getOwnersService() { return ownersService; } public void setOwnersService(OwnersService ownersService) { this.ownersService = ownersService; } public ProjectsService getProjectsService() { return projectsService; } public void setProjectsService(ProjectsService projectsService) { this.projectsService = projectsService; } public SignupService getSignupService() { return signupService; } public void setSignupService(SignupService signupService) { this.signupService = signupService; } }
25.352113
69
0.735
83d5df75722e2c6aa75efc6930221f73b43f0a1c
7,758
package pojo; import java.math.BigDecimal; import java.util.Date; /** * Created by Administrator on 2020/8/13. */ public class OrderInformation { private Integer id; private String storgeName; private String assignCarState = "否"; private String clientName; private String contect; private String contcetNum; private String lat; private String areaId; private float vol; private float standard; //总件数 private float num; private float wholeNum; private float weight; private double money; private BigDecimal clientId; private String lon; private String waveId; private float turnoverNumber; private String turnoverNumberType; //复核后总体积 private float turnoverVol; private float departVol; private float totalCheckedVol; private float totaUnCheckedVol; private Date createTime; private Date assignCarTime; private String assignCarId; private char checkState; private Integer orderTypeAssign; private String turnBoxCode; private String yesOrno; private int SendSeq; //派车顺序 //点到纺锤体中线的直线距离 private double distanceToMidline = 0; public OrderInformation(BigDecimal clientId,String lat, String lon, float turnoverVol) { this.lat = lat; this.clientId = clientId; this.lon = lon; this.turnoverVol = turnoverVol; } public OrderInformation(){ } public int getSendSeq() { return SendSeq; } public void setSendSeq(int sendSeq) { SendSeq = sendSeq; } public Integer getOrderTypeAssign() { return orderTypeAssign; } public void setOrderTypeAssign(Integer orderTypeAssign) { this.orderTypeAssign = orderTypeAssign; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getStorgeName() { return storgeName; } public void setStorgeName(String storgeName) { this.storgeName = storgeName; } public String getWaveId() { return waveId; } public void setWaveId(String waveId) { this.waveId = waveId; } public String getAssignCarState() { return assignCarState; } public void setAssignCarState(String assignCarState) { this.assignCarState = assignCarState; } public String getClientName() { return clientName; } public void setClientName(String clientName) { this.clientName = clientName == null ? null : clientName.trim(); } public String getContect() { return contect; } public void setContect(String contect) { this.contect = contect == null ? null : contect.trim(); } public String getContcetNum() { return contcetNum; } public void setContcetNum(String contcetNum) { this.contcetNum = contcetNum == null ? null : contcetNum.trim(); } public String getLat() { return lat; } public void setLat(String lat) { this.lat = lat == null ? null : lat.trim(); } public String getAreaId() { return areaId; } public void setAreaId(String areaId) { this.areaId = areaId == null ? null : areaId.trim(); } public float getVol() { return vol; } public void setVol(float vol) { this.vol = vol; } public float getNum() { return num; } public void setNum(float num) { this.num = num; } public float getWeight() { return weight; } public void setWeight(float weight) { this.weight = weight; } public double getMoney() { return money; } public void setMoney(double money) { this.money = money; } public BigDecimal getClientId() { return clientId; } public void setClientId(BigDecimal clientId) { this.clientId = clientId; } public String getLon() { return lon; } public void setLon(String lon) { this.lon = lon == null ? null : lon.trim(); } public float getTurnoverNumber() { return turnoverNumber; } public void setTurnoverNumber( float turnoverNumber) { this.turnoverNumber = turnoverNumber; } public float getTurnoverVol() { return turnoverVol; } public void setTurnoverVol( float turnoverVol) { this.turnoverVol = turnoverVol; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getAssignCarTime() { return assignCarTime; } public void setAssignCarTime(Date assignCarTime) { this.assignCarTime = assignCarTime; } public String getAssignCarId() { return assignCarId; } public void setAssignCarId(String assignCarId) { this.assignCarId = assignCarId; } public char getCheckState() { return checkState; } public void setCheckState(char checkState) { this.checkState = checkState; } @Override public int hashCode(){ final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return false; if (obj == null) return false; if (getClass() != obj.getClass()) return false; OrderInformation other = (OrderInformation) obj; return this.clientId.equals(other.clientId) &&this.waveId.equals(other.waveId) &&this.storgeName.equals(other.storgeName); } public String getTurnBoxCode() { return turnBoxCode; } public void setTurnBoxCode(String turnBoxCode) { this.turnBoxCode = turnBoxCode; } public String getYesOrno() { return yesOrno; } public void setYesOrno(String yesOrno) { this.yesOrno = yesOrno; } public float getDepartVol() { return departVol; } public void setDepartVol(float departVol) { this.departVol = departVol; } public float getTotalCheckedVol() { return totalCheckedVol; } public void setTotalCheckedVol(float totalCheckedVol) { this.totalCheckedVol = totalCheckedVol; } public float getTotaUnCheckedVol() { return totaUnCheckedVol; } public void setTotaUnCheckedVol(float totaUnCheckedVol) { this.totaUnCheckedVol = totaUnCheckedVol; } public String getTurnoverNumberType() { return turnoverNumberType; } public void setTurnoverNumberType(String turnoverNumberType) { this.turnoverNumberType = turnoverNumberType; } public float getWholeNum() { return wholeNum; } public void setWholeNum(float wholeNum) { this.wholeNum = wholeNum; } public float getStandard() { return standard; } public void setStandard(float standard) { this.standard = standard; } public double getDistanceToMidline() { return distanceToMidline; } public void setDistanceToMidline(double distanceToMidline) { this.distanceToMidline = distanceToMidline; } }
21.610028
94
0.593839
71d23e5723608ebe0254c85aba3cc51bde8af589
396
package com.xiaobai.order.client; import com.xiaobai.order.entity.UcenterMemberOrder; import org.springframework.stereotype.Component; /** * @author xiaobai * @create 2021-08-19 17:29 */ @Component public class UcoreClientImpl implements UcoreClient{ @Override public UcenterMemberOrder getMemberById(String id) { System.out.println("服务降级了~~~"); return null; } }
22
56
0.724747
4df129f53ff3ac26200b61525e852a1849bb8cce
3,391
package de.mpg.mpi_inf.ambiversenlu.nlu.entitylinking.service.web.model; import com.fasterxml.jackson.annotation.*; import javax.annotation.Generated; import java.util.HashMap; import java.util.List; import java.util.Map; @JsonInclude(JsonInclude.Include.NON_NULL) @Generated("org.jsonschema2pojo") @JsonPropertyOrder({ "text", "normalizedForm", "charOffset", "charLength", "uri", "confidence" }) public class Constituent { @JsonProperty("text") private String text; @JsonProperty("charOffset") private Integer charOffset; @JsonProperty("charLength") private Integer charLength; @JsonProperty("uri") private String uri; @JsonProperty("confidence") private Double confidence; @JsonProperty("entities") @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonIgnore private List<Entity> entitis; @JsonProperty("normalizedForm") private String normalizedForm; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); public Constituent() { } public String getnormalizedForm() { return normalizedForm; } public void setnormalizedForm(String normalizedForm) { this.normalizedForm = normalizedForm; } public Constituent withNormalizedForm(String normalizedForm) { this.normalizedForm = normalizedForm; return this; } public String getText() { return text; } public void setText(String text) { this.text = text; } public Constituent withText(String Text) { this.text = text; return this; } public Integer getCharOffset() { return charOffset; } public void setCharOffset(Integer charOffset) { this.charOffset = charOffset; } public Constituent withCharOffset(Integer charOffset) { this.charOffset = charOffset; return this; } public Integer getCharLength() { return charLength; } public void setCharLength(Integer charLength) { this.charLength = charLength; } public Constituent withCharLength(Integer charLength) { this.charLength = charLength; return this; } public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public Constituent withUri(String uri) { this.uri = uri; return this; } public Double getConfidence() { return confidence; } public void setConfidence(Double confidence) { this.confidence = confidence; } public Constituent withConfidence(Double confidence) { this.confidence = confidence; return this; } @JsonIgnore public List<Entity> getEntitis() { return entitis; } @JsonIgnore public void setEntitis(List<Entity> entitis) { this.entitis = entitis; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } public Constituent withAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); return this; } }
22.163399
85
0.651135
f75b207939d70b3778027994bfc2068198f51db3
1,521
package ai.prima.prima.commands; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.IntStream; import ai.prima.prima.PrimaAI; import ai.prima.prima.nodes.Node; import ai.prima.prima.util.Log; public class NetworkCommand extends Command{ private static final String NETWORK = "network"; private final PrimaAI ai; public NetworkCommand(PrimaAI ai) { super("network", "Lists all loaded networks. or shows details about a specific network", Arrays.asList(), Arrays.asList(NETWORK), Arrays.asList()); this.ai = ai; } @Override public void execute(Map<String, String> args) { if(args.containsKey(NETWORK)) { } else { ai.getNetworks().forEach(network -> { Log.writeLine(" -" + network.getName()); }); } } private void printNodeInfo(List<Node> nodes, Node node) { Log.writeLine(node.getClass().getSimpleName() + ":" + nodes.indexOf(node)); node.getConnections().forEach(connection -> { printNodeInfo(nodes, connection.getTarget(), 1); }); } private void printNodeInfo(List<Node> nodes, Node node, int depth) { Log.writeLine(buildIndent(depth) + node.getClass().getSimpleName() + ":" + nodes.indexOf(node)); node.getConnections().forEach(connection -> { printNodeInfo(nodes, connection.getTarget(), depth + 1); }); } private String buildIndent(int depth) { StringBuilder indent = new StringBuilder(); IntStream.of(0, depth).forEach(i -> { indent.append(" "); }); return indent.toString(); } }
25.779661
98
0.693623
0b5002fc627f0c8fcf390d03104ceccdc0ad4854
7,129
/******************************************************************************* * Copyright (C) 2021, Ko Sugawara * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ package org.elephant.actions.mixins; import java.io.File; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import javax.swing.JOptionPane; import org.elephant.actions.ElephantStatusService.ElephantStatus; import bdv.viewer.animate.TextOverlayAnimator.TextPosition; import kong.unirest.Callback; import kong.unirest.HttpResponse; import kong.unirest.MultipartBody; import kong.unirest.RequestBodyEntity; import kong.unirest.Unirest; import kong.unirest.UnirestException; /** * Wrapper for Unirest. * * @author Ko Sugawara */ public interface UnirestMixin extends ElephantActionMixin, ElephantStateManagerMixin, LoggerMixin, UIActionMixin { default void validateServerAvailability() throws ElephantConnectException { if ( getServerStateManager().getElephantServerStatus() == ElephantStatus.UNAVAILABLE ) { getClientLogger().severe( "The ELEPHANT server is unavailable" ); JOptionPane.showMessageDialog( null, "The ELEPHANT server is unavailable. Please set it up first.", "ELEPHANT server is unavailable", JOptionPane.ERROR_MESSAGE ); throw new ElephantConnectException( "ELEPHANT server is unavailable" ); } } default RequestBodyEntity postBaseJson( final String endpointUrl, final String body ) throws ElephantConnectException { validateServerAvailability(); return Unirest.post( endpointUrl ) .header( "Content-Type", "application/json" ) .body( body ); } default MultipartBody postBaseMultipartFormData( final String endpointUrl, final File file, final String data ) throws ElephantConnectException { validateServerAvailability(); return Unirest.post( endpointUrl ) .field( "file", file ) .field( "data", data ); } default CompletableFuture< HttpResponse< String > > postMultipartFormDataAsStringAsync( final String endpointUrl, final File file, final String data, final Consumer< HttpResponse< String > > completed ) throws ElephantConnectException { return postMultipartFormDataAsStringAsync( endpointUrl, file, data, completed, e -> { handleError( e ); getClientLogger().severe( "The request has failed" ); showTextOverlayAnimator( e.getLocalizedMessage(), 3000, TextPosition.CENTER ); }, () -> getClientLogger().info( "The request has been cancelled" ) ); } default CompletableFuture< HttpResponse< String > > postMultipartFormDataAsStringAsync( final String endpointUrl, final File file, final String data, final Consumer< HttpResponse< String > > completed, final Consumer< UnirestException > failed, final Runnable cancelled ) throws ElephantConnectException { return postBaseMultipartFormData( endpointUrl, file, data ).asStringAsync( new Callback< String >() { @Override public void failed( UnirestException e ) { failed.accept( e ); }; @Override public void completed( HttpResponse< String > response ) { completed.accept( response ); } @Override public void cancelled() { cancelled.run(); } } ); } default CompletableFuture< HttpResponse< String > > postAsStringAsync( final String endpointUrl, final String body, final Consumer< HttpResponse< String > > completed ) throws ElephantConnectException { return postAsStringAsync( endpointUrl, body, completed, e -> { handleError( e ); getClientLogger().severe( "The request has failed" ); showTextOverlayAnimator( e.getLocalizedMessage(), 3000, TextPosition.CENTER ); }, () -> getClientLogger().info( "The request has been cancelled" ) ); } default CompletableFuture< HttpResponse< String > > postAsStringAsync( final String endpointUrl, final String body, final Consumer< HttpResponse< String > > completed, final Consumer< UnirestException > failed, final Runnable cancelled ) throws ElephantConnectException { return postBaseJson( endpointUrl, body ).asStringAsync( new Callback< String >() { @Override public void failed( UnirestException e ) { failed.accept( e ); }; @Override public void completed( HttpResponse< String > response ) { completed.accept( response ); } @Override public void cancelled() { cancelled.run(); } } ); } default HttpResponse< String > postAsString( final String endpointUrl, final String body ) throws ElephantConnectException { return postBaseJson( endpointUrl, body ).asString(); } default CompletableFuture< HttpResponse< File > > postAsFileAsync( final String endpointUrl, final String body, final String path, final Consumer< HttpResponse< File > > completed ) throws ElephantConnectException { return postAsFileAsync( endpointUrl, body, path, completed, e -> { handleError( e ); getClientLogger().severe( "The request has failed" ); showTextOverlayAnimator( e.getLocalizedMessage(), 3000, TextPosition.CENTER ); }, () -> getClientLogger().info( "The request has been cancelled" ) ); } default CompletableFuture< HttpResponse< File > > postAsFileAsync( final String endpointUrl, final String body, final String path, final Consumer< HttpResponse< File > > completed, final Consumer< UnirestException > failed, final Runnable cancelled ) throws ElephantConnectException { return postBaseJson( endpointUrl, body ).asFileAsync( path, new Callback< File >() { @Override public void failed( UnirestException e ) { failed.accept( e ); }; @Override public void completed( HttpResponse< File > response ) { completed.accept( response ); } @Override public void cancelled() { cancelled.run(); } } ); } }
35.292079
165
0.723103
2b5cf4c339a89909fa6c924c7b33f38ce06b239f
1,712
/* * Copyright (c) 2013-2018, Bingo.Chen (finesoft@gmail.com). * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.corant.asosat.ddd.domain.shared; import java.util.Map; import org.corant.asosat.ddd.domain.model.AbstractValueObject; import org.corant.asosat.ddd.domain.shared.DynamicAttributes.DynamicAttributeMap; /** * @author bingo 下午9:13:58 * */ public class MaintainResultInfo extends AbstractValueObject { private static final long serialVersionUID = 7024532037862347695L; final Long id; final Long vn; final DynamicAttributeMap attributes = new DynamicAttributeMap(); /** * * @param id * @param vn * @param attrs */ public MaintainResultInfo(Long id, Long vn, Map<String, Object> attrs) { super(); this.id = id; this.vn = vn; if (attrs != null) { attributes.putAll(attrs); } } /** * @return the attributes */ public DynamicAttributeMap getAttributes() { return attributes; } /** * @return the id */ public Long getId() { return id; } /** * @return the vn */ public Long getVn() { return vn; } }
23.135135
82
0.655374
198bce9690be3af751f8ae9b254ac780aeab530e
318
package net.okair.springcloud.auth.authorization.service; import net.okair.springcloud.sysadmin.organization.entity.po.User; /** * @author LiuShiZeng */ public interface IUserService { /** * 根据用户唯一标识获取用户信息 * * @param uniqueId * @return */ User getByUniqueId(String uniqueId); }
15.9
66
0.672956
883dc4f23555351218ba58d08be49351e6a02696
18,357
/* * Copyright 2016-2018 Leon Chen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.moilioncircle.redis.replicator; import static com.moilioncircle.redis.replicator.Constants.DOLLAR; import static com.moilioncircle.redis.replicator.Constants.STAR; import static com.moilioncircle.redis.replicator.RedisSocketReplicator.SyncMode.PSYNC; import static com.moilioncircle.redis.replicator.RedisSocketReplicator.SyncMode.SYNC; import static com.moilioncircle.redis.replicator.RedisSocketReplicator.SyncMode.SYNC_LATER; import static com.moilioncircle.redis.replicator.Status.CONNECTED; import static com.moilioncircle.redis.replicator.Status.CONNECTING; import static com.moilioncircle.redis.replicator.Status.DISCONNECTED; import static com.moilioncircle.redis.replicator.Status.DISCONNECTING; import static com.moilioncircle.redis.replicator.cmd.CommandParsers.toInt; import static com.moilioncircle.redis.replicator.util.Concurrents.terminateQuietly; import static com.moilioncircle.redis.replicator.util.Strings.format; import static com.moilioncircle.redis.replicator.util.Strings.isEquals; import static com.moilioncircle.redis.replicator.util.Tuples.of; import static java.util.concurrent.TimeUnit.MILLISECONDS; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import java.util.Objects; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.moilioncircle.redis.replicator.cmd.BulkReplyHandler; import com.moilioncircle.redis.replicator.cmd.Command; import com.moilioncircle.redis.replicator.cmd.CommandName; import com.moilioncircle.redis.replicator.cmd.CommandParser; import com.moilioncircle.redis.replicator.cmd.RedisCodec; import com.moilioncircle.redis.replicator.cmd.ReplyParser; import com.moilioncircle.redis.replicator.cmd.impl.SelectCommand; import com.moilioncircle.redis.replicator.event.PostCommandSyncEvent; import com.moilioncircle.redis.replicator.event.PreCommandSyncEvent; import com.moilioncircle.redis.replicator.io.AsyncBufferedInputStream; import com.moilioncircle.redis.replicator.io.RateLimitInputStream; import com.moilioncircle.redis.replicator.io.RedisInputStream; import com.moilioncircle.redis.replicator.io.RedisOutputStream; import com.moilioncircle.redis.replicator.net.RedisSocketFactory; import com.moilioncircle.redis.replicator.rdb.RdbParser; import com.moilioncircle.redis.replicator.util.Strings; /** * @author Leon Chen * @since 2.1.0 */ public class RedisSocketReplicator extends AbstractReplicator { protected static final Logger logger = LoggerFactory.getLogger(RedisSocketReplicator.class); protected final int port; protected final String host; protected int db = -1; protected Socket socket; protected ReplyParser replyParser; protected ScheduledFuture<?> heartbeat; protected RedisOutputStream outputStream; protected ScheduledExecutorService executor; protected final RedisSocketFactory socketFactory; public RedisSocketReplicator(String host, int port, Configuration configuration) { Objects.requireNonNull(host); if (port <= 0 || port > 65535) throw new IllegalArgumentException("illegal argument port: " + port); Objects.requireNonNull(configuration); this.host = host; this.port = port; this.configuration = configuration; this.socketFactory = new RedisSocketFactory(configuration); builtInCommandParserRegister(); if (configuration.isUseDefaultExceptionListener()) addExceptionListener(new DefaultExceptionListener()); } public String getHost() { return this.host; } public int getPort() { return this.port; } /** * PSYNC * <p> * * @throws IOException when read timeout or connect timeout */ @Override public void open() throws IOException { super.open(); this.executor = Executors.newSingleThreadScheduledExecutor(); try { new RedisSocketReplicatorRetrier().retry(this); } finally { doClose(); doCloseListener(this); terminateQuietly(executor, configuration.getConnectionTimeout(), MILLISECONDS); } } protected SyncMode trySync(final String reply) throws IOException { logger.info(reply); if (reply.startsWith("FULLRESYNC")) { // reset db this.db = -1; parseDump(this); String[] ary = reply.split(" "); configuration.setReplId(ary[1]); configuration.setReplOffset(Long.parseLong(ary[2])); return PSYNC; } else if (reply.startsWith("CONTINUE")) { String[] ary = reply.split(" "); // redis-4.0 compatible String replId = configuration.getReplId(); if (ary.length > 1 && replId != null && !replId.equals(ary[1])) configuration.setReplId(ary[1]); return PSYNC; } else if (reply.startsWith("NOMASTERLINK") || reply.startsWith("LOADING")) { return SYNC_LATER; } else { logger.info("SYNC"); send("SYNC".getBytes()); // reset db this.db = -1; parseDump(this); return SYNC; } } protected void parseDump(final AbstractReplicator replicator) throws IOException { byte[] rawReply = reply(new BulkReplyHandler() { @Override public byte[] handle(long len, RedisInputStream in) throws IOException { if (len != -1) { logger.info("RDB dump file size:{}", len); } else { logger.info("Disk-less replication."); } if (len != -1 && configuration.isDiscardRdbEvent()) { logger.info("discard {} bytes", len); in.skip(len); } else { new RdbParser(in, replicator).parse(); // skip 40 bytes delimiter when disk-less replication if (len == -1) in.skip(40, false); } return "OK".getBytes(); } }); String reply = Strings.toString(rawReply); if ("OK".equals(reply)) return; throw new IOException("SYNC failed. reason : [" + reply + "]"); } protected void establishConnection() throws IOException { connect(); if (configuration.getAuthPassword() != null) auth(configuration.getAuthUser(), configuration.getAuthPassword()); sendPing(); sendSlavePort(); sendSlaveIp(); sendSlaveCapa("eof"); sendSlaveCapa("psync2"); } protected void auth(String user, String password) throws IOException { if (password != null) { // sha256 mask password String mask = "#" + Strings.mask(password); logger.info("AUTH {} {}", user, mask); if (user != null) { send("AUTH".getBytes(), user.getBytes(), password.getBytes()); } else { send("AUTH".getBytes(), password.getBytes()); } final String reply = Strings.toString(reply()); logger.info(reply); if ("OK".equals(reply)) return; if (reply.contains("no password")) { logger.warn("[AUTH {} {}] failed. {}", user, mask, reply); return; } throw new AssertionError("[AUTH " + user + " " + mask + "] failed. " + reply); } } protected void sendPing() throws IOException { logger.info("PING"); send("PING".getBytes()); final String reply = Strings.toString(reply()); logger.info(reply); if ("PONG".equalsIgnoreCase(reply)) return; if (reply.contains("NOAUTH")) throw new AssertionError(reply); if (reply.contains("operation not permitted")) throw new AssertionError("-NOAUTH Authentication required."); logger.warn("[PING] failed. {}", reply); } protected void sendSlavePort() throws IOException { // REPLCONF listening-prot ${port} logger.info("REPLCONF listening-port {}", socket.getLocalPort()); send("REPLCONF".getBytes(), "listening-port".getBytes(), String.valueOf(socket.getLocalPort()).getBytes()); final String reply = Strings.toString(reply()); logger.info(reply); if ("OK".equals(reply)) return; logger.warn("[REPLCONF listening-port {}] failed. {}", socket.getLocalPort(), reply); } protected void sendSlaveIp() throws IOException { // REPLCONF ip-address ${address} logger.info("REPLCONF ip-address {}", socket.getLocalAddress().getHostAddress()); send("REPLCONF".getBytes(), "ip-address".getBytes(), socket.getLocalAddress().getHostAddress().getBytes()); final String reply = Strings.toString(reply()); logger.info(reply); if ("OK".equals(reply)) return; //redis 3.2+ logger.warn("[REPLCONF ip-address {}] failed. {}", socket.getLocalAddress().getHostAddress(), reply); } protected void sendSlaveCapa(String cmd) throws IOException { // REPLCONF capa eof logger.info("REPLCONF capa {}", cmd); send("REPLCONF".getBytes(), "capa".getBytes(), cmd.getBytes()); final String reply = Strings.toString(reply()); logger.info(reply); if ("OK".equals(reply)) return; logger.warn("[REPLCONF capa {}] failed. {}", cmd, reply); } protected void heartbeat() { assert heartbeat == null || heartbeat.isCancelled(); heartbeat = executor.scheduleWithFixedDelay(new Runnable() { @Override public void run() { sendQuietly("REPLCONF".getBytes(), "ACK".getBytes(), String.valueOf(configuration.getReplOffset()).getBytes()); } }, configuration.getHeartbeatPeriod(), configuration.getHeartbeatPeriod(), MILLISECONDS); logger.info("heartbeat started."); } protected void send(byte[] command) throws IOException { send(command, new byte[0][]); } protected void send(byte[] command, final byte[]... args) throws IOException { outputStream.write(STAR); outputStream.write(String.valueOf(args.length + 1).getBytes()); outputStream.writeCrLf(); outputStream.write(DOLLAR); outputStream.write(String.valueOf(command.length).getBytes()); outputStream.writeCrLf(); outputStream.write(command); outputStream.writeCrLf(); for (final byte[] arg : args) { outputStream.write(DOLLAR); outputStream.write(String.valueOf(arg.length).getBytes()); outputStream.writeCrLf(); outputStream.write(arg); outputStream.writeCrLf(); } outputStream.flush(); } protected void sendQuietly(byte[] command, final byte[]... args) { try { send(command, args); } catch (IOException e) { // NOP } } @SuppressWarnings("unchecked") protected <T> T reply() throws IOException { return (T) replyParser.parse(); } @SuppressWarnings("unchecked") protected <T> T reply(BulkReplyHandler handler) throws IOException { return (T) replyParser.parse(handler); } protected void connect() throws IOException { if (!compareAndSet(DISCONNECTED, CONNECTING)) return; try { socket = socketFactory.createSocket(host, port, configuration.getConnectionTimeout()); outputStream = new RedisOutputStream(socket.getOutputStream()); InputStream inputStream = socket.getInputStream(); if (configuration.getAsyncCachedBytes() > 0) { inputStream = new AsyncBufferedInputStream(inputStream, configuration.getAsyncCachedBytes()); } if (configuration.getRateLimit() > 0) { inputStream = new RateLimitInputStream(inputStream, configuration.getRateLimit()); } this.inputStream = new RedisInputStream(inputStream, configuration.getBufferSize()); this.inputStream.setRawByteListeners(this.rawByteListeners); replyParser = new ReplyParser(this.inputStream, new RedisCodec()); logger.info("Connected to redis-server[{}:{}]", host, port); } finally { setStatus(CONNECTED); } } @Override protected void doClose() throws IOException { compareAndSet(CONNECTED, DISCONNECTING); try { if (heartbeat != null) { if (!heartbeat.isCancelled()) heartbeat.cancel(true); logger.info("heartbeat canceled."); } try { if (inputStream != null) { inputStream.setRawByteListeners(null); inputStream.close(); } } catch (IOException e) { // NOP } try { if (outputStream != null) outputStream.close(); } catch (IOException e) { // NOP } try { if (socket != null && !socket.isClosed()) socket.close(); } catch (IOException e) { // NOP } logger.info("socket closed. redis-server[{}:{}]", host, port); } finally { setStatus(DISCONNECTED); } } protected enum SyncMode {SYNC, PSYNC, SYNC_LATER} private class RedisSocketReplicatorRetrier extends AbstractReplicatorRetrier { @Override protected boolean connect() throws IOException { establishConnection(); return true; } @Override protected boolean close(IOException reason) throws IOException { if (reason != null) logger.error("[redis-replicator] socket error. redis-server[{}:{}]", host, port, reason); doClose(); if (reason != null) logger.info("reconnecting to redis-server[{}:{}]. retry times:{}", host, port, (retries + 1)); return true; } @Override protected boolean isManualClosed() { return RedisSocketReplicator.this.isClosed(); } @Override protected boolean open() throws IOException { String replId = configuration.getReplId(); long replOffset = configuration.getReplOffset(); logger.info("PSYNC {} {}", replId, String.valueOf(replOffset >= 0 ? replOffset + 1 : replOffset)); send("PSYNC".getBytes(), replId.getBytes(), String.valueOf(replOffset >= 0 ? replOffset + 1 : replOffset).getBytes()); final String reply = Strings.toString(reply()); SyncMode mode = trySync(reply); if (mode == PSYNC && getStatus() == CONNECTED) { heartbeat(); } else if (mode == SYNC_LATER && getStatus() == CONNECTED) { return false; } if (getStatus() != CONNECTED) return true; submitEvent(new PreCommandSyncEvent()); if (db != -1) { submitEvent(new SelectCommand(db)); } final long[] offset = new long[1]; while (getStatus() == CONNECTED) { Object obj = replyParser.parse(len -> offset[0] = len); if (obj instanceof Object[]) { if (verbose() && logger.isDebugEnabled()) logger.debug(format((Object[]) obj)); Object[] raw = (Object[]) obj; CommandName name = CommandName.name(Strings.toString(raw[0])); final CommandParser<? extends Command> parser; if ((parser = commands.get(name)) == null) { logger.warn("command [{}] not register. raw command:{}", name, format(raw)); configuration.addOffset(offset[0]); offset[0] = 0L; continue; } final long st = configuration.getReplOffset(); final long ed = st + offset[0]; if (isEquals(Strings.toString(raw[0]), "SELECT")) { db = toInt(raw[1]); submitEvent(parser.parse(raw), of(st, ed)); } else if (isEquals(Strings.toString(raw[0]), "REPLCONF") && isEquals(Strings.toString(raw[1]), "GETACK")) { if (mode == PSYNC) executor.execute(new Runnable() { @Override public void run() { sendQuietly("REPLCONF".getBytes(), "ACK".getBytes(), String.valueOf(configuration.getReplOffset()).getBytes()); } }); } else { // include ping command submitEvent(parser.parse(raw), of(st, ed)); } } else { logger.warn("unexpected redis reply:{}", obj); } configuration.addOffset(offset[0]); offset[0] = 0L; } if (getStatus() == CONNECTED) { // should not reach here. add this line for code idempotent. submitEvent(new PostCommandSyncEvent()); } return true; } } }
41.437923
143
0.596666
bdbdba761da545bc3033793794829e6090fad49f
17,660
package org.springframework.samples.petclinic.migration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.samples.petclinic.owner.Owner; import org.springframework.samples.petclinic.owner.Pet; import org.springframework.samples.petclinic.owner.PetType; import org.springframework.samples.petclinic.vet.Vet; import org.springframework.samples.petclinic.visit.Visit; import javax.xml.crypto.Data; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.util.*; /** * @author Alireza ziarizi */ public class OwnerDAO implements IDAO<Owner> { private static final Logger log = LoggerFactory.getLogger(OwnerDAO.class); private Connection SQLite_CONNECTION; private Connection H2_CONNECTION; public OwnerDAO() { SQLite_CONNECTION = DatastoreConnection.connectSqlite(); H2_CONNECTION = DatastoreConnection.connectH2(); } public void initTable() { String query = "DROP TABLE IF EXISTS owners;"; try { Statement statement = SQLite_CONNECTION.createStatement(); statement.execute(query); } catch (SQLException e) { log.error(e.getMessage()); } this.createOwnerTable(); } public void initHashTable(){ String query = "DROP TABLE IF EXISTS hashTable;"; try { Statement statement = SQLite_CONNECTION.createStatement(); statement.execute(query); } catch (SQLException e) { log.error(e.getMessage()); } this.createHashTable(); } public void createHashTable(){ String createQuery = "CREATE TABLE IF NOT EXISTS hashTable (\n" + " hashtype VARCHAR(30),\n" + " hashStorage VARCHAR(255)\n" + ");"; try { Statement statement = SQLite_CONNECTION.createStatement(); statement.execute(createQuery); } catch (SQLException e) { log.error(e.getMessage()); } } public void addHashStorage(String type,String hash){ String insertQuery = "INSERT INTO hashTable (hashtype, hashStorage) VALUES (" +" '" + type + "'"+ ",'" + hash + "');"; try { Statement statement = SQLite_CONNECTION.createStatement(); statement.execute(insertQuery); } catch (SQLException e) { log.error(e.getMessage()); } } public String getHash(String type){ String hashStorage = ""; String query = "SELECT hashStorage FROM hashTable WHERE hashtype = " +"'"+ type +"'" + ";"; try { Statement statement = SQLite_CONNECTION.createStatement(); ResultSet resultSet = statement.executeQuery(query); hashStorage = resultSet.getString("hashStorage"); } catch (SQLException e) { log.error(e.getMessage()); } return hashStorage; } private void createOwnerTable() { String createQuery = "CREATE TABLE IF NOT EXISTS owners (\n" + " id INTEGER PRIMARY KEY AUTOINCREMENT,\n" + " first_name VARCHAR(30),\n" + " last_name VARCHAR(30),\n" + " address VARCHAR(255),\n" + " city VARCHAR(80),\n" + " telephone VARCHAR(20)\n" + ");"; try { Statement statement = SQLite_CONNECTION.createStatement(); statement.execute(createQuery); } catch (SQLException e) { log.error(e.getMessage()); } } public Owner get(Integer ownerId, Datastores datastore) { Owner owner = null; String query = "SELECT * FROM owners WHERE id = " + ownerId + ";"; if (datastore == Datastores.SQLITE) { try { Statement statement = SQLite_CONNECTION.createStatement(); ResultSet resultSet = statement.executeQuery(query); owner = new Owner(resultSet.getInt("id"), resultSet.getString("first_name"), resultSet.getString("last_name"), resultSet.getString("address"), resultSet.getString("city"), resultSet.getString("telephone")); Statement statement1 = SQLite_CONNECTION.createStatement(); ResultSet resultSet1 = statement1.executeQuery("SELECT * FROM pets WHERE owner_id = " + owner.getId() + ";"); while (resultSet1.next()) { Pet pet = new Pet(resultSet1.getInt("id"), resultSet1.getString("name") , PetMigration.convertToLocalDate(new SimpleDateFormat("yyyy-MM-dd") .parse(resultSet1.getString("birth_date")))); int type_id = resultSet1.getInt("type_id"); pet.setOwner(owner); Statement statement2 = SQLite_CONNECTION.createStatement(); ResultSet resultSet2 = statement2.executeQuery("SELECT * FROM visits WHERE pet_id = " + pet.getId() + ";"); List<Visit> visits = new ArrayList<>(); while (resultSet2.next()) { Visit visit = new Visit(resultSet2.getInt("id"), resultSet2.getInt("pet_id"), VisitMigration.convertToLocalDateViaInstant (new SimpleDateFormat("yyyy-MM-dd") .parse(resultSet2.getString("visit_date"))), resultSet2.getString("description")); visits.add(visit); } pet.setVisits(visits); Statement statement3 = SQLite_CONNECTION.createStatement(); ResultSet resultSet3 = statement3.executeQuery("SELECT * FROM types WHERE id = " + type_id + ";"); if (resultSet3 != null) { pet.setType(new PetType(resultSet3.getInt("id"), resultSet3.getString("name"))); } owner.addPetNew(pet); } } catch (SQLException | ParseException e) { log.error(e.getMessage()); } } return owner; } public List<Owner> getAll(Datastores datastore) { List<Owner> owners = new ArrayList<>(); String query = "SELECT * FROM owners;"; if (datastore == Datastores.SQLITE) { try { Statement statement = SQLite_CONNECTION.createStatement(); ResultSet resultSet = statement.executeQuery(query); while (resultSet.next()) { owners.add(new Owner(resultSet.getInt("id"), resultSet.getString("first_name"), resultSet.getString("last_name"), resultSet.getString("address"), resultSet.getString("city"), resultSet.getString("telephone"))); } } catch (SQLException e) { log.error(e.getMessage()); } } if (datastore == Datastores.H2) { try { Statement statement = H2_CONNECTION.createStatement(); ResultSet resultSet = statement.executeQuery(query); while (resultSet.next()) { owners.add(new Owner(resultSet.getInt("id"), resultSet.getString("first_name"), resultSet.getString("last_name"), resultSet.getString("address"), resultSet.getString("city"), resultSet.getString("telephone"))); } } catch (SQLException e) { log.error(e.getMessage()); } } return owners; } public boolean migrate(Owner owner) { String insertQuery = "INSERT INTO owners (id, first_name, last_name, address, city, telephone) VALUES (" + owner.getId() + ",'" + owner.getFirstName() + "','" + owner.getLastName() + "','" + owner.getAddress() + "','" + owner.getCity() + "','" + owner.getTelephone() + "');"; try { Statement statement = SQLite_CONNECTION.createStatement(); statement.executeUpdate(insertQuery); } catch (SQLException e) { log.error(e.getMessage()); return false; } return true; } public int add(Owner owner, Datastores datastore) { int id = -1; String insertQuery = "INSERT INTO owners (id, first_name, last_name, address, city, telephone) VALUES (NULL" + ",'" + owner.getFirstName() + "','" + owner.getLastName() + "','" + owner.getAddress() + "','" + owner.getCity() + "','" + owner.getTelephone() + "');"; if (datastore == Datastores.SQLITE) { try { Statement statement = SQLite_CONNECTION.createStatement(); statement.executeUpdate(insertQuery); return statement.getGeneratedKeys().getInt(1); } catch (SQLException e) { log.error(e.getMessage()); } } if (datastore == Datastores.H2) { try { Statement statement = H2_CONNECTION.createStatement(); statement.executeUpdate(insertQuery); return statement.getGeneratedKeys().getInt(1); } catch (SQLException e) { log.error(e.getMessage()); } } return id; } public void update(Owner owner, Datastores datastore) { String query = "UPDATE owners SET first_name = '" + owner.getFirstName() + "', last_name = '" + owner.getLastName() + "', address = '" + owner.getAddress() + "', city = '" + owner.getCity() + "', telephone = '" + owner.getTelephone() + "' WHERE id = " + owner.getId() + ";"; if (datastore == Datastores.SQLITE) { try { Statement statement = SQLite_CONNECTION.createStatement(); statement.executeUpdate(query); } catch (SQLException e) { log.error(e.getMessage()); } } if (datastore == Datastores.H2) { try { Statement statement = H2_CONNECTION.createStatement(); statement.executeUpdate(query); } catch (SQLException e) { log.error(e.getMessage()); } } } public Collection<Owner> getByLastName(String lastName) { String query; Collection<Owner> owners = new HashSet<>(); if (lastName.equals("")) { query = "SELECT * FROM owners"; } else { query = "SELECT * FROM owners WHERE last_name = '" + lastName + "';"; } try { Statement statement = SQLite_CONNECTION.createStatement(); ResultSet resultSet = statement.executeQuery(query); while (resultSet.next()) { Owner owner = new Owner(resultSet.getInt("id"), resultSet.getString("first_name"), resultSet.getString("last_name"), resultSet.getString("address"), resultSet.getString("city"), resultSet.getString("telephone")); Statement statement1 = SQLite_CONNECTION.createStatement(); ResultSet resultSet1 = statement1.executeQuery("SELECT * FROM pets where owner_id = " + owner.getId() + ";"); while (resultSet1.next()) { Pet pet = new Pet(resultSet1.getInt("id"), resultSet1.getString("name"), PetMigration.convertToLocalDate(new SimpleDateFormat("yyyy-MM-dd") .parse(resultSet1.getString("birth_date")))); int type_id = resultSet1.getInt("type_id"); pet.setOwner(owner); Statement statement2 = SQLite_CONNECTION.createStatement(); ResultSet resultSet2 = statement2.executeQuery("SELECT * FROM visits WHERE pet_id = " + pet.getId() + ";"); List<Visit> visits = new ArrayList<>(); while (resultSet2.next()) { Visit visit = new Visit(resultSet2.getInt("id"), resultSet2.getInt("pet_id"), VisitMigration.convertToLocalDateViaInstant (new SimpleDateFormat("yyyy-MM-dd") .parse(resultSet2.getString("visit_date"))), resultSet2.getString("description")); visits.add(visit); } pet.setVisits(visits); Statement statement3 = SQLite_CONNECTION.createStatement(); ResultSet resultSet3 = statement3.executeQuery("SELECT * FROM types WHERE id = " + type_id + ";"); if (resultSet3 != null) { pet.setType(new PetType(resultSet3.getInt("id"), resultSet3.getString("name"))); } owner.addPetNew(pet); } owners.add(owner); } } catch (SQLException | ParseException e) { log.error(e.getMessage()); } return owners; } public Collection<Owner> getByFirstName(String firstName) { String query; Collection<Owner> owners = new HashSet<>(); if (firstName.equals("")) { query = "SELECT * FROM owners"; } else { query = "SELECT * FROM owners WHERE first_name='" + firstName + "';"; } try { Statement statement = SQLite_CONNECTION.createStatement(); ResultSet resultSet = statement.executeQuery(query); while (resultSet.next()) { Owner owner = new Owner(resultSet.getInt("id"), resultSet.getString("first_name"), resultSet.getString("last_name"), resultSet.getString("address"), resultSet.getString("city"), resultSet.getString("telephone")); Statement statement1 = SQLite_CONNECTION.createStatement(); ResultSet resultSet1 = statement1.executeQuery("SELECT * FROM pets where owner_id = " + owner.getId() + ";"); while (resultSet1.next()) { Pet pet = new Pet(resultSet1.getInt("id"), resultSet1.getString("name"), PetMigration.convertToLocalDate(new SimpleDateFormat("yyyy-MM-dd") .parse(resultSet1.getString("birth_date")))); int type_id = resultSet1.getInt("type_id"); pet.setOwner(owner); Statement statement2 = SQLite_CONNECTION.createStatement(); ResultSet resultSet2 = statement2.executeQuery("SELECT * FROM visits WHERE pet_id = " + pet.getId() + ";"); List<Visit> visits = new ArrayList<>(); while (resultSet2.next()) { Visit visit = new Visit(resultSet2.getInt("id"), resultSet2.getInt("pet_id"), VisitMigration.convertToLocalDateViaInstant (new SimpleDateFormat("yyyy-MM-dd") .parse(resultSet2.getString("visit_date"))), resultSet2.getString("description")); visits.add(visit); } pet.setVisits(visits); Statement statement3 = SQLite_CONNECTION.createStatement(); ResultSet resultSet3 = statement3.executeQuery("SELECT * FROM types WHERE id = " + type_id + ";"); if (resultSet3 != null) { pet.setType(new PetType(resultSet3.getInt("id"), resultSet3.getString("name"))); } owner.addPetNew(pet); } owners.add(owner); } } catch (SQLException | ParseException e) { log.error(e.getMessage()); } return owners; } public void closeConnections() throws SQLException { SQLite_CONNECTION.close(); H2_CONNECTION.close(); } }
45.05102
135
0.505549
3ace2e174208c26a000edd2a6b5ff13937608dd8
3,770
package uk.co.stikman.utils; import java.io.ByteArrayInputStream; import java.io.EOFException; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StreamCorruptedException; import java.nio.charset.Charset; public class StikDataInputStream extends FilterInputStream { private static final int DEFAULT_MAX_LEN = 1024 * 1024; private int maxLen = DEFAULT_MAX_LEN; private Charset charset; private byte tmp[] = new byte[8]; public StikDataInputStream(InputStream in, int maxLen) { this(in, Charset.forName("UTF-8"), maxLen); } public StikDataInputStream(InputStream in) { this(in, Charset.forName("UTF-8"), DEFAULT_MAX_LEN); } public StikDataInputStream(InputStream in, Charset charset) { this(in, charset, DEFAULT_MAX_LEN); } public StikDataInputStream(InputStream in, Charset charset, int maxLen) { super(in); this.maxLen = maxLen; this.charset = charset; } public String readString() throws IOException { int len = readInt(); if (len > maxLen) throw new StreamCorruptedException("String in stream is larger than maxLen"); byte[] buf = new byte[len]; readFully(buf, 0, len); return new String(buf, charset); } /** * See the general contract of the <code>readFully</code> method of * <code>DataInput</code>. * <p> * Bytes for this operation are read from the contained input stream. * * @param b * the buffer into which the data is read. * @param off * the start offset of the data. * @param len * the number of bytes to read. * @exception EOFException * if this input stream reaches the end before reading all * the bytes. * @exception IOException * the stream has been closed and the contained input stream * does not support reading after close, or another I/O error * occurs. * @see java.io.FilterInputStream#in */ private final void readFully(byte b[], int off, int len) throws IOException { if (len < 0) throw new IndexOutOfBoundsException(); int n = 0; while (n < len) { int count = in.read(b, off + n, len - n); if (count < 0) throw new EOFException(); n += count; } } public int readInt() throws IOException { int ch1 = in.read(); int ch2 = in.read(); int ch3 = in.read(); int ch4 = in.read(); if ((ch1 | ch2 | ch3 | ch4) < 0) throw new EOFException(); return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0)); } public long readLong() throws IOException { readFully(tmp, 0, 8); return (((long) tmp[0] << 56) + ((long) (tmp[1] & 255) << 48) + ((long) (tmp[2] & 255) << 40) + ((long) (tmp[3] & 255) << 32) + ((long) (tmp[4] & 255) << 24) + ((tmp[5] & 255) << 16) + ((tmp[6] & 255) << 8) + ((tmp[7] & 255) << 0)); } public int readByte() throws IOException { int x = in.read(); if (x == -1) throw new EOFException(); return x; } public short readShort() throws IOException { int ch1 = in.read(); int ch2 = in.read(); if ((ch1 | ch2) < 0) throw new EOFException(); return (short) ((ch1 << 8) + (ch2 << 0)); } public String readShortString() throws IOException { int len = readShort(); byte[] buf = new byte[len]; readFully(buf, 0, len); return new String(buf, charset); } public byte[] readBytes(int len) throws IOException { byte[] res = new byte[len]; return readBytes(len, res); } public byte[] readBytes(int len, byte[] res) throws IOException { readFully(res, 0, len); return res; } public float readFloat() throws IOException { return Float.intBitsToFloat(readInt()); } public int getMaxLen() { return maxLen; } public void setMaxLen(int maxLen) { this.maxLen = maxLen; } }
27.122302
234
0.637931
b4556e80c9a4e1bfc8e1e7ceb5c16d8987c6f619
1,979
package com.miu.se.order; import com.miu.se.common.entity.Order; import com.miu.se.common.entity.Product; import com.miu.se.common.interfacing.OrderService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping("orders") public class OrderController { @Autowired private OrderService orderService; @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE) public List<Order> getAll(){ return orderService.getAll(); } @GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE) public Order getOrder(@PathVariable("id") Long id) { return orderService.getOrderById(id); //orderService.getTopSellingProduct(); } @GetMapping(value = "/top-product", produces = MediaType.APPLICATION_JSON_VALUE) public List<Product> getTopSellingProduct(@RequestParam int year, @RequestParam int k) { return orderService.getTopSellingProduct(year, k); } @GetMapping(value = "/top-payment-gateway", produces = MediaType.APPLICATION_JSON_VALUE) public List<String> getPopularPaymentGateway(@RequestParam int year, @RequestParam int k) { return orderService.getPopularPaymentGateway(year, k); } @GetMapping(value = "/list-order", produces = MediaType.APPLICATION_JSON_VALUE) public List<Order> getListOrderofProduct(@RequestParam int year, @RequestParam int product_id) { return orderService.getListOrderofProduct(year, product_id); } }
38.803922
100
0.769581
17981c2491cf69cb0573ca7b9f25d0b0bb8055b4
1,445
import java.util.Iterator; public class ZipMatrix<E> extends Matrix<E> { private final MemoryController encodedMatrix; public final ZipEncoder<E> zipEncoder; public final MatrixEncoder<E> baseEncoder; private int height, width; public ZipMatrix(MemoryController encodedMatrix, MatrixEncoder<E> baseEncoder){ this.encodedMatrix = encodedMatrix; this.baseEncoder = baseEncoder; this.zipEncoder = new ZipEncoder<>(baseEncoder); Matrix<E> temp = nestedMatrix(); height = temp.height(); width = temp.width(); trim(); } private Matrix<E> nestedMatrix(){ return baseEncoder.getMatrix( zipEncoder.unZip(encodedMatrix,new MemoryController()), 0 ); } public int estimateBitSize() { return encodedMatrix.size(); } public void trim() { encodedMatrix.trim(); } public E get(int r, int c) { return nestedMatrix().get(r,c); } public E set(int r, int c, E value) { return null; // Not supported } public int height(){ return height; } public int width(){ return width; } public E[][] toRawMatrix(){ return zipEncoder.decodeMatrix(encodedMatrix); } public Iterator<DataPoint<E>> iterator(int r, int c, int h, int w, IteratorType type){ return nestedMatrix().iterator(r,c,h,w,type); } }
24.491525
90
0.609689
366268a7d2a2daaa121d2931b25498245d9a813a
776
package io.nutz.nutzsite.module.tool.gen.querys; import org.nutz.dao.sql.Sql; /** * IDbQuery * @author kricss */ public interface IDbQuery { /** * 查询数据库表信息 * @param tableName 表名称 * @param tableComment 表注释 * @param orderByColumn 排序字段 * @param isAsc 排序方式 * @return */ public Sql tableList(String tableName, String tableComment, String orderByColumn, String isAsc); /** * 查询表信息 * @param tableName 表名称 * @return */ public Sql tableByName(String tableName); /** * 表字段查询 * @param tableName 表名称 * @return */ public Sql tableColumnsByName(String tableName); /** * 主键查询 * @param tableName * @return */ public Sql getPrimaryKey(String tableName); }
18.47619
100
0.601804
4c1c7a98b760a8ad4b8417bb4e9a2e07a23f057c
518
package cn.gson.oasys.model.dao.discuss; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import cn.gson.oasys.model.entity.discuss.Comment; import cn.gson.oasys.model.entity.discuss.Reply; public interface CommentDao extends JpaRepository<Comment, Long>{ //根据回复表来找有关的所有评论 List<Comment> findByReply(Reply reply); @Query("from Comment t where t.reply.replyId in (?1)") List<Comment> findComments(Long[] taskids); }
25.9
65
0.785714
87c7183d2328306aed87ae38a7ed6ddc0eade7b8
753
package com.blocklang.system.service.impl; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import com.blocklang.system.service.EncryptService; import com.blocklang.system.test.AbstractServiceTest; public class EncryptServiceImplTest extends AbstractServiceTest{ @Autowired private EncryptService encryptService; @Test public void encrypt() { assertThat(encryptService.encrypt("a")).isNotEqualTo("a"); } @Test public void check() { assertThat(encryptService.check("a", "a")).isFalse(); assertThat(encryptService.check("a", "b")).isFalse(); assertThat(encryptService.check("a", encryptService.encrypt("a"))).isTrue(); } }
26.892857
78
0.772908
bbd9e0e56760f1686568d62c202f81f60c2cac92
4,610
package org.intermine.web.struts; /* * Copyright (C) 2002-2014 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.util.Properties; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.intermine.api.InterMineAPI; import org.intermine.api.bag.SharedBagManager; import org.intermine.api.bag.SharingInvite; import org.intermine.api.bag.SharingInvite.NotFoundException; import org.intermine.api.profile.Profile; import org.intermine.api.profile.ProfileManager; import org.intermine.api.profile.UserAlreadyShareBagException; import org.intermine.util.Emailer; import org.intermine.web.context.InterMineContext; import org.intermine.web.context.MailAction; import org.intermine.web.logic.session.SessionMethods; /** * Action that processes invitations. * @author Alex Kalderimis * */ public class InvitationAction extends InterMineAction { private static final Logger LOG = Logger.getLogger(InvitationAction.class); @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { InvitationForm inviteForm = (InvitationForm) form; InterMineAPI api = SessionMethods.getInterMineAPI(request); SharedBagManager sbm = SharedBagManager.getInstance(api.getProfileManager()); ProfileManager pm = api.getProfileManager(); Profile p = SessionMethods.getProfile(request.getSession()); Properties props = SessionMethods.getWebProperties(request); if (!p.isLoggedIn()) { ActionMessage message = new ActionMessage("invitation-errors.mustlogin"); recordMessage(message, request); ForwardParameters fp = new ForwardParameters(mapping.findForward("login")); fp.addParameter("returnto", "/accept.do?invite=" + inviteForm.getInvite()); return fp.forward(); } SharingInvite invite = null; try { invite = SharingInvite.getByToken(api, inviteForm.getInvite()); sbm.acceptInvitation(invite, p); notifyInvitee(pm, invite, p, props); return forwardToBagDetails(mapping, invite); } catch (UserAlreadyShareBagException e) { sendErrorMsg(request, e, "invitation-errors.alreadyshared", new Object[]{}); return forwardToBagDetails(mapping, invite); } catch (IllegalStateException e) { sendErrorMsg(request, e, "invitation-errors.couldntaccept", e.getMessage()); } catch (NotFoundException e) { sendErrorMsg(request, e, "invitation-errors.couldntretrieve", new Object[]{}); } return mapping.findForward("mymine"); } private void notifyInvitee( final ProfileManager pm, final SharingInvite invite, final Profile accepter, final Properties props) { MailAction action = new MailAction() { @Override public void act(Emailer emailer) throws Exception { emailer.email( pm.getProfileUserName(invite.getBag().getProfileId()), "was-accepted", invite.getCreatedAt(), invite.getInvitee(), invite.getBag().getName(), accepter.getUsername(), props.getProperty("project.title")); } }; boolean queued = InterMineContext.queueMessage(action); if (!queued) { LOG.warn("Mail queue is full - could not send message"); } } private ActionForward forwardToBagDetails(ActionMapping mapping, SharingInvite invite) { ForwardParameters forwardParameters = new ForwardParameters(mapping.findForward("bagDetails")); forwardParameters.addParameter("name", invite.getBag().getName()); return forwardParameters.forward(); } private void sendErrorMsg(HttpServletRequest request, Exception e, String key, Object... vals) { recordError(new ActionMessage(key, vals), request, e, LOG); } }
39.067797
100
0.677874
89bdbc3d8e5496bf4773b0723df877f3f635b6c1
25,767
/** * Apache License * Version 2.0, January 2004 * http://www.apache.org/licenses/ * * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION * * 1. Definitions. * * "License" shall mean the terms and conditions for use, reproduction, * and distribution as defined by Sections 1 through 9 of this document. * * "Licensor" shall mean the copyright owner or entity authorized by * the copyright owner that is granting the License. * * "Legal Entity" shall mean the union of the acting entity and all * other entities that control, are controlled by, or are under common * control with that entity. For the purposes of this definition, * "control" means (i) the power, direct or indirect, to cause the * direction or management of such entity, whether by contract or * otherwise, or (ii) ownership of fifty percent (50%) or more of the * outstanding shares, or (iii) beneficial ownership of such entity. * * "You" (or "Your") shall mean an individual or Legal Entity * exercising permissions granted by this License. * * "Source" form shall mean the preferred form for making modifications, * including but not limited to software source code, documentation * source, and configuration files. * * "Object" form shall mean any form resulting from mechanical * transformation or translation of a Source form, including but * not limited to compiled object code, generated documentation, * and conversions to other media types. * * "Work" shall mean the work of authorship, whether in Source or * Object form, made available under the License, as indicated by a * copyright notice that is included in or attached to the work * (an example is provided in the Appendix below). * * "Derivative Works" shall mean any work, whether in Source or Object * form, that is based on (or derived from) the Work and for which the * editorial revisions, annotations, elaborations, or other modifications * represent, as a whole, an original work of authorship. For the purposes * of this License, Derivative Works shall not include works that remain * separable from, or merely link (or bind by name) to the interfaces of, * the Work and Derivative Works thereof. * * "Contribution" shall mean any work of authorship, including * the original version of the Work and any modifications or additions * to that Work or Derivative Works thereof, that is intentionally * submitted to Licensor for inclusion in the Work by the copyright owner * or by an individual or Legal Entity authorized to submit on behalf of * the copyright owner. For the purposes of this definition, "submitted" * means any form of electronic, verbal, or written communication sent * to the Licensor or its representatives, including but not limited to * communication on electronic mailing lists, source code control systems, * and issue tracking systems that are managed by, or on behalf of, the * Licensor for the purpose of discussing and improving the Work, but * excluding communication that is conspicuously marked or otherwise * designated in writing by the copyright owner as "Not a Contribution." * * "Contributor" shall mean Licensor and any individual or Legal Entity * on behalf of whom a Contribution has been received by Licensor and * subsequently incorporated within the Work. * * 2. Grant of Copyright License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * copyright license to reproduce, prepare Derivative Works of, * publicly display, publicly perform, sublicense, and distribute the * Work and such Derivative Works in Source or Object form. * * 3. Grant of Patent License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * (except as stated in this section) patent license to make, have made, * use, offer to sell, sell, import, and otherwise transfer the Work, * where such license applies only to those patent claims licensable * by such Contributor that are necessarily infringed by their * Contribution(s) alone or by combination of their Contribution(s) * with the Work to which such Contribution(s) was submitted. If You * institute patent litigation against any entity (including a * cross-claim or counterclaim in a lawsuit) alleging that the Work * or a Contribution incorporated within the Work constitutes direct * or contributory patent infringement, then any patent licenses * granted to You under this License for that Work shall terminate * as of the date such litigation is filed. * * 4. Redistribution. You may reproduce and distribute copies of the * Work or Derivative Works thereof in any medium, with or without * modifications, and in Source or Object form, provided that You * meet the following conditions: * * (a) You must give any other recipients of the Work or * Derivative Works a copy of this License; and * * (b) You must cause any modified files to carry prominent notices * stating that You changed the files; and * * (c) You must retain, in the Source form of any Derivative Works * that You distribute, all copyright, patent, trademark, and * attribution notices from the Source form of the Work, * excluding those notices that do not pertain to any part of * the Derivative Works; and * * (d) If the Work includes a "NOTICE" text file as part of its * distribution, then any Derivative Works that You distribute must * include a readable copy of the attribution notices contained * within such NOTICE file, excluding those notices that do not * pertain to any part of the Derivative Works, in at least one * of the following places: within a NOTICE text file distributed * as part of the Derivative Works; within the Source form or * documentation, if provided along with the Derivative Works; or, * within a display generated by the Derivative Works, if and * wherever such third-party notices normally appear. The contents * of the NOTICE file are for informational purposes only and * do not modify the License. You may add Your own attribution * notices within Derivative Works that You distribute, alongside * or as an addendum to the NOTICE text from the Work, provided * that such additional attribution notices cannot be construed * as modifying the License. * * You may add Your own copyright statement to Your modifications and * may provide additional or different license terms and conditions * for use, reproduction, or distribution of Your modifications, or * for any such Derivative Works as a whole, provided Your use, * reproduction, and distribution of the Work otherwise complies with * the conditions stated in this License. * * 5. Submission of Contributions. Unless You explicitly state otherwise, * any Contribution intentionally submitted for inclusion in the Work * by You to the Licensor shall be under the terms and conditions of * this License, without any additional terms or conditions. * Notwithstanding the above, nothing herein shall supersede or modify * the terms of any separate license agreement you may have executed * with Licensor regarding such Contributions. * * 6. Trademarks. This License does not grant permission to use the trade * names, trademarks, service marks, or product names of the Licensor, * except as required for reasonable and customary use in describing the * origin of the Work and reproducing the content of the NOTICE file. * * 7. Disclaimer of Warranty. Unless required by applicable law or * agreed to in writing, Licensor provides the Work (and each * Contributor provides its Contributions) on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied, including, without limitation, any warranties or conditions * of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A * PARTICULAR PURPOSE. You are solely responsible for determining the * appropriateness of using or redistributing the Work and assume any * risks associated with Your exercise of permissions under this License. * * 8. Limitation of Liability. In no event and under no legal theory, * whether in tort (including negligence), contract, or otherwise, * unless required by applicable law (such as deliberate and grossly * negligent acts) or agreed to in writing, shall any Contributor be * liable to You for damages, including any direct, indirect, special, * incidental, or consequential damages of any character arising as a * result of this License or out of the use or inability to use the * Work (including but not limited to damages for loss of goodwill, * work stoppage, computer failure or malfunction, or any and all * other commercial damages or losses), even if such Contributor * has been advised of the possibility of such damages. * * 9. Accepting Warranty or Additional Liability. While redistributing * the Work or Derivative Works thereof, You may choose to offer, * and charge a fee for, acceptance of support, warranty, indemnity, * or other liability obligations and/or rights consistent with this * License. However, in accepting such obligations, You may act only * on Your own behalf and on Your sole responsibility, not on behalf * of any other Contributor, and only if You agree to indemnify, * defend, and hold each Contributor harmless for any liability * incurred by, or claims asserted against, such Contributor by reason * of your accepting any such warranty or additional liability. * * END OF TERMS AND CONDITIONS * * APPENDIX: How to apply the Apache License to your work. * * To apply the Apache License to your work, attach the following * boilerplate notice, with the fields enclosed by brackets "{}" * replaced with your own identifying information. (Don't include * the brackets!) The text should be enclosed in the appropriate * comment syntax for the file format. We also recommend that a * file or class name and description of purpose be included on the * same "printed page" as the copyright notice for easier * identification within third-party archives. * * Copyright {yyyy} {name of copyright owner} * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.deleidos.rtws.commons.util; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.RandomAccessFile; import java.util.Map; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.apache.commons.compress.utils.IOUtils; import org.apache.commons.io.FileUtils; import org.apache.log4j.Logger; public class FileUtil { private static Logger logger = Logger.getLogger(FileUtil.class); public static void replaceFileContent(File f, String regex, String replacement) throws IOException { String content = fileToString(f); content = content.replaceAll(regex, replacement); stringToFile(content, f); } public static void replaceFileContent(File f, Map<String, String> regexReplaceMap) throws IOException { String content = fileToString(f); for (Map.Entry<String, String> entry : regexReplaceMap.entrySet()) { String regex = entry.getKey(); String replacement = entry.getValue(); content = content.replaceAll(regex, replacement); } stringToFile(content, f); } public static String fileToString(File f) throws IOException { FileInputStream fis = null; String content = ""; try { fis = new FileInputStream(f); content = org.apache.commons.io.IOUtils.toString(fis); return content; } finally { org.apache.commons.io.IOUtils.closeQuietly(fis); } } // Erases existing file contents! public static void stringToFile(String content, File f) throws IOException { FileOutputStream fos = null; try { fos = new FileOutputStream(f, false); org.apache.commons.io.IOUtils.write(content, fos); } finally { org.apache.commons.io.IOUtils.closeQuietly(fos); } } // @TODO handle paths in the tar.gz and multiple files public static File extractFileFromTarGzip(File tarGzip, String fileNameToExtract, File outputDirectory) throws IOException { // Make sure the outputDirectory is actually a directory if(outputDirectory.isFile()) { outputDirectory = outputDirectory.getParentFile(); } TarArchiveInputStream ais = null; BufferedOutputStream bos = null; try { // create the input stream to the original tar.gz file ais = new TarArchiveInputStream( new GZIPInputStream(new BufferedInputStream( new FileInputStream(tarGzip)))); // create the output stream for the extracted file File extractedFile = new File(outputDirectory, fileNameToExtract); bos = new BufferedOutputStream( new FileOutputStream(extractedFile)); // find the file by name ArchiveEntry nextEntry; while ((nextEntry = ais.getNextEntry()) != null) { if (nextEntry.getName().equals(fileNameToExtract)) { IOUtils.copy(ais, bos); } } // need to close the streams before potentially deleting the file below org.apache.commons.io.IOUtils.closeQuietly(ais); ais = null; org.apache.commons.io.IOUtils.closeQuietly(bos); bos = null; // check that we actually got something if (extractedFile.length() == 0) { extractedFile.delete(); return null; } else { return extractedFile; } } finally { // if an exception happened and the streams were not closed, close them here if (ais != null) { org.apache.commons.io.IOUtils.closeQuietly(ais); } if (bos != null) { org.apache.commons.io.IOUtils.closeQuietly(bos); } } } // @TODO handle paths in the tar.gz and multiple files public static File extractFileFromTarGzip(File tarGzip, String fileNameToExtract) throws IOException { return extractFileFromTarGzip(tarGzip, fileNameToExtract, tarGzip.getParentFile()); } // @TODO handle paths in the tar.gz and multiple files public static void replaceFileInTarGZip(File tarGzip, File fileToReplace) throws IOException { TarArchiveInputStream ais = null; TarArchiveOutputStream aos = null; FileInputStream fis = null; try { // create the input stream to the original tar.gz file ais = new TarArchiveInputStream( new GZIPInputStream(new BufferedInputStream( new FileInputStream(tarGzip)))); // create the output stream to the temp.tar.gz file File tempFile = new File(tarGzip.getParent(), "tmp" + tarGzip.getName()); tempFile.createNewFile(); aos = new TarArchiveOutputStream( new GZIPOutputStream(new BufferedOutputStream( new FileOutputStream(tempFile)))); // copy the files from the original tar.gz into the tmp.tar.gz // excluding the file to be replaced ArchiveEntry nextEntry; while ((nextEntry = ais.getNextEntry()) != null) { if (!nextEntry.getName().equals(fileToReplace.getName())) { aos.putArchiveEntry(nextEntry); IOUtils.copy(ais, aos); aos.closeArchiveEntry(); } } // create the new entry for the file we are replacing and add it to the tmp.tar.gz TarArchiveEntry entry = new TarArchiveEntry(fileToReplace.getName()); entry.setSize(fileToReplace.length()); aos.putArchiveEntry(entry); fis = new FileInputStream(fileToReplace); IOUtils.copy(fis, aos); org.apache.commons.io.IOUtils.closeQuietly(fis); fis = null; // close the tmp.tar.gz archive, these need to close before renaming the file below aos.closeArchiveEntry(); aos.finish(); org.apache.commons.io.IOUtils.closeQuietly(ais); ais = null; org.apache.commons.io.IOUtils.closeQuietly(aos); aos = null; // replace the original tar.gz with the tmp.tar.gz boolean success = tarGzip.delete(); if (!success) { throw new IOException("Failed to delete original tar.gz file:" + tarGzip.getName()); } success = tempFile.renameTo(tarGzip); if (!success) { throw new IOException("Failed to rename the new tar.gz file:" + tempFile.getName()); } } finally { // if an exception happened and the streams were not closed, close them here if (fis != null) { org.apache.commons.io.IOUtils.closeQuietly(fis); } if (ais != null) { org.apache.commons.io.IOUtils.closeQuietly(ais); } if (aos != null) { org.apache.commons.io.IOUtils.closeQuietly(aos); } } } // creates a new empty file if it doesn't exist (including non-existent parent dirs) // if the file does exist, it blows it away and creates a new empty one public static File initializeFile(String parent, String child) throws IOException { File f = new File(parent, child); if (f.exists()) { f.delete(); } if (!f.getParentFile().exists()) { f.getParentFile().mkdirs(); } f.createNewFile(); return f; } public static boolean isGZipped(File f) { int magic = 0; try { RandomAccessFile raf = new RandomAccessFile(f, "r"); magic = raf.read() & 0xff | ((raf.read() << 8) & 0xff00); raf.close(); } catch (Throwable e) { logger.error("Error checking gzip status of file", e); } return magic == GZIPInputStream.GZIP_MAGIC; } // only supports checking for gzip files for now public static InputStream getInputStream(File file) throws IOException { if (isGZipped(file)) { FileInputStream fStream = new FileInputStream(file); return new GZIPInputStream(fStream); } else { return new FileInputStream(file); } } /** * Extracts the contents of the Tar GZip file to the directory in which it is located */ public static boolean extractTarGZip(File tarGZip) { return extractTarGZip(tarGZip, new File(tarGZip.getParent())); } /** * Extracts the contents of the Tar GZip file to a specified directory */ public static boolean extractTarGZip(File tarGZip, File outputDirectory) { if(isGZipped(tarGZip)) { TarArchiveInputStream ais = null; try { // Open the Tar GZip file ais = new TarArchiveInputStream( new GZIPInputStream(new BufferedInputStream( new FileInputStream(tarGZip)))); // Ensure the directory to extract to exists if(!outputDirectory.exists()) { outputDirectory.mkdirs(); } // Extract all the contents of the Tar GZip file TarArchiveEntry nextEntry; while ((nextEntry = ais.getNextTarEntry()) != null) { // Create a file for the extracted file File extractedFile = new File(outputDirectory, nextEntry.getName()); if(nextEntry.isDirectory()) { if(!extractedFile.exists()) { extractedFile.mkdirs(); } } else { // Copy the contents of the Tar GZip entry BufferedOutputStream bos = null; try { bos = new BufferedOutputStream( new FileOutputStream(extractedFile)); IOUtils.copy(ais, bos); } catch (Exception ex) { throw ex; } finally { if(bos != null) try { bos.close(); } catch(Exception ignore) {} } } } return true; } catch(Exception ex) { logger.error("Unable to extract Tar GZip file [" + tarGZip.getAbsolutePath() + "] to directory [" + outputDirectory.getAbsolutePath() + "]", ex); } finally { if(ais != null) try { ais.close(); } catch(Exception ignore) {} } } return false; } /** * Compresses the contents of a directory to a Tar GZip file. If the source is not a * directory, then only the specified file will be compressed to the output file. */ public static boolean compressDirToTarGZip(File sourceDirectory, File outputFile) { TarArchiveOutputStream aos = null; try { // Ensure the outputFile exists outputFile.createNewFile(); aos = new TarArchiveOutputStream( new GZIPOutputStream(new BufferedOutputStream( new FileOutputStream(outputFile)))); // Make sure to record the path of the sourceDirectory to properly form the sub directories // in the Tar GZip file String sourceDirectoryPath; if(sourceDirectory.isDirectory()) { // The source directory is the directory specified sourceDirectoryPath = sourceDirectory.getAbsolutePath(); } else { // A single file is all we are compressing, the source directory of the // file is the directory in which it is located sourceDirectoryPath = sourceDirectory.getParent(); } compressDirToTarGZip(sourceDirectoryPath, sourceDirectory, aos, outputFile.getAbsolutePath()); return true; } catch (Exception ex) { logger.error("Unable to compress directory [" + sourceDirectory.getAbsolutePath() + "] to Tar GZip file [" + outputFile.getAbsolutePath() + "]", ex); } finally { if(aos != null) try { aos.close(); } catch(Exception ignore) {} } return false; } private static void compressDirToTarGZip(String sourceDirectoryPath, File file, TarArchiveOutputStream aos, String outputFilePath) throws IOException { if(file.isDirectory()) { // Work through all the files in the directory String[] fileNames = file.list(); for(String fileName : fileNames) { compressDirToTarGZip(sourceDirectoryPath, new File(file, fileName), aos, outputFilePath); } } else { // Make sure not to compress the output file if(file.getAbsolutePath().equals(outputFilePath)) { return; } // The name of the archive entry must be the name of the current file excluding the source directory // which is being compressed. For example, if we are compressing /tmp/lib/commons-core.jar and the // directory being compressed is the tmp directory, then the entry name in the compressed file must // be lib/commons-core.jar. String archiveEntryName = file.getAbsolutePath().substring( file.getAbsolutePath().lastIndexOf(sourceDirectoryPath) + sourceDirectoryPath.length() + 1, file.getAbsolutePath().length()); // Create an archive entry to write to TarArchiveEntry entry = new TarArchiveEntry(archiveEntryName); entry.setSize(file.length()); aos.putArchiveEntry(entry); // Copy the contents of the file to the entry FileInputStream fis = new FileInputStream(file); IOUtils.copy(fis, aos); org.apache.commons.io.IOUtils.closeQuietly(fis); fis = null; aos.closeArchiveEntry(); } } public static void copyDirectory(File sourceDirectory, File destDirectory) { try { FileUtils.copyDirectory(sourceDirectory, destDirectory); } catch (IOException e) { logger.error("Failed to copy directory [" + sourceDirectory.getAbsolutePath() + "] to [" + destDirectory.getAbsolutePath() + "]", e); } } public static void copyFile(File sourceFile, File destFile) { try { FileUtils.copyFile(sourceFile, destFile); } catch (IOException e) { logger.error("Failed to copy file [" + sourceFile.getAbsolutePath() + "] to [" + destFile.getAbsolutePath() + "]", e); } } public static void moveFile(File sourceFile, File destFile) { try { FileUtils.moveFile(sourceFile, destFile); } catch (IOException e) { logger.error("Failed to move file [" + sourceFile.getAbsolutePath() + "] to [" + destFile.getAbsolutePath() + "]", e); } } // Convenience Wrapper class public static boolean deleteQuietly(File file) { return FileUtils.deleteQuietly(file); } public static String buildPath(String basePath, String... paths) { // If the basePath ends with a path separator, remove it since it will be added below if(basePath.endsWith(File.separator)) { basePath = basePath.substring(0, basePath.length()-1); } StringBuilder sb = new StringBuilder(basePath); for(String path : paths) { sb.append(File.separator).append(path); } return sb.toString(); } }
40.77057
152
0.697365
9238c37b07b77fff7ff8a155848924caf6887009
19,424
// Copyright 2007 Xito.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.xito.boot; import java.awt.*; import java.awt.event.*; import java.text.*; import java.util.*; import java.util.logging.*; import java.lang.ref.*; import javax.swing.*; import java.security.*; import org.xito.boot.util.*; /** * <p> * Security manager for bootstrap environment. * </p> * <p> * The security manager tracks windows created by an * application, allowing those windows to be disposed when the * application exits but the JVM does not. If security is not * enabled then the first application to call System.exit will * halt the JVM. * </p> * <p> * Some functionality in this Security Manager is derived from the Security Manager * found at netx project on SourceForge created by Jon Maxwell * </p> * * @author <a href="mailto:drichan@users.sourceforge.net">Deane Richan</a> * @author <a href="mailto:jmaxwell@users.sourceforge.net">Jon A. Maxwell (JAM)</a> - initial author * @version $Revision: 1.32 $ */ public class BootSecurityManager extends SecurityManager { private Class exitClass = null; private Vector weakWindows = new Vector(); //have to use real vector because of change from 1.4.2 to 1.4.2_08 and 1.5 private WeakVector weakApplications = new WeakVector(); /** listener installs the app's classloader on the event dispatch thread */ private SecurityWindowListener windowListener = new SecurityWindowListener(); private WeakReference activeApplication; public static final String XITO_SECURITY_LOG_CAT = "xito.security"; protected static final Logger securityLogger = Logger.getLogger(XITO_SECURITY_LOG_CAT); /** * Creates a SecurityManager. */ public BootSecurityManager() { super(); // this has the side-effect of creating the Swing shared Frame // owner. Since no application is running at this time, it is // not added to any window list when checkTopLevelWindow is // called for it (and not disposed). } /** * Returns whether the exit class is present on the stack, or * true if no exit class is set. */ private boolean isExitClass(Class stack[]) { if (exitClass == null) return false; for (int i=0; i < stack.length; i++) if (stack[i] == exitClass) return true; return false; } /** * Returns true if the Class item is on the Stack */ private boolean isOnStack(Class stack[], Class item) { for (int i=0; i < stack.length; i++) if (stack[i] == item) return true; return false; } /** * Returns true if the Class Name item is on the Stack * @param * @param className is a full class name or can end in * */ private boolean isOnStack(Class stack[], String className) { boolean useWildCard = false; if(className.endsWith("*")) { useWildCard = true; className = className.substring(0,className.lastIndexOf('*')-1); } for (int i=0; i < stack.length; i++) { if(useWildCard){ if (stack[i].getName().startsWith(className)) return true; } else { if (stack[i].getName().equals(className)) return true; } } return false; } /** * Set the exit class, which is the only class that can exit the * JVM; if not set then any class can exit the JVM. * * @param exitClass the exit class * @throws IllegalStateException if the exit class is already set */ public void setExitClass(Class exitClass) throws IllegalStateException { if (this.exitClass != null) throw new IllegalStateException("Exit Class already set"); this.exitClass = exitClass; } /** * Get the exit class, which is the only class that can exit the * JVM; if not set then any class can exit the JVM. * */ protected Object getExitClass() { return this.exitClass; } /** * Return the current Application, or null if none can be * determined. */ public AppInstance getApplication() { return getApplication(getClassContext()); } /** * Return the application the opened the specified window (only * call from event dispatch thread). */ protected AppInstance getApplication(Window window) { Iterator it = weakApplications.iterator(); while(it.hasNext()) { AppInstance app = (AppInstance)it.next(); if(app == null) { it.remove(); continue; } WeakVector windows = app.getWindows(); for(int i=0;i<windows.size();i++) { Object w = windows.get(i); if(w != null && w == window) return app; } } return null; } /** * Return the current Application, or null. */ protected AppInstance getApplication(final Class stack[]) { AppInstance app = (AppInstance)AccessController.doPrivileged(new PrivilegedAction() { public Object run() { // this needs to be tightened up for (int i=0; i < stack.length; i++) { ClassLoader loader = stack[i].getClassLoader(); if (loader instanceof AppClassLoader) { AppClassLoader apploader = (AppClassLoader)loader; if (apploader.getAppInstance() != null) { return apploader.getAppInstance(); } } } return null; } }); return app; } /** * Returns the application's thread group if the application can * be determined; otherwise returns super.getThreadGroup() */ public ThreadGroup getThreadGroup() { AppInstance app = getApplication(); if (app == null) return super.getThreadGroup(); return app.getThreadGroup(); } /** * Throws a SecurityException if the permission is denied, * otherwise return normally. This method always denies * permission to change the security manager or policy. */ public void checkPermission(final Permission perm) { //First ask the Super if this permission is allowed SecurityException exp = null; try { super.checkPermission(perm); } catch(SecurityException secExp) { exp = secExp; } //Check to see if they are trying to Change Security Manager if(perm.getName().equals("setSecurityManager") && Boot.isLaunchingExternal()==false) { showSetSecurityManagerWarning(); //Throw an exception throw new SecurityException("Application not allowed to change Security Manager"); } //Throw the original Expception if(exp != null) { throw exp; } } /** * Prompt the user to grant permission for an action. This can only be called from Trusted code * If this method returns true then the user granted permission and the Trusted code can perform * an operation on behalf of untrusted code * * @param subtitle for org.xito * @param msg for org.xito * @param perm to be granted * @param execDesc of the App requesting the Grant */ public boolean promptForPermission(String subtitle, String msg, Permission perm, ExecutableDesc execDesc) { try { super.checkPermission(new AllPermission()); } catch(SecurityException secExp) { //this is ok it means the caller is not trusted so just return false return false; } //Must be using Boot Policy if(!(Policy.getPolicy() instanceof BootPolicy)) { return false; } return ((BootPolicy)Policy.getPolicy()).promptForPermission(subtitle, msg, perm, execDesc); } /** * Show a Warning about setting a Security Manager in the Shared VM */ private void showSetSecurityManagerWarning() { if(Boot.isHeadless() == true) return; String title = Resources.bundle.getString("boot.security.warning.title"); title = java.text.MessageFormat.format(title, Boot.getAppDisplayName()); String subtitle = Resources.bundle.getString("boot.security.manager.changed.subtitle"); String msg = Resources.bundle.getString("boot.security.manager.changed.msg"); msg = java.text.MessageFormat.format(msg, Boot.getAppDisplayName()); Boot.showError(title,subtitle,msg, null); } /** * Show a warning message about the security violation */ private void showSecurityViolation(final Permission permission) { AccessController.doPrivileged(new PrivilegedAction() { public Object run() { String permissionName = null; if(permission != null) permissionName = permission.toString(); JOptionPane.showMessageDialog(null, "Security Violation: "+ permissionName +" caused by: unknown", "Security Violation", JOptionPane.OK_OPTION); return null; } }); return; } /** * Checks whether the window can be displayed without an * warning banner, and adds the window to the list of windows to * be disposed when the calling application exits. */ public boolean checkTopLevelWindow(Object window) { //If prompting user then pause until finished /* AccessController.doPrivileged(new PrivilegedAction() { public Object run() { Policy policy = Policy.getPolicy(); if(policy instanceof BootPolicy) { Thread promptThread = ((BootPolicy)policy).getPromptThread(); if(promptThread != null && promptThread.isAlive() && promptThread != Thread.currentThread()) { try { promptThread.join(); } catch(InterruptedException exp) { securityLogger.log(Level.SEVERE, exp.getMessage(), exp); } } } return null; } }); */ weakWindows.add(window); AppInstance app = getApplication(); // remember window -> application mapping for focus, close on exit if (app != null && window instanceof Window) { Window w = (Window) window; weakApplications.add(app); w.addWindowListener(windowListener); // for dynamic context classloader app.addWindow(w); } // change coffee cup to app default icon ImageIcon icon = Boot.getAppIcon(); if ((window instanceof Window) && (icon != null)) { Window w = (Window)window; while(w != null) { if (w instanceof Frame) { ((Frame)w).setIconImage(icon.getImage()); } w = ((Window)w).getOwner(); } } return super.checkTopLevelWindow(window); } /** * Checks to see if a Window has been created since the Security Manager was Started * If there is not a visible window then the BootStrap may use this information to * end the Session */ protected boolean checkWindowVisible() { //Check All Windows for(int i=0;i<weakWindows.size();i++) { Window w = (Window)weakWindows.get(i); if(w != null && w.isVisible()) { return true; } } //Check Boot Context Frames Frame frames[] = Frame.getFrames(); for(int i=0;i<frames.length;i++) { if(frames[i].isVisible()) return true; } //If we make it down here then there are no visible windows return false; } /** * Checks whether the caller can exit the VM. In this implementation only the ExitClass or the Boot class * have permission to Exit the VM. If another application attempts to exit the VM the Application will be * Identified by searching the classloaders of the call Stack and then the App will be destroyed. * If the call to checkExit is not done via the Runtime class then checkExit will behave the same as the default * security manager */ public void checkExit(int status) { //Check to see if we are in Launch External mode if so then Anybody can exit the VM so just return if(Boot.isLaunchingExternal()) { return; } //Check to see if Runtime is actually trying to exit the VM or is //Somebody just calling SecurityManager.checkVM like JFrame does when setDefaultCloseOperation is called Class stack[] = getClassContext(); boolean realCall = false; if(isOnStack(stack, Runtime.class)) { realCall = true; } //If not a real call just let Super implementation handle it if(realCall == false) { //Check for JFrame or Frame on the Stack if(isOnStack(stack, java.awt.Frame.class)) { return; } else if(isOnStack(stack, javax.swing.JFrame.class)) { return; } else { super.checkExit(status); return; } } //First see if the Exit Class is on the Stack if so then its ok to exit if(isExitClass(stack)) { return; } //Check to see if Boot is on the Stack if so then it is ok to exit if(isOnStack(stack, Boot.class)) { return; } //Check to see if Apple Application on Stack //if exit called from com.apple.eawt.Application then user clicked quit from App Menu if(isOnStack(stack, "com.apple.eawt.Application*")) return; //Now check to see if we should destroy a running App // but when they really call, stop only the app instead of the JVM AppInstance app = getApplication(stack); //At this point we can't tell what to do. This could happen if the App is using //setDefaultCloseOperation on Frame or JFrame set to Exit VM //In such a case we can't tell which app is trying to Exit //So we assume the Active Application based on last active Window is the App if (app == null) { app = windowListener.getActiveApplication(); } //Now attempt to Destory the Application if (app != null) { app.destroy(); throw new SecurityException("Exit VM not allowed by this application"); } if(checkWindowVisible()) { securityLogger.info("Some Visible Apps are still active. Not shutting down VM"); throw new SecurityException("Exit VM not allowed by this application"); } else if(Boot.isHeadless()==false) { //shutdown because all visible Windows have been disposed securityLogger.info("Shutting Down because all Visible UI has been disposed!"); return; } //Finally Check permissions by calling super super.checkExit(status); } /** * Throws a <code>SecurityException</code> if the * calling thread is not allowed to dynamic link the library code * specified by the string argument file. The argument is either a * simple library name or a complete filename. * <p> * This method is invoked for the current security manager by * methods <code>load</code> and <code>loadLibrary</code> of class * <code>Runtime</code>. * <p> * This method calls <code>checkPermission</code> with the * <code>RuntimePermission("loadLibrary."+lib)</code> permission. * <p> * If you override this method, then you should make a call to * <code>super.checkLink</code> * at the point the overridden method would normally throw an * exception. * * @param lib the name of the library. * @exception SecurityException if the calling thread does not have * permission to dynamically link the library. * @exception NullPointerException if the <code>lib</code> argument is * <code>null</code>. * @see java.lang.Runtime#load(java.lang.String) * @see java.lang.Runtime#loadLibrary(java.lang.String) * @see #checkPermission(java.security.Permission) checkPermission */ public void checkLink(String lib) { Class[] execStack = getClassContext(); for(int i=0;i<execStack.length;i++) { //Skip these classes on the Stack if(execStack[i] == this.getClass()) continue; if(execStack[i] == Runtime.class) continue; if(execStack[i] == System.class) continue; //See if a System class is trying to load the library if(execStack[i].getClassLoader() == ClassLoader.getSystemClassLoader()) { super.checkLink(lib); return; } } //Thread.dumpStack(); super.checkLink(lib); } /***************************************************** * Listener for Windows *****************************************************/ private class SecurityWindowListener extends WindowAdapter { private WeakReference activeApplication; /** * Get the currently know application based on last window Active */ public AppInstance getActiveApplication() { if(activeApplication != null) return (AppInstance)activeApplication.get(); else return null; } public void windowActivated(WindowEvent e) { AppInstance app = getApplication(e.getWindow()); if(app != null) { activeApplication = new WeakReference(app); } else { activeApplication = null; } } public void windowDeactivated(WindowEvent e) { activeApplication = null; } public void windowClosed(WindowEvent e) { AppInstance closingApp = getApplication(e.getWindow()); if(closingApp == null) return; WeakVector windows = closingApp.getWindows(); Iterator it = windows.iterator(); boolean openWindows = false; while(it.hasNext()) { Window w = (Window)it.next(); if(w != null && w.isDisplayable()) openWindows = true; } //If no open windows check active threads and exit VM if we should if(openWindows == false) { if(Boot.isHeadless() == false && Boot.isLaunchingExternal()) { Boot.endSession(true); return; } } } }; }
33.146758
156
0.600391
9d5e2ef5988ed673512fdcb1ef940818f8b11437
1,348
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.samples.config; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; import java.security.interfaces.RSAPublicKey; import static org.assertj.core.api.Assertions.assertThat; public class PemParsingPublicKeyOnlyRSAKeyProviderTests { @Test public void whenPemEncoded_thenCanParse() throws IOException { InputStream is = this.getClass() .getClassLoader().getResourceAsStream("id_rsa.pub"); PemParsingPublicKeyOnlyRSAKeyProvider provider = new PemParsingPublicKeyOnlyRSAKeyProvider(is); RSAPublicKey key = provider.getPublicKeyById("123"); assertThat(key.getPublicExponent()).isEqualTo(new BigInteger("65537")); } }
32.878049
75
0.775964
658917ee2969f5acbbe2e780f24d74c5e9b050e8
2,542
/** * Copyright 2017 Matthieu Jimenez. All rights reserved. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package paw.graph.customTypes.bitset.fastbitset; import greycat.Type; import greycat.struct.EStruct; import greycat.struct.EStructArray; import greycat.struct.IntArray; import org.roaringbitmap.IntIterator; import paw.graph.customTypes.bitset.CTBitset; import java.util.List; public class CTFastBitSet extends CTBitset { private IntArray gBits; protected BitSet bitSet; protected EStruct root; public static final String NAME = "FastBitSet"; public CTFastBitSet(EStructArray array) { super(array); root = array.root(); if (root == null) { root = array.newEStruct(); array.setRoot(root); } gBits = (IntArray) root.getOrCreateAt(BITS_H, Type.INT_ARRAY); bitSet = new BitSet(gBits.extract()); } public void clear() { gBits.initWith(new int[0]); bitSet.clear(); } @Override public boolean add(int index) { return bitSet.add(index); } @Override public boolean addAll(List<Integer> indexs) { for (int index : indexs) { bitSet.add(index); } return true; } @Override public void clear(int index) { bitSet.clear(index); } @Override public int size() { return bitSet.size(); } @Override public int cardinality() { return bitSet.cardinality(); } @Override public boolean get(int index) { return bitSet.get(index); } @Override public int nextSetBit(int startIndex) { return bitSet.nextSetBit(startIndex); } @Override public IntIterator iterator() { return bitSet.iterator(); } public void save() { gBits.initWith(bitSet.toIntArray()); } public BitSet getBitSet() { return bitSet; } public void setBitset(BitSet bitSet) { this.bitSet = bitSet; } }
23.757009
75
0.641227
b64581f15448e944a7a61d180eb818e7f94b9daa
4,433
/** * Copyright (c) 2007-2014 The Apereo 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://opensource.org/licenses/ecl2 * * 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. */ /* * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * The Apereo Foundation licenses this file to you under the 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://opensource.org/licenses/ecl2.txt * * 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.sakaiproject.hierarchy.dao.model; /** * This is the persistent object for storing Hierarchy Nodes * * @author Aaron Zeckoski (aaronz@vt.edu) */ public class HierarchyPersistentNode { /** * The unique internal id for this hierarchy node */ private Long id; /** * the ids of parent nodes that touch this node directly, * similar treatment to the way the it works for the {@link #parentIds} */ private String directParentIds; /** * the ids of all parents of this node, * this goes all the way up the hierarchy to the root node, * expect this to be only one parent in most cases, * the path to the root is determined using the directParentId only<br/> * Uses a ":" separator between each id, also includes the separator in front * of and behind every id.<br/> * Examples: ":123:432:43:", ":38:", "" (no parent) */ private String parentIds; /** * the ids of child nodes that touch this node directly, * similar treatment to the way the it works for the {@link #parentIds} */ private String directChildIds; /** * the ids of all children of this node, * this goes all the way down the hierarchy to the leaf nodes, * similar treatment to the way the it works for the {@link #parentIds} */ private String childIds; /** * Empty constructor */ public HierarchyPersistentNode() { } /** * Leaf constructor */ public HierarchyPersistentNode(String directParentIds, String parentIds) { this.directParentIds = directParentIds; this.parentIds = parentIds; } /** * Full constructor */ public HierarchyPersistentNode(String directParentIds, String parentIds, String directChildIds, String childIds) { this.directParentIds = directParentIds; this.directChildIds = directChildIds; this.parentIds = parentIds; this.childIds = childIds; } /** * Getters and Setters */ public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getParentIds() { return parentIds; } public void setParentIds(String parentIds) { this.parentIds = parentIds; } public String getDirectChildIds() { return directChildIds; } public void setDirectChildIds(String directChildIds) { this.directChildIds = directChildIds; } public String getDirectParentIds() { return directParentIds; } public void setDirectParentIds(String directParentIds) { this.directParentIds = directParentIds; } public String getChildIds() { return childIds; } public void setChildIds(String childIds) { this.childIds = childIds; } }
30.363014
119
0.654861
4b4ecce1fe3b7620be8849e510503d9ccf76e295
147
package by.brest.karas.model; /** * POJO Role for model. * * @author Tsikhan Karas * @version 1.0 */ public enum Role {ROLE_USER, ROLE_ADMIN}
16.333333
40
0.680272
f95bd38c7f71e8461e77f313eef9d143cf59c2c5
1,159
package seedu.address.logic.autocomplete.nodes.customer; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static seedu.address.testutil.Assert.assertThrows; import static seedu.address.testutil.TypicalCustomers.CUSTOMERONE; import java.util.Collections; import java.util.List; import org.junit.jupiter.api.Test; import seedu.address.model.customer.Customer; class CustomerContactNumberNodeTest { @Test void constructor_null_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> new CustomerContactNumberNode(null)); } @Test void getValues_emptyList_emptySet() { CustomerContactNumberNode node = new CustomerContactNumberNode(Collections.emptyList()); assertEquals(node.getValues(), Collections.emptySortedSet()); } @Test void getValues_nonEmptyList_nonEmptySet() { List<Customer> customerList = Collections.singletonList(CUSTOMERONE); CustomerContactNumberNode node = new CustomerContactNumberNode(customerList); assertTrue(() -> !node.getValues().isEmpty()); } }
32.194444
96
0.765315
1c0e0f0bfaafe1a914f3a5308ed9ff0a87ecd437
3,805
/* * ============================================================================= * * Copyright (c) 2011-2018, The THYMELEAF team (http://www.thymeleaf.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.thymeleaf.extras.springsecurity3.dialect; import java.util.LinkedHashSet; import java.util.Set; import org.thymeleaf.dialect.AbstractDialect; import org.thymeleaf.dialect.IExpressionObjectDialect; import org.thymeleaf.dialect.IProcessorDialect; import org.thymeleaf.expression.IExpressionObjectFactory; import org.thymeleaf.extras.springsecurity3.dialect.expression.SpringSecurityExpressionObjectFactory; import org.thymeleaf.extras.springsecurity3.dialect.processor.AuthenticationAttrProcessor; import org.thymeleaf.extras.springsecurity3.dialect.processor.AuthorizeAclAttrProcessor; import org.thymeleaf.extras.springsecurity3.dialect.processor.AuthorizeAttrProcessor; import org.thymeleaf.extras.springsecurity3.dialect.processor.AuthorizeUrlAttrProcessor; import org.thymeleaf.processor.IProcessor; import org.thymeleaf.standard.processor.StandardXmlNsTagProcessor; import org.thymeleaf.templatemode.TemplateMode; /** * * @author Daniel Fern&aacute;ndez * */ public class SpringSecurityDialect extends AbstractDialect implements IProcessorDialect, IExpressionObjectDialect { public static final String NAME = "SpringSecurity"; public static final String DEFAULT_PREFIX = "sec"; public static final int PROCESSOR_PRECEDENCE = 800; private static final IExpressionObjectFactory EXPRESSION_OBJECT_FACTORY = new SpringSecurityExpressionObjectFactory(); public SpringSecurityDialect() { super(NAME); } public String getPrefix() { return DEFAULT_PREFIX; } public int getDialectProcessorPrecedence() { return PROCESSOR_PRECEDENCE; } public Set<IProcessor> getProcessors(final String dialectPrefix) { final Set<IProcessor> processors = new LinkedHashSet<IProcessor>(); final TemplateMode[] templateModes = new TemplateMode[] { TemplateMode.HTML, TemplateMode.XML, TemplateMode.TEXT, TemplateMode.JAVASCRIPT, TemplateMode.CSS }; for (final TemplateMode templateMode : templateModes) { processors.add(new AuthenticationAttrProcessor(templateMode, dialectPrefix)); // synonym (sec:authorize = sec:authorize-expr) for similarity with // "authorize-url" and "autorize-acl" processors.add(new AuthorizeAttrProcessor(templateMode, dialectPrefix, AuthorizeAttrProcessor.ATTR_NAME)); processors.add(new AuthorizeAttrProcessor(templateMode, dialectPrefix, AuthorizeAttrProcessor.ATTR_NAME_EXPR)); processors.add(new AuthorizeUrlAttrProcessor(templateMode, dialectPrefix)); processors.add(new AuthorizeAclAttrProcessor(templateMode, dialectPrefix)); processors.add(new StandardXmlNsTagProcessor(templateMode, dialectPrefix)); } return processors; } public IExpressionObjectFactory getExpressionObjectFactory() { return EXPRESSION_OBJECT_FACTORY; } }
33.973214
123
0.715112
680367a58388c49a8da19d6e07ee2429e36b394e
1,378
package com.sandbox.model; import com.sandbox.exceptions.InvalidIdException; import com.sandbox.model.items.animals.Dog; import com.sandbox.model.items.solids.Ball; import com.sandbox.model.items.solids.Box; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class ItemTest { @Test void testConstructor() { Exception exception; exception = assertThrows(InvalidIdException.class, () -> new Ball(null, "Red", 1.0), "Item ID can't be null."); assertTrue(exception.getMessage().contains("can't be empty")); exception = assertThrows(InvalidIdException.class, () -> new Ball(" ", "Blue", 1.0), "Item ID can't be blank."); assertTrue(exception.getMessage().contains("can't be empty")); final String tooLong = "a".repeat(33); exception = assertThrows(InvalidIdException.class, () -> new Box(tooLong, "Brown", 1.0, 1.0, 1.0), "Max Item ID is 32."); assertTrue(exception.getMessage().contains("can't be longer than 32 char")); exception = assertThrows(InvalidIdException.class, () -> new Dog("æ"), "Item ID can only contain alphanumerical characters."); assertTrue(exception.getMessage().contains("may only contain alphanumeric")); assertDoesNotThrow(() -> new Dog("ABC123")); } }
38.277778
106
0.650218
19dc9caef80a71d1dd172bd57c707721175ad7f6
18,575
package YuxinBookstore; /** * Created by Orthocenter on 5/12/15. */ import com.sun.media.sound.UlawCodec; import org.omg.IOP.TAG_MULTIPLE_COMPONENTS; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.sql.ResultSet; import java.util.ArrayList; import javax.json.*; import javax.rmi.CORBA.Util; public class Book { private static JsonObjectBuilder JSONBook(ResultSet rs, JsonObjectBuilder book) throws Exception { String sql; Connector con2 = null; try { con2 = new Connector(); String isbn = rs.getString("isbn"); book.add("ISBN", isbn); String title = rs.getString("title"); book.add("title", title); String subtitle = rs.getString("subtitle"); book.add("subtitle", subtitle == null ? "" : subtitle); double price = rs.getDouble("price"); book.add("price", price); int amount = rs.getInt("copies"); book.add("amount", amount); String pubdate = rs.getString("pubdate"); book.add("pubdate", pubdate == null ? "" : pubdate); String format = rs.getString("format"); book.add("format", format == null ? "" : format); String keyword = rs.getString("keyword"); book.add("keyword", keyword == null ? "" : format); String subject = rs.getString("subject"); book.add("subject", subject == null ? "" : subject); String summary = rs.getString("summary"); book.add("summary", summary == null ? "" : summary); String img = rs.getString("img"); book.add("img", img == null ? "" : img); int pid = rs.getInt("pid"); book.add("publisher", pid); sql = "SELECT * FROM WrittenBy W WHERE W.isbn = '" + Utility.sanitize(isbn) + "'"; con2.newStatement(); ResultSet rs2 = con2.stmt.executeQuery(sql); JsonArrayBuilder authors = Json.createArrayBuilder(); while (rs2.next()) { int authid = rs2.getInt("authid"); authors.add(authid); } book.add("authors", authors); sql = "SELECT fid FROM Feedback WHERE isbn = '" + Utility.sanitize(isbn) + "'"; JsonArrayBuilder feedbacks = Json.createArrayBuilder(); con2.newStatement(); rs2 = con2.stmt.executeQuery(sql); while (rs2.next()) { feedbacks.add(rs2.getInt("fid")); } book.add("feedbacks", feedbacks); sql = "SELECT I2.isbn, SUM(I2.amount) as sales FROM ItemInOrder I1, ItemInOrder I2, Orders O1, Orders O2 WHERE " + "O1.cid = O2.cid AND O1.orderid = I1.orderid AND O2.orderid = I2.orderid AND " + "I1.isbn='" + Utility.sanitize(isbn) + "'" + " AND I2.isbn != '" + Utility.sanitize(isbn) + "'" + " GROUP BY I2.isbn" + " ORDER BY sales DESC " + " LIMIT 5 "; //System.err.println(sql); con2.newStatement(); rs2 = con2.stmt.executeQuery(sql); JsonArrayBuilder suggestions = Json.createArrayBuilder(); while (rs2.next()) { suggestions.add(rs2.getString("I2.isbn")); } book.add("suggestions", suggestions); if (con2 != null) con2.closeConnection(); return book; } catch(Exception e) { if(con2!=null) con2.closeConnection(); throw new Exception(); } } private static JsonObjectBuilder JSONBook(String ISBN, JsonObjectBuilder book) throws Exception { Connector con = null; try { con = new Connector(); String sql = "SELECT * from Book where isbn = '" + Utility.sanitize(ISBN) + "'"; ResultSet rs = con.stmt.executeQuery(sql); rs.next(); book = JSONBook(rs, book); if (con != null) con.closeConnection(); return book; } catch(Exception e) { if(con!=null) con.closeConnection(); throw new Exception(); } } public static String details(final String isbn) { JsonObjectBuilder result = Json.createObjectBuilder(); Connector con = null; try { con = new Connector(); System.err.println("Connected to the database."); } catch (Exception e) { System.err.println("Cannot connect to the database."); System.err.println(e.getMessage()); if(con!=null) con.closeConnection(); return null; } // get details String sql = "SELECT * FROM Book B" + " WHERE isbn = " + isbn; ResultSet rs = null; try { rs = con.stmt.executeQuery(sql); } catch (Exception e) { System.out.println("Failed to get details"); System.err.println(e.getMessage()); if(con!=null) con.closeConnection(); return null; } JsonObjectBuilder book = Json.createObjectBuilder(); try { rs.next(); book = JSONBook(rs, book); } catch (Exception e) { System.err.println("Failed to add details of this book into result"); System.err.println(e); if(con!=null) con.closeConnection(); return null; } result.add("book", book); if(con!=null) con.closeConnection(); return result.build().toString(); } public static String add(JsonObject payload) { JsonObject book = payload.getJsonObject("book"); JsonObjectBuilder newBook = Json.createObjectBuilder(); JsonObjectBuilder result = Json.createObjectBuilder(); Connector con = null; try { String isbn = book.getString("ISBN"); String title = book.getString("title"); int pid = Integer.parseInt(book.getString("publisher")); int copies = book.getInt("amount"); double price = book.getJsonNumber("price").doubleValue(); String pubdate = book.getString("pubdate").split("T")[0]; String format = book.isNull("format") ? null : book.getString("format"); String summary = book.isNull("summary") ? null : book.getString("summary"); String subject = book.isNull("subject") ? null : book.getString("subject"); String keyword = book.isNull("keyword") ? null : book.getString("keyword"); String subtitle = book.isNull("subtitle") ? null : book.getString("subtitle"); String img = book.isNull("img") ? null : book.getString("img"); String sql = "INSERT INTO Book (isbn, title, pid, copies, price, pubdate, " + "format, summary, subject, keyword, subtitle, img) VALUES "; sql += "('" + Utility.sanitize(isbn) + "','" + Utility.sanitize(title) + "',"; sql += pid + "," + copies + "," + price + ",'" + Utility.sanitize(pubdate) + "',"; sql += Utility.genStringAttr(format, ","); sql += Utility.genStringAttr(summary, ","); sql += Utility.genStringAttr(subject, ","); sql += Utility.genStringAttr(keyword, ","); sql += Utility.genStringAttr(subtitle, ","); sql += Utility.genStringAttr(img, ""); sql += ") ON DUPLICATE KEY UPDATE copies=VALUES(copies)"; // System.err.println(sql); con = new Connector(); con.stmt.executeUpdate(sql); newBook.add("ISBN", isbn); sql = "INSERT INTO WrittenBy (isbn, authid) VALUES "; boolean first = true; for (JsonValue authid : book.getJsonArray("authors")) { if (!first) sql += ','; else first = false; String _authid = authid.toString(); _authid = _authid.substring(1, _authid.length() - 1); sql += "('" + Utility.sanitize(isbn) + "'," + _authid + ")"; } sql += " ON DUPLICATE KEY UPDATE isbn=isbn"; con.stmt.executeUpdate(sql); } catch (Exception e) { System.out.println("Failed to add the book into database"); System.err.println(e.getMessage()); if(con!=null) con.closeConnection(); return null; } result.add("book", newBook); if(con!=null) con.closeConnection(); return result.build().toString(); } public static String simpleSearch(int cid, int limit, int offset, String all, String _orderBy) { int orderBy = _orderBy == null ? 1 : Integer.parseInt(_orderBy); JsonObjectBuilder result = Json.createObjectBuilder(); JsonArrayBuilder books = Json.createArrayBuilder(); Connector con = null; try { String[] keyWords = all.split(" "); String conditions = "true"; for (String _keyWord : keyWords) { System.err.println(_keyWord); String keyWord = Utility.sanitize(_keyWord); conditions += " AND (" + "B.title LIKE '%" + Utility.sanitize(keyWord) + "%' OR B.subtitle like '%" + Utility.sanitize(keyWord) + "%' OR A.authname like '%" + Utility.sanitize(keyWord) + "%' OR B.isbn like '%" + Utility.sanitize(keyWord) + "%' OR B.summary LIKE '%" + Utility.sanitize(keyWord) + "%' OR P.pubname LIKE '%" + Utility.sanitize(keyWord) + "%' OR B.keyword LIKE '%" + Utility.sanitize(keyWord) + "%' OR B.subject LIKE '%" + Utility.sanitize(keyWord) + "%'" + ") "; } con = new Connector(); String sql = "SELECT * FROM Book B, Publisher P, WrittenBy W, Author A WHERE "; sql += " B.pid = P.pid AND W.isbn = B.isbn AND A.authid = W.authid AND "; sql += conditions; sql += " GROUP BY B.isbn "; if (orderBy == 0) { sql += " ORDER BY pubdate ASC"; } else if (orderBy == 1) { sql += " ORDER BY pubdate DESC"; } else if (orderBy == 2) { sql += " ORDER BY (SELECT AVG(score) FROM Feedback F WHERE F.isbn = B.isbn)ASC"; } else if (orderBy == 3) { sql += " ORDER BY (SELECT AVG(score) FROM Feedback F WHERE F.isbn = B.isbn)DESC"; } else if (orderBy == 4) { sql += " ORDER BY (SELECT AVG(score) FROM Feedback F WHERE F.isbn = B.isbn AND " + "(F.cid = " + cid + " OR F.cid IN ( " + "SELECT T.cid2 FROM TrustRecords T WHERE T.trust = TRUE AND T.cid1 = " + cid + ")))ASC"; } else if (orderBy == 5) { sql += " ORDER BY (SELECT AVG(score) FROM Feedback F WHERE F.isbn = B.isbn AND " + "(F.cid = " + cid + " OR F.cid IN ( " + "SELECT T.cid2 FROM TrustRecords T WHERE T.trust = TRUE AND T.cid1 = " + cid + ")))DESC"; } sql += " LIMIT " + limit + " OFFSET " + offset; // System.out.println(sql); ResultSet rs = con.stmt.executeQuery(sql); while (rs.next()) { JsonObjectBuilder book = Json.createObjectBuilder(); book = JSONBook(rs, book); books.add(book); } sql = "SELECT COUNT(DISTINCT B.isbn) as total FROM Book B, Publisher P, WrittenBy W, Author A WHERE "; sql += " B.pid = P.pid AND W.isbn = B.isbn AND A.authid = W.authid AND "; sql += conditions; // System.out.println(sql); rs = con.stmt.executeQuery(sql); rs.next(); int total = rs.getInt("total"); JsonObjectBuilder meta = Json.createObjectBuilder(); meta.add("total", total); result.add("meta", meta); result.add("books", books); if(con!=null) con.closeConnection(); return result.build().toString(); } catch (Exception e) { System.out.println("Simple search failed"); System.err.println(e.getMessage()); if(con!=null) con.closeConnection(); return null; } } public static String advancedSearch(int cid, int limit, int offset, JsonArray advanced, String _orderBy) { Connector con = null; try { int orderBy = _orderBy == null ? 1 : Integer.parseInt(_orderBy); JsonObjectBuilder result = Json.createObjectBuilder(); JsonArrayBuilder books = Json.createArrayBuilder(); String conditions = ""; for (int i = 0; i < advanced.size(); i++) { JsonObject condition = advanced.getJsonObject(i); String term = condition.getString("term"); String included = Utility.sanitize(condition.getString("cond")); String conj = condition.getString("conj"); if (term.equals("Title")) conditions += " title LIKE '%" + Utility.sanitize(included) + "%'"; else if (term.equals("Author")) conditions += " authname LIKE '%" + Utility.sanitize(included) + "%'"; else if (term.equals("Publisher")) conditions += " pubname LIKE '%" + Utility.sanitize(included) + "%'"; else if (term.equals("Subject")) conditions += " subject LIKE '%" + Utility.sanitize(included) + "%'"; else {if(con!=null) con.closeConnection(); return null;} if (i != advanced.size() - 1) { if (conj.equals("OR")) conditions += " OR "; else conditions += " AND "; } } String sql = "SELECT * FROM Book B, Publisher P, WrittenBy W, Author A WHERE "; sql += " B.pid = P.pid AND W.isbn = B.isbn AND A.authid = W.authid AND "; sql += conditions; sql += " GROUP BY B.isbn "; if (orderBy == 0) { sql += " ORDER BY pubdate ASC"; } else if (orderBy == 1) { sql += " ORDER BY pubdate DESC"; } else if (orderBy == 2) { sql += " ORDER BY (SELECT AVG(score) FROM Feedback F WHERE F.isbn = B.isbn)ASC"; } else if (orderBy == 3) { sql += " ORDER BY (SELECT AVG(score) FROM Feedback F WHERE F.isbn = B.isbn)DESC"; } else if (orderBy == 4) { sql += " ORDER BY (SELECT AVG(score) FROM Feedback F WHERE F.isbn = B.isbn AND " + "(F.cid = " + cid + " OR F.cid IN ( " + "SELECT T.cid2 FROM TrustRecords T WHERE T.trust = TRUE AND T.cid1 = " + cid + ")))ASC"; } else if (orderBy == 5) { sql += " ORDER BY (SELECT AVG(score) FROM Feedback F WHERE F.isbn = B.isbn AND " + "(F.cid = " + cid + " OR F.cid IN ( " + "SELECT T.cid2 FROM TrustRecords T WHERE T.trust = TRUE AND T.cid1 = " + cid + ")))DESC"; } sql += " LIMIT " + limit + " OFFSET " + offset; con = new Connector(); ResultSet rs = con.stmt.executeQuery(sql); while (rs.next()) { JsonObjectBuilder book = Json.createObjectBuilder(); book = JSONBook(rs, book); books.add(book); } sql = "SELECT COUNT(DISTINCT B.isbn) as total FROM Book B, Publisher P, WrittenBy W, Author A WHERE "; sql += " B.pid = P.pid AND W.isbn = B.isbn AND A.authid = W.authid AND "; sql += conditions; rs = con.stmt.executeQuery(sql); rs.next(); int total = rs.getInt("total"); JsonObjectBuilder meta = Json.createObjectBuilder(); meta.add("total", total); result.add("meta", meta); result.add("books", books); if(con!=null) con.closeConnection(); return result.build().toString(); } catch (Exception e) { System.out.println("Failed to build conditions"); System.err.println(e.getMessage()); if(con!=null) con.closeConnection(); return null; } } public static String popular(int limit, int offset, String start, String end) { JsonObjectBuilder result = Json.createObjectBuilder(); JsonArrayBuilder books = Json.createArrayBuilder(); JsonObjectBuilder sales = Json.createObjectBuilder(); String st = start.split("T")[0]; String ed = end.split("T")[0]; Connector con = null; try { String sql = "SELECT isbn, SUM(amount) as sales FROM ItemInOrder I, Orders O " + "WHERE I.orderid = O.orderid AND O.time >= '" + Utility.sanitize(st) + "' AND O.time <= '" + Utility.sanitize(ed) + "' GROUP BY isbn ORDER BY SUM(amount) DESC"; sql += " LIMIT " + limit + " OFFSET " + offset; // System.err.println(sql); con = new Connector(); ResultSet rs = con.stmt.executeQuery(sql); while (rs.next()) { final String isbn = rs.getString("isbn"); final int _sales = rs.getInt("sales"); JsonObjectBuilder book = Json.createObjectBuilder(); book = JSONBook(isbn, book); books.add(book); sales.add(isbn, _sales); } sql = "SELECT COUNT(DISTINCT isbn) AS total FROM ItemInOrder I, Orders O " + "WHERE I.orderid = O.orderid AND O.time >= '" + Utility.sanitize(st) + "' AND O.time <= '" + Utility.sanitize(ed) + "'"; rs = con.stmt.executeQuery(sql); rs.next(); JsonObjectBuilder meta = Json.createObjectBuilder(); meta.add("total", rs.getInt("total")); result.add("meta", meta); result.add("books", books); result.add("sales", sales); if(con!=null) con.closeConnection(); return result.build().toString(); } catch (Exception e) { System.out.println("Failed to query popular books"); System.err.println(e.getMessage()); if(con!=null) con.closeConnection(); return null; } } };
41.930023
148
0.523284
360906a61dbeb45525943e1e66d006bedd48c7cc
2,026
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.config.server.http.v2; import com.yahoo.config.application.api.ApplicationFile; import com.yahoo.config.provision.Zone; import com.yahoo.container.jdisc.HttpRequest; import com.yahoo.jdisc.application.BindingMatch; import com.yahoo.config.provision.ApplicationId; import com.yahoo.vespa.config.server.http.ContentRequest; import com.yahoo.vespa.config.server.http.Utils; /** * Represents a content request for an application. * * @author Ulf Lilleengen * @since 5.3 */ public class ApplicationContentRequest extends ContentRequest { private static final String uriPattern = "http://*/application/v2/tenant/*/application/*/environment/*/region/*/instance/*/content/*"; private final ApplicationId applicationId; private final Zone zone; ApplicationContentRequest(HttpRequest request, long sessionId, ApplicationId applicationId, Zone zone, String contentPath, ApplicationFile applicationFile) { super(request, sessionId, contentPath, applicationFile); this.applicationId = applicationId; this.zone = zone; } static String getContentPath(HttpRequest request) { BindingMatch<?> bm = Utils.getBindingMatch(request, uriPattern); return bm.group(7); } @Override public String getPathPrefix() { StringBuilder sb = new StringBuilder(); sb.append("/application/v2/tenant/").append(applicationId.tenant().value()); sb.append("/application/").append(applicationId.application().value()); sb.append("/environment/").append(zone.environment().value()); sb.append("/region/").append(zone.region().value()); sb.append("/instance/").append(applicationId.instance().value()); return sb.toString(); } }
38.961538
138
0.671767
d4b13d673fa7b5511babd9ee27ac39dc5985f6e1
5,499
package com.markzhai.lyrichere.ui; import android.app.Activity; import android.content.Context; import android.content.res.ColorStateList; import android.graphics.Bitmap; import android.graphics.drawable.AnimationDrawable; import android.support.v4.app.ActivityCompat; import android.support.v4.media.MediaDescriptionCompat; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.markzhai.lyrichere.AlbumArtCache; import com.markzhai.lyrichere.R; import com.markzhai.lyrichere.utils.LogUtils; import com.markzhai.lyrichere.utils.LollipopUtils; public class MediaItemViewHolder { static final int STATE_INVALID = -1; static final int STATE_NONE = 0; static final int STATE_PLAYABLE = 1; static final int STATE_PAUSED = 2; static final int STATE_PLAYING = 3; private static ColorStateList sColorStatePlaying; private static ColorStateList sColorStateNotPlaying; ImageView mImageView; TextView mTitleView; TextView mDescriptionView; static View setupView(Activity activity, View convertView, ViewGroup parent, MediaDescriptionCompat description, int state) { if (sColorStateNotPlaying == null || sColorStatePlaying == null) { initializeColorStateLists(activity); } final MediaItemViewHolder holder; Integer cachedState = STATE_INVALID; if (convertView == null) { convertView = LayoutInflater.from(activity) .inflate(R.layout.media_list_item, parent, false); holder = new MediaItemViewHolder(); holder.mImageView = (ImageView) convertView.findViewById(R.id.play_eq); holder.mTitleView = (TextView) convertView.findViewById(R.id.title); holder.mDescriptionView = (TextView) convertView.findViewById(R.id.description); convertView.setTag(holder); } else { holder = (MediaItemViewHolder) convertView.getTag(); cachedState = (Integer) convertView.getTag(R.id.tag_mediaitem_state_cache); } holder.mTitleView.setText(description.getTitle()); holder.mDescriptionView.setText(description.getSubtitle()); // If the state of convertView is different, we need to adapt the view to the // new state. if (cachedState == null || cachedState != state) { switch (state) { case STATE_PLAYABLE: holder.mImageView.setImageDrawable( ActivityCompat.getDrawable(activity, R.drawable.ic_play_arrow_black_36dp)); LollipopUtils.setImageTintList(holder.mImageView, sColorStateNotPlaying); holder.mImageView.setVisibility(View.VISIBLE); break; case STATE_PLAYING: AnimationDrawable animation = (AnimationDrawable) ActivityCompat.getDrawable(activity, R.drawable.ic_equalizer_white_36dp); holder.mImageView.setImageDrawable(animation); LollipopUtils.setImageTintList(holder.mImageView, sColorStatePlaying); holder.mImageView.setVisibility(View.VISIBLE); animation.start(); break; case STATE_PAUSED: holder.mImageView.setImageDrawable( ActivityCompat.getDrawable(activity, R.drawable.ic_equalizer1_white_36dp)); LollipopUtils.setImageTintList(holder.mImageView, sColorStateNotPlaying); holder.mImageView.setVisibility(View.VISIBLE); break; default: if (description.getIconUri() != null) { String artUrl = description.getIconUri().toString(); Bitmap art = description.getIconBitmap(); AlbumArtCache cache = AlbumArtCache.getInstance(); if (art == null) { art = cache.getIconImage(artUrl); } if (art != null) { holder.mImageView.setImageBitmap(art); } else { cache.fetch(artUrl, new AlbumArtCache.FetchListener() { @Override public void onFetched(String artUrl, Bitmap bitmap, Bitmap icon) { if (icon != null) { holder.mImageView.setImageBitmap(icon); } } } ); } } else { holder.mImageView.setVisibility(View.GONE); } } convertView.setTag(R.id.tag_mediaitem_state_cache, state); } return convertView; } static private void initializeColorStateLists(Context ctx) { sColorStateNotPlaying = ColorStateList.valueOf(ctx.getResources().getColor( R.color.media_item_icon_not_playing)); sColorStatePlaying = ColorStateList.valueOf(ctx.getResources().getColor( R.color.media_item_icon_playing)); } }
43.992
106
0.588834
42e37a960f790ea224fad6b641af6154da10fe5b
1,695
package com.cts.servlet.controller; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.servlet.RequestDispatcher; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/login") public class LoginServlet extends HttpServlet { public boolean isValidUser(String userName, String passWord) throws ClassNotFoundException, SQLException { Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/cts"; String username = "root"; String password = "admin"; Connection conn = DriverManager.getConnection(url, username, password); System.out.println("Connection Succesfull"); String query = "select * from Practice where username=? and password=?"; PreparedStatement ps = conn.prepareStatement(query); ps.setString(1, userName); ps.setString(2, passWord); ResultSet rs = ps.executeQuery(); if (rs.next()) { return true; } else return false; } protected void doPost(HttpServletRequest request, HttpServletResponse response) { String userName = request.getParameter("user"); String passWord = request.getParameter("pass"); RequestDispatcher rd; try { if (isValidUser(userName, passWord)) { rd = request.getRequestDispatcher("welcome.html"); rd.forward(request, response); } else { rd = request.getRequestDispatcher("login.html"); rd.include(request, response); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
30.267857
107
0.746903
e9d50b22f424ff3c1d696de5c42f594296602a21
2,100
package org.sdase.commons.server.mongo.testing; import com.mongodb.MongoClient; import de.flapdoodle.embed.mongo.distribution.IFeatureAwareVersion; import org.junit.rules.ExternalResource; /** * JUnit Test rule for running a MongoDB instance alongside the (integration) tests. Can be * configured with custom user credentials and database name. Use {@link #getHosts()} to retrieve * the host to connect to. * * <p>Example usage: * * <pre> * &#64;ClassRule * public static final MongoDbRule RULE = MongoDbRule * .builder() * .withDatabase("my_db") * .withUsername("my_user") * .withPassword("my_s3cr3t") * .build(); * </pre> */ public class StartLocalMongoDbRule extends ExternalResource implements MongoDbRule { private final StartLocalMongoDb startLocalMongoDb; StartLocalMongoDbRule( String username, String password, String database, boolean enableScripting, IFeatureAwareVersion version, long timeoutMs) { startLocalMongoDb = new StartLocalMongoDb(username, password, database, enableScripting, version, timeoutMs); } @Override protected void before() { startLocalMongoDb.startMongo(); } @Override protected void after() { startLocalMongoDb.stopMongo(); } @Override public String getDatabase() { return startLocalMongoDb.database; } @Override public String getHosts() { return startLocalMongoDb.getHosts(); } @Override public String getUsername() { return startLocalMongoDb.username; } @Override public String getPassword() { return startLocalMongoDb.password; } @Override public String getOptions() { return ""; } /** * @return the version of the MongoDB instance which is associated with this MongoDbRule * @deprecated because this is specific to flap doodle, use {@link #getServerVersion()} */ @Override @Deprecated public IFeatureAwareVersion getVersion() { return startLocalMongoDb.version; } @Override public MongoClient createClient() { return startLocalMongoDb.createClient(); } }
23.333333
97
0.709048
f835d43a0d2d1918e38d750755aed43393bbd41d
2,633
package com.elchologamer.userlogin.api.event; import com.elchologamer.userlogin.UserLogin; import com.elchologamer.userlogin.api.types.AuthType; import com.elchologamer.userlogin.util.Utils; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; import org.bukkit.event.player.PlayerEvent; public class AuthenticationEvent extends PlayerEvent implements Cancellable { private final UserLogin plugin = UserLogin.getPlugin(); private static final HandlerList HANDLERS = new HandlerList(); private final AuthType type; private boolean cancelled = false; private Location destination = null; private String targetServer = null; private String message; private String announcement = null; private AuthenticationEvent(Player player, AuthType type) { super(player); this.type = type; message = Utils.color(plugin.getLang().getMessage("messages." + type.getMessageKey())); if (plugin.getConfig().getBoolean("loginBroadcast")) { announcement = plugin.getLang().getMessage("messages.login_announcement").replace("{player}", player.getName()); } } public AuthenticationEvent(Player player, AuthType type, String targetServer) { this(player, type); this.targetServer = targetServer; } public AuthenticationEvent(Player player, AuthType type, Location destination) { this(player, type); this.destination = destination; } public static HandlerList getHandlerList() { return HANDLERS; } @Override public HandlerList getHandlers() { return HANDLERS; } public AuthType getType() { return type; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getTargetServer() { return targetServer; } public void setTargetServer(String targetServer) { this.targetServer = targetServer; } public String getAnnouncement() { return announcement; } public void setAnnouncement(String announcement) { this.announcement = announcement; } public Location getDestination() { return destination; } public void setDestination(Location destination) { this.destination = destination; } @Override public boolean isCancelled() { return cancelled; } @Override public void setCancelled(boolean cancelled) { this.cancelled = cancelled; } }
26.59596
124
0.683251
bb331b47081874044470ae60d22e434d33905a77
880
package me.welkinbai.bsonmapper; import org.bson.BsonReader; import org.bson.BsonString; import org.bson.BsonValue; import org.bson.BsonWriter; /** * Created by welkinbai on 2017/3/23. */ final class BsonStringConverter extends AbstractBsonConverter<String, BsonString> { private BsonStringConverter() { } public static BsonStringConverter getInstance() { return new BsonStringConverter(); } @Override public String decode(BsonValue bsonValue) { return bsonValue.asString().getValue(); } @Override public BsonString encode(String object) { return new BsonString(object); } @Override public String decode(BsonReader bsonReader) { return bsonReader.readString(); } @Override public void encode(BsonWriter bsonWriter, String value) { bsonWriter.writeString(value); } }
22
83
0.693182
a195f95972b22faa3a85542668070eed11abadef
372
package com.wxy.appstartfaster.util; import android.util.Log; import com.wxy.appstartfaster.dispatcher.AppStartTaskDispatcher; public class AppStartTaskLogUtil { private static final String TAG="AppStartTask: "; public static void showLog(String log){ if (AppStartTaskDispatcher.getInstance().isShowLog()){ Log.e(TAG,log); } } }
24.8
64
0.709677
4343fc0586387aac4d05f69400cfe11bc8a21942
1,547
package org.inspirerobotics.sumobots.driverstation.gui; import javafx.scene.Scene; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.BorderPane; import org.inspirerobotics.sumobots.driverstation.gui.style.StyleManager; import org.inspirerobotics.sumobots.driverstation.gui.style.StyleType; import org.inspirerobotics.sumobots.driverstation.state.DriverstationState; public class RootPane extends AnchorPane { private final BorderPane borderPane; private final StatusPane statusPane; private final SettingsMenu settingsMenu; private final LogPane logPane; public RootPane() { this.borderPane = new BorderPane(); this.statusPane = new StatusPane(); this.settingsMenu = new SettingsMenu(); this.logPane = new LogPane(); borderPane.setBottom(statusPane); borderPane.setTop(settingsMenu); borderPane.setCenter(logPane); GuiUtils.anchorInAnchorPane(borderPane); this.getChildren().add(borderPane); StyleManager.getInstance().styleChildren(StyleType.DARK); } public Scene createScene() { return new Scene(this); } public void onStateUpdated(DriverstationState currentState) { statusPane.onStateUpdated(currentState); } BorderPane getBorderPane() { return borderPane; } SettingsMenu getSettingsMenu() { return settingsMenu; } StatusPane getStatusPane() { return statusPane; } public LogPane getLogPane() { return logPane; } }
26.672414
75
0.710407
d53d82cb0a4b487547cbd31a3aa27fcb6ef9906c
233
package com.example.step; public class RealDatabase implements Database { private String value; public RealDatabase(String val) { this.value = val; } public String getValue() { return value; } }
17.923077
47
0.643777
832e025eb9bfc3f6921524f9def6620c6a1d8c72
7,145
/* * Copyright (C) 2015 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.sqlbrite.todo.ui; import android.app.Activity; import android.database.Cursor; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.view.MenuItemCompat; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import butterknife.ButterKnife; import butterknife.InjectView; import com.example.sqlbrite.todo.R; import com.example.sqlbrite.todo.TodoApp; import com.example.sqlbrite.todo.db.Db; import com.example.sqlbrite.todo.db.TodoItem; import com.example.sqlbrite.todo.db.TodoList; import com.squareup.sqlbrite.BriteDatabase; import javax.inject.Inject; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.android.widget.OnItemClickEvent; import rx.android.widget.WidgetObservable; import rx.functions.Action1; import rx.functions.Func1; import rx.functions.Func2; import rx.schedulers.Schedulers; import rx.subscriptions.CompositeSubscription; import static android.support.v4.view.MenuItemCompat.SHOW_AS_ACTION_IF_ROOM; import static android.support.v4.view.MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT; import static com.squareup.sqlbrite.SqlBrite.Query; public final class ItemsFragment extends Fragment { private static final String KEY_LIST_ID = "list_id"; private static final String LIST_QUERY = "SELECT * FROM " + TodoItem.TABLE + " WHERE " + TodoItem.LIST_ID + " = ? ORDER BY " + TodoItem.COMPLETE + " ASC"; private static final String COUNT_QUERY = "SELECT COUNT(*) FROM " + TodoItem.TABLE + " WHERE " + TodoItem.COMPLETE + " = " + Db.BOOLEAN_FALSE + " AND " + TodoItem.LIST_ID + " = ?"; private static final String TITLE_QUERY = "SELECT " + TodoList.NAME + " FROM " + TodoList.TABLE + " WHERE " + TodoList.ID + " = ?"; public interface Listener { void onNewItemClicked(long listId); } public static ItemsFragment newInstance(long listId) { Bundle arguments = new Bundle(); arguments.putLong(KEY_LIST_ID, listId); ItemsFragment fragment = new ItemsFragment(); fragment.setArguments(arguments); return fragment; } @Inject BriteDatabase db; @InjectView(android.R.id.list) ListView listView; @InjectView(android.R.id.empty) View emptyView; private Listener listener; private ItemsAdapter adapter; private CompositeSubscription subscriptions; private long getListId() { return getArguments().getLong(KEY_LIST_ID); } @Override public void onAttach(Activity activity) { if (!(activity instanceof Listener)) { throw new IllegalStateException("Activity must implement fragment Listener."); } super.onAttach(activity); TodoApp.objectGraph(activity).inject(this); setHasOptionsMenu(true); listener = (Listener) activity; adapter = new ItemsAdapter(activity); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); MenuItem item = menu.add(R.string.new_item) .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { listener.onNewItemClicked(getListId()); return true; } }); MenuItemCompat.setShowAsAction(item, SHOW_AS_ACTION_IF_ROOM | SHOW_AS_ACTION_WITH_TEXT); } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.items, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); ButterKnife.inject(this, view); listView.setEmptyView(emptyView); listView.setAdapter(adapter); WidgetObservable.itemClicks(listView) // .subscribeOn(AndroidSchedulers.mainThread()) .observeOn(Schedulers.io()) .subscribe(new Action1<OnItemClickEvent>() { @Override public void call(OnItemClickEvent event) { boolean newValue = !adapter.getItem(event.position()).complete(); db.update(TodoItem.TABLE, new TodoItem.Builder().complete(newValue).build(), TodoItem.ID + " = ?", String.valueOf(event.id())); } }); } @Override public void onResume() { super.onResume(); String listId = String.valueOf(getListId()); subscriptions = new CompositeSubscription(); Observable<Integer> itemCount = db.createQuery(TodoItem.TABLE, COUNT_QUERY, listId) // .map(new Func1<Query, Integer>() { @Override public Integer call(Query query) { Cursor cursor = query.run(); try { if (!cursor.moveToNext()) { throw new AssertionError("No rows"); } return cursor.getInt(0); } finally { cursor.close(); } } }); Observable<String> listName = db.createQuery(TodoList.TABLE, TITLE_QUERY, listId).map(new Func1<Query, String>() { @Override public String call(Query query) { Cursor cursor = query.run(); try { if (!cursor.moveToNext()) { throw new AssertionError("No rows"); } return cursor.getString(0); } finally { cursor.close(); } } }); subscriptions.add( Observable.combineLatest(listName, itemCount, new Func2<String, Integer, String>() { @Override public String call(String listName, Integer itemCount) { return listName + " (" + itemCount + ")"; } }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Action1<String>() { @Override public void call(String title) { getActivity().setTitle(title); } })); subscriptions.add(db.createQuery(TodoItem.TABLE, LIST_QUERY, listId) .map(TodoItem.MAP) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(adapter)); } @Override public void onPause() { super.onPause(); subscriptions.unsubscribe(); } }
33.862559
95
0.674878
4a1aa4269e9fc8e619c171966550fb7527c6a286
296
package tddmicroexercises.turnticketdispenser; public class TicketDispenser { public TurnTicket getTurnTicket() { int newTurnNumber = TurnNumberSequence.getNextTurnNumber(); TurnTicket newTurnTicket = new TurnTicket(newTurnNumber); return newTurnTicket; } }
22.769231
67
0.733108
e157602fd5d8a70a50b8c7853cc1f920efa6b8d0
2,010
package com.vhoh.vhonlinehospital; import androidx.appcompat.app.AppCompatActivity; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.util.Random; public class SendFeedbackActivity extends AppCompatActivity { private EditText yourFeedback; private ProgressDialog loadingBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_send_feedback); loadingBar = new ProgressDialog(this); yourFeedback = findViewById(R.id.your_feedback); } public void sendFeedbackButton(View view) { loadingBar.setTitle("Sending"); loadingBar.setMessage("Please wait ..."); loadingBar.setCanceledOnTouchOutside(true); loadingBar.show(); String fb = yourFeedback.getText().toString(); if (fb.isEmpty()) { loadingBar.dismiss(); Toast.makeText(this, "Please, write something.", Toast.LENGTH_SHORT).show(); } else { try { DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference() .child("User Feedback") .child((FirebaseAuth.getInstance().getCurrentUser().getUid())) .child(String.valueOf(Math.abs(((new Random()).nextInt()*1000)))); databaseReference.setValue(fb); } catch (Exception e) { Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show(); } finally { startActivity(new Intent(SendFeedbackActivity.this, HomepageDrawerActivity.class)); finish(); } } } }
34.067797
99
0.656219
f80f78b26d282ec5569a75bb71322dc29f44c9e5
2,745
/* * Copyright 2016-2026 TinyZ * * 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.ogcs.netty.handler.mq; import io.netty.channel.Channel; import io.netty.channel.ChannelHandler.Sharable; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import org.ogcs.app.NetSession; import org.ogcs.app.Executor; import org.ogcs.app.Session; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; /** * 基于同步消息队列的单生产者的Disruptor模式 * * @author TinyZ. * @since 1.0 */ @Sharable public abstract class MessageQueueHandler<O> extends SimpleChannelInboundHandler<O> { private static final ConcurrentHashMap<UUID, Session> SESSIONS = new ConcurrentHashMap<>(); private static final ConcurrentHashMap<Channel, UUID> CHANNEL_UUID = new ConcurrentHashMap<>(); protected LogicProcessor processor; public MessageQueueHandler(LogicProcessor processor) { this.processor = processor; new Thread(this.processor, "Thread - LogicProcessor:" + processor.toString()).start(); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { UUID uuid = UUID.randomUUID(); CHANNEL_UUID.put(ctx.channel(), uuid); NetSession session = new NetSession(ctx.channel()); SESSIONS.put(uuid, session); super.channelActive(ctx); } @Override protected void channelRead0(ChannelHandlerContext ctx, O msg) throws Exception { UUID uuid = CHANNEL_UUID.get(ctx.channel()); if (null != uuid) { Session session = SESSIONS.get(uuid); if (null != session) { this.processor.addRequest(newExecutor(session, msg)); } } } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { UUID uuid = CHANNEL_UUID.remove(ctx.channel()); if (null != uuid) { sessionInactive(SESSIONS.remove(uuid)); } super.channelInactive(ctx); } protected abstract Executor newExecutor(Session session, O msg); protected void sessionInactive(Session session) { if (null != session) { session.close(); } } }
32.678571
99
0.692896
600a5ef8a43705f8fe60514dbdf327a6e2b3147d
1,084
package org.apereo.cas.configuration.model.support.interrupt; import org.apereo.cas.configuration.support.RequiresModule; import com.fasterxml.jackson.annotation.JsonFilter; import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; import java.io.Serializable; /** * This is {@link RegexInterruptProperties}. * * @author Misagh Moayyed * @since 6.4.0 */ @RequiresModule(name = "cas-server-support-interrupt-webflow") @Getter @Setter @Accessors(chain = true) @JsonFilter("RegexInterruptProperties") public class RegexInterruptProperties implements Serializable { private static final long serialVersionUID = 2169027840047126083L; /** * A regex pattern on the attribute name that if matches will successfully * complete the first condition for the interrupt notifications trigger. */ private String attributeName; /** * A regex pattern on the attribute value that if matches will successfully * complete the first condition for the interrupt notifications trigger. */ private String attributeValue; }
28.526316
79
0.762915
d66a42e7a273a938c38c5036c94459a6c9a2f9d3
4,476
/* * 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. * under the License. */ package org.apache.karaf.jaas.modules.encryption; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Map; import javax.xml.bind.DatatypeConverter; import org.apache.karaf.jaas.modules.Encryption; import org.apache.karaf.jaas.modules.EncryptionService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class BasicEncryption implements Encryption { private static final Logger log = LoggerFactory.getLogger(BasicEncryption.class); private String algorithm; private String encoding; private MessageDigest md; public BasicEncryption(Map<String, String> params) { for (String key : params.keySet()) { if (EncryptionService.ALGORITHM.equalsIgnoreCase(key)) { algorithm = params.get(key); } else if (EncryptionService.ENCODING.equalsIgnoreCase(key)) { encoding = params.get(key); } else { throw new IllegalArgumentException("Unsupported encryption parameter: " + key); } } if (algorithm == null) { throw new IllegalArgumentException("Digest algorithm must be specified"); } // Check if the algorithm algorithm is available try { md = MessageDigest.getInstance(algorithm); } catch (NoSuchAlgorithmException e) { log.error("Initialization failed. Digest algorithm " + algorithm + " is not available.", e); throw new IllegalArgumentException("Unable to configure login module: " + e.getMessage(), e); } if (encoding != null && encoding.length() > 0 && !EncryptionService.ENCODING_HEXADECIMAL.equalsIgnoreCase(encoding) && !EncryptionService.ENCODING_BASE64.equalsIgnoreCase(encoding)) { log.error("Initialization failed. Digest encoding " + encoding + " is not supported."); throw new IllegalArgumentException( "Unable to configure login module. Digest Encoding " + encoding + " not supported."); } } public String encryptPassword(String password) { if (password == null) { return null; } // Digest the user provided password byte[] data = md.digest(password.getBytes()); if (encoding == null || encoding.length() == 0 || EncryptionService.ENCODING_HEXADECIMAL.equalsIgnoreCase(encoding)) { return hexEncode(data); } else if (EncryptionService.ENCODING_BASE64.equalsIgnoreCase(encoding)) { return base64Encode(data); } else { throw new IllegalArgumentException( "Unable to configure login module. Digest Encoding " + encoding + " not supported."); } } public boolean checkPassword(String provided, String real) { if (real == null && provided == null) { return true; } if (real == null || provided == null) { return false; } // both are non-null String encoded = encryptPassword(provided); if (encoding == null || encoding.length() == 0 || EncryptionService.ENCODING_HEXADECIMAL.equalsIgnoreCase(encoding)) { return real.equalsIgnoreCase(encoded); } else if (EncryptionService.ENCODING_BASE64.equalsIgnoreCase(encoding)) { return real.equals(encoded); } return false; } public static String hexEncode(byte[] in) { return DatatypeConverter.printHexBinary(in); } /** * Encode the input data producing a base 64 encoded byte array. * * @param input the String to encore as an array of byte. * @return a byte array containing the base 64 encoded data. */ public static String base64Encode(byte[] input) { return DatatypeConverter.printBase64Binary(input); } }
39.964286
126
0.649911
4799ca4a20b6123db4065f8a3f905304d9c267f5
1,703
package me.Eclipse.Modules.Impl; import java.awt.Color; import java.io.File; import me.Eclipse.Brain; import me.Eclipse.Utils.Helper; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.MessageChannel; import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import net.dv8tion.jda.api.utils.AttachmentOption; public class WallpaperModule { public static void run(MessageReceivedEvent var0) { MessageChannel var1 = var0.getChannel(); Message var2 = var0.getMessage(); if (var2.getChannel().getName().contains("module-wallpaper")) { if (var2.getContentDisplay().startsWith("!Wallpaper " + Brain.Username) || var2.getContentDisplay().startsWith("!Wallpaper @ALL")) { String var3 = var2.getContentDisplay().replaceFirst("!Wallpaper " + Brain.Username + " ", "").replaceFirst("!Wallpaper @ALL ", ""); if ((new File(var3)).exists()) { try { Helper.User32.INSTANCE.SystemParametersInfo(20, 0, var3, 1); Helper.sendMessage(Color.GREEN, "Module Wallpaper (" + Brain.Username + ")", "Wallpaper has been successfully changed to:", var0); var1.sendFile(new File(var3), new AttachmentOption[0]).queue(); } catch (ClassFormatError var5) { Helper.sendMessage(Color.RED, "Module Wallpaper (" + Brain.Username + ")", "Failed to load wallpaper.", var0); } } else { Helper.sendMessage(Color.RED, "Module Wallpaper (" + Brain.Username + ")", "File not found.", var0); } } } } }
47.305556
154
0.607751
3fae1d9f7adad4f97896d8db3fe76fd0c5980f41
2,710
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @ClassName RansomNote * @Description #383 赎金信 * @Author MatthewHan * @Date 2020/5/11 21:43 * @Version 1.0 **/ public class No383 { /** * 执行用时 : 15 ms , 在所有 Java 提交中击败了 30.25% 的用户 * 内存消耗 : 40 MB , 在所有 Java 提交中击败了 8.33% 的用户 * * @param ransomNote * @param magazine * @return */ public static boolean canConstructPro(String ransomNote, String magazine) { List<Character> list1 = new ArrayList<>(ransomNote.length()); List<Character> list2 = new ArrayList<>(magazine.length()); for (int i = 0; i < ransomNote.length(); i++) { list1.add(ransomNote.charAt(i)); } for (int i = 0; i < magazine.length(); i++) { list2.add(magazine.charAt(i)); } System.out.println(list1); System.out.println(list2); for (int i = list1.size() - 1; i >= 0; i--) { for (int i1 = list2.size() - 1; i1 >= 0; i1--) { if (list1.get(i).equals(list2.get(i1))) { list1.remove(i); list2.remove(i1); break; } } } System.out.println(list1); System.out.println(list2); return list1.size() == 0; } /** * 执行用时 : 40 ms , 在所有 Java 提交中击败了 8.59% 的用户 * 内存消耗 : 40.4 MB , 在所有 Java 提交中击败了 8.33% 的用户 * * @param ransomNote * @param magazine * @return */ public static boolean canConstruct(String ransomNote, String magazine) { Map<String, Integer> map1 = new HashMap<>(ransomNote.length() * 4 / 3 + 1); Map<String, Integer> map2 = new HashMap<>(magazine.length() * 4 / 3 + 1); for (int i = 0; i < ransomNote.length(); i++) { map1.put(String.valueOf(ransomNote.charAt(i)), map1.getOrDefault(String.valueOf(ransomNote.charAt(i)), 0) + 1); } for (int i = 0; i < magazine.length(); i++) { map2.put(String.valueOf(magazine.charAt(i)), map2.getOrDefault(String.valueOf(magazine.charAt(i)), 0) + 1); } System.out.println(map1); System.out.println(map2); int count = 0; for (String s1 : map1.keySet()) { for (String s2 : map2.keySet()) { if (s1.equals(s2) && map1.get(s1) <= map2.get(s2)) { count++; break; } } } System.out.println(count); return count == map1.size(); } public static void main(String[] args) { System.out.println(canConstructPro("abssad", "sabacds")); } }
30.795455
123
0.523616
b3619b1ccc7325398bc4343db3564f2641742729
855
package net.minestom.server.utils.async; import net.minestom.server.MinecraftServer; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import java.util.concurrent.CompletableFuture; @ApiStatus.Internal public final class AsyncUtils { public static final CompletableFuture<Void> VOID_FUTURE = CompletableFuture.completedFuture(null); public static <T> CompletableFuture<T> empty() { //noinspection unchecked return (CompletableFuture<T>) VOID_FUTURE; } public static @NotNull CompletableFuture<Void> runAsync(@NotNull Runnable runnable) { return CompletableFuture.runAsync(() -> { try { runnable.run(); } catch (Exception e) { MinecraftServer.getExceptionManager().handleException(e); } }); } }
30.535714
102
0.687719
5f98cf0ff22f7624feb68b897043b2bb6887ee71
1,470
package org.openforis.collect.android.gui; import android.app.Activity; import android.content.SharedPreferences; import android.preference.PreferenceManager; import org.openforis.collect.R; /** * @author Daniel Wiell * @author Stefano Ricci */ public class ThemeInitializer { public static final String THEME_PREFERENCE_KEY = "theme"; private static final String DARK_THEME_PREFERENCE_KEY = "darkTheme"; public enum Theme { DARK(R.style.AppTheme), LIGHT(R.style.AppTheme_Light); int code; Theme(int code) { this.code = code; } public int getCode() { return code; } } public static void init(Activity activity) { Theme theme = determineThemeFromPreferences(activity); activity.setTheme(theme.getCode()); } public static Theme determineThemeFromPreferences(Activity activity) { SharedPreferences preferences = getPrefs(activity); String themeName = preferences.getString(THEME_PREFERENCE_KEY, null); if (themeName == null) { boolean darkTheme = preferences.getBoolean(DARK_THEME_PREFERENCE_KEY, true); return darkTheme ? Theme.DARK: Theme.LIGHT; } else { return Theme.valueOf(themeName.toUpperCase()); } } private static SharedPreferences getPrefs(Activity activity) { return PreferenceManager.getDefaultSharedPreferences(activity); } }
27.735849
88
0.67415
6ac20723b55f0680de2d64e69602234ba2e12357
3,784
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.sysnatura.goldrate.di.module; import android.content.Context; import android.support.v4.app.NotificationManagerCompat; import com.path.android.jobqueue.Job; import com.path.android.jobqueue.JobManager; import com.path.android.jobqueue.config.Configuration; import com.path.android.jobqueue.di.DependencyInjector; import com.raizlabs.android.dbflow.config.FlowManager; import com.raizlabs.android.dbflow.structure.database.DatabaseWrapper; import com.sysnatura.goldrate.App; import com.sysnatura.goldrate.config.DemoConfig; import com.sysnatura.goldrate.controller.FeedController; import com.sysnatura.goldrate.job.BaseJob; import com.sysnatura.goldrate.model.DemoDatabase; import com.sysnatura.goldrate.model.FeedModel; import com.sysnatura.goldrate.model.PostModel; import com.sysnatura.goldrate.model.UserModel; import com.sysnatura.goldrate.util.L; import org.greenrobot.eventbus.EventBus; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; @Module public class ApplicationModule { private final App mApp; public ApplicationModule(App app) { mApp = app; } @Provides @Singleton public UserModel userModel(DatabaseWrapper database) { return new UserModel(mApp, database); } @Provides @Singleton public PostModel postModel(DatabaseWrapper database) { return new PostModel(mApp, database); } @Provides @Singleton public FeedModel feedModel(DatabaseWrapper database) { return new FeedModel(mApp, database); } @Provides @Singleton public Context appContext() { return mApp; } @Provides @Singleton public FeedController feedController() { return new FeedController(mApp.getAppComponent()); } @Provides @Singleton public EventBus eventBus() { return new EventBus(); } /*@Provides @Singleton public SQLiteDatabase database() { return FlowManager.getDatabase(DemoDatabase.NAME).getWritableDatabase(); } }*/ @Provides @Singleton public DatabaseWrapper database() { return FlowManager.getDatabase(DemoDatabase.NAME).getWritableDatabase(); } @Provides @Singleton public DemoConfig demoConfig() { return new DemoConfig(mApp); } @Provides @Singleton public JobManager jobManager() { Configuration config = new Configuration.Builder(mApp) .consumerKeepAlive(45) .maxConsumerCount(3) .minConsumerCount(1) .customLogger(L.getJobLogger()) .injector(new DependencyInjector() { @Override public void inject(Job job) { if (job instanceof BaseJob) { ((BaseJob) job).inject(mApp.getAppComponent()); } } }) .build(); return new JobManager(mApp, config); } @Provides @Singleton public NotificationManagerCompat notificationCompat() { return NotificationManagerCompat.from(mApp); } }
28.02963
80
0.678383
05ee5687e78fcfbe7dfed1d663b78eeeb5a0f299
1,935
package sgf.gateway.web.controllers.dataset.relatedLink; import org.hibernate.validator.constraints.NotBlank; import org.hibernate.validator.constraints.URL; import org.safehaus.uuid.UUID; import sgf.gateway.model.metadata.Dataset; import sgf.gateway.model.metadata.RelatedLink; import sgf.gateway.validation.groups.Data; import sgf.gateway.validation.groups.Persistence; import sgf.gateway.validation.groups.Required; import sgf.gateway.validation.groups.Type; import javax.validation.GroupSequence; @GroupSequence({Required.class, Type.class, Data.class, Persistence.class, RelatedLinkCommand.class}) public class RelatedLinkCommand { private Dataset dataset; @NotBlank(groups = Required.class, message = "Related Link is required.") @URL(message = "Invalid website address") private String linkUri; @NotBlank(groups = Required.class, message = "Description is required.") private String linkText; private UUID relatedLinkId; public RelatedLinkCommand(Dataset dataset) { this.dataset = dataset; } public RelatedLinkCommand(Dataset dataset, RelatedLink link) { this.dataset = dataset; this.relatedLinkId = link.getIdentifier(); this.linkUri = link.getUri().toString(); this.linkText = link.getText(); } public Dataset getDataset() { return dataset; } public void setDataset(Dataset dataset) { this.dataset = dataset; } public String getLinkUri() { return linkUri; } public void setLinkUri(String linkUri) { this.linkUri = linkUri; } public String getLinkText() { return linkText; } public void setLinkText(String linkText) { this.linkText = linkText; } public UUID getRelatedLinkId() { return relatedLinkId; } public void setRelatedLinkId(UUID relatedLinkId) { this.relatedLinkId = relatedLinkId; } }
25.460526
101
0.703876
721f68992476ce94e1b1183edfd97ca919addc78
7,729
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jackrabbit.oak.plugins.index.solr.index; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.apache.jackrabbit.oak.api.CommitFailedException; import org.apache.jackrabbit.oak.api.PropertyState; import org.apache.jackrabbit.oak.api.Type; import org.apache.jackrabbit.oak.plugins.index.IndexHook; import org.apache.jackrabbit.oak.plugins.index.solr.OakSolrConfiguration; import org.apache.jackrabbit.oak.plugins.index.solr.query.SolrQueryIndex; import org.apache.jackrabbit.oak.spi.state.NodeBuilder; import org.apache.jackrabbit.oak.spi.state.NodeState; import org.apache.jackrabbit.oak.spi.state.NodeStateUtils; import org.apache.jackrabbit.oak.spi.state.ReadOnlyBuilder; import org.apache.solr.client.solrj.SolrServer; import static org.apache.jackrabbit.JcrConstants.JCR_PRIMARYTYPE; import static org.apache.jackrabbit.oak.commons.PathUtils.concat; import static org.apache.jackrabbit.oak.plugins.memory.EmptyNodeState.EMPTY_NODE; /** * {@link IndexHook} implementation that is responsible for keeping the * {@link org.apache.jackrabbit.oak.plugins.index.solr.query.SolrQueryIndex} up to date * <p/> * This handles index updates by keeping a {@link Map} of <code>String</code> * and {@link SolrIndexUpdate} for each path. * * @see org.apache.jackrabbit.oak.plugins.index.solr.query.SolrQueryIndex * @see SolrIndexHook */ public class SolrIndexDiff implements IndexHook { private final SolrIndexDiff parent; private final NodeBuilder node; private final String name; private String path; private final Map<String, SolrIndexUpdate> updates; private SolrServer solrServer; private OakSolrConfiguration configuration; private SolrIndexDiff(SolrIndexDiff parent, NodeBuilder node, SolrServer solrServer, String name, String path, Map<String, SolrIndexUpdate> updates, OakSolrConfiguration configuration) { this.parent = parent; this.node = node; this.name = name; this.path = path; this.updates = updates; this.solrServer = solrServer; this.configuration = configuration; // TODO : test properly on PDFs if (node != null && node.hasChildNode("oak:index")) { NodeBuilder index = node.child("oak:index"); for (String indexName : index.getChildNodeNames()) { NodeBuilder child = index.child(indexName); if (isIndexNode(child) && !this.updates.containsKey(getPath())) { this.updates.put(getPath(), new SolrIndexUpdate( getPath(), child, configuration)); } } } if (node != null && name != null && !NodeStateUtils.isHidden(name)) { for (SolrIndexUpdate update : updates.values()) { update.insert(getPath(), node); } } } private SolrIndexDiff(SolrIndexDiff parent, SolrServer solrServer, String name) { this(parent, getChildNode(parent.node, name), solrServer, name, null, parent.updates, parent.configuration); } public SolrIndexDiff(NodeBuilder root, SolrServer solrServer, OakSolrConfiguration configuration) { this(null, root, solrServer, null, "/", new HashMap<String, SolrIndexUpdate>(), configuration); } private static NodeBuilder getChildNode(NodeBuilder node, String name) { if (node != null && node.hasChildNode(name)) { return node.child(name); } else { return null; } } public String getPath() { if (path == null) { path = concat(parent.getPath(), name); } return path; } private static boolean isIndexNode(NodeBuilder node) { PropertyState ps = node.getProperty(JCR_PRIMARYTYPE); boolean isNodeType = ps != null && !ps.isArray() && ps.getValue(Type.STRING).equals("oak:queryIndexDefinition"); if (!isNodeType) { return false; } PropertyState type = node.getProperty("type"); boolean isIndexType = type != null && !type.isArray() && type.getValue(Type.STRING).equals(SolrQueryIndex.TYPE); return isIndexType; } // -----------------------------------------------------< NodeStateDiff >-- @Override public void propertyAdded(PropertyState after) { for (SolrIndexUpdate update : updates.values()) { update.insert(getPath(), node); } } @Override public void propertyChanged(PropertyState before, PropertyState after) { for (SolrIndexUpdate update : updates.values()) { update.insert(getPath(), node); } } @Override public void propertyDeleted(PropertyState before) { for (SolrIndexUpdate update : updates.values()) { update.insert(getPath(), node); } } @Override public void childNodeAdded(String name, NodeState after) { if (NodeStateUtils.isHidden(name)) { return; } for (SolrIndexUpdate update : updates.values()) { update.insert(concat(getPath(), name), new ReadOnlyBuilder(after)); } after.compareAgainstBaseState(EMPTY_NODE, child(name)); } @Override public void childNodeChanged(String name, NodeState before, NodeState after) { if (NodeStateUtils.isHidden(name)) { return; } after.compareAgainstBaseState(before, child(name)); } @Override public void childNodeDeleted(String name, NodeState before) { if (NodeStateUtils.isHidden(name)) { return; } for (SolrIndexUpdate update : updates.values()) { update.remove(concat(getPath(), name)); } } // -----------------------------------------------------< IndexHook >-- @Override public void apply() throws CommitFailedException { for (SolrIndexUpdate update : updates.values()) { update.apply(solrServer); } } @Override public void reindex(NodeBuilder state) throws CommitFailedException { boolean reindex = false; for (SolrIndexUpdate update : updates.values()) { if (update.getAndResetReindexFlag()) { reindex = true; } } if (reindex) { state.getNodeState().compareAgainstBaseState( EMPTY_NODE, new SolrIndexDiff(null, state, solrServer, null, "/", updates, configuration)); } } @Override public IndexHook child(String name) { return new SolrIndexDiff(this, solrServer, name); } @Override public void close() throws IOException { for (SolrIndexUpdate update : updates.values()) { update.close(); } updates.clear(); } }
34.972851
127
0.641221
65106a2022298db555507e9037f261bd8ad5c83e
2,059
package com.ilya40umov.badge.repository; import com.ilya40umov.badge.entity.Account; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.EntityGraph; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import java.util.Optional; /** * DAO for {@link Account} entity. * * @author isorokoumov */ @Transactional(propagation = Propagation.MANDATORY) public interface AccountRepository extends JpaRepository<Account, Long> { @EntityGraph(value = "Account.withPrivileges", type = EntityGraph.EntityGraphType.LOAD) @Query("select a from Account a where a.accountId = :accountId") Optional<Account> findByIdWithPrivileges(@Param("accountId") Long accountId); @EntityGraph(value = "Account.withAllJoins", type = EntityGraph.EntityGraphType.LOAD) @Query("select a from Account a where a.accountId = :accountId") Optional<Account> findByIdWithAllJoins(@Param("accountId") Long accountId); Optional<Account> findByEmail(String email); @EntityGraph(value = "Account.withAllJoins", type = EntityGraph.EntityGraphType.LOAD) @Query("select a from Account a where a.email = :email") Optional<Account> findByEmailWithAllJoins(@Param("email") String email); @EntityGraph(value = "Account.withPrivileges", type = EntityGraph.EntityGraphType.LOAD) @Query("select a from Account a where a.email = :email") Optional<Account> findByEmailWithPrivileges(@Param("email") String email); @EntityGraph(value = "Account.withAllJoins", type = EntityGraph.EntityGraphType.LOAD) @Query("select a from Account a inner join a.accountBadges ab " + "where ab.badge.badgeId = :badgeId") Page<Account> listWithBadgeId(@Param("badgeId") Long badgeId, Pageable pageable); }
43.808511
91
0.76882
06c84b6689c3463beff322eacb6a7b937b2e9fba
5,197
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/run/v2/traffic_target.proto package com.google.cloud.run.v2; /** * * * <pre> * The type of instance allocation. * </pre> * * Protobuf enum {@code google.cloud.run.v2.TrafficTargetAllocationType} */ public enum TrafficTargetAllocationType implements com.google.protobuf.ProtocolMessageEnum { /** * * * <pre> * Unspecified instance allocation type. * </pre> * * <code>TRAFFIC_TARGET_ALLOCATION_TYPE_UNSPECIFIED = 0;</code> */ TRAFFIC_TARGET_ALLOCATION_TYPE_UNSPECIFIED(0), /** * * * <pre> * Allocates instances to the Service's latest ready Revision. * </pre> * * <code>TRAFFIC_TARGET_ALLOCATION_TYPE_LATEST = 1;</code> */ TRAFFIC_TARGET_ALLOCATION_TYPE_LATEST(1), /** * * * <pre> * Allocates instances to a Revision by name. * </pre> * * <code>TRAFFIC_TARGET_ALLOCATION_TYPE_REVISION = 2;</code> */ TRAFFIC_TARGET_ALLOCATION_TYPE_REVISION(2), UNRECOGNIZED(-1), ; /** * * * <pre> * Unspecified instance allocation type. * </pre> * * <code>TRAFFIC_TARGET_ALLOCATION_TYPE_UNSPECIFIED = 0;</code> */ public static final int TRAFFIC_TARGET_ALLOCATION_TYPE_UNSPECIFIED_VALUE = 0; /** * * * <pre> * Allocates instances to the Service's latest ready Revision. * </pre> * * <code>TRAFFIC_TARGET_ALLOCATION_TYPE_LATEST = 1;</code> */ public static final int TRAFFIC_TARGET_ALLOCATION_TYPE_LATEST_VALUE = 1; /** * * * <pre> * Allocates instances to a Revision by name. * </pre> * * <code>TRAFFIC_TARGET_ALLOCATION_TYPE_REVISION = 2;</code> */ public static final int TRAFFIC_TARGET_ALLOCATION_TYPE_REVISION_VALUE = 2; public final int getNumber() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalArgumentException( "Can't get the number of an unknown enum value."); } return value; } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static TrafficTargetAllocationType valueOf(int value) { return forNumber(value); } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. */ public static TrafficTargetAllocationType forNumber(int value) { switch (value) { case 0: return TRAFFIC_TARGET_ALLOCATION_TYPE_UNSPECIFIED; case 1: return TRAFFIC_TARGET_ALLOCATION_TYPE_LATEST; case 2: return TRAFFIC_TARGET_ALLOCATION_TYPE_REVISION; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<TrafficTargetAllocationType> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap<TrafficTargetAllocationType> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<TrafficTargetAllocationType>() { public TrafficTargetAllocationType findValueByNumber(int number) { return TrafficTargetAllocationType.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalStateException( "Can't get the descriptor of an unrecognized enum value."); } return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return com.google.cloud.run.v2.TrafficTargetProto.getDescriptor().getEnumTypes().get(0); } private static final TrafficTargetAllocationType[] VALUES = values(); public static TrafficTargetAllocationType valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException("EnumValueDescriptor is not for this type."); } if (desc.getIndex() == -1) { return UNRECOGNIZED; } return VALUES[desc.getIndex()]; } private final int value; private TrafficTargetAllocationType(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:google.cloud.run.v2.TrafficTargetAllocationType) }
28.872222
96
0.697518
bae3b9f6367b94064acf626b29aab9a670450bb4
31,995
package org.apache.hadoop.hdfs.server.common; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.zip.Checksum; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.fs.FSInputChecker; import org.apache.hadoop.fs.FSOutputSummer; import org.apache.hadoop.fs.FileUtil; import org.apache.hadoop.hdfs.protocol.Block; import org.apache.hadoop.hdfs.protocol.DatanodeInfo; import org.apache.hadoop.hdfs.protocol.FSConstants; import org.apache.hadoop.hdfs.protocol.LocatedBlock; import org.apache.hadoop.hdfs.server.common.HdfsConstants.ReplicaState; import org.apache.hadoop.hdfs.server.common.PoolDataTransferProtocol.FileConstructionStage; import org.apache.hadoop.hdfs.server.common.PoolDataTransferProtocol.Status; import org.apache.hadoop.hdfs.server.common.PoolDataTransferProtocol.PipelineAck; import org.apache.hadoop.hdfs.server.common.PoolFile.NameNodeInfo; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.util.Daemon; import org.apache.hadoop.util.DataChecksum; import org.apache.hadoop.util.PureJavaCrc32; import org.apache.hadoop.util.StringUtils; import org.apache.hadoop.hdfs.server.common.PoolFile; import org.apache.hadoop.hdfs.server.datanode.FSDataset; import org.apache.hadoop.hdfs.server.datanode.FSDatasetInterface.BlockInputStreams; import org.apache.hadoop.hdfs.server.datanode.FinalizedPoolReplica; import org.apache.hadoop.hdfs.server.datanode.ReplicaPoolFile; import org.apache.hadoop.hdfs.server.datanode.ReplicaPoolInfo; import org.apache.hadoop.hdfs.server.datanode.ReplicaPoolPipeline; import org.apache.hadoop.hdfs.server.datanode.ReplicaPoolUnderRecovery; import org.apache.hadoop.hdfs.server.datanode.FSDatasetInterface.BlockWriteStreams; import org.apache.hadoop.hdfs.server.datanode.BlockMetadataHeader; import org.apache.hadoop.hdfs.server.datanode.ReplicaInPipelineInterface; import org.apache.hadoop.hdfs.server.namenode.NameNode; import static org.apache.hadoop.hdfs.server.common.PoolDataTransferProtocol.Status.SUCCESS; import static org.apache.hadoop.hdfs.server.common.PoolDataTransferProtocol.Status.ERROR; /** A class that receives a file and write to its own disk, * meanwhile may copies it to another site. * **/ class FileReceiver implements java.io.Closeable, FSConstants { public static final Log LOG = LogFactory.getLog(FileReceiver.class); private ReplicaPoolFile rpf; private long len; // file length private long generalstamp; private DataInputStream in = null; //from where data are read private DataChecksum checksum; private OutputStream out = null; //to file at local disk private DataOutputStream checksumOut = null; //to meta file at local disk private int bytesPerChecksum; private int checksumSize; private ByteBuffer buf; //contains one full packet private int bufRead; //amount of valid data in the buf private int maxPacketReadLen; protected final String inAddr; protected final String myAddr; private String mirrorAddr; private DataOutputStream mirrorOut; private Daemon responder = null; // throttler private BlockWriteStreams streams; private String clientName; private Checksum partialCrc = null; private final PoolServer server; private ReplicaInPipelineInterface replicaInfo; volatile private boolean mirrorError; FileReceiver(ReplicaPoolFile rpf, DataInputStream in, String inAddr, String myAddr, FileConstructionStage stage, long newGs, String clientName,PoolServer namenode) throws IOException { try{ this.rpf = rpf; this.in = in; this.inAddr = inAddr; this.myAddr = myAddr; this.clientName = clientName; this.server = namenode; LOG.info("create filereceiver, remote:" + inAddr + ", local:" + myAddr + ", clientname:" + clientName); //open local disk out switch(stage) { case PIPELINE_SETUP_CREATE: LOG.info("state: pipeline_setup_create"); replicaInfo = createTmp(FileType.RBW_FILE); break; case PIPELINE_SETUP_STREAMING_RECOVERY: //FIXME //replicaInfo = recoverRbw(); break; case PIPELINE_SETUP_APPEND: //FIXME //replicaInfo = append(); break; case PIPELINE_SETUP_APPEND_RECOVERY: //FIXME //replicaInfo = recoveryAppend(); break; default: throw new IOException("Unsupported stage " + stage + "while receiving file " + rpf + " from " + inAddr); } //read checksum meta information this.checksum = DataChecksum.newDataChecksum(in); this.bytesPerChecksum = checksum.getBytesPerChecksum(); this.checksumSize = checksum.getChecksumSize(); LOG.info("receive checksum meta, bytesperchecksum:" + bytesPerChecksum + ", checksumsize:" + checksumSize); boolean isCreate = stage == FileConstructionStage.PIPELINE_SETUP_CREATE; streams = replicaInfo.createStreams(isCreate, this.bytesPerChecksum, this.checksumSize); if (streams != null){ this.out = streams.getDataOut(); this.checksumOut = new DataOutputStream(new BufferedOutputStream( streams.getChecksumOut(), SMALL_BUFFER_SIZE)); // checksum meta file header |2B(version)|1B(type)|4B(bytesperchecksum) if (isCreate) { BlockMetadataHeader.writeHeader(checksumOut, checksum); } } } catch (IOException ioe) { IOUtils.closeStream(this); throw ioe; } } void writeChecksumHeader(DataOutputStream mirrorOut) throws IOException { checksum.writeHeader(mirrorOut); } public enum FileType { TEM_FILE("tmp"), RBW_FILE("rbw"); public final String dir; private FileType(String dir) {this.dir = dir;} public String getName() {return dir;} } public synchronized ReplicaInPipelineInterface createTmp(FileType type) throws IOException { ReplicaPoolInfo replicaInfo = server.map.get(rpf.getFilename()); if (replicaInfo != null) { throw new IOException("file " + rpf + " already exists in state " + replicaInfo.getState() + " and thus cannot be created."); } // create a temporary file to hold file File f = new File(rpf.getRootpath(), rpf.getFilename()); File tmpDir = new File(f.getParentFile() + "/" + type.getName()); if (tmpDir.exists()) { FileUtil.fullyDelete(tmpDir); } if (!tmpDir.mkdirs()) { if (!tmpDir.isDirectory()) { throw new IOException("Mkdirs failed to create " + tmpDir.toString()); } } File tmpfile = new File(tmpDir, rpf.getName()); if (tmpfile.exists()) { throw new IOException("Unexcepted problem in creating temporary file for " + tmpfile + ". File " + rpf.getName() + "should not be present, but is."); } //Create the zero-length tmp file boolean fileCreated = false; try { fileCreated = tmpfile.createNewFile(); } catch (IOException ioe) { throw ioe; } if (!fileCreated) { throw new IOException("Unexcepted problem in creating temporary file. " + "File " + tmpfile + "should be creatable, but is already present."); } LOG.info("create zero-length tmp file:" + tmpfile.getPath()); ReplicaPoolPipeline newReplicaInfo = new ReplicaPoolPipeline(rpf.getRootpath(), rpf.getFilename(), tmpfile.getParentFile()); server.map.put(rpf.getFilename(), newReplicaInfo); return newReplicaInfo; } void receiveFile( DataOutputStream mirrOut, // output to next namenode DataInputStream mirrIn, // input from next namenode DataOutputStream replyOut, // output to previous namenode String mirrAddr, int numTargets) throws IOException { boolean responderClosed = false; this.mirrorOut = mirrOut; this.mirrorAddr = mirrAddr; LOG.info("prepare to receive file, next addr:" + mirrAddr + ", numtargets:" + numTargets); try { //FIXME can be commented when test firstly responder = new Daemon(server.threadGroup, new PacketResponder(this, rpf, mirrIn, replyOut, numTargets, Thread.currentThread())); responder.start(); // start thread to process response /** * Receiver non-zero if not the last packet */ while (receivePacket() >=0) {} // wait for all outstanding packet responses. And then // indicate responder to gracefully shutdown. // Mark that responder has been closed for future processing if (responder != null) { ((PacketResponder)responder.getRunnable()).close(); responderClosed = true; } } catch (IOException ioe) { LOG.info("Exception in receiveFile from file " + rpf + " " + ioe); throw ioe; } finally { if (!responderClosed) { //Abnormal termination of the flow above IOUtils.closeStream(this); if (responder != null) { responder.interrupt(); } } if (responder != null) { try { responder.join(); } catch (InterruptedException e) { throw new IOException("Interrupted receiveFile"); } responder = null; } } } /** * Receives and processes a packet. It can contain many chunks. * returns the number of data bytes that the packet has. */ private int receivePacket() throws IOException { // read the next packet readNextPacket(); //FIXME buf.position at this moment? buf.mark(); //read the header buf.getInt(); //packet length long offsetInFile = buf.getLong(); //get offset of packet in file if (offsetInFile > replicaInfo.getNumBytes()) { throw new IOException("Received an out-of-sequence packet for " + rpf + "from " + inAddr + " at offset " + offsetInFile + ". Expecting packet starting at " + replicaInfo.getNumBytes()); } long seqno = buf.getLong(); //get seqno boolean lastPacketInFile = (buf.get() != 0); int len = buf.getInt(); //length of data LOG.info("read packet" + seqno + ", offset in file:" + offsetInFile + ", lastpacket in file:" + lastPacketInFile + ", len: " + len); if (len < 0) { throw new IOException("Got wrong length during writeFile(" + rpf + ") from " + inAddr + " at offset " + offsetInFile + ": " + len); } int endOfHeader = buf.position(); buf.reset(); return receivePacket(offsetInFile, seqno, lastPacketInFile, len, endOfHeader); } /** * Receives and processes a packet. It can contain many chunks. * returns the number of data bytes that the packet has. */ private int receivePacket(long offsetInFile, long seqno, boolean lastPacketInFile, int len, int endOfHeader) throws IOException { //update received bytes long firstByteInFile = offsetInFile; offsetInFile += len; if (replicaInfo.getNumBytes() < offsetInFile) { replicaInfo.setNumBytes(offsetInFile); } ///FIXME can be commented in first test if (responder != null) { ((PacketResponder)responder.getRunnable()).enqueue(seqno, lastPacketInFile, offsetInFile); } //First write the packet to the mirror, flush local later if (mirrorOut != null && !mirrorError) { try { mirrorOut.write(buf.array(), buf.position(), buf.remaining()); mirrorOut.flush(); } catch (IOException e) { handleMirrorOutError(e); } } buf.position(endOfHeader); //position at: |checksumdata|data| if(lastPacketInFile || len ==0) { LOG.info("Receiving last empty packet or the end of the file " + rpf); } else { int checksumLen = ((len + bytesPerChecksum - 1)/bytesPerChecksum)* checksumSize; if ( buf.remaining() != (checksumLen + len)) { throw new IOException("Data remaining in packet does not match" + "sum of checksumLen and dataLen " + " size remaining: " + buf.remaining() + " data len: " + len + " checksum Len: " + checksumLen); } int checksumOff = buf.position(); //position at: |checksumdata| int dataOff = checksumOff + checksumLen; //position at: |data| byte pktBuf[] = buf.array(); buf.position(buf.limit()); //move to the end of the data // when client is writing the data, only the last namenode // needs to verify checksum for packet if (mirrorOut == null ) { //very packet with chunk checksum verifyChunks(pktBuf, dataOff, len, pktBuf, checksumOff); } byte[] lastChunkChecksum; try { long onDiskLen = replicaInfo.getBytesOnDisk(); if (onDiskLen < offsetInFile) { //onDiskLen - firstByteInFile should be zero int startByteToDisk = dataOff+(int)(onDiskLen-firstByteInFile); int numBytesToDisk = (int)(offsetInFile-onDiskLen); //write packet to disk out.write(pktBuf, startByteToDisk, numBytesToDisk); // get last checksum bytes lastChunkChecksum = Arrays.copyOfRange( pktBuf, checksumOff + checksumLen - checksumSize, checksumOff + checksumLen ); checksumOut.write(pktBuf, checksumOff, checksumLen); /// flush entire packet flush(); //set bytesondisk, lastchunkchecksum replicaInfo.setLastChecksumAndDataLen( offsetInFile, lastChunkChecksum); } } catch (IOException iex) { throw iex; } } //LOG.info("bufposition:" + buf.position() + ", remaining:" + // buf.remaining() + ", limit:" + buf.limit() + ", islastpacket:" // + lastPacketInFile); return lastPacketInFile?-1:len; } /** * Returns handles to the block file and its metadata file */ public synchronized BlockInputStreams getTmpInputStreams(ReplicaPoolFile rpf, long blkOffset, long ckoff) throws IOException { ReplicaPoolInfo info = server.map.get(rpf.getFilename()); File blockFile = info.getTempFile(); RandomAccessFile blockInFile = new RandomAccessFile(blockFile, "r"); if (blkOffset > 0) { blockInFile.seek(blkOffset); } File metaFile = info.getTempMetaFile(); RandomAccessFile metaInFile = new RandomAccessFile(metaFile, "r"); if (ckoff > 0) { metaInFile.seek(ckoff); } return new BlockInputStreams(new FileInputStream(blockInFile.getFD()), new FileInputStream(metaInFile.getFD())); } /** * Returns the size of the header */ int getHeaderSize() { return Short.SIZE/Byte.SIZE + DataChecksum.getChecksumHeaderSize(); } /** * Flush block data and metadata files to disk. * @throws IOException */ void flush() throws IOException { if (checksumOut != null) { checksumOut.flush(); } if (out != null) { out.flush(); } } /** * Adjust the file pointer in the local meta file so that the last checksum * will be overwritten. */ private void adjustCrcFilePosition() throws IOException { if (out != null) { out.flush(); } if (checksumOut != null){ checksumOut.flush(); } FileOutputStream file = (FileOutputStream)streams.getChecksumOut(); FileChannel channel = file.getChannel(); long oldPos = channel.position(); long newPos = oldPos - checksumSize; LOG.info("Changing meta file offset of file " + rpf + " from " + oldPos + " to " + newPos); channel.position(newPos); } /** * Reads (at least) one packet and returns the packet length. * buf.position() points to the start of the packet and * buf.limit() point to the end of the packet. There could * be more data from next packet in buf.<br><br> * * It tries to read a full packet with single read call. * Consecutive packets are usually of the same length. */ private void readNextPacket() throws IOException { if (buf == null ){ LOG.info("create new buf to read packet"); int chunkSize = bytesPerChecksum + checksumSize; int chunksPerPacket = (server.wirtePacketSize - server.PKT_HEADER_LEN - SIZE_OF_INTEGER + chunkSize -1)/chunkSize; buf = ByteBuffer.allocate(server.PKT_HEADER_LEN + SIZE_OF_INTEGER + Math.max(chunksPerPacket, 1) * chunkSize); buf.limit(0); } //See if there is data left in the buffer if (bufRead > buf.limit()) { buf.limit(bufRead); } LOG.info("bufread:" + bufRead + ", buf position:" + buf.position() + ", buf limit:" + buf.limit() + ", remaining:" + buf.remaining() + ", capacity:" + buf.capacity()); while (buf.remaining() < SIZE_OF_INTEGER) { if (buf.position() > 0) { shiftBufData(); } readToBuf(-1); } //we mostly have the full packet or at least enough for an int buf.mark(); int payloadLen = buf.getInt(); buf.reset(); // check corrupt values for pktLen, 100MB upper limit should be ok? if (payloadLen < 0 || payloadLen > (100*1024*1024)) { throw new IOException("Incorrect value for packet payload : " + payloadLen); } int pktSize = payloadLen + server.PKT_HEADER_LEN; LOG.info("buf.remaining:" + buf.remaining() + "==" + "payloadlen:" + payloadLen + " + header:" + server.PKT_HEADER_LEN + " ?"); if (buf.remaining() < pktSize) { LOG.info("need read more"); //we need to read more data int toRead = pktSize - buf.remaining(); // first make sure buf has enough space. int spaceLeft = buf.capacity() - buf.limit(); if (toRead > spaceLeft && buf.position() > 0) { shiftBufData(); spaceLeft = buf.capacity() - buf.limit(); } if (toRead > spaceLeft) { byte oldBuf[] = buf.array(); int toCopy = buf.limit(); buf = ByteBuffer.allocate(toCopy + toRead); System.arraycopy(oldBuf, 0, buf.array(), 0, toCopy); buf.limit(toCopy); } //now loop read while (toRead > 0) { toRead -= readToBuf(toRead); } } if (buf.remaining() > pktSize) { buf.limit(buf.position() + pktSize); } if (pktSize > maxPacketReadLen) { maxPacketReadLen = pktSize; } } /** * Makes sure buf.position() is zero without modifying buf.remaining(). * It moves the data if position needs to be changed. */ private void shiftBufData() { if (bufRead != buf.limit()) { throw new IllegalStateException("bufRead should be same as " + "buf.limit()"); } //shift the remaining data on buf to the front if (buf.position() > 0) { int dataLeft = buf.remaining(); if (dataLeft > 0) { byte[] b = buf.array(); System.arraycopy(b, buf.position(), b, 0, dataLeft); } buf.position(0); bufRead = dataLeft; buf.limit(bufRead); } } /** * reads upto toRead byte to buf at buf.limit() and increments the limit. * throws an IOException if read does not succeed. */ private int readToBuf(int toRead) throws IOException { if (toRead < 0) { toRead = (maxPacketReadLen > 0 ? maxPacketReadLen : buf.capacity()) - buf.limit(); } int nRead = in.read(buf.array(), buf.limit(), toRead); if (nRead < 0) { throw new EOFException("while trying to read " + toRead + " bytes"); } bufRead = buf.limit() + nRead; buf.limit(bufRead); LOG.info("read to buf, buf position:" + buf.position() + " buf limit:" + buf.limit() + ", toread:" + toRead + ", nread:" + nRead); return nRead; } /** * While writing to mirrorOut, failure to write to mirror should not * affect this namenode unless it is caused by interruption. */ private void handleMirrorOutError(IOException ioe) throws IOException { LOG.info(server + ":Exception writing block " + rpf + " to mirror " + mirrorAddr + "\n" + StringUtils.stringifyException(ioe)); if (Thread.interrupted()) { // shut down if the thread is interrupted throw ioe; } else { // encounter an error while writing to mirror // continue to run even if can not write to mirror // notify client of the error // and wait for the client to shut down the pipeline mirrorError = true; } } /** * Verify multiple CRC chunks. */ private void verifyChunks( byte[] dataBuf, int dataOff, int len, byte[] checksumBuf, int checksumOff ) throws IOException { LOG.info("verify chunks"); while (len > 0) { int chunkLen = Math.min(len, bytesPerChecksum); checksum.update(dataBuf, dataOff, chunkLen); if (!checksum.compare(checksumBuf, checksumOff)) { LOG.info("report corrupt file" + rpf + "from namenode " + NameNode.client.clientName); //FIXME //reportBadFile throw new IOException("Unexpected checksum mismatch " + "while writing " + rpf + " from " + inAddr); } checksum.reset(); dataOff += chunkLen; checksumOff += checksumSize; len -= chunkLen; } } /** * Processed responses from downstream namenodes in the pipeline * and sends back replies to the originator. */ class PacketResponder implements Runnable, FSConstants { //packet waiting for ack private LinkedList<Packet> ackQueue = new LinkedList<Packet>(); private volatile boolean running = true; private ReplicaPoolFile rpf; DataInputStream mirrorIn; //input from downstream(next) namenode DataOutputStream replyOut; // output for upstream namenode private int numTargets; private FileReceiver receiver; //the owner of this responder. private Thread receiverThread; // the thread that spawns this responder public String toString() { return "PacketResponder " + numTargets + " from file " + this.rpf; } PacketResponder(FileReceiver receiver, ReplicaPoolFile rpf, DataInputStream in, DataOutputStream out, int numTargets, Thread receiverThread) { this.receiverThread = receiverThread; this.receiver = receiver; this.rpf = rpf; mirrorIn = in; replyOut = out; this.numTargets = numTargets; } /** * enqueue the seqno that is still be to acked by the downstream datanode. * @param seqno * @param lastPacketInFile * @param lastByteInFile */ synchronized void enqueue(long seqno, boolean lastPacketInFile, long lastByteInPacket) { if (running){ LOG.info("Packet Responder enqueue, numtargets " + numTargets + "adding seqno" + seqno + " to ack queue."); ackQueue.addLast(new Packet(seqno, lastPacketInFile, lastByteInPacket)); notifyAll(); } } /** * wait for all pending packets to be acked. Then shutdown thread. */ synchronized void close() { while (running && ackQueue.size() != 0 && server.shouldRun) { try { wait(); } catch (InterruptedException e) { running = false; } } LOG.debug("PacketResponder " + numTargets + " for file " + this.rpf + "Closing down"); running = false; notifyAll(); } /** * Thread to process incoming acks. * @see java.lang.Runnable#run() */ public void run() { boolean lastPacketInFile = false; final long startTime = System.nanoTime(); LOG.info("start packet responder thread, running:" + running + ", server shouldrun:" + server.shouldRun + ", lastpacket:" + lastPacketInFile); while (running && server.shouldRun && !lastPacketInFile) { boolean isInterrupted = false; try { Packet pkt = null; long expected = -2; PipelineAck ack = new PipelineAck(); long seqno = PipelineAck.UNKOWN_SEQNO; try { if (numTargets != 0 && !mirrorError) { //not the last NN & no mirror error //read an ack from downstream namenode: |seqno|num|replies| ack.readFields(mirrorIn); seqno = ack.getSeqno(); } if (seqno != PipelineAck.UNKOWN_SEQNO || numTargets == 0){ synchronized (this) { while (running && server.shouldRun && ackQueue.size() == 0){ wait(); } if (!running || !server.shouldRun) { break; } pkt = ackQueue.getFirst(); expected = pkt.seqno; if (numTargets > 0 && seqno != expected) { throw new IOException("PacketResponder " + numTargets + " for file " + rpf + " expected seqno: " + expected + " received: " + seqno); } lastPacketInFile = pkt.lastPacketInFile; } } } catch (InterruptedException ine) { isInterrupted = true; } catch (IOException ioe) { if (Thread.interrupted()) { isInterrupted = true; } else { // continue to run even if can not read from mirror // notify client of the error and wait for client to shutdown pipeline mirrorError = true; LOG.info("PacketResponder " + rpf + " " + numTargets + " Exception " + StringUtils.stringifyException(ioe)); } } if (Thread.interrupted() || isInterrupted) { // The receiver thread cancelled this thread LOG.info("PacketResponder " + rpf + " " + numTargets + " : Thread is interrupted."); running = false; continue; } // If this is the last packet in file, then close // file and finalize the file before responding success if (lastPacketInFile) { receiver.close(); final long endTime = System.nanoTime(); rpf.setNumBytes(replicaInfo.getNumBytes()); finalizeFile(); } //construct my ack message Status[] replies = null; if (mirrorError) { //ack read error replies = new Status[2]; replies[0] = SUCCESS; replies[1] = ERROR; } else { short ackLen = numTargets == 0 ? 0 : ack.getNumOfReplies(); replies = new Status[1+ackLen]; replies[0] = SUCCESS; for (int i=0; i<ackLen; i++) { replies[i+1] = ack.getReply(i); } } PipelineAck replyAck = new PipelineAck(expected, replies); //send my ack back to upstream namenode LOG.info("send packet" + expected + " ack to upstream node"); replyAck.write(replyOut); replyOut.flush(); if(LOG.isDebugEnabled()) { LOG.debug("PacketResponder " + numTargets + " for file " + rpf + "responded an ack: " + replyAck); } if (pkt != null) { // remove the packet from the ack queue removeAckHead(); // update bytes acked if (replyAck.isSuccess() && pkt.lastByteInFile > replicaInfo.getBytesAcked()) { replicaInfo.setBytesAcked(pkt.lastByteInFile); } } } catch (IOException e) { LOG.warn("IOException in FileReceiver.run(): ", e); if (running) { LOG.info("PacketResponder " + rpf + " " + numTargets + " Exception " + StringUtils.stringifyException(e)); running = false; if (!Thread.interrupted()) { //failure not caused by interruption receiverThread.interrupt(); } } } catch (Throwable e) { if (running) { LOG.info("PacketResponder " + rpf + " " + numTargets + "Exception " + StringUtils.stringifyException(e)); running = false; receiverThread.interrupt(); } } } LOG.info("PacketResponder, numtargets: " + numTargets + " for file " + rpf + " terminating"); } /** * Remove a packet from the head of the ack queue * * This should be called only when the ack queue is not empty */ private synchronized void removeAckHead() { ackQueue.removeFirst(); notifyAll(); } } /** * Complete the file write! */ public synchronized void finalizeFile() throws IOException { ReplicaPoolInfo replicaInfo = server.map.get(rpf.getFilename()); if (replicaInfo.getState() == ReplicaState.FINALIZED) { // this is legal, when recovery happens on a file that has // been opened for append but never modified return; } FinalizedPoolReplica newReplicaInfo = null; if (replicaInfo.getState() == ReplicaState.RUR && ((ReplicaPoolUnderRecovery)replicaInfo).getOriginalReplicaState() == ReplicaState.FINALIZED) { newReplicaInfo = (FinalizedPoolReplica) ((ReplicaPoolUnderRecovery)replicaInfo).getOriginalReplica(); } else { File src = replicaInfo.getTempFile(); File srcmeta = replicaInfo.getTempMetaFile(); File dst = replicaInfo.getFinalFile(); File dstmeta = replicaInfo.getFinalMetaFile(); LOG.info("finalize, src:" + src.getPath() + ", srcmeta:" + srcmeta.getPath() + ", dst:" + dst.getPath() + ", dstmeta:" + dstmeta.getPath()); if (src == null || srcmeta == null) { throw new IOException("No file for temporary file " + src + " for file" + replicaInfo); } if (!srcmeta.renameTo(dstmeta) || !src.renameTo(dst)) { throw new IOException("could not move files for" + rpf + " from " + src + " to " + dst.getAbsolutePath() + " or from " + srcmeta + "to " + dstmeta); } newReplicaInfo = new FinalizedPoolReplica(replicaInfo, dst.getParentFile()); } server.map.put(replicaInfo.getFilename(), newReplicaInfo); } /** * close files. */ public void close() throws IOException { IOException ioe = null; // close checksum file try { if (checksumOut != null) { checksumOut.flush(); checksumOut.close(); checksumOut = null; } } catch(IOException e) { ioe = e; } // close block file try { if (out != null) { out.flush(); out.close(); out = null; } } catch (IOException e) { ioe = e; } // disk check if(ioe != null) { throw ioe; } } /** * This information is cached by the Datanode in the ackQueue. */ static private class Packet { long seqno; boolean lastPacketInFile; long lastByteInFile; Packet(long seqno, boolean lastPacketInFile, long lastByteInPacket) { this.seqno = seqno; this.lastPacketInFile = lastPacketInFile; this.lastByteInFile = lastByteInPacket; } } }
34.589189
97
0.615565
ee3868e7b1ec916df17abf923d6f2c4906f54251
6,121
package com.jukusoft.engine2d.ui; import com.badlogic.gdx.InputAdapter; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.utils.Array; import com.jukusoft.engine2d.ui.parser.SelectorCompiler; import com.jukusoft.engine2d.ui.style.UIStyleManager; import com.jukusoft.engine2d.view.assets.assetmanager.GameAssetManager; import net.sf.saxon.s9api.XdmItem; import java.util.Objects; /** * widget base class */ public abstract class Widget extends InputAdapter { /** * widget id like in JavaFX */ private String id; //widget position private float xPos; private float yPos; private float zPos = 1; //widget dimension (e.q. to detect, if mouse is inner widget) private int width; private int height; //scaling private float scaleX = 1; private float scaleY = 1; private Array<String> requiredFeaturesTags = new Array<>(); private boolean visible; /** * initialize widget with ui drawer, load required assets, if neccessary */ protected final void init(UIStyleManager styleManager, GameAssetManager assetManager) { initWidget(styleManager, assetManager); } /** * check, if mouse is inner widget * * @param mouseX * @param mouseY * * @return */ public boolean isMouseInner(float mouseX, float mouseY) { return (mouseX >= xPos && mouseX <= xPos + width) && (mouseY >= yPos && mouseY <= yPos + height); } /** * this method is called, if mouse is inner widget. * Can be used to implement hover effects and so on * * @param mouseX absolute mouse x position * @param mouseY absolute mouse y position * @param relX relative mouse x position inner widget * @param relY relative mouse y position inner widget */ public abstract void mouseHover(float mouseX, float mouseY, float relX, float relY); /** * this method is called, if mouse clicks into this widget * Can be used to implement hover effects and so on * * @param mouseX absolute mouse x position * @param mouseY absolute mouse y position * @param relX relative mouse x position inner widget * @param relY relative mouse y position inner widget */ public abstract void mouseClick(float mouseX, float mouseY, float relX, float relY); public String getId() { return id; } public void setId(String id) { Objects.requireNonNull(id); this.id = id; } public float getxPos() { return xPos; } public void setXPos(float xPos) { this.xPos = xPos; } public float getyPos() { return yPos; } public void setYPos(float yPos) { this.yPos = yPos; } public float getzPos() { return zPos; } public void setZPos(float zPos) { this.zPos = zPos; } public void setPosition(float x, float y, float z) { this.xPos = x; this.yPos = y; this.zPos = z; } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public float getScaleX() { return scaleX; } public void setScaleX(float scaleX) { this.scaleX = scaleX; } public float getScaleY() { return scaleY; } public void setScaleY(float scaleY) { this.scaleY = scaleY; } public void addRequiredFeatureTag(String featureTag) { requiredFeaturesTags.add(featureTag); } public void removeRequiredFeatureTag(String featureTag) { requiredFeaturesTags.removeValue(featureTag, false); } public Array<String> listRequiredFeatureTags() { return requiredFeaturesTags; } public boolean isVisible() { return visible; } public void setVisible(boolean visible) { this.visible = visible; } /** * find widget by id * * @param id id of the widget * @param cls return class * @param <T> widget type * * @return widget with the specific id */ public <T extends Widget> T findWidgetbyId(String id, Class<T> cls) { if (this.id.equals(id)) { return cls.cast(this); } return null; } /** * update widgets, e.q. call onClick listener and so on * * @param delta delta time * @param offsetX offset x, e.q. used for scrolling * @param offsetY offset y, e.q. used for scrolling */ public abstract void update(float delta, float offsetX, float offsetY); /** * draw widget * * @param batch sprite batch * @param offsetX offset x, e.q. used for scrolling * @param offsetY offset y, e.q. used for scrolling */ public abstract void draw(SpriteBatch batch, float offsetX, float offsetY); /** * this method can be overriden, if custom widgets want to parse specific attributes from xml * @param widgetItem * @param selectorCompiler */ public void parseFromXml(XdmItem widgetItem, SelectorCompiler selectorCompiler) { // } public final void disposeWidget(UIStyleManager styleManager, GameAssetManager assetManager) { dispose(styleManager, assetManager); } /** * this method can be overriden to do some things on widget initialization * * @param styleManager style manager to get current style * @param assetManager asset manager to load and unload assets */ protected void initWidget(UIStyleManager styleManager, GameAssetManager assetManager) { // } /** * this method can be overriden to dispose widget, e.q. unload assets and so on * * @param styleManager style manager to get current style * @param assetManager asset manager to load and unload assets */ protected void dispose(UIStyleManager styleManager, GameAssetManager assetManager) { // } }
25.504167
105
0.634864
abb5960a06b648cae1127ff15f20d7a0b63e6647
202
package world.arossa.reusing_classes; import static world.arossa.helpers.Print.*; public class WithFinalMethod { public final void show() { print("from super class final method"); } }
20.2
47
0.707921
4c10de3099e179b78cc98d9c8054ad9db48bafda
11,189
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.jps.incremental.groovy; import com.intellij.execution.process.ProcessOutputTypes; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.groovy.compiler.rt.GroovyCompilerMessageCategories; import org.jetbrains.groovy.compiler.rt.GroovyRtConstants; import org.jetbrains.jps.ModuleChunk; import org.jetbrains.jps.incremental.CompileContext; import org.jetbrains.jps.incremental.messages.BuildMessage; import org.jetbrains.jps.incremental.messages.CompilerMessage; import org.jetbrains.jps.incremental.messages.ProgressMessage; import java.io.*; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; /** * @author: Dmitry.Krasilschikov * @date: 16.04.2007 */ public class GroovycOutputParser { private static final String GROOVY_COMPILER_IN_OPERATION = "Groovy compiler in operation..."; public static final String GRAPE_ROOT = "grape.root"; private final List<OutputItem> myCompiledItems = new ArrayList<>(); private final List<CompilerMessage> compilerMessages = new ArrayList<>(); private final StringBuffer stdErr = new StringBuffer(); private final ModuleChunk myChunk; private final CompileContext myContext; public GroovycOutputParser(ModuleChunk chunk, CompileContext context) { myChunk = chunk; myContext = context; } private static final Logger LOG = Logger.getInstance("#org.jetbrains.jps.incremental.groovy.GroovycOSProcessHandler"); private int myExitCode; public void notifyTextAvailable(final String text, final Key outputType) { if (LOG.isDebugEnabled()) { LOG.debug("Received from groovyc " + outputType + ": " + text); } if (outputType == ProcessOutputTypes.SYSTEM) { return; } if (outputType == ProcessOutputTypes.STDERR && !isSafeStderr(text)) { stdErr.append(StringUtil.convertLineSeparators(text)); return; } parseOutput(text); } private static boolean isSafeStderr(String line) { return line.startsWith("SLF4J:") || line.startsWith("Picked up JAVA_TOOL_OPTIONS"); } private final StringBuffer outputBuffer = new StringBuffer(); private void updateStatus(@NotNull String status) { myContext.processMessage(new ProgressMessage(status + " [" + myChunk.getPresentableShortName() + "]")); } private void parseOutput(String text) { final String trimmed = text.trim(); if (trimmed.startsWith(GroovyRtConstants.PRESENTABLE_MESSAGE)) { updateStatus(trimmed.substring(GroovyRtConstants.PRESENTABLE_MESSAGE.length())); return; } if (GroovyRtConstants.CLEAR_PRESENTABLE.equals(trimmed)) { updateStatus(GROOVY_COMPILER_IN_OPERATION); return; } if (StringUtil.isNotEmpty(text)) { outputBuffer.append(text); //compiled start marker have to be in the beginning on each string if (outputBuffer.indexOf(GroovyRtConstants.COMPILED_START) != -1) { if (outputBuffer.indexOf(GroovyRtConstants.COMPILED_END) == -1) { return; } final String compiled = handleOutputBuffer(GroovyRtConstants.COMPILED_START, GroovyRtConstants.COMPILED_END); final List<String> list = splitAndTrim(compiled); String outputPath = list.get(0); String sourceFile = list.get(1); OutputItem item = new OutputItem(outputPath, sourceFile); if (LOG.isDebugEnabled()) { LOG.debug("Output: " + item); } myCompiledItems.add(item); } else if (outputBuffer.indexOf(GroovyRtConstants.MESSAGES_START) != -1) { if (outputBuffer.indexOf(GroovyRtConstants.MESSAGES_END) == -1) { return; } text = handleOutputBuffer(GroovyRtConstants.MESSAGES_START, GroovyRtConstants.MESSAGES_END); List<String> tokens = splitAndTrim(text); LOG.assertTrue(tokens.size() > 4, "Wrong number of output params"); String category = tokens.get(0); String message = tokens.get(1); String url = tokens.get(2); String lineNum = tokens.get(3); String columnNum = tokens.get(4); int lineInt; int columnInt; try { lineInt = Integer.parseInt(lineNum); columnInt = Integer.parseInt(columnNum); } catch (NumberFormatException e) { LOG.error(e); lineInt = 0; columnInt = 0; } BuildMessage.Kind kind = category.equals(GroovyCompilerMessageCategories.ERROR) ? BuildMessage.Kind.ERROR : category.equals(GroovyCompilerMessageCategories.WARNING) ? BuildMessage.Kind.WARNING : BuildMessage.Kind.INFO; if (StringUtil.isEmpty(url) || "null".equals(url)) { url = null; message = "While compiling " + myChunk.getPresentableShortName() + ": " + message; } CompilerMessage compilerMessage = new CompilerMessage("Groovyc", kind, message, url, -1, -1, -1, lineInt, columnInt); if (LOG.isDebugEnabled()) { LOG.debug("Message: " + compilerMessage); } addCompilerMessage(compilerMessage); } } } void addCompilerMessage(CompilerMessage compilerMessage) { compilerMessages.add(compilerMessage); } private String handleOutputBuffer(String startMarker, String endMarker) { final int start = outputBuffer.indexOf(startMarker); final int end = outputBuffer.indexOf(endMarker); if (start > end) { throw new AssertionError("Malformed Groovyc output: " + outputBuffer.toString()); } String text = outputBuffer.substring(start + startMarker.length(), end); outputBuffer.delete(start, end + endMarker.length()); return text.trim(); } private static List<String> splitAndTrim(String compiled) { return ContainerUtil.map(StringUtil.split(compiled, GroovyRtConstants.SEPARATOR), s -> s.trim()); } public List<OutputItem> getSuccessfullyCompiled() { return myCompiledItems; } public boolean shouldRetry() { for (CompilerMessage message : compilerMessages) { String text = message.getMessageText(); if (text.contains("java.lang.NoClassDefFoundError") || text.contains("java.lang.TypeNotPresentException") || text.contains("unable to resolve class")) { LOG.debug("Resolve issue: " + message); return true; } } return false; } public List<CompilerMessage> getCompilerMessages() { ArrayList<CompilerMessage> messages = new ArrayList<>(compilerMessages); final StringBuffer unparsedBuffer = getStdErr(); if (unparsedBuffer.length() != 0) { String msg = unparsedBuffer.toString(); if (msg.contains(GroovyRtConstants.NO_GROOVY)) { messages.add(reportNoGroovy()); } else { messages.add(new CompilerMessage("Groovyc", BuildMessage.Kind.INFO, "While compiling " + myChunk.getPresentableShortName() + ":" + msg)); } } if (myExitCode != 0) { for (CompilerMessage message : messages) { if (message.getKind() == BuildMessage.Kind.ERROR) { return messages; } } messages.add(new CompilerMessage("Groovyc", BuildMessage.Kind.ERROR, "Internal groovyc error: code " + myExitCode)); } return messages; } @NotNull CompilerMessage reportNoGroovy() { String moduleName = myChunk.representativeTarget().getModule().getName(); return new CompilerMessage("", BuildMessage.Kind.ERROR, "Cannot compile Groovy files: no Groovy library is defined for module '" + moduleName + "'"); } public StringBuffer getStdErr() { return stdErr; } public static File fillFileWithGroovycParameters(final String outputDir, final Collection<String> changedSources, Collection<String> finalOutputs, Map<String, String> class2Src, @Nullable final String encoding, List<String> patchers, String classpath) throws IOException { File tempFile = FileUtil.createTempFile("ideaGroovyToCompile", ".txt", true); final Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempFile))); try { writer.write(classpath); writer.write("\n"); for (String file : changedSources) { writer.write(GroovyRtConstants.SRC_FILE + "\n"); writer.write(file); writer.write("\n"); } writer.write("class2src\n"); for (Map.Entry<String, String> entry : class2Src.entrySet()) { writer.write(entry.getKey() + "\n"); writer.write(entry.getValue() + "\n"); } writer.write(GroovyRtConstants.END + "\n"); writer.write(GroovyRtConstants.PATCHERS + "\n"); for (String patcher : patchers) { writer.write(patcher + "\n"); } writer.write(GroovyRtConstants.END + "\n"); if (encoding != null) { writer.write(GroovyRtConstants.ENCODING + "\n"); writer.write(encoding + "\n"); } writer.write(GroovyRtConstants.OUTPUTPATH + "\n"); writer.write(outputDir); writer.write("\n"); writer.write(GroovyRtConstants.FINAL_OUTPUTPATH + "\n"); writer.write(StringUtil.join(finalOutputs, File.pathSeparator)); writer.write("\n"); } finally { writer.close(); } return tempFile; } void notifyFinished(int exitCode) { myExitCode = exitCode; } public void onContinuation() { myCompiledItems.clear(); compilerMessages.clear(); stdErr.setLength(0); outputBuffer.setLength(0); } static class OutputItem { public final String outputPath; public final String sourcePath; public OutputItem(String outputPath, String sourceFileName) { this.outputPath = outputPath; sourcePath = sourceFileName; } @Override public String toString() { return "OutputItem{" + "outputPath='" + outputPath + '\'' + ", sourcePath='" + sourcePath + '\'' + '}'; } } }
34.322086
158
0.655644
3ab66e2b526c83910f22566b01dcf616c27e377c
1,473
package com.ziroom.ziroomcustomer.newclean.periodclean.bean; public class SuggestAddressBean { private String addressId; private String addressLat; private String addressLon; private String connectPhone; private String doorplate; private String village; public String getAddressId() { return this.addressId; } public String getAddressLat() { return this.addressLat; } public String getAddressLon() { return this.addressLon; } public String getConnectPhone() { return this.connectPhone; } public String getDoorplate() { return this.doorplate; } public String getVillage() { return this.village; } public void setAddressId(String paramString) { this.addressId = paramString; } public void setAddressLat(String paramString) { this.addressLat = paramString; } public void setAddressLon(String paramString) { this.addressLon = paramString; } public void setConnectPhone(String paramString) { this.connectPhone = paramString; } public void setDoorplate(String paramString) { this.doorplate = paramString; } public void setVillage(String paramString) { this.village = paramString; } } /* Location: /Users/gaoht/Downloads/zirom/classes3-dex2jar.jar!/com/ziroom/ziroomcustomer/newclean/periodclean/bean/SuggestAddressBean.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
19.12987
153
0.694501
bcfc97e620074fd31ea1b02d295d2f9246ce827e
1,479
/* Import2: An RPG */ package studio.ignitionigloogames.twistedtrek.import2.maze.objects; import studio.ignitionigloogames.twistedtrek.import2.Import2; import studio.ignitionigloogames.twistedtrek.import2.maze.abc.AbstractTrap; import studio.ignitionigloogames.twistedtrek.import2.maze.effects.MazeEffectConstants; import studio.ignitionigloogames.twistedtrek.import2.resourcemanagers.ObjectImageConstants; import studio.ignitionigloogames.twistedtrek.import2.resourcemanagers.SoundConstants; import studio.ignitionigloogames.twistedtrek.import2.resourcemanagers.SoundManager; public class CounterclockwiseRotationTrap extends AbstractTrap { // Constructors public CounterclockwiseRotationTrap() { super(ObjectImageConstants.OBJECT_IMAGE_CCW_ROTATION_TRAP); } @Override public String getName() { return "Counterclockwise Rotation Trap"; } @Override public String getPluralName() { return "Counterclockwise Rotation Traps"; } @Override public void postMoveAction(final boolean ie, final int dirX, final int dirY) { SoundManager.playSound(SoundConstants.SOUND_CHANGE); Import2.getApplication().showMessage("Your controls are rotated!"); Import2.getApplication().getGameManager() .activateEffect(MazeEffectConstants.EFFECT_ROTATED_COUNTERCLOCKWISE); } @Override public String getDescription() { return "Counterclockwise Rotation Traps rotate your controls counterclockwise for 6 steps when stepped on."; } }
37.923077
109
0.806626
e968f6c51a0561fc263852bd132b6aa2b437df6b
747
import java.util.Scanner; public class Solution{ public static void main(String args[]){ int n; Scanner s = new Scanner(System.in); n = s.nextInt(); int a[] = new int[n]; for(int i=0;i<=n-1;i++){ a[i] = s.nextInt(); } int init=1; boolean spring; for(int j=0;j<=n-1;j++){ spring = true; init=1; for(int i=1;i<=a[j];i++){ if(spring){ spring = false; init=init*2; continue; }else{ spring = true; init++; } } System.out.println(init); } } }
24.096774
43
0.369478
5317f3adade9104eb68ebc0c1308cd91c5e48a80
1,852
package com.blinkfox.zealot.config.entity; import com.blinkfox.zealot.consts.ZealotConst; import com.blinkfox.zealot.core.IConditHandler; /** * 标签对应的动态sql生成的处理类. * @author blinkfox on 2016-11-01. */ public class TagHandler { /** 生成sql的前缀,如:and, or 等. */ private String prefix; /** 生成动态sql的处理实现反射类型,如:EqualHandler. */ private Class<? extends IConditHandler> handlerCls; /** 生成sql的后缀,如:>, <, = 等. */ private String suffix; /** * 仅标签对应处理类的构造方法. * @param handlerCls 动态处理类的反射类型 */ public TagHandler(Class<? extends IConditHandler> handlerCls) { this.prefix = ZealotConst.ONE_SPACE; this.handlerCls = handlerCls; } /** * 含前缀、标签处理器的构造方法. * @param prefix sql前缀 * @param handlerCls 动态处理类的反射类型 */ public TagHandler(String prefix, Class<? extends IConditHandler> handlerCls) { this.prefix = prefix; this.handlerCls = handlerCls; } /** * 含标签处理器、后缀的构造方法. * @param handlerCls 动态处理类的反射类型 * @param suffix sql前后缀 */ public TagHandler(Class<? extends IConditHandler> handlerCls, String suffix) { this.prefix = ZealotConst.ONE_SPACE; this.handlerCls = handlerCls; this.suffix = suffix; } /** * 全构造方法. * @param prefix sql前缀 * @param suffix sql后缀 * @param handlerCls 动态处理类的反射类型 */ public TagHandler(String prefix, Class<? extends IConditHandler> handlerCls, String suffix) { this.prefix = prefix; this.handlerCls = handlerCls; this.suffix = suffix; } /* ------------ getter 和 setter 方法 ------------- */ public String getPrefix() { return prefix; } public Class<? extends IConditHandler> getHandlerCls() { return handlerCls; } public String getSuffix() { return suffix; } }
24.051948
97
0.615551
0b4d6c7a157baa84ebdbc6a5ee5953cdbc827671
659
package com.wodejia.myapp.server; /** * Created by clarence on 16/10/11. */ public class CarServerDO { private int carId; /** * 车牌 */ private String numberPlates; private int userId; public int getCarId() { return carId; } public void setCarId(int carId) { this.carId = carId; } public String getNumberPlates() { return numberPlates; } public void setNumberPlates(String numberPlates) { this.numberPlates = numberPlates; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } }
16.897436
54
0.593323
5d2e38963bbdbb706fc576e32a394b9cd12f0db8
6,754
package koldur.losversados.dao; import android.content.res.Resources; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import koldur.losversados.R; /** * Created by Juan on 10/12/17. */ public class DAOContent_Imp extends DAOContent { @Override public HashMap<Integer, String> getAllYoNunca(Resources resources) { HashMap<Integer, String> list = new HashMap<>(); // Resoult list is created InputStream inputStream = null; //Input stream is created String text; //Raw text variable is created String[] lines; //Subdivision for the text is created int last = 0; //Last line read (used for error control) try{ inputStream = resources.openRawResource(R.raw.yonuncafile); //Input stream instanced for raw file that contains all the data text = byteToString(inputStream); //Internal function that reads all the file and returns it in string format lines = text.split("\n"); //Plain string divided by lines, represented by the regular expression "\n" for (int i = 0; i < lines.length; i++){ //loop to process every line of raw data last = i; //Update the line we are currently reading. If an error occurs, the troubling line is saved. String linea[] = lines[i].split(";"); //The raw line is formatted between ';' chars list.put(i,linea[1]); //Currently, the only important part of the line is the second one } }catch (IOException e){ System.err.println("last " + last); //Just for debug. If an error occurs, the problematic line is shown in the console. } finally{ try{ inputStream.close(); //Either an error occurs or not, the inputStream must be closed }catch(IOException e){ System.err.println("Error al cerrar"); //The closing exceptions must be controlled } } return list; //Finally, the list is returned (with as much entries as the system could load) } @Override public HashMap<Integer,String> getHighDare(Resources androidResources, Boolean getExplicit){ HashMap<Integer, String> list = new HashMap<>(); // Resoult list is created InputStream inputStream = null; //Input stream is created String text; //Raw text variable is created String[] lines; //Subdivision for the text is created int last = 0; //Last line read (used for error control) try{ inputStream = androidResources.openRawResource(R.raw.rethighfile); //Input stream instanced for raw file that contains all the data text = byteToString(inputStream); //Internal function that reads all the file and returns it in string format lines = text.split("\n"); //Plain string divided by lines, represented by the regular expression "\n" int counter = 0; for (int i = 0; i < lines.length; i++){ //loop to process every line of raw data String linea[] = lines[i].split(";"); //The raw line is formatted between ';' chars if (linea[1].equals("Reto")) { list.put(counter, linea[2]); counter++; last = i; //Update the line we are currently reading. If an error occurs, the troubling line is saved. } else if(getExplicit && (linea[1].equals("EXPL"))) { list.put(counter, linea[2]); counter++; last = i; //Update the line we are currently reading. If an error occurs, the troubling line is saved. } } }catch (IOException e){ System.err.println("last " + last); //Just for debug. If an error occurs, the problematic line is shown in the console. } finally{ try{ inputStream.close(); //Either an error occurs or not, the inputStream must be closed }catch(IOException e){ System.err.println("Error al cerrar"); //The closing exceptions must be controlled } } return list; //Finally, the list is returned (with as much entries as the system could load) } @Override public void addHighDare(Resources resources, HashMap<Integer,String> list, Integer length, Boolean getExplicit){} @Override public HashMap<Integer,String> getHighTruth(Resources androidResources){ HashMap<Integer, String> list = new HashMap<>(); // Resoult list is created InputStream inputStream = null; //Input stream is created String text; //Raw text variable is created String[] lines; //Subdivision for the text is created int last = 0; //Last line read (used for error control) try{ inputStream = androidResources.openRawResource(R.raw.verdhighfile); //Input stream instanced for raw file that contains all the data text = byteToString(inputStream); //Internal function that reads all the file and returns it in string format lines = text.split("\n"); //Plain string divided by lines, represented by the regular expression "\n" for (int i = 0; i < lines.length; i++){ //loop to process every line of raw data last = i; //Update the line we are currently reading. If an error occurs, the troubling line is saved. String linea[] = lines[i].split(";"); //The raw line is formatted between ';' chars list.put(i,linea[2]); //Currently, the only important part of the line is the third one } }catch (IOException e){ System.err.println("last " + last); //Just for debug. If an error occurs, the problematic line is shown in the console. } finally{ try{ inputStream.close(); //Either an error occurs or not, the inputStream must be closed }catch(IOException e){ System.err.println("Error al cerrar"); //The closing exceptions must be controlled } } return list; //Finally, the list is returned (with as much entries as the system could load) } @Override public void addHighTruth(Resources androidResources, HashMap<Integer,String> list, Integer length){ } public String byteToString( InputStream inputStream ) throws IOException { ByteArrayOutputStream b = new ByteArrayOutputStream(); byte[] bytes = new byte[4096]; int len = 0; while ( (len=inputStream.read(bytes))>0 ) { b.write(bytes,0,len); } return new String( b.toByteArray(),"UTF8"); } }
47.900709
144
0.623482
36d53aa9d166a1ca62d29250494b1395d328205a
286
package com.guaxinim.api.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.guaxinim.api.model.Clientes; @Repository public interface ClienteRepository extends JpaRepository<Clientes, Long> { }
23.833333
74
0.825175
9ef8f6553d1eaa8cf77fb8fbbd4ac011b0af306c
5,331
package com.revolsys.geometry.index.rtree; import java.util.Arrays; import java.util.List; import java.util.function.Consumer; import java.util.function.Predicate; import com.revolsys.geometry.model.BoundingBox; public class RTreeLeaf<T> extends RTreeNode<T> { private BoundingBox[] objectBoundingBoxes; private T[] objects; private int size = 0; public RTreeLeaf() { } @SuppressWarnings("unchecked") public RTreeLeaf(final int size) { this.objects = (T[])new Object[size]; this.objectBoundingBoxes = new BoundingBox[size]; } public void add(final BoundingBox objectBoundingBox, final T object) { this.objectBoundingBoxes[this.size] = objectBoundingBox; this.objects[this.size] = object; this.size++; expandBoundingBox(objectBoundingBox); } @Override protected RTreeLeaf<T> chooseLeaf(final List<RTreeBranch<T>> path, final BoundingBox boundingBox) { return this; } @Override public void forEach(final double x, final double y, final Consumer<? super T> action) { for (int i = 0; i < this.size; i++) { final BoundingBox objectBounds = this.objectBoundingBoxes[i]; if (objectBounds.bboxIntersects(x, y)) { final T object = this.objects[i]; action.accept(object); } } } @Override public void forEach(final double minX, final double minY, final double maxX, final double maxY, final Consumer<? super T> action) { for (int i = 0; i < this.size; i++) { final BoundingBox objectBounds = this.objectBoundingBoxes[i]; if (objectBounds.bboxIntersects(minX, minY, maxX, maxY)) { final T object = this.objects[i]; action.accept(object); } } } @Override public void forEach(final double minX, final double minY, final double maxX, final double maxY, final Predicate<? super T> filter, final Consumer<? super T> action) { for (int i = 0; i < this.size; i++) { final BoundingBox objectBounds = this.objectBoundingBoxes[i]; if (objectBounds.bboxIntersects(minX, minY, maxX, maxY)) { final T object = this.objects[i]; if (filter.test(object)) { action.accept(object); } } } } @Override public void forEachValue(final Consumer<? super T> action) { for (int i = 0; i < this.size; i++) { final T object = this.objects[i]; action.accept(object); } } @Override public void forEachValue(final Predicate<? super T> filter, final Consumer<? super T> action) { for (int i = 0; i < this.size; i++) { final T object = this.objects[i]; if (filter.test(object)) { action.accept(object); } } } public int getSize() { return this.size; } @Override public boolean remove(final double minX, final double minY, final double maxX, final double maxY, final T object) { for (int i = 0; i < this.size; i++) { final BoundingBox objectBounds = this.objectBoundingBoxes[i]; final T object1 = this.objects[i]; if (object1 == object) { if (objectBounds.getMinX() == minX && objectBounds.getMinY() == minY && objectBounds.getMaxX() == maxX && objectBounds.getMaxY() == maxY) { System.arraycopy(this.objectBoundingBoxes, i + 1, this.objectBoundingBoxes, i, this.size - i - 1); this.objectBoundingBoxes[this.size - 1] = null; System.arraycopy(this.objects, i + 1, this.objects, i, this.size - i - 1); this.objects[this.size - 1] = null; this.size--; updateEnvelope(); return true; } else { // ERROR } } } return false; } public List<RTreeNode<T>> split(final T object, final BoundingBox objectBoundingBox) { final RTreeLeaf<T> leaf1 = new RTreeLeaf<>(this.objects.length); final RTreeLeaf<T> leaf2 = new RTreeLeaf<>(this.objects.length); // TODO Add some ordering to the results final int midPoint = (int)Math.ceil(this.size / 2.0); for (int i = 0; i <= midPoint; i++) { final BoundingBox objectBounds = this.objectBoundingBoxes[i]; final T object1 = this.objects[i]; leaf1.add(objectBounds, object1); } for (int i = midPoint + 1; i < this.size; i++) { final BoundingBox objectBounds = this.objectBoundingBoxes[i]; final T object1 = this.objects[i]; leaf2.add(objectBounds, object1); } leaf2.add(objectBoundingBox, object); return Arrays.<RTreeNode<T>> asList(leaf1, leaf2); } @Override protected void updateEnvelope() { double minX = Double.MAX_VALUE; double maxX = -Double.MAX_VALUE; double minY = Double.MAX_VALUE; double maxY = -Double.MAX_VALUE; for (int i = 0; i < this.size; i++) { final BoundingBox objectBounds = this.objectBoundingBoxes[i]; final double nodeMinX = objectBounds.getMinX(); if (nodeMinX < minX) { minX = nodeMinX; } final double nodeMinY = objectBounds.getMinY(); if (nodeMinY < minY) { minY = nodeMinY; } final double nodeMaxX = objectBounds.getMaxX(); if (nodeMaxX > maxX) { maxX = nodeMaxX; } final double nodeMaxY = objectBounds.getMaxY(); if (nodeMaxY > maxY) { maxY = nodeMaxY; } } setBoundingBox(minX, minY, maxX, maxY); } }
30.637931
99
0.631964
7e1fa9c0b9a23682dd3a43169f36901aad1ae7fe
214
package com.example.project.exceptions.user; public class EmptyShoppingCartException extends Exception{ public EmptyShoppingCartException() { super("Cannot buy! Your shopping cart is empty!"); } }
26.75
58
0.747664
bfd3b400be0dc2811d9f4d8ca5bf87ec444d0b8f
267
package com.kadir.twitterbots.crocodile.enumeration; /** * @author akadir * Date: 2019-05-06 * Time: 19:24 */ public enum SourceType { STATUS_ID_LIST, TWITTER_DATA_JS; private final int value; SourceType() { this.value = ordinal(); } }
15.705882
52
0.64794
42f819b045985c8a0c35e35142e03728cfd123cd
2,118
/** * Write a description of class Tester here. * * @author (your name) * @version (a version number or a date) */ import java.util.*; public class Tester { public void testLogEntry() { LogEntry le = new LogEntry("1.2.3.4", new Date(), "example request", 200, 500); System.out.println(le); LogEntry le2 = new LogEntry("1.2.100.4", new Date(), "example request 2", 300, 400); System.out.println(le2); } public void testLogAnalyzer() { // complete method LogAnalyzer la = new LogAnalyzer(); la.readFile("data/short-test log.txt"); la.printAll(); } /*In the Tester class (or you can write a new class for testing) write the void method testUniqueIP * that has no parameters. This method should create a LogAnalyzer, read from the file short-test_log, * and then test the method countUniqueIPs.*/ public void testUniqueIP() { LogAnalyzer la = new LogAnalyzer(); la.readFile("weblog2_log"); int count = la.countUniqueIPs(); System.out.println("There are " + count + " unique IP's in weblog-short_log.txt"); //la.printAllHigherThanNum(400); } public void testUniqueIPVisitsOnDay() { LogAnalyzer la = new LogAnalyzer(); la.readFile("weblog2_log"); ArrayList<String> sep14 = la.uniqueIPVisitsOnDay("Sep 27"); for(String s: sep14){ System.out.println(s); } System.out.println("\n"); ArrayList<String> sep30 = la.uniqueIPVisitsOnDay("Sep 30"); for(String s1: sep30) { //System.out.println(s1); } } public void testCountUniqueIPsInRange() { LogAnalyzer la = new LogAnalyzer(); la.readFile("weblog2_log"); int test1 = la.countUniqueIPsInRange(200, 299); System.out.println("Expected: 4 Got: " + test1); int test2 = la.countUniqueIPsInRange(300, 399); //System.out.println("Expected: 2 Got: " + test2); } }
29.416667
107
0.580264
7a1edefafac68e1bfbd53a4a3f81059b84c947cb
263
package karstenroethig.imagetags.webapp.dto.info; import lombok.Getter; import lombok.Setter; @Getter @Setter public class MemoryInfoDto { private String totalFormated; private String usedFormated; private long freePercentage; private String freeFormated; }
18.785714
49
0.821293
454073db8f64dc85aa0a95daf148f917b6cf6f2d
663
package com.github.aloomaio.androidsdk.aloomametrics; /** * For use with {@link AloomaAPI.People#addOnMixpanelUpdatesReceivedListener(OnMixpanelUpdatesReceivedListener)} */ /* package */ interface OnMixpanelUpdatesReceivedListener { /** * Called when the Mixpanel library has updates, for example, Surveys or Notifications. * This method will not be called once per update, but rather any time a batch of updates * becomes available. The related updates can be checked with * {@link AloomaAPI.People#getSurveyIfAvailable()} or {@link AloomaAPI.People#getNotificationIfAvailable()} */ public void onMixpanelUpdatesReceived(); }
44.2
112
0.758673
e366df867786d9e38294c84384e15ae4ff5fdc59
595
package org.springframework.boot.autoconfigure.cassandra; import com.datastax.driver.core.Cluster; import com.datastax.driver.core.Cluster.Builder; /** * Callback interface that can be implemented by beans wishing to customize the * {@link Cluster} via a {@link Builder Cluster.Builder} whilst retaining default * auto-configuration. * * @author Eddú Meléndez * @since 1.5.0 */ @FunctionalInterface public interface ClusterBuilderCustomizer { /** * Customize the {@link Builder}. * @param clusterBuilder the builder to customize */ void customize(Builder clusterBuilder); }
22.884615
81
0.757983
4ff28d1c35179d76a81ea2a9f26b7399c5ad82c4
1,277
/* * Copyright 2012 by The JFlux Project (www.jflux.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.jflux.api.core; /** * Interface for grouping Listeners together * @author Matthew Stevenson <www.jflux.org> * @param <E> type of event the Listeners handle */ public interface Notifier<E> { /** * Adds a listener to the managed set * @param listener Listener to add */ public void addListener(Listener<E> listener); /** * Removes a Listener from the managed set * @param listener Listener to remove */ public void removeListener(Listener<E> listener); /** * Sends an event to all managed listeners * @param e event to send */ public void notifyListeners(E e); }
29.697674
75
0.689115
a57b441e75fc79919ec6889f0f14432908ec61c7
339
package io.prophecies.automapper; public class TestDoubleGuiceModule extends GuiceModule { public TestDoubleGuiceModule() { super(null, PropheciesTestDoubleResolver.class); } @Override protected void configure() { super.configure(); bind(PropheciesRepositoryFactory.class).to(PropheciesTestDoubleRepositoryFactory.class); } }
24.214286
90
0.80236
2c91376c1230291aaaa39ab985e4699d96c6b43d
632
package io.github.harvies.charon.tests.base.jdk.concurrent.lock; /** * @author harvies */ public class SynchronizedTest implements Runnable { public synchronized void get() { System.out.println(Thread.currentThread().getId()); set(); } public synchronized void set() { System.out.println(Thread.currentThread().getId()); } @Override public void run() { get(); } public static void main(String[] args) { SynchronizedTest ss = new SynchronizedTest(); new Thread(ss).start(); new Thread(ss).start(); new Thread(ss).start(); } }
21.793103
64
0.607595
579da00155f1fccd0366d832e6b14ec09078b03b
5,146
/** * Copyright 2015 Keith Wannamaker * * 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 edmtools; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import name.fraser.neil.plaintext.diff_match_patch; import name.fraser.neil.plaintext.diff_match_patch.Diff; import name.fraser.neil.plaintext.diff_match_patch.Operation; import org.junit.Test; import com.google.common.base.Charsets; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import com.google.common.io.Files; import edmtools.JpiDecoder.JpiDecoderConfiguration; import edmtools.Proto.DataRecord; import edmtools.Proto.DataRecord.Mark; import edmtools.Proto.EngineDataRecord; import edmtools.Proto.Flight; import edmtools.Proto.JpiFile; public class FunctionalTest { @Test public void testEdm830() throws IOException { diff("testdata/edm830.jpi", 45, "testdata/edm830.45.txt"); diff("testdata/edm830.jpi", 72, "testdata/edm830.72.txt"); } private void diff(String jpiFile, int flightNumber, String goldenCsv) throws IOException { Flight golden = readGoldenCsvToProto(goldenCsv); Flight parsed = readJpiFile(jpiFile, flightNumber); assertEquals(golden.getDataCount(), parsed.getDataCount()); diff_match_patch dmp = new diff_match_patch(); for (int i = 0; i < golden.getDataCount(); ++i) { List<Diff> unequalDiffs = new ArrayList<>(); for (Diff diff : dmp.diff_main(golden.getData(i).toString(), parsed.getData(i).toString())) { if (diff.operation != Operation.EQUAL) { unequalDiffs.add(diff); } } assertTrue("DataRecord " + i + ": " + Joiner.on('\n').join(unequalDiffs), unequalDiffs.isEmpty()); } } private static final Splitter SPLITTER = Splitter.on(',').trimResults(); // TODO: this is 830 specific. Use header row when we have samples from other models. private static Flight readGoldenCsvToProto(String filename) throws IOException { List<String> lines = Files.readLines(new File(filename), Charsets.UTF_8); Flight.Builder builder = Flight.newBuilder(); for (String line : lines) { List<String> parts = SPLITTER.splitToList(line); if (parts.size() != 29 || parts.get(0).equals("Date")) { continue; } DataRecord.Builder record = builder.addDataBuilder(); EngineDataRecord.Builder engineRecord = record.addEngineBuilder(); engineRecord.addAllExhaustGasTemperature(intSublist(parts, 2, 7)); engineRecord.addAllCylinderHeadTemperature(intSublist(parts, 8, 13)); int i = 14; engineRecord.setOilTemperature(Integer.parseInt(parts.get(i++))); engineRecord.setMaxExhaustGasTemperatureDifference(Integer.parseInt(parts.get(i++))); engineRecord.setCylinderHeadTemperatureCoolingRate(Integer.parseInt(parts.get(i++))); record.setOutsideAirTemperature(Integer.parseInt(parts.get(i++))); record.addVoltage(Float.parseFloat(parts.get(i++))); engineRecord.addFuelFlow(Float.parseFloat(parts.get(i++))); engineRecord.addFuelUsed(Float.parseFloat(parts.get(i++))); engineRecord.setRpm(Integer.parseInt(parts.get(i++))); engineRecord.setManifoldPressure(Float.parseFloat(parts.get(i++))); engineRecord.setHorsepower(Integer.parseInt(parts.get(i++))); engineRecord.setOilPressure(Integer.parseInt(parts.get(i++))); engineRecord.setHours(Float.parseFloat(parts.get(i++))); switch (parts.get(28)) { case "": record.setMark(Mark.NOT_MARKED); break; case "[": record.setMark(Mark.RICH_START); break; case "]": record.setMark(Mark.RICH_END); break; default: throw new IllegalStateException("Need to handle mark [" + parts.get(28) + "]"); } } return builder.build(); } private static Iterable<Integer> intSublist(List<String> list, int start, int end) { ImmutableList.Builder<Integer> result = ImmutableList.builder(); for (int i = start; i <= end; ++i) { result.add(Integer.parseInt(list.get(i))); } return result.build(); } private static Flight readJpiFile(String filename, int flightNumber) throws IOException { JpiInputStream inputStream = new JpiInputStream(filename); JpiFile jpiFile = JpiDecoder.decode( inputStream, JpiDecoderConfiguration.newBuilder().withExactFlightNumber(flightNumber).build()); assertEquals(1, jpiFile.getFlightCount()); return jpiFile.getFlight(0); } }
41.168
99
0.715896
5c266b2e1b20526bc20f00a7b945700ccc97f2b5
1,071
package org.ovirt.engine.api.restapi.resource; import org.ovirt.engine.api.model.Application; import org.ovirt.engine.api.model.Applications; import org.ovirt.engine.api.resource.VmApplicationResource; public class BackendVmApplicationResource extends AbstractBackendSubResource<Application, Applications> implements VmApplicationResource { BackendVmApplicationsResource parent; public BackendVmApplicationResource(String id, BackendVmApplicationsResource parent) { super(id, Application.class, Applications.class); this.parent = parent; } public BackendVmApplicationsResource getParent() { return parent; } @Override public Application get() { Applications applications = parent.list(); for (Application app : applications.getApplications()) { if (app.getId().equals(id)) { return app; } } return notFound(); } @Override protected Application doPopulate(Application model, Applications entity) { return model; } }
28.945946
138
0.70028
2acc44323aab9e4397c6ba081827809731631441
1,818
package plug.language.soup.examples.nbits; import plug.language.soup.model.Behavior; import plug.language.soup.model.BehaviorSoup; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; public class NBits { List<Behavior<Configuration>> behaviors(int i) { List<Behavior<Configuration>> behaviors = new ArrayList<>(); //final int f[] = new int[] {170, 377, 399, 394, 554, 1004, 208, 350, 755, 96, 305, 72, 699, 516, 675, 716, 321, 491, 777, 601}; final int f[] = null; Behavior<Configuration> t2f = new Behavior<>( i + "_t2f", (c) -> ((c.bits >> i) & 1) > 0 && ( (f != null) ? (((f[(int)c.bits%f.length] >> i) & 1) > 0) : true), (c) -> { c.bits &= ~ (1 << i); return c; }); Behavior<Configuration> f2t = new Behavior<>( i + "_f2t", (c) -> ((c.bits >> i) & 1) == 0 && ( (f != null) ? (((f[(int)c.bits%f.length] >> i) & 1) > 0) : true), (c) -> { c.bits |= 1 << i; return c; }); return Arrays.asList(t2f, f2t); } public BehaviorSoup<Configuration> model(int nbits) { BehaviorSoup<Configuration> soup = new BehaviorSoup<>(new Configuration()); for (int i = 0; i<nbits; i++) { soup.behaviors.addAll(behaviors(i)); } return soup; } public static void main(String[] args) { Random r = new Random(); for (int i =0 ;i < 20; i++) { System.out.print(r.nextInt(1024) + ", "); } } }
30.3
136
0.455446
64e28d2555a0ed61bbfb10d8251666f570654516
6,565
/*------------------------------------------------------------------------ * (The MIT License) * * Copyright (c) 2008-2012 Rhomobile, Inc. * * 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. * * http://rhomobile.com *------------------------------------------------------------------------*/ package com.rhomobile.rhodes.fcm; import android.content.Context; import android.content.Intent; import android.app.NotificationManager; import android.graphics.BitmapFactory; import android.media.RingtoneManager; import android.net.Uri; import androidx.core.app.NotificationCompat; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; import com.google.firebase.messaging.Constants; import com.rhomobile.rhodes.util.ContextFactory; import com.rhomobile.rhodes.Logger; import com.rhomobile.rhodes.PushContract; import com.rhomobile.rhodes.R; import com.google.firebase.FirebaseApp; import com.google.firebase.FirebaseOptions; import android.util.Log; import java.util.HashMap; import java.util.Map; import org.json.JSONException; import org.json.JSONObject; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.TimeUnit; import android.os.Bundle; import android.os.Handler; import java.util.Queue; import java.util.LinkedList; public class FCMIntentService extends FirebaseMessagingService { private static final String TAG = FCMIntentService.class.getSimpleName(); public static final FCMListener listener = FCMListener.getInstance(); public static Queue<String> messagesQueue = new LinkedList<String>(); public FCMIntentService(){ super(); Logger.I(TAG, "FCM: creating FCMIntentService"); } @Override public void handleIntent(Intent intent) { Logger.W(TAG, "FCM: onHandleIntent()"); extractDataFromIntent(intent); super.handleIntent(intent); } void extractDataFromIntent(Intent intent){ Bundle bundle = intent.getExtras(); if (bundle != null) { try{ RemoteMessage remoteMessage = new RemoteMessage(bundle); if (remoteMessage.getMessageId() == null) return; Logger.I(TAG, "FCM: onMessageReceived()"); Map<String, String> params = new HashMap<String, String>(); if (remoteMessage.getMessageId() != null) params.put("id", remoteMessage.getMessageId()); Logger.I(TAG, "FCM: id - " + remoteMessage.getMessageId()); if (remoteMessage.getFrom() != null) params.put("from", remoteMessage.getFrom()); Logger.I(TAG, "FCM: from - " + remoteMessage.getFrom()); if (remoteMessage.getTo() != null) params.put("to", remoteMessage.getTo()); Logger.I(TAG, "FCM: to - " + remoteMessage.getTo()); if (remoteMessage.getNotification() != null){ if (remoteMessage.getNotification().getBody() != null) params.put("body", remoteMessage.getNotification().getBody()); Logger.I(TAG, "FCM: body - " + remoteMessage.getNotification().getBody()); if (remoteMessage.getNotification().getTitle() != null) params.put("title", remoteMessage.getNotification().getTitle()); Logger.I(TAG, "FCM: title - " + remoteMessage.getNotification().getTitle()); if (remoteMessage.getNotification().getTag() != null) params.put("tag", remoteMessage.getNotification().getTag()); Logger.I(TAG, "FCM: tag - " + remoteMessage.getNotification().getTag()); } JSONObject jsonObject = new JSONObject(params); try { jsonObject.put("data", new JSONObject(remoteMessage.getData())); Logger.I(TAG, "FCM: data - " + remoteMessage.getData()); } catch (JSONException e) { Logger.I(TAG, "FCM: jsonObject generation error"); e.printStackTrace(); } Logger.W(TAG, "FCM: push message in JSON: " + jsonObject.toString()); messagesQueue.add(jsonObject.toString()); }catch(Exception e){ Logger.W(TAG, "FCM: exception on extracting data from intent"); e.printStackTrace(); } handleMessagesQueue(); } } public static void handleMessagesQueue(){ try{ while(messagesQueue.size() != 0){ Logger.W(TAG, "FCM: tryToHandleIntent() - trying to handle messages queue"); PushContract.handleMessage(ContextFactory.getContext(), messagesQueue.peek(), FCMFacade.FCM_PUSH_CLIENT); messagesQueue.remove(); } }catch(Exception e){ Logger.E(TAG, "FCM: can't handle the messages queue"); e.printStackTrace(); } } static public void resume() { Timer timerObj = new Timer(); TimerTask timerTaskObj = new TimerTask() { public void run() { handleMessagesQueue(); } }; timerObj.schedule(timerTaskObj, 1000); } @Override public void onNewToken(String token){ super.onNewToken(token); Logger.W(TAG, "FCM: onNewToken: " + token); ContextFactory.getContext().getSharedPreferences("FireBase", MODE_PRIVATE).edit().putString("token", token).apply(); FCMFacade.refreshToken(); } }
37.514286
140
0.633206
8d96c273f586bafe796c001491ce5197ee1ed991
581
/** * Copyright 2015-现在 广州市领课网络科技有限公司 */ package com.roncoo.education; import org.springframework.boot.SpringApplication; import org.springframework.cloud.client.SpringCloudApplication; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.scheduling.annotation.EnableScheduling; /** * 定时任务 */ @EnableScheduling @EnableFeignClients @SpringCloudApplication public class CrontabPlanApplication { public static void main(String[] args) { SpringApplication.run(CrontabPlanApplication.class, args); } }
24.208333
67
0.765921
130148e6709178d3c42d8097092428871c458997
1,397
package skd.app.androidfeatures.sRecylerView; /** * Created by sapan on 7/19/2017. */ import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.List; import skd.app.androidfeatures.R; /** * THis class will be the data adapter for the recycler view * This class must exxtend the Recycler view adapter. */ public class RvDataAdpt2 extends RecyclerView.Adapter { List<DummyModel> dummyModelsList; public RvDataAdpt2(List<DummyModel> listDummyModels) { dummyModelsList = listDummyModels; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { //lets populate our recyler view with the item created; //get the view from the layout inflator // third parameter is set to false to prevent viewgroup to attach to root View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item,parent,false); return new DummyVH(view); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { //bind the view with the holder ((DummyVH)holder).bindVH(dummyModelsList.get(position)); } @Override public int getItemCount() { return dummyModelsList.size(); // to display the 100 items } }
27.392157
106
0.714388
30c3f62abb6de8cf9bf179df0c6b64b5696019d2
6,588
class PoP3b { public int[][] pKIsJiyRf (boolean[][] r2, iTdqvAjk5qn6 z2n3b0qhxhjt) { void ZhsSGWYuNvp5tY; void VaL_FNzbssUKm = this.slNzG() = !!-this.clJoj4WGHWo(); boolean aSAJZU; boolean J0mUJdxNx6 = !new nKGyeaBEB8aF().RBLc = false.suqXRgMUtmIR; new lR9QstHSdPq().SYrj9fHz(); return ( !-( new void[ new mR2Mxandslhl()[ this[ false[ !-null.YO]]]].Djknr5cWKt())[ !false[ false[ this[ !false[ -true[ !null[ !true[ z3ddR.NJq70bslMM()]]]]]]]]).ciB7E0zlM; ; ; new int[ !mG56lg1CEDkfcQ.K5V].T; NC[][][][] k; ; boolean[][] xP0m2 = !( --!Wo.Jxvgo)[ !!!new BgYeMl().YTneRWS1m6ixU()]; nunu ka8wABaok; return; new eacOO().bO(); o[][] imbmoFgInVi; boolean[][][] tT5BmkM9gO0 = ( !!null.Oz42hOquJ).PVkoksu8X1Y() = !!--null[ new boolean[ false.AR3347iMSW()].J]; { yIbLO4s0Mzi _i; while ( ( ( false.McN()).XXwmHiZFT00yBo()).aSeW_k8()) return; ; boolean LBv; int ZsOPf; boolean SZcFsw; return; int OZXff2r8m; while ( 8550[ !null.rTkZK0()]) while ( t4sRp[ !( -17243209.USaOwqyveEsRM4).sPYnSyb()]) if ( this[ new AEZO_()[ -!!true[ new orBeKxNQU().gOLN9D_u7]]]) while ( new mFeodO_t1GF().Nw0T1eULGcIWW()) if ( --null.LmG()) if ( -689400116.Eh()) 36882[ ( !-new EvD22W().R14OGlf()).IfPfAaKDrjUcTl()]; { { return; } } void g7e211GycE; while ( !-false[ new void[ --!false[ true[ tfh49vf6an()[ !!-new Ah5hmvN[ null[ new void[ null.YH][ 000171.OvmBzbG()]]].lwdEbQULVysQ]]]].L0bbM]) if ( !this.kpNHVwOwua()) ; if ( this.n) { b b3Rea; } return; { ; } if ( !!-T3GaSuBge.qP1KFBAKP) return; --false.vOvhCqrOBNl(); { !-null[ !true.NCF7N()]; } wgFwNyQizISQ6.U2TJgFndgFlSg(); } F_B GmmYH; { boolean[] iQIR2fQAzsKbY; int[] EiASAqhmfBsN; int[] byfT9e; boolean[] CfL; true.T4gP6(); while ( a4a13LYG2iLxk1().A28I()) if ( zs.vKUw3TMjr) { if ( null[ --!29380407.HMduHbUL0GiB()]) false.S65; } !new hdD[ j7bnOcFFrWs().aG6S9uR0C4PME()].wyZitTLVAJeQGa; } } public void[][][][][] d4 () { 7.XGKql; void wphFLlTw; boolean g = -( --true.gekkfvUYUDTK8()).BDyonXP9jrNC; int[] qW; if ( -( --41982470.CTw)[ !!-!false.M3cjS42bXh]) ;else -UlF.EMhKxDFLXt(); if ( dgWxSG61zTWD().P()) if ( -!-this.RTPHcWubTYMIA()) while ( !!x().Aac9w()) null.kRSWdPSZWih3(); } public f9OiM_a nfbbdQ_xLBH (void[][] YQJX, void L3z5q1WGNMSrh, boolean j, boolean WGB9NYIMo, rZM[] UUOzDG, int xN6MBnFmH23nFO, int[] Q7XySFb51_7) { int wu0wV; rexhal zMzCYoq3JmbHlx; return; if ( ( !----( false[ new HduJoau().I3oX0kqapjufC]).Qoc()).ttRpP41x()) while ( !!new opQT3()[ !new int[ ( null[ null[ feeKqhsP().xbKaWnb()]]).Ilvrz].WCU4rwYX8Gtk]) return;else return; return ( new dYpX().HFIIDPLe).kZDjxfKXb(); { return; { void[] LToA; } void B; int[][] oosi1; !-!lVJY9W2H().J(); return; boolean HUQPFPR3Bgh; MLQLYX YyJxfj6oXAWUgs; void pTj4v; int[][] i4bQnEJzo9; QXwDFERkD aceel7F0SYd0Y; } new c()[ !-( -S.LKdA)[ !!!this[ -null[ this[ !--false[ new vXjxQD8Idvxux5()[ YfGCH3()[ rctUit()[ !---!null.r2MX53hs9RneV()]]]]]]]]]; null.hodCYt(); return; return !null.GxDlOen2yHQ3ma; while ( false._g57h5) ; jJjU7Wy6[][][][] zg = -!-!--!( -!-new h00p5aL[ -( !860.i())[ rouTd57ZQa42t().LKC8o()]].fl4XJiAeY2B()).EWrUJImrkJ_YBf(); ; int iXRoGeN; { while ( t7dMq97jnogyz().PqSgnJOjq) if ( -!45248486[ !JgllN.qhLth()]) while ( -!new int[ false.Q2Sl9p4wwGP2][ true[ !null.z()]]) while ( -!wytZmjox.dgtU4UMLO) { if ( --new void[ TA_.dGi].QqPRut8VAyUhqU()) ; } void Fb; if ( !new void[ !--false[ !this[ --HLAMJ.TqsMGZInzKb()]]].iCRTWEIG) if ( -new void[ -mTig7E3().l].bvlY) ; ; void rIa28Ql_IV; { boolean ZNAoSwAJf; } return; while ( new QeKkV6pynBX()[ !-!this.Ksf]) return; return; } boolean[][] DXf2bEe60CH = -new mppaXaeHuA().Z4X8IZJ5uCPo = -!-!!!!--7998.Ga0GqPRtfriY; } public void[][] YY3 (KPUHFOZOYj adAGfL8yZ, int[] U, boolean[] aRQcVKcIBP, int _cJF, INn Z8I, boolean uNGGi, kP43WgWgx[] x_eiuPsUu0KQ3n) throws PxvdmSN6lT { while ( YXrdE[ -true.fYxwJAY9lD9()]) { boolean[] _csfh2WIO7Y; } if ( I7BWX.pEgD6) if ( !----( true.Teh()).ya) if ( -!--new uQvdge().IFSMBicJ22p()) while ( iE[ !bnm0osLE6If().T19IqES]) return;else while ( new vevmipv8().qjvRe1) !new int[ !4204.g24NkZ2_ER8D7j()].SwGOZFn2BFK7T; boolean vqy2m = !-this.ym5Auyp = -true.EAg2ygWiD(); while ( new boolean[ !true.huEnww()].xTZn()) if ( this.KVgZNVLOO) if ( false.l) --!--this.ZI7INd9EeFVB; if ( -this[ -73152[ D2IhV9z[ ( new T8W().z9HFRVXoo)[ --new if1().kXqByV()]]]]) return;else ; boolean LgExuLwd; while ( this[ QvvTGS7qUV().RZMt()]) { if ( -false[ -!-null[ -!( true[ hNAO2XRgBOj0().kJXZP()])[ !null[ new boolean[ !---this.quCMjPWH2A4d][ lTfvP0Q2rOFPXJ.y1UbE]]]]]) { if ( QF0ezRl4x4LJZ()[ true.g59OIKIaaK6m]) { boolean[][] XZAnx0; } } } this[ new int[ -true[ !-new rDO9nOkF().Y21_nPnwLt4VP]].XCH]; while ( new lA241g()[ -new MTBbGA[ -this[ true.nbWilGTC_3Pqk]].Hsvkcp_Y]) ; ; int Psf3K; RK7y k2Xs; if ( --this.IjwN4ij3()) -!--false[ 9705.ENoRA6qXcxhQ()];else while ( true.O2b9g()) if ( !new int[ !-!61390571[ new boolean[ !( -WM3hl()[ null.T1ytPHHRhVOf])[ -!!this.WcbuoaFy]].QIgaAXIQU]].n6etT()) { return; } if ( !gxob1Yc1gz()[ --null.Bt()]) return;else ; CuS8xl5olPtRq zytj; -!9.coBlfMyOyRfJu(); } public int CSiy4q; public void[][][] kpqyJpWYLPb08; public uNv7VA2flPv4t[][][] UwF; } class tvG83Y3XmNwm { }
42.779221
300
0.506072
2cee78443f4ddfe3e736f880dccafaed56b55555
1,082
package tools; import java.awt.event.MouseEvent; import uHotDrawFigures.IFigure; import uHotDrawFiguresFramework.uDrawingView; /** * * Pablo Bermejo * https://github.com/PabloAsekas/ * **/ public class uSelectionTool extends uAbstractTool{ private uDrawingView v; private uAbstractTool fChild; public uSelectionTool(uDrawingView v1){ v = v1; } public IFigure findFigure(int x, int y){ return v.getDrawing().findFigure(x, y); } @Override public void mouseDown(MouseEvent e){ IFigure figure = findFigure(e.getX(), e.getY()); if (figure != null) { fChild = new uDragTool(v, figure); } else { fChild = new uSelectAreaTool(v); } fChild.mouseDown(e); } @Override public void mouseUp(MouseEvent e){ fChild.mouseUp(e); } @Override public void mouseDrag(MouseEvent e){ fChild.mouseDrag(e); } @Override public void mouseMove(MouseEvent e){} }
22.081633
57
0.582255
f6314d3fb534ba7ea10d811d2d0bf20709c39e8f
1,264
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.mycompany.payarars.dao; import com.mycompany.payarars.entity.Cliente; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * * @author guilherme */ public class ClienteDAO { private static List<Cliente> clientes = new ArrayList<>(); public List<Cliente> busca() { return clientes; } public void add(Cliente cliente) { clientes.add(cliente); } public void remove(int codigo) { for(int i = 0; i < clientes.size(); i++) { if(clientes.get(i).getCodigo() == codigo) { clientes.remove(i); } } } public void edit(Cliente cliente) { for (Cliente c : clientes) { if(cliente.getCodigo() == c.getCodigo()) { c.setNome(cliente.getNome()); c.setCidade(cliente.getCidade()); } } } public Cliente busca(int codigo) { return this.clientes.stream().filter(c -> c.getCodigo() == codigo).findFirst().orElse(null); } }
24.784314
100
0.585443
92485592612c994002616963c0ac9422f9c80990
2,121
package com.snail.job.common.web.aop; import com.snail.job.common.constant.HttpConstants; import com.snail.job.common.constant.ServiceStatus; import com.snail.job.common.model.ResultT; import com.snail.job.common.tools.SignTool; import com.snail.job.common.tools.SpringMVCTool; import com.snail.job.common.web.filter.ServletRequestWrapper; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import java.nio.charset.StandardCharsets; /** * API 接口验签 * @author WuQinglong created on 2021/12/25 19:03 */ @Aspect @Component public class ValidSignAspect { @Value("${rabbit-job.admin.secret-key}") private String secretKey; @Around("@within(com.snail.job.common.annotation.CheckSign)") public Object valid(ProceedingJoinPoint joinPoint) throws Throwable { // 验证服务是否可用 if (ServiceStatus.status == ServiceStatus.Status.STOPPING) { return ResultT.DOWN; } HttpServletRequest request = SpringMVCTool.getRequest(); if (!(request instanceof ServletRequestWrapper)) { return new ResultT<>(ResultT.FAIL_CODE, "内部错误"); } ServletRequestWrapper wrapper = (ServletRequestWrapper) request; // 请求是否超时 String timestamp = wrapper.getHeader(HttpConstants.TIMESTAMP); long ts = Long.parseLong(timestamp); if (ts < System.currentTimeMillis() - 1000 * 10) { return new ResultT<>(ResultT.TIMEOUT_CODE, "请求超时"); } // 验签 byte[] body = wrapper.getBody(); String bodyData = new String(body, StandardCharsets.UTF_8); String headerSign = wrapper.getHeader(HttpConstants.SIGN); String sign = SignTool.sign(bodyData, secretKey, timestamp); if (headerSign == null || !headerSign.equals(sign)) { return new ResultT<>(ResultT.SIGN_ERROR_CODE, "签名错误"); } return joinPoint.proceed(); } }
34.209677
73
0.701556
517a4133ee9a8821c1e2cc341448abfd39056e1d
1,105
package frc.robot.commands.shooter; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj2.command.CommandBase; import frc.robot.subsystems.shooter.HoodSubsystem; // Home Hood Command public class HomeHoodCommand extends CommandBase { // Variables HoodSubsystem hoodSubsystem; Timer timer; // In the constructor set the variables public HomeHoodCommand(HoodSubsystem hoodSubsystem) { this.hoodSubsystem = hoodSubsystem; addRequirements(hoodSubsystem); timer = new Timer(); timer.start(); } // In the initialize method set the hood to move down at a slow rate @Override public void initialize() { hoodSubsystem.setVoltage(-3.0); } // If it has been 0.25 seconds and the hood is not moving then the command is over @Override public boolean isFinished() { return Math.abs(hoodSubsystem.getVelocity()) < 2.0 && timer.get() >= 0.25; } // In the end method set the hood to 0 @Override public void end(boolean interrupted) { hoodSubsystem.setVoltage(0.0); } }
26.309524
86
0.676923
de599a85a9ef12d31fdea92792de8b81d8796d7f
4,144
/* * Copyright 2020 Haulmont. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.jmix.ui.component; import io.jmix.core.annotation.Internal; import io.jmix.ui.meta.PropertyType; import io.jmix.ui.meta.StudioElement; import io.jmix.ui.meta.StudioElementsGroup; import io.jmix.ui.meta.StudioProperty; import javax.annotation.Nullable; import java.util.Collection; import java.util.function.Consumer; /** * Base interface for actions aware dialog facets. * * @param <T> dialog facet type * @see OptionDialogFacet * @see InputDialogFacet */ public interface ActionsAwareDialogFacet<T> { /** * Sets dialog actions. * * @param actions actions */ @StudioElementsGroup(caption = "Dialog Actions", xmlElement = "actions", icon = "io/jmix/ui/icon/element/actions.svg") void setActions(@Nullable Collection<DialogAction<T>> actions); /** * @return dialog actions */ @Nullable Collection<DialogAction<T>> getActions(); /** * The event that is fired when {@link DialogAction#actionHandler} is triggered. */ class DialogActionPerformedEvent<T> { protected T dialog; protected DialogAction<T> dialogAction; public DialogActionPerformedEvent(T dialog, DialogAction<T> dialogAction) { this.dialog = dialog; this.dialogAction = dialogAction; } public T getDialog() { return dialog; } public DialogAction<T> getDialogAction() { return dialogAction; } } /** * Immutable POJO that stores dialog action settings. */ @StudioElement(xmlElement = "action", caption = "Dialog Action", icon = "io/jmix/ui/icon/element/action.svg") class DialogAction<T> { protected final String id; protected final String caption; protected final String description; protected final String icon; protected final boolean primary; protected Consumer<DialogActionPerformedEvent<T>> actionHandler; public DialogAction(String id, @Nullable String caption, @Nullable String description, @Nullable String icon, boolean primary) { this.id = id; this.caption = caption; this.description = description; this.icon = icon; this.primary = primary; } @StudioProperty(type = PropertyType.COMPONENT_ID, required = true) public String getId() { return id; } @StudioProperty(type = PropertyType.LOCALIZED_STRING) @Nullable public String getCaption() { return caption; } @StudioProperty(type = PropertyType.LOCALIZED_STRING) @Nullable public String getDescription() { return description; } @StudioProperty(type = PropertyType.ICON_ID) @Nullable public String getIcon() { return icon; } @StudioProperty(name = "primary", defaultValue = "false") public boolean isPrimary() { return primary; } @Nullable public Consumer<DialogActionPerformedEvent<T>> getActionHandler() { return actionHandler; } /** * INTERNAL. * <p> * Intended to set handlers via {@code @Install} annotation. * * @param actionHandler action handler */ @Internal public void setActionHandler(Consumer<DialogActionPerformedEvent<T>> actionHandler) { this.actionHandler = actionHandler; } } }
28.777778
136
0.634653
81813b02e74f8fd54eb5799962f5af7c864cce56
1,572
/******************************************************************************* * Copyright 2017 Bstek * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package com.bstek.urule.console.repository.model; public enum PermissionType { ProjectVisible, NewVar, NewParam, NewConst, NewAction, NewRule, NewDslRule, NewDecisionTable, NewDslDecisionTable, NewRuleFlow, NewDecisionTree, DelVar, DelParam, DelConst, DelAction, DelRule, DelDslRule, DelDecisionTable, DelDslDecisionTable, DelRuleFlow, DelDecisionTree, ModVar, ModParam, ModConst, ModAction, ModRule, ModDslRule, ModDecisionTable, ModDslDecisionTable, ModRuleFlow, ModDecisionTree, InsertRow, DelRow, InsertConditionCol, ModConditionCol, DelConditionCol, InsertActionCol, ModActionCol, DelActionCol, InsertDslRow, DelDslRow, InsertDslConditionCol, ModDslConditionCol, DelDslConditionCol, InsertDslActionCol, ModDslActionCol, DelDslActionCol; private PermissionType() { } }
22.140845
80
0.693384
e53808f242f24c56cc3a915e164da8fe06490441
3,698
package seedu.address.logic.commands; import static java.util.Objects.requireNonNull; import java.util.Arrays; import java.util.function.Predicate; import javafx.collections.transformation.FilteredList; import seedu.address.commons.core.Messages; import seedu.address.commons.core.index.Index; import seedu.address.logic.commands.exceptions.CommandException; import seedu.address.logic.parser.exceptions.ParseException; import seedu.address.model.Model; import seedu.address.model.person.Name; import seedu.address.model.person.NameContainsKeywordsPredicate; import seedu.address.model.person.Person; /** * Deletes a person identified using it's displayed index from the hustle book. */ public class DeleteCommand extends Command { public static final String COMMAND_WORD = "delete"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Deletes the client identified by their name in the displayed client list.\n" + "Parameters: Name (Alphanumerical characters and spaces only)\n" + "Example: " + COMMAND_WORD + " John Doe"; public static final String MESSAGE_DELETE_PERSON_SUCCESS = "Deleted Client: %1$s"; public static final String MESSAGE_MULTIPLE_PERSON = "More than 1 client exists with that name. Please look at " + "the list below and enter the index of the client you wish to delete \n" + "Example: 1, 2, 3 ..."; private final Name targetName; private final String targetNameStr; private int index = 0; private int listSize; /** * @param targetName name of the person in the filtered person list to delete */ public DeleteCommand(Name targetName) { requireNonNull(targetName); this.targetName = targetName; this.targetNameStr = targetName.fullName; } @Override public CommandResult execute(Model model) throws CommandException { requireNonNull(model); // Copied code FilteredList<Person> lastShownList = (FilteredList<Person>) model.getFilteredPersonList(); Index targetIndex; if (index == 0) { FilteredList<Person> tempList = new FilteredList<Person>(lastShownList); String[] nameKeywords = {targetNameStr}; Predicate<Person> predicate = new NameContainsKeywordsPredicate(Arrays.asList(nameKeywords)); tempList.setPredicate(predicate); if (tempList.size() > 1) { lastShownList.setPredicate(predicate); listSize = lastShownList.size(); return new CommandResult(MESSAGE_MULTIPLE_PERSON); } targetIndex = model.getPersonListIndex(targetName); if (targetIndex.getZeroBased() >= lastShownList.size()) { throw new CommandException(Messages.MESSAGE_INVALID_PERSON_NAME); } } else { targetIndex = Index.fromOneBased(index); } Person personToDelete = lastShownList.get(targetIndex.getZeroBased()); model.deletePerson(personToDelete); return new CommandResult(String.format(MESSAGE_DELETE_PERSON_SUCCESS, personToDelete)); } public void setIndex(int index) throws ParseException { if (index <= 0 || index > listSize) { throw new ParseException(Messages.MESSAGE_INVALID_PERSON_DISPLAYED_INDEX); } this.index = index; } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof DeleteCommand // instanceof handles nulls && targetName.equals(((DeleteCommand) other).targetName)); // state check } }
38.123711
116
0.683072
0ca69d4176f0c5ffebe3509960a643e105701c60
197
public class Solution { public int lengthOfLastWord(String s) { String t = s.trim(); return t.lastIndexOf(' ') == -1 ? t.length() : t.length() - t.lastIndexOf(' ') - 1; } }
28.142857
91
0.553299
a2637f9e6df0db0f1e6ad81cb4ed020cc02f161e
1,041
package com.moonlightpixels.jrpg.legacy.dice; import java.util.LinkedList; import java.util.List; /** * Created by jgelais on 12/27/16. */ public final class Dice { private List<Rollable> rolls = new LinkedList<>(); public Dice add(final String rollDescription) { String[] numbers = rollDescription.split("[dD]"); if (numbers.length == 1) { rolls.add(new FixedRoll(Integer.parseInt(numbers[0]))); } else if (numbers.length == 2) { rolls.add(new DieRoll(Integer.parseInt(numbers[0]), Integer.parseInt(numbers[1]))); } else { throw new IllegalArgumentException( "Input must either be a fixed number or a die roll specified as {rolls}d{sidesOfDie}" ); } return this; } void add(final Rollable roll) { rolls.add(roll); } public int roll() { int result = 0; for (Rollable thisRoll : rolls) { result += thisRoll.roll(); } return result; } }
25.390244
105
0.580211
60379fed36524a3a9b6a7327b64ef5961e25e834
5,046
/** * The MIT License * Copyright (c) 2011 Kuali Mobility Team * * 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.kuali.mobility.shared; import java.util.ArrayList; import java.util.List; public class ToolFromXML { // Constants used for the Requisites field. // !!! DON'T CHANGE VALUES!!! Matches values in Tool.java. public static final int NATIVE = 1; public static final int IOS = 2; public static final int ANDROID = 4; public static final int WINDOWS_PHONE = 8; public static final int BLACKBERRY = 16; public static final int NON_NATIVE = 32; private String title; private String subtitle; private String contacts; private String keywords; private String alias; private String url; private String description; private String iconUrl; private boolean isNative; private boolean isiOS; private boolean isAndroid; private boolean isWindows; private boolean isBlackberry; private boolean isNonNative; private List<String> publishingACLS = new ArrayList(); private List<String> viewingACLS = new ArrayList(); public List<String> getPublishingACLS() { return publishingACLS; } public void setPublishingACLS(List<String> publishingACLS) { this.publishingACLS = publishingACLS; } public List<String> getViewingACLS() { return viewingACLS; } public void setViewingACLS(List<String> viewingACLS) { this.viewingACLS = viewingACLS; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getSubtitle() { return subtitle; } public void setSubtitle(String subtitle) { this.subtitle = subtitle; } public String getContacts() { return contacts; } public void setContacts(String contacts) { this.contacts = contacts; } public String getKeywords() { return keywords; } public void setKeywords(String keywords) { this.keywords = keywords; } public String getAlias() { return alias; } public void setAlias(String alias) { this.alias = alias; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getIconUrl() { return iconUrl; } public void setIconUrl(String iconUrl) { this.iconUrl = iconUrl; } public boolean isNative() { return isNative; } public void setNative(boolean isNative) { this.isNative = isNative; } public boolean isiOS() { return isiOS; } public void setIsiOS(boolean isiOS) { this.isiOS = isiOS; } public boolean isAndroid() { return isAndroid; } public void setAndroid(boolean isAndroid) { this.isAndroid = isAndroid; } public boolean isWindows() { return isWindows; } public void setWindows(boolean isWindows) { this.isWindows = isWindows; } public boolean isBlackberry() { return isBlackberry; } public void setBlackberry(boolean isBlackberry) { this.isBlackberry = isBlackberry; } public boolean isNonNative() { return isNonNative; } public void setNonNative(boolean isNonNative) { this.isNonNative = isNonNative; } public int getRequisites() { int reqs = 0; if (this.isNative()) reqs |= NATIVE; if (this.isiOS()) reqs |= IOS; if (this.isAndroid()) reqs |= ANDROID; if (this.isWindows()) reqs |= WINDOWS_PHONE; if (this.isBlackberry()) reqs |= BLACKBERRY; if (this.isNonNative()) reqs |= NON_NATIVE; return reqs; } @Override public String toString() { return "\nToolFromXML \n[title=" + title + ", \nsubtitle=" + subtitle + ", \ncontacts=" + contacts + ", \nkeywords=" + keywords + ", \nalias=" + alias + ", \nurl=" + url + ", \ndescription=" + description + ", \niconUrl=" + iconUrl + ", \nisNative=" + isNative + ", \nisiOS=" + isiOS + ", \nisAndroid=" + isAndroid + ", \nisWindows=" + isWindows + ", \nisBlackberry=" + isBlackberry + ", \nisNonNative=" + isNonNative + super.toString() + "]"; } }
23.801887
80
0.712247
ca2cf510482f756717082b6ba8b7e889900f9957
811
/** * Leetcode - divide_two_integers */ package com.leetcode.divide_two_integers; import java.util.*; import com.ciaoshen.leetcode.util.*; /** * log instance is defined in Solution interface * this is how slf4j will work in this class: * ============================================= * if (log.isDebugEnabled()) { * log.debug("a + b = {}", sum); * } * ============================================= */ class Solution1 implements Solution { public int divide(int dividend, int divisor) { if (dividend == Integer.MIN_VALUE && divisor == -1) { return Integer.MAX_VALUE; } return dividend / divisor; } public static void main(String[] args) { Solution1 solution1 = new Solution1(); System.out.println(-2 >>> 1); } }
25.34375
61
0.535142
5762cff65df0bb4bd2bfd7f23f85b13c9e66a99a
2,484
package top.lrshuai.mq.mq; import org.apache.rocketmq.client.QueryResult; import org.apache.rocketmq.client.exception.MQClientException; import org.apache.rocketmq.client.producer.*; import org.apache.rocketmq.common.message.Message; import org.apache.rocketmq.common.message.MessageExt; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.util.Map; @Component public class PlanProducer { /** * 生产者的组名 */ @Value("${apache.rocketmq.producer.producerGroup}") private String producerGroup; /** * NameServer 地址 */ @Value("${apache.rocketmq.namesrvAddr}") private String namesrvAddr; private TransactionMQProducer producer; @PostConstruct public void startProducer() { this.producer = new TransactionMQProducer(producerGroup); this.producer.setNamesrvAddr(namesrvAddr); //nameserver服务 this.producer.setCheckThreadPoolMinSize(5); // 事务回查最小并发数 this.producer.setCheckThreadPoolMaxSize(20); // 事务回查最大并发数 this.producer.setCheckRequestHoldMax(2000); // 队列数 //服务器回调Producer,检查本地事务分支成功还是失败 this.producer.setTransactionCheckListener(new TransactionCheckListener() { public LocalTransactionState checkLocalTransactionState(MessageExt msg) { System.out.println("state -- "+ new String(msg.getBody())); System.out.println("==========================================================================="); return LocalTransactionState.COMMIT_MESSAGE; } }); try { this.producer.start(); } catch (MQClientException e) { e.printStackTrace(); } } public QueryResult queryMessage(String topic, String key, int maxNum, long begin, long end) throws Exception { return this.producer.queryMessage(topic, key, maxNum, begin, end); } public LocalTransactionState check(MessageExt me){ LocalTransactionState ls = this.producer.getTransactionCheckListener().checkLocalTransactionState(me); return ls; } public void sendTransactionMessage(Message message, LocalTransactionExecuter localTransactionExecuter, Map<String, Object> transactionMapArgs) throws Exception { TransactionSendResult tsr = this.producer.sendMessageInTransaction(message, localTransactionExecuter, transactionMapArgs); System.out.println("send返回内容:" + tsr.toString()); } public void shutdown(){ Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { public void run() { producer.shutdown(); } })); System.exit(0); } }
33.12
162
0.747585
fdf0cb7a7bb607f1ba8c9f8e207b9f5f01452bad
560
package algorithm.leetcode.s1_two_sum; import java.util.HashMap; import java.util.Map; public class Solution2 { public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<>(); for(int i = 0; i<nums.length;i++){ int tmp = target - nums[i]; if(map.containsKey(tmp)){ return new int[]{map.get(tmp),i}; //存在即返回 } map.put(nums[i],i); //不存在,则加入 } throw new IllegalArgumentException("No two sum solution"); } }
28
67
0.539286
28983b2ac9baf6144d88c95593f013b27146431f
4,885
package cucumber.runtime.model; import cucumber.runtime.CucumberException; import cucumber.runtime.io.MultiLoader; import cucumber.runtime.io.Resource; import cucumber.runtime.io.ResourceLoader; import cucumber.runtime.model.CucumberFeature; import cucumber.runtime.model.FeatureBuilder; import cucumber.runtime.model.PathWithLines; import cucumber.util.Encoding; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public final class FeatureLoader { private static final Pattern RERUN_PATH_SPECIFICATION = Pattern.compile("(?m:^| |)(.*?\\.feature(?:(?::\\d+)*))"); private final ResourceLoader resourceLoader; public FeatureLoader(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } public List<CucumberFeature> load(List<String> featurePaths, PrintStream out) { final List<CucumberFeature> cucumberFeatures = load(featurePaths); if (cucumberFeatures.isEmpty()) { if (featurePaths.isEmpty()) { out.println("Got no path to feature directory or feature file"); } else { out.println(String.format("No features found at %s", featurePaths)); } } return cucumberFeatures; } public List<CucumberFeature> load(List<String> featurePaths) { final List<CucumberFeature> cucumberFeatures = new ArrayList<CucumberFeature>(); final FeatureBuilder builder = new FeatureBuilder(cucumberFeatures); for (String featurePath : featurePaths) { if (featurePath.startsWith("@")) { loadFromRerunFile(builder, resourceLoader, featurePath.substring(1)); } else { loadFromFeaturePath(builder, resourceLoader, featurePath, false); } } Collections.sort(cucumberFeatures, new CucumberFeature.CucumberFeatureUriComparator()); return cucumberFeatures; } private void loadFromRerunFile(FeatureBuilder builder, ResourceLoader resourceLoader, String rerunPath) { for (PathWithLines pathWithLines : loadRerunFile(rerunPath)) { loadFromFileSystemOrClasspath(builder, resourceLoader, pathWithLines.path); } } public List<PathWithLines> loadRerunFile(String rerunPath) { List<PathWithLines> featurePaths = new ArrayList<PathWithLines>(); Iterable<Resource> resources = resourceLoader.resources(rerunPath, null); for (Resource resource : resources) { String source = read(resource); if (!source.isEmpty()) { Matcher matcher = RERUN_PATH_SPECIFICATION.matcher(source); while (matcher.find()) { featurePaths.add(new PathWithLines(matcher.group(1))); } } } return featurePaths; } private static String read(Resource resource) { try { return Encoding.readFile(resource); } catch (IOException e) { throw new CucumberException("Failed to read resource:" + resource.getPath(), e); } } private static void loadFromFileSystemOrClasspath(FeatureBuilder builder, ResourceLoader resourceLoader, String featurePath) { try { loadFromFeaturePath(builder, resourceLoader, featurePath, false); } catch (IllegalArgumentException originalException) { if (!featurePath.startsWith(MultiLoader.CLASSPATH_SCHEME) && originalException.getMessage().contains("Not a file or directory")) { try { loadFromFeaturePath(builder, resourceLoader, MultiLoader.CLASSPATH_SCHEME + featurePath, true); } catch (IllegalArgumentException secondException) { if (secondException.getMessage().contains("No resource found for")) { throw new IllegalArgumentException("Neither found on file system or on classpath: " + originalException.getMessage() + ", " + secondException.getMessage()); } else { throw secondException; } } } else { throw originalException; } } } private static void loadFromFeaturePath(FeatureBuilder builder, ResourceLoader resourceLoader, String featurePath, boolean failOnNoResource) { Iterable<Resource> resources = resourceLoader.resources(featurePath, ".feature"); if (failOnNoResource && !resources.iterator().hasNext()) { throw new IllegalArgumentException("No resource found for: " + featurePath); } for (Resource resource : resources) { builder.parse(resource); } } }
41.752137
146
0.650972