text
stringlengths
7
1.01M
/******************************************************************************* * 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.uflo.model.task.reminder; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.Id; import javax.persistence.Table; /** * @author Jacky.gao * @since 2013年8月20日 */ @Entity @Table(name="UFLO_TASK_REMINDER") public class TaskReminder { @Id @Column(name="ID_") private long id; @Column(name="TASK_ID_") private long taskId; @Column(name="PROCESS_ID_") private long processId; @Column(name="CRON_",length=60) private String cron; @Column(name="TASK_NODE_NAME_",length=60) private String taskNodeName; @Column(name="REMINDER_HANDLER_BEAN_",length=120) private String reminderHandlerBean; @Column(name="REMINDER_TYPE_",length=20) @Enumerated(EnumType.STRING) private ReminderType type; @Column(name="START_DATE_") private Date startDate; public long getId() { return id; } public void setId(long id) { this.id = id; } public long getTaskId() { return taskId; } public void setTaskId(long taskId) { this.taskId = taskId; } public String getCron() { return cron; } public void setCron(String cron) { this.cron = cron; } public long getProcessId() { return processId; } public void setProcessId(long processId) { this.processId = processId; } public String getTaskNodeName() { return taskNodeName; } public void setTaskNodeName(String taskNodeName) { this.taskNodeName = taskNodeName; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public ReminderType getType() { return type; } public void setType(ReminderType type) { this.type = type; } public String getReminderHandlerBean() { return reminderHandlerBean; } public void setReminderHandlerBean(String reminderHandlerBean) { this.reminderHandlerBean = reminderHandlerBean; } }
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2013 by Pentaho : http://www.pentaho.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.pentaho.di.core.encryption; import java.security.KeyPair; import java.util.Arrays; import org.junit.Test; import java.security.Key; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; import static org.junit.Assert.fail; public class CertificateGenEncryptUtilTest { private String pattern = "Test string \u2020"; @Test public void testPublicPrivate() { byte[] pat = pattern.getBytes(); KeyPair kp = CertificateGenEncryptUtil.generateKeyPair(); byte [] encr = CertificateGenEncryptUtil.encryptUsingKey( pat, kp.getPublic() ); byte [] decr = CertificateGenEncryptUtil.decryptUsingKey( encr, kp.getPrivate() ); assertTrue( Arrays.equals( pat, decr ) ); } @Test public void testPrivatePublic() { byte[] pat = pattern.getBytes(); KeyPair kp = CertificateGenEncryptUtil.generateKeyPair(); byte [] encr = CertificateGenEncryptUtil.encryptUsingKey( pat, kp.getPrivate() ); byte [] decr = CertificateGenEncryptUtil.decryptUsingKey( encr, kp.getPublic() ); assertTrue( Arrays.equals( pat, decr ) ); } @Test public void testPrivateAnotherPublic() { byte[] pat = pattern.getBytes(); KeyPair kp = CertificateGenEncryptUtil.generateKeyPair(); byte [] encr = CertificateGenEncryptUtil.encryptUsingKey( pat, kp.getPrivate() ); KeyPair kp1 = CertificateGenEncryptUtil.generateKeyPair(); try { byte [] decr = CertificateGenEncryptUtil.decryptUsingKey( encr, kp1.getPublic() ); assertFalse( Arrays.equals( encr, decr ) ); fail(); } catch ( Exception ex ) { ex.printStackTrace(); } byte [] decr = CertificateGenEncryptUtil.decryptUsingKey( encr, kp.getPublic() ); assertTrue( Arrays.equals( pat, decr ) ); } @Test public void testPublicPublic() { byte[] pat = pattern.getBytes(); try { KeyPair kp = CertificateGenEncryptUtil.generateKeyPair(); byte [] encr = CertificateGenEncryptUtil.encryptUsingKey( pat, kp.getPublic() ); byte [] decr = CertificateGenEncryptUtil.decryptUsingKey( encr, kp.getPublic() ); assertFalse( Arrays.equals( encr, decr ) ); fail(); } catch ( Exception ex ) { ex.printStackTrace(); } } @Test public void testPrivatePrivate() { byte[] pat = pattern.getBytes(); try { KeyPair kp = CertificateGenEncryptUtil.generateKeyPair(); byte [] encr = CertificateGenEncryptUtil.encryptUsingKey( pat, kp.getPrivate() ); byte [] decr = CertificateGenEncryptUtil.decryptUsingKey( encr, kp.getPrivate() ); assertFalse( Arrays.equals( encr, decr ) ); fail(); } catch ( Exception ex ) { ex.printStackTrace(); } } @Test public void testRandomSessionKeyGeneration() throws Exception { Key key = CertificateGenEncryptUtil.generateSingleKey(); Key key1 = CertificateGenEncryptUtil.generateSingleKey(); assertFalse( key.equals( key1 ) ); assertFalse( Arrays.equals( key.getEncoded(), key1.getEncoded() ) ); } @Test public void testSessionKeyEncryptionDecryption() throws Exception { Key key = CertificateGenEncryptUtil.generateSingleKey(); KeyPair kp = CertificateGenEncryptUtil.generateKeyPair(); Key privateKey = kp.getPrivate(); byte[] encryptedKey = CertificateGenEncryptUtil.encodeKeyForTransmission( privateKey, key ); Key key1 = CertificateGenEncryptUtil.decodeTransmittedKey( kp.getPublic().getEncoded(), encryptedKey, false ); assertTrue( key.equals( key1 ) ); } @Test public void testSessionKeyEncryptionDecryption2() throws Exception { Key key = CertificateGenEncryptUtil.generateSingleKey(); KeyPair kp = CertificateGenEncryptUtil.generateKeyPair(); Key privateKey = kp.getPrivate(); byte[] encryptedKey = CertificateGenEncryptUtil.encodeKeyForTransmission( kp.getPublic(), key ); Key key1 = CertificateGenEncryptUtil.decodeTransmittedKey( privateKey.getEncoded(), encryptedKey, true ); assertTrue( key.equals( key1 ) ); } @Test public void testImproperSessionKeyEncryptionDecryption() { try { Key key = CertificateGenEncryptUtil.generateSingleKey(); KeyPair kp = CertificateGenEncryptUtil.generateKeyPair(); Key privateKey = kp.getPrivate(); byte[] encryptedKey = CertificateGenEncryptUtil.encodeKeyForTransmission( kp.getPublic(), key ); CertificateGenEncryptUtil.decodeTransmittedKey( privateKey.getEncoded(), encryptedKey, false ); fail(); } catch ( Exception ex ) { ex.printStackTrace(); } } @Test public void testImproperSessionKeyEncryptionDecryption2() throws Exception { try { Key key = CertificateGenEncryptUtil.generateSingleKey(); KeyPair kp = CertificateGenEncryptUtil.generateKeyPair(); Key privateKey = kp.getPrivate(); byte[] encryptedKey = CertificateGenEncryptUtil.encodeKeyForTransmission( privateKey, key ); CertificateGenEncryptUtil.decodeTransmittedKey( kp.getPublic().getEncoded(), encryptedKey, true ); fail(); } catch ( Exception ex ) { ex.printStackTrace(); } } @Test public void testImproperSessionKeyEncryptionDecryption3() { try { Key key = CertificateGenEncryptUtil.generateSingleKey(); KeyPair kp = CertificateGenEncryptUtil.generateKeyPair(); Key privateKey = kp.getPrivate(); byte[] encryptedKey = CertificateGenEncryptUtil.encodeKeyForTransmission( kp.getPublic(), key ); byte[] encryptedKey1 = new byte[encryptedKey.length]; System.arraycopy( encryptedKey, 0, encryptedKey1, 0, encryptedKey.length ); encryptedKey1[encryptedKey1.length - 1] = (byte) ( encryptedKey1[encryptedKey1.length - 1] - 1 ); encryptedKey = encryptedKey1; CertificateGenEncryptUtil.decodeTransmittedKey( privateKey.getEncoded(), encryptedKey, true ); fail(); } catch ( Exception ex ) { ex.printStackTrace(); } } @Test public void testImproperSessionKeyEncryptionDecryption4() throws Exception { try { Key key = CertificateGenEncryptUtil.generateSingleKey(); KeyPair kp = CertificateGenEncryptUtil.generateKeyPair(); Key privateKey = kp.getPrivate(); byte[] encryptedKey = CertificateGenEncryptUtil.encodeKeyForTransmission( privateKey, key ); byte[] encryptedKey1 = new byte[encryptedKey.length]; System.arraycopy( encryptedKey, 0, encryptedKey1, 0, encryptedKey.length ); encryptedKey1[encryptedKey1.length - 1] = (byte) ( encryptedKey1[encryptedKey1.length - 1] - 1 ); encryptedKey = encryptedKey1; CertificateGenEncryptUtil.decodeTransmittedKey( kp.getPublic().getEncoded(), encryptedKey, false ); fail(); } catch ( Exception ex ) { ex.printStackTrace(); } } @Test public void testImproperSessionKeyEncryptionDecryption5() { try { Key key = CertificateGenEncryptUtil.generateSingleKey(); KeyPair kp = CertificateGenEncryptUtil.generateKeyPair(); Key privateKey = kp.getPrivate(); byte[] encryptedKey = CertificateGenEncryptUtil.encodeKeyForTransmission( kp.getPublic(), key ); byte[] encryptedKey1 = new byte[privateKey.getEncoded().length]; System.arraycopy( privateKey.getEncoded(), 0, encryptedKey1, 0, privateKey.getEncoded().length ); encryptedKey1[encryptedKey1.length - 1] = (byte) ( encryptedKey1[encryptedKey1.length - 1] - 1 ); CertificateGenEncryptUtil.decodeTransmittedKey( encryptedKey1, encryptedKey, true ); fail(); } catch ( Exception ex ) { ex.printStackTrace(); } } @Test public void testImproperSessionKeyEncryptionDecryption6() throws Exception { try { Key key = CertificateGenEncryptUtil.generateSingleKey(); KeyPair kp = CertificateGenEncryptUtil.generateKeyPair(); Key privateKey = kp.getPrivate(); byte[] encryptedKey = CertificateGenEncryptUtil.encodeKeyForTransmission( privateKey, key ); byte[] encryptedKey1 = new byte[kp.getPublic().getEncoded().length]; System.arraycopy( kp.getPublic().getEncoded(), 0, encryptedKey1, 0, kp.getPublic().getEncoded().length ); encryptedKey1[encryptedKey1.length - 1] = (byte) ( encryptedKey1[encryptedKey1.length - 1] - 1 ); CertificateGenEncryptUtil.decodeTransmittedKey( encryptedKey1, encryptedKey, false ); fail(); } catch ( Exception ex ) { ex.printStackTrace(); } } }
/* * 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.geode.internal.cache.tier.sockets.command; import java.io.IOException; import java.util.HashSet; import java.util.NoSuchElementException; import java.util.Set; import org.apache.geode.cache.Region; import org.apache.geode.cache.execute.Function; import org.apache.geode.cache.execute.FunctionException; import org.apache.geode.cache.execute.FunctionInvocationTargetException; import org.apache.geode.cache.execute.FunctionService; import org.apache.geode.cache.operations.ExecuteFunctionOperationContext; import org.apache.geode.internal.Version; import org.apache.geode.internal.cache.GemFireCacheImpl; import org.apache.geode.internal.cache.PartitionedRegion; import org.apache.geode.internal.cache.execute.AbstractExecution; import org.apache.geode.internal.cache.execute.InternalFunctionInvocationTargetException; import org.apache.geode.internal.cache.execute.MemberMappedArgument; import org.apache.geode.internal.cache.execute.PartitionedRegionFunctionExecutor; import org.apache.geode.internal.cache.execute.ServerToClientFunctionResultSender; import org.apache.geode.internal.cache.execute.ServerToClientFunctionResultSender65; import org.apache.geode.internal.cache.tier.CachedRegionHelper; import org.apache.geode.internal.cache.tier.Command; import org.apache.geode.internal.cache.tier.MessageType; import org.apache.geode.internal.cache.tier.sockets.BaseCommand; import org.apache.geode.internal.cache.tier.sockets.ChunkedMessage; import org.apache.geode.internal.cache.tier.sockets.HandShake; import org.apache.geode.internal.cache.tier.sockets.Message; import org.apache.geode.internal.cache.tier.sockets.Part; import org.apache.geode.internal.cache.tier.sockets.ServerConnection; import org.apache.geode.internal.i18n.LocalizedStrings; import org.apache.geode.internal.logging.log4j.LocalizedMessage; import org.apache.geode.internal.security.AuthorizeRequest; /** * @since GemFire 6.5 */ public class ExecuteRegionFunctionSingleHop extends BaseCommand { private final static ExecuteRegionFunctionSingleHop singleton = new ExecuteRegionFunctionSingleHop(); public static Command getCommand() { return singleton; } private ExecuteRegionFunctionSingleHop() {} @Override public void cmdExecute(Message msg, ServerConnection servConn, long start) throws IOException { String regionName = null; Object function = null; Object args = null; MemberMappedArgument memberMappedArg = null; byte isExecuteOnAllBuckets = 0; Set<Object> filter = null; Set<Integer> buckets = null; byte hasResult = 0; byte functionState = 0; int removedNodesSize = 0; Set<Object> removedNodesSet = null; int filterSize = 0, bucketIdsSize = 0, partNumber = 0; CachedRegionHelper crHelper = servConn.getCachedRegionHelper(); int functionTimeout = GemFireCacheImpl.DEFAULT_CLIENT_FUNCTION_TIMEOUT; try { byte[] bytes = msg.getPart(0).getSerializedForm(); functionState = bytes[0]; if (bytes.length >= 5 && servConn.getClientVersion().ordinal() >= Version.GFE_8009.ordinal()) { functionTimeout = Part.decodeInt(bytes, 1); } if (functionState != 1) { hasResult = (byte) ((functionState & 2) - 1); } else { hasResult = functionState; } if (hasResult == 1) { servConn.setAsTrue(REQUIRES_RESPONSE); servConn.setAsTrue(REQUIRES_CHUNKED_RESPONSE); } regionName = msg.getPart(1).getString(); function = msg.getPart(2).getStringOrObject(); args = msg.getPart(3).getObject(); Part part = msg.getPart(4); if (part != null) { Object obj = part.getObject(); if (obj instanceof MemberMappedArgument) { memberMappedArg = (MemberMappedArgument) obj; } } isExecuteOnAllBuckets = msg.getPart(5).getSerializedForm()[0]; if (isExecuteOnAllBuckets == 1) { filter = new HashSet(); bucketIdsSize = msg.getPart(6).getInt(); if (bucketIdsSize != 0) { buckets = new HashSet<Integer>(); partNumber = 7; for (int i = 0; i < bucketIdsSize; i++) { buckets.add(msg.getPart(partNumber + i).getInt()); } } partNumber = 7 + bucketIdsSize; } else { filterSize = msg.getPart(6).getInt(); if (filterSize != 0) { filter = new HashSet<Object>(); partNumber = 7; for (int i = 0; i < filterSize; i++) { filter.add(msg.getPart(partNumber + i).getStringOrObject()); } } partNumber = 7 + filterSize; } removedNodesSize = msg.getPart(partNumber).getInt(); if (removedNodesSize != 0) { removedNodesSet = new HashSet<Object>(); partNumber = partNumber + 1; for (int i = 0; i < removedNodesSize; i++) { removedNodesSet.add(msg.getPart(partNumber + i).getStringOrObject()); } } } catch (ClassNotFoundException exception) { logger.warn(LocalizedMessage.create( LocalizedStrings.ExecuteRegionFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, function), exception); if (hasResult == 1) { writeChunkedException(msg, exception, false, servConn); servConn.setAsTrue(RESPONDED); return; } } if (function == null || regionName == null) { String message = null; if (function == null) { message = LocalizedStrings.ExecuteRegionFunction_THE_INPUT_0_FOR_THE_EXECUTE_FUNCTION_REQUEST_IS_NULL .toLocalizedString("function"); } if (regionName == null) { message = LocalizedStrings.ExecuteRegionFunction_THE_INPUT_0_FOR_THE_EXECUTE_FUNCTION_REQUEST_IS_NULL .toLocalizedString("region"); } logger.warn("{}: {}", servConn.getName(), message); sendError(hasResult, msg, message, servConn); return; } Region region = crHelper.getRegion(regionName); if (region == null) { String message = LocalizedStrings.ExecuteRegionFunction_THE_REGION_NAMED_0_WAS_NOT_FOUND_DURING_EXECUTE_FUNCTION_REQUEST .toLocalizedString(regionName); logger.warn("{}: {}", servConn.getName(), message); sendError(hasResult, msg, message, servConn); return; } HandShake handShake = (HandShake) servConn.getHandshake(); int earlierClientReadTimeout = handShake.getClientReadTimeout(); handShake.setClientReadTimeout(functionTimeout); ServerToClientFunctionResultSender resultSender = null; Function functionObject = null; try { if (function instanceof String) { functionObject = FunctionService.getFunction((String) function); if (functionObject == null) { String message = LocalizedStrings.ExecuteRegionFunction_THE_FUNCTION_0_HAS_NOT_BEEN_REGISTERED .toLocalizedString(function); logger.warn("{}: {}", servConn.getName(), message); sendError(hasResult, msg, message, servConn); return; } else { byte functionStateOnServer = AbstractExecution.getFunctionState(functionObject.isHA(), functionObject.hasResult(), functionObject.optimizeForWrite()); if (functionStateOnServer != functionState) { String message = LocalizedStrings.FunctionService_FUNCTION_ATTRIBUTE_MISMATCH_CLIENT_SERVER .toLocalizedString(function); logger.warn("{}: {}", servConn.getName(), message); sendError(hasResult, msg, message, servConn); return; } } } else { functionObject = (Function) function; } this.securityService.authorizeDataWrite(); // check if the caller is authorized to do this operation on server AuthorizeRequest authzRequest = servConn.getAuthzRequest(); final String functionName = functionObject.getId(); final String regionPath = region.getFullPath(); ExecuteFunctionOperationContext executeContext = null; if (authzRequest != null) { executeContext = authzRequest.executeFunctionAuthorize(functionName, regionPath, filter, args, functionObject.optimizeForWrite()); } // Construct execution AbstractExecution execution = (AbstractExecution) FunctionService.onRegion(region); ChunkedMessage m = servConn.getFunctionResponseMessage(); m.setTransactionId(msg.getTransactionId()); resultSender = new ServerToClientFunctionResultSender65(m, MessageType.EXECUTE_REGION_FUNCTION_RESULT, servConn, functionObject, executeContext); if (isExecuteOnAllBuckets == 1) { PartitionedRegion pr = (PartitionedRegion) region; Set<Integer> actualBucketSet = pr.getRegionAdvisor().getBucketSet(); try { buckets.retainAll(actualBucketSet); } catch (NoSuchElementException done) { } if (buckets.isEmpty()) { throw new FunctionException("Buckets are null"); } execution = new PartitionedRegionFunctionExecutor((PartitionedRegion) region, buckets, args, memberMappedArg, resultSender, removedNodesSet, true, true); } else { execution = new PartitionedRegionFunctionExecutor((PartitionedRegion) region, filter, args, memberMappedArg, resultSender, removedNodesSet, false, true); } if ((hasResult == 1) && filter != null && filter.size() == 1) { ServerConnection.executeFunctionOnLocalNodeOnly((byte) 1); } if (logger.isDebugEnabled()) { logger.debug("Executing Function: {} on Server: {} with Execution: {}", functionObject.getId(), servConn, execution); } if (hasResult == 1) { if (function instanceof String) { switch (functionState) { case AbstractExecution.NO_HA_HASRESULT_NO_OPTIMIZEFORWRITE: execution.execute((String) function, true, false, false).getResult(); break; case AbstractExecution.HA_HASRESULT_NO_OPTIMIZEFORWRITE: execution.execute((String) function, true, true, false).getResult(); break; case AbstractExecution.HA_HASRESULT_OPTIMIZEFORWRITE: execution.execute((String) function, true, true, true).getResult(); break; case AbstractExecution.NO_HA_HASRESULT_OPTIMIZEFORWRITE: execution.execute((String) function, true, false, true).getResult(); break; } } else { execution.execute(functionObject).getResult(); } } else { if (function instanceof String) { switch (functionState) { case AbstractExecution.NO_HA_NO_HASRESULT_NO_OPTIMIZEFORWRITE: execution.execute((String) function, false, false, false); break; case AbstractExecution.NO_HA_NO_HASRESULT_OPTIMIZEFORWRITE: execution.execute((String) function, false, false, true); break; } } else { execution.execute(functionObject); } } } catch (IOException ioe) { logger.warn(LocalizedMessage.create( LocalizedStrings.ExecuteRegionFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, function), ioe); final String message = LocalizedStrings.ExecuteRegionFunction_SERVER_COULD_NOT_SEND_THE_REPLY .toLocalizedString(); sendException(hasResult, msg, message, servConn, ioe); } catch (FunctionException fe) { String message = fe.getMessage(); if (fe.getCause() instanceof FunctionInvocationTargetException) { if (functionObject.isHA() && logger.isDebugEnabled()) { logger.debug("Exception on server while executing function: {}: {}", function, message); } else if (logger.isDebugEnabled()) { logger.debug("Exception on server while executing function: {}: {}", function, message, fe); } synchronized (msg) { resultSender.setException(fe); } } else { logger.warn(LocalizedMessage.create( LocalizedStrings.ExecuteRegionFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, function), fe); sendException(hasResult, msg, message, servConn, fe); } } catch (Exception e) { logger.warn(LocalizedMessage.create( LocalizedStrings.ExecuteRegionFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, function), e); String message = e.getMessage(); sendException(hasResult, msg, message, servConn, e); } finally { handShake.setClientReadTimeout(earlierClientReadTimeout); ServerConnection.executeFunctionOnLocalNodeOnly((byte) 0); } } private void sendException(byte hasResult, Message msg, String message, ServerConnection servConn, Throwable e) throws IOException { synchronized (msg) { if (hasResult == 1) { writeFunctionResponseException(msg, MessageType.EXCEPTION, message, servConn, e); servConn.setAsTrue(RESPONDED); } } } private void sendError(byte hasResult, Message msg, String message, ServerConnection servConn) throws IOException { synchronized (msg) { if (hasResult == 1) { writeFunctionResponseError(msg, MessageType.EXECUTE_REGION_FUNCTION_ERROR, message, servConn); servConn.setAsTrue(RESPONDED); } } } protected static void writeFunctionResponseException(Message origMsg, int messageType, String message, ServerConnection servConn, Throwable e) throws IOException { ChunkedMessage functionResponseMsg = servConn.getFunctionResponseMessage(); ChunkedMessage chunkedResponseMsg = servConn.getChunkedResponseMessage(); int numParts = 0; if (functionResponseMsg.headerHasBeenSent()) { if (e instanceof FunctionException && e.getCause() instanceof InternalFunctionInvocationTargetException) { functionResponseMsg.setNumberOfParts(3); functionResponseMsg.addObjPart(e); functionResponseMsg.addStringPart(BaseCommand.getExceptionTrace(e)); InternalFunctionInvocationTargetException fe = (InternalFunctionInvocationTargetException) e.getCause(); functionResponseMsg.addObjPart(fe.getFailedNodeSet()); numParts = 3; } else { functionResponseMsg.setNumberOfParts(2); functionResponseMsg.addObjPart(e); functionResponseMsg.addStringPart(BaseCommand.getExceptionTrace(e)); numParts = 2; } if (logger.isDebugEnabled()) { logger.debug("{}: Sending exception chunk while reply in progress: ", servConn.getName(), e); } functionResponseMsg.setServerConnection(servConn); functionResponseMsg.setLastChunkAndNumParts(true, numParts); functionResponseMsg.sendChunk(servConn); } else { chunkedResponseMsg.setMessageType(messageType); chunkedResponseMsg.setTransactionId(origMsg.getTransactionId()); chunkedResponseMsg.sendHeader(); if (e instanceof FunctionException && e.getCause() instanceof InternalFunctionInvocationTargetException) { chunkedResponseMsg.setNumberOfParts(3); chunkedResponseMsg.addObjPart(e); chunkedResponseMsg.addStringPart(BaseCommand.getExceptionTrace(e)); InternalFunctionInvocationTargetException fe = (InternalFunctionInvocationTargetException) e.getCause(); chunkedResponseMsg.addObjPart(fe.getFailedNodeSet()); numParts = 3; } else { chunkedResponseMsg.setNumberOfParts(2); chunkedResponseMsg.addObjPart(e); chunkedResponseMsg.addStringPart(BaseCommand.getExceptionTrace(e)); numParts = 2; } if (logger.isDebugEnabled()) { logger.debug("{}: Sending exception chunk: ", servConn.getName(), e); } chunkedResponseMsg.setServerConnection(servConn); chunkedResponseMsg.setLastChunkAndNumParts(true, numParts); chunkedResponseMsg.sendChunk(servConn); } } }
/******************************************************************************* * Copyright (c) 1998, 2014 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.oxm.mappings.nullpolicy; import org.eclipse.persistence.core.sessions.CoreSession; import org.eclipse.persistence.internal.core.sessions.CoreAbstractSession; import org.eclipse.persistence.internal.oxm.Constants; import org.eclipse.persistence.internal.oxm.NamespaceResolver; import org.eclipse.persistence.internal.oxm.NullCapableValue; import org.eclipse.persistence.internal.oxm.XPathEngine; import org.eclipse.persistence.internal.oxm.XPathFragment; import org.eclipse.persistence.internal.oxm.XPathNode; import org.eclipse.persistence.internal.oxm.mappings.Field; import org.eclipse.persistence.internal.oxm.record.AbstractMarshalRecord; import org.eclipse.persistence.internal.oxm.record.MarshalRecord; import org.eclipse.persistence.internal.oxm.record.XMLRecord; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.Attributes; /** * PUBLIC: <b>Description</b>: This node null policy allows for the handling of * various representations of null in XML documents.<br> * <p> * <b>Null policies have 2 concrete implementations</b>: * <ul> * <li> NullPolicy (default implementation)</li> * <li> IsSetNullPolicy (keyed off isSet() state of the node)</li> * </ul> * * <table summary="" border="1"> * <tr> * <th id="c1" align="left">Unmarshal Flag</th> * <th id="c2" align="left">Description</th> * </tr> * <tr> * <td headers="c1"> isSetPerformedForAbsentNode </td> * <td headers="c2">This umarshal flag represents whether a set is done for * absent nodes only.</td> * </tr> * <tr> * <td headers="c1"> isNullRepresentedByEmptyNode </td> * <td headers="c2">If this unmarshal flag is false for empty nodes we set an * empty Object for composite mappings, otherwise we set to null.</td> * </tr> * <tr> * <td headers="c1" style="nowrap"> isNullRepresentedByXsiNil </td> * <td headers="c2">If this unmarshal flag is false for xsi:nil nodes we ignore * the xsi:nil attribute and treat as an empty node.<br> * Otherwise we set to null.</td> * </tr> * </table> * * <table summary="" border="1"> * <tr> * <th id="c3" align="left">Marshal Enum</th> * <th id="c4" align="left">XMLNullRepresentationType Description</th> * </tr> * <tr> * <td headers="c3"> XSI_NIL </td> * <td headers="c4">Nillable: Write out an xsi:nil="true" attribute.</td> * </tr> * <tr> * <td headers="c3"> ABSENT_NODE(default) </td> * <td headers="c4">Optional: Write out no node.</td> * </tr> * <tr> * <td headers="c3" style="nowrap"> EMPTY_NODE </td> * <td headers="c4">Required: Write out an empty {@literal <node/>} or node="" node.</td> * </tr> * </table> &nbsp;<b>Usage</b>:<br> * * @see org.eclipse.persistence.internal.oxm.NullCapableValue * @since Oracle TopLink 11<i>g</i> Release 1 (11.1.1) */ public abstract class AbstractNullPolicy { protected static final String TRUE = "true"; protected static final String COLON_W_SCHEMA_NIL_ATTRIBUTE = Constants.COLON + Constants.SCHEMA_NIL_ATTRIBUTE; protected static final String XSI_NIL_ATTRIBUTE = Constants.SCHEMA_INSTANCE_PREFIX + COLON_W_SCHEMA_NIL_ATTRIBUTE; /** * This state flag determines how we unmarshal absent nodes. true = * (default) Perform a set(null). false = Do not perform a set(null). */ protected boolean isSetPerformedForAbsentNode = true; /** * This state flag determines how we unmarshal empty nodes. true = Perform a * set(null) or primitive type equivalent. false = (default) Perform a * set(new Object()). */ protected boolean isNullRepresentedByEmptyNode = false; /** * This state flag determines how we unmarshal xsi:nil nodes. A set is * performed in both cases. true = Perform a set(null) or primitive type * equivalent.. false = (default) do nothing and treat as an empty node. */ protected boolean isNullRepresentedByXsiNil = false; /** * This state flag determines how we unmarshal xsi:nil nodes when there * are other attributes (other than xsi:nil) present. If false, we ignore * any attributes and treat the element as nil. If true, we inspect if * some attributes are present and if yes, we process them. */ protected boolean ignoreAttributesForNil = true; /** * This enum instance determines what to write out during a marshal * operation. We are defaulting to ABSENT_NODE */ protected XMLNullRepresentationType marshalNullRepresentation = XMLNullRepresentationType.ABSENT_NODE; /** * Get the enum that determines what XML to write when a null value is encountered. */ public XMLNullRepresentationType getMarshalNullRepresentation() { return marshalNullRepresentation; } /** * Set the enum that determines what XML to write when a null value is encountered. */ public void setMarshalNullRepresentation(XMLNullRepresentationType anEnumInstance) { marshalNullRepresentation = anEnumInstance; } /** * INTERNAL: * When using the SAX or DOM Platform, this method is responsible for * marshalling null values for the XML Direct Mapping. * * @param xPathFragment * @param marshalRecord * @param object * @param session * @param namespaceResolver * @return true if this method caused any nodes to be marshaled, else false. */ public boolean directMarshal(XPathFragment xPathFragment, MarshalRecord marshalRecord, // Object object, CoreSession session, NamespaceResolver namespaceResolver) { // Handle attributes - XSI_NIL, ABSENT_NODE have the same behavior if (xPathFragment.isAttribute()) { // Write out an empty attribute if (marshalNullRepresentation == XMLNullRepresentationType.EMPTY_NODE) { marshalRecord.emptyAttribute(xPathFragment, namespaceResolver); return true; } else { // XSI_NIL attributes are invalid - and are ignored // ABSENT_NODE - Write out nothing return false; } } else { // Nillable: write out xsi:nil="true" attribute in empty element if (marshalNullRepresentation == XMLNullRepresentationType.XSI_NIL) { marshalRecord.nilSimple(namespaceResolver); return true; } else { // EMPTY_NODE - Write out empty element if (marshalNullRepresentation == XMLNullRepresentationType.EMPTY_NODE) { marshalRecord.emptySimple(namespaceResolver); return true; } else { // ABSENT_NODE - Write out nothing return false; } } } } /** * INTERNAL: When using the SAX Platform, this method is responsible for * marshalling null values for the XML Composite Object Mapping. * * @param xPathFragment * @param marshalRecord * @param object * @param session * @param namespaceResolver * @return true if this method caused any nodes to be marshaled, else false. */ public boolean compositeObjectMarshal(XPathFragment xPathFragment, MarshalRecord marshalRecord, // Object object, CoreSession session, NamespaceResolver namespaceResolver) { if (marshalNullRepresentation == XMLNullRepresentationType.ABSENT_NODE){ return false; } // Nillable else if (marshalNullRepresentation == XMLNullRepresentationType.XSI_NIL) { marshalRecord.nilComplex(xPathFragment, namespaceResolver); return true; } else if (marshalNullRepresentation == XMLNullRepresentationType.EMPTY_NODE) { // Optional and Required // This call is really only valid when using DOM - TBD false // Write out empty element - we need to differentiate between // object=null and object=new Object() with null fields and 0-numeric primitive values // EMPTY_NODE - Write out empty element - Required marshalRecord.emptyComplex(xPathFragment, namespaceResolver); return true; } return false; } /** * INTERNAL: When using the DOM Platform, this method is responsible for * marshalling null values for the XML Composite Object Mapping. * * @param record * @param object * @param field * @return true if this method caused any objects to be marshaled, else false. */ public boolean compositeObjectMarshal(AbstractMarshalRecord record, Object object, Field field, CoreAbstractSession session) { if (marshalNullRepresentation == XMLNullRepresentationType.XSI_NIL) { record.put(field, XMLRecord.NIL); return true; } else { // EMPTY_NODE - Write out empty element - Required if (marshalNullRepresentation == XMLNullRepresentationType.EMPTY_NODE) { Node element = XPathEngine.getInstance().createUnownedElement(record.getDOM(), field); record.put(field, element); return true; } else { // ABSENT_NODE - Write out nothing - Optional return false; } } } /** * INTERNAL: When using the SAX or DOM Platform during unmarshal operations. * Use the attributes to determine if the element represents a null value. * * @param attributes * @return true if based on the attributes the corresponding element * represents a null value, else false. */ public boolean valueIsNull(Attributes attributes) { // Nillable if (isNullRepresentedByXsiNil()) { // Ignore any other attributes that are in addition to xsi:nil if(null == attributes) { return false; } return attributes.getValue(javax.xml.XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, Constants.SCHEMA_NIL_ATTRIBUTE) != null; } else { // EMPTY_NODE - Required if (isNullRepresentedByEmptyNode() && (null == attributes || attributes.getLength() == 0)) { return true; } } return false; } /** * INTERNAL: When using the DOM Platform during unmarshal operations. * Use the element to determine if the element represents a null value. * * @param element * @return true if based on the element it represents a null value, else false. */ public boolean valueIsNull(Element element) { // Check Nillable: Ignore any other attributes that are in addition to xsi:nil if (null == element) { return true; } else { if (isNullRepresentedByXsiNil() && element.hasAttributeNS(javax.xml.XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, Constants.SCHEMA_NIL_ATTRIBUTE)) { return true; } else { // EMPTY_NODE - Required // Verify no attributes and no child nodes on the DOM element if (isNullRepresentedByEmptyNode() && !element.hasAttributes() && (element.getChildNodes().getLength() == 0)) { return true; } else { return false; } } } } /** * INTERNAL: When using the SAX Platform this allows a NodeValue to be * registered to receive events from the TreeObjectBuilder. * @param xPathNode * @param nullCapableValue */ public abstract void xPathNode(XPathNode xPathNode, NullCapableValue nullCapableValue); /** * @return the isSetPerformedForAbsentNode flag */ public boolean getIsSetPerformedForAbsentNode() { return isSetPerformedForAbsentNode; } /** * * @return */ public boolean isNullRepresentedByEmptyNode() { return isNullRepresentedByEmptyNode; } /** * * @param bIsNullRepresentedByEmptyNode */ public void setNullRepresentedByEmptyNode(boolean bIsNullRepresentedByEmptyNode) { isNullRepresentedByEmptyNode = bIsNullRepresentedByEmptyNode; } /** * * @return */ public boolean isNullRepresentedByXsiNil() { return isNullRepresentedByXsiNil; } /** * * @param bIsNullRepresentedByXsiNil */ public void setNullRepresentedByXsiNil(boolean bIsNullRepresentedByXsiNil) { isNullRepresentedByXsiNil = bIsNullRepresentedByXsiNil; } /** * * @return */ public boolean ignoreAttributesForNil() { return ignoreAttributesForNil; } /** * * @param ignoreAttributesForNil */ public void setIgnoreAttributesForNil(boolean ignoreAttributesForNil) { this.ignoreAttributesForNil = ignoreAttributesForNil; } /** * INTERNAL: * Private function to process or create an entry in the NamespaceResolver for the xsi prefix. * @param namespaceResolver * @return xsi prefix */ protected String processNamespaceResolverForXSIPrefix(NamespaceResolver namespaceResolver, MarshalRecord marshalRecord) { String xsiPrefix; if (null == namespaceResolver) { // add new xsi entry into the properties map xsiPrefix = Constants.SCHEMA_INSTANCE_PREFIX; marshalRecord.namespaceDeclaration(xsiPrefix, javax.xml.XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI); } else { // find an existing xsi entry in the map xsiPrefix = namespaceResolver.resolveNamespaceURI(javax.xml.XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI); if (null == xsiPrefix) { xsiPrefix = namespaceResolver.generatePrefix(Constants.SCHEMA_INSTANCE_PREFIX); marshalRecord.namespaceDeclaration(xsiPrefix, javax.xml.XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI); } } return xsiPrefix; } /** * INTERNAL */ public void directMarshal(Field field, AbstractMarshalRecord record, Object object) { Object fieldValue = null; if(marshalNullRepresentation == XMLNullRepresentationType.EMPTY_NODE) { fieldValue = Constants.EMPTY_STRING; } else { if(!field.getLastXPathFragment().isAttribute()) { if(marshalNullRepresentation == XMLNullRepresentationType.XSI_NIL) { fieldValue = XMLRecord.NIL; } } } record.put(field, fieldValue); } }
package edu.uiuc.zenvisage.data.roaringdb.db; import java.util.HashMap; import java.util.Map; public class DatabaseMetaData { public Map<String,ColumnMetadata> xAxisColumns= new HashMap<String,ColumnMetadata>(); public Map<String,ColumnMetadata> yAxisColumns= new HashMap<String,ColumnMetadata>(); public Map<String,ColumnMetadata> zAxisColumns= new HashMap<String,ColumnMetadata>(); public Map<String,ColumnMetadata> predicateColumns= new HashMap<String,ColumnMetadata>(); public String dataset; public DatabaseMetaData() { } public Map<String, ColumnMetadata> getxAxisColumns() { return xAxisColumns; } public void setxAxisColumns(Map<String, ColumnMetadata> xAxisColumns) { this.xAxisColumns = xAxisColumns; } public Map<String, ColumnMetadata> getyAxisColumns() { return yAxisColumns; } public void setyAxisColumns(Map<String, ColumnMetadata> yAxisColumns) { this.yAxisColumns = yAxisColumns; } public Map<String, ColumnMetadata> getzAxisColumns() { return zAxisColumns; } public void setzAxisColumns(Map<String, ColumnMetadata> zAxisColumns) { this.zAxisColumns = zAxisColumns; } public Map<String, ColumnMetadata> getPredicateColumns() { return predicateColumns; } public void setPredicateColumns(Map<String, ColumnMetadata> predicateColumns) { this.predicateColumns = predicateColumns; } }
import org.junit.Test; import java.io.File; import static org.junit.Assert.assertTrue; public class TestRequiredFilesExist { // ./Docker or docker/Docker @Test public void checkDockerExists() { boolean dockerExists = new File("./docker/Dockerfile").exists() || new File("./docker/Docker").exists(); assertTrue(dockerExists); } /* // ./docker-compose.yml or ./docker/docker-compose.yml @Test public void checkDockerComposeExists() { boolean dockerComposeExists = new File("./docker-compose.yml").exists() || new File("./docker/docker-compose.yml").exists(); assertTrue(dockerComposeExists); } // ./.env_sample @Test public void checkEnvSampleExists() { assertTrue(new File("./.env_sample").exists()); } */ // ./.gitignore @Test public void checkGitIgnoreExists() { assertTrue(new File("./.gitignore").exists()); } // ./CHANGELOG.md @Test public void checkChangelogExists() { assertTrue(new File("./CHANGELOG.md").exists()); } // ./CODE_OF_CONDUCT.md @Test public void checkCodeOfConductExists() { assertTrue(new File("./CODE_OF_CONDUCT.md").exists()); } // ./CONTRIBUTING.md @Test public void checkContributingGuideExists() { assertTrue(new File("./CONTRIBUTING.md").exists()); } // ./ISSUE_TEMPLATE.md @Test public void checkIssuesTemplateExists() { assertTrue(new File("./ISSUE_TEMPLATE.md").exists()); } // ./LICENSE @Test public void checkLicenseExists() { assertTrue(new File("./LICENSE").exists()); } // ./PULL_REQUEST_TEMPLATE.md @Test public void checkPullRequestExists() { assertTrue(new File("./PULL_REQUEST_TEMPLATE.md").exists()); } // ./README.md @Test public void checkReadMeExists() { assertTrue(new File("./README.md").exists()); } // ./TROUBLESHOOTING.md @Test public void checkTroubleShootingGuideExists() { assertTrue(new File("./TROUBLESHOOTING.md").exists()); } // ./USAGE.md @Test public void checkUsageGuideExists() { assertTrue(new File("./USAGE.md").exists()); } /* // ./USE_CASES.md @Test public void checkUseCases() { assertTrue(new File("./USE_CASES.md").exists()); } */ }
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2019 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package frc.robot.commands.climber; import com.ctre.phoenix.motorcontrol.TalonFXControlMode; import com.ctre.phoenix.motorcontrol.can.TalonFX; import edu.wpi.first.wpilibj2.command.CommandBase; import frc.robot.subsystems.Climber.ClimberTalon; public class MoveClimberArm extends CommandBase { /** * Creates a new MoveClimberArm. */ private double initPos; private double targetPosition; private TalonFX arm; private double ticks; public MoveClimberArm(ClimberTalon climberTalon, double ticks, TalonFX arm) { // Use addRequirements() here to declare subsystem dependencies. this.arm = arm; this.ticks = ticks; addRequirements(climberTalon); } // Called when the command is initially scheduled. @Override public void initialize() { initPos = arm.getSelectedSensorPosition(); targetPosition = initPos + ticks; // 1 inch = 6.03 ticks arm.set(TalonFXControlMode.Position, targetPosition); //arm.getPIDController().setReference(targetPosition, ControlType.kPosition); } // Called every time the scheduler runs while the command is scheduled. @Override public void execute() { System.out.println("Actual Pos:" + this.arm.getSelectedSensorPosition()); System.out.println("Expected Pos:" + targetPosition); System.out.println("Diff " + (targetPosition - this.arm.getSelectedSensorPosition())); } // Called once the command ends or is interrupted. @Override public void end(boolean interrupted) { } // Returns true when the command should end. @Override public boolean isFinished() { return Math.abs(targetPosition - arm.getSelectedSensorPosition()) < 500; } }
package org.springframework.samples.petclinic.controller; import org.springframework.samples.petclinic.dao.PetRepository; import org.springframework.samples.petclinic.model.Pet; import org.springframework.samples.petclinic.model.Visit; import org.springframework.samples.petclinic.dao.VisitRepository; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.Map; /** * @author Juergen Hoeller * @author Ken Krebs * @author Arjen Poutsma * @author Michael Isvy * @author Dave Syer */ @Controller public class VisitController { private final VisitRepository visits; private final PetRepository pets; public VisitController(VisitRepository visits, PetRepository pets) { this.visits = visits; this.pets = pets; } @InitBinder public void setAllowedFields(WebDataBinder dataBinder) { dataBinder.setDisallowedFields("id"); } /** * Called before each and every @RequestMapping annotated method. * 2 goals: * - Make sure we always have fresh data * - Since we do not use the session scope, make sure that Pet object always has an id * (Even though id is not part of the form fields) * * @param petId * @return Pet */ @ModelAttribute("visit") public Visit loadPetWithVisit(@PathVariable("petId") int petId, Map<String, Object> model) { Pet pet = this.pets.findById(petId); model.put("pet", pet); Visit visit = new Visit(); pet.addVisit(visit); return visit; } // Spring MVC calls method loadPetWithVisit(...) before initNewVisitForm is called @GetMapping("/owners/*/pets/{petId}/visits/new") public String initNewVisitForm(@PathVariable("petId") int petId, Map<String, Object> model) { return "pets/createOrUpdateVisitForm"; } // Spring MVC calls method loadPetWithVisit(...) before processNewVisitForm is called @PostMapping("/owners/{ownerId}/pets/{petId}/visits/new") public String processNewVisitForm(@Valid Visit visit, BindingResult result) { if (result.hasErrors()) { return "pets/createOrUpdateVisitForm"; } else { this.visits.save(visit); return "redirect:/owners/{ownerId}"; } } }
package br.ucb.dao.impl; import javax.persistence.Query; import br.ucb.dao.OrganizacaoEventoDao; import br.ucb.entity.OrganizacaoEvento; public class OrganizacaoEventoDaoImpl extends DaoGenericoImpl<OrganizacaoEvento, Integer> implements OrganizacaoEventoDao{ @Override public OrganizacaoEvento buscarByIdProducao(Integer idProducaoAcademica) { Query query = getManager().createQuery(" from OrganizacaoEvento st WHERE st.producaoAcademica.idProducaoAcademica = ? "); query.setParameter(1, idProducaoAcademica); return (OrganizacaoEvento) query.getSingleResult(); } }
public class Knight extends Character{ public Knight() { super(new SwordBehavior()); } @Override public void fight() { System.out.println("Knight is for justice"); } }
/* * 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.commons.math3.ode.nonstiff; import org.apache.commons.math3.Field; import org.apache.commons.math3.RealFieldElement; import org.apache.commons.math3.ode.FieldEquationsMapper; import org.apache.commons.math3.ode.FieldODEStateAndDerivative; import org.apache.commons.math3.util.Decimal64Field; import org.junit.Test; public class DormandPrince54FieldStepInterpolatorTest extends RungeKuttaFieldStepInterpolatorAbstractTest { protected <T extends RealFieldElement<T>> RungeKuttaFieldStepInterpolator<T> createInterpolator(Field<T> field, boolean forward, T[][] yDotK, FieldODEStateAndDerivative<T> globalPreviousState, FieldODEStateAndDerivative<T> globalCurrentState, FieldODEStateAndDerivative<T> softPreviousState, FieldODEStateAndDerivative<T> softCurrentState, FieldEquationsMapper<T> mapper) { return new DormandPrince54FieldStepInterpolator<T>(field, forward, yDotK, globalPreviousState, globalCurrentState, softPreviousState, softCurrentState, mapper); } protected <T extends RealFieldElement<T>> FieldButcherArrayProvider<T> createButcherArrayProvider(final Field<T> field) { return new DormandPrince54FieldIntegrator<T>(field, 0, 1, 1, 1); } @Test public void interpolationAtBounds() { doInterpolationAtBounds(Decimal64Field.getInstance(), 1.0e-50); } @Test public void interpolationInside() { doInterpolationInside(Decimal64Field.getInstance(), 9.5e-14, 1.8e-15); } @Test public void nonFieldInterpolatorConsistency() { doNonFieldInterpolatorConsistency(Decimal64Field.getInstance(), 2.8e-17, 2.3e-16, 5.6e-16, 5.6e-17); } }
package mage.cards.o; import java.util.UUID; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.SimpleActivatedAbility; import mage.abilities.costs.common.SacrificeTargetCost; import mage.abilities.costs.common.TapSourceCost; import mage.abilities.effects.common.continuous.BoostAllEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Duration; import mage.constants.SubType; import mage.constants.Zone; import mage.filter.common.FilterControlledPermanent; import mage.filter.common.FilterCreaturePermanent; import mage.filter.predicate.Predicates; import mage.filter.predicate.mageobject.SubtypePredicate; import mage.filter.predicate.permanent.AnotherPredicate; import mage.target.common.TargetControlledPermanent; /** * * @author fireshoes */ public final class OrcGeneral extends CardImpl { private static final FilterControlledPermanent filterOrcOrGoblin = new FilterControlledPermanent("another Orc or Goblin"); private static final FilterCreaturePermanent filterOrc = new FilterCreaturePermanent("Other Orc creatures"); static { filterOrcOrGoblin.add(Predicates.or(new SubtypePredicate(SubType.ORC), new SubtypePredicate(SubType.GOBLIN))); filterOrcOrGoblin.add(AnotherPredicate.instance); filterOrc.add(new SubtypePredicate(SubType.ORC)); } public OrcGeneral(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{2}{R}"); this.subtype.add(SubType.ORC); this.subtype.add(SubType.WARRIOR); this.power = new MageInt(2); this.toughness = new MageInt(2); // {tap}, Sacrifice another Orc or Goblin: Other Orc creatures get +1/+1 until end of turn. Ability ability = new SimpleActivatedAbility(Zone.BATTLEFIELD, new BoostAllEffect(1, 1, Duration.EndOfTurn, filterOrc, true), new TapSourceCost()); ability.addCost(new SacrificeTargetCost(new TargetControlledPermanent(filterOrcOrGoblin))); this.addAbility(ability); } public OrcGeneral(final OrcGeneral card) { super(card); } @Override public OrcGeneral copy() { return new OrcGeneral(this); } }
/* * Copyright (C) 2008 ZXing 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 com.google.zxing.client.android.share; import android.app.ListActivity; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.provider.Browser; import android.util.Log; import android.view.View; import android.widget.ListView; /** * This class is only needed because I can't successfully send an ACTION_PICK intent to * com.android.browser.BrowserBookmarksPage. It can go away if that starts working in the future. * * @author dswitkin@google.com (Daniel Switkin) */ public final class BookmarkPickerActivity extends ListActivity { private static final String TAG = BookmarkPickerActivity.class.getSimpleName(); private static final String[] BOOKMARK_PROJECTION = { Browser.BookmarkColumns.TITLE, Browser.BookmarkColumns.URL }; static final int TITLE_COLUMN = 0; static final int URL_COLUMN = 1; private static final String BOOKMARK_SELECTION = Browser.BookmarkColumns.BOOKMARK + " = 1 AND " + Browser.BookmarkColumns.URL + " IS NOT NULL"; private Cursor cursor; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); cursor = getContentResolver().query(Browser.BOOKMARKS_URI, BOOKMARK_PROJECTION, BOOKMARK_SELECTION, null, null); if (cursor == null) { Log.w(TAG, "No cursor returned for bookmark query"); finish(); return; } setListAdapter(new BookmarkAdapter(this, cursor)); } @Override protected void onDestroy() { if (cursor != null) { cursor.close(); } super.onDestroy(); } @Override protected void onListItemClick(ListView l, View view, int position, long id) { if (!cursor.isClosed() && cursor.moveToPosition(position)) { Intent intent = new Intent(); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); intent.putExtra(Browser.BookmarkColumns.TITLE, cursor.getString(TITLE_COLUMN)); intent.putExtra(Browser.BookmarkColumns.URL, cursor.getString(URL_COLUMN)); setResult(RESULT_OK, intent); } else { setResult(RESULT_CANCELED); } finish(); } }
package org.wso2.carbon.identity.application.common.model; public enum ProvisioningServiceProviderType { OAUTH }
package cn.bravedawn.latte.ec.main.index.search; /** * Created by 冯晓 on 2017/10/2. */ public class SearchItemType { static final int ITEM_SEARCH = 50; }
/* 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.batik.bridge; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import org.apache.batik.gvt.font.GVTFontFamily; import org.apache.batik.gvt.font.GVTFontFace; import org.apache.batik.gvt.font.UnresolvedFontFamily; import org.apache.batik.util.SVGConstants; import org.apache.batik.anim.dom.SVGOMDocument; import org.apache.batik.css.engine.CSSEngine; import org.apache.batik.css.engine.FontFaceRule; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; /** * Utility class for SVG fonts. * * @author <a href="mailto:bella.robinson@cmis.csiro.au">Bella Robinson</a> * @version $Id: SVGFontUtilities.java 1804130 2017-08-04 14:41:11Z ssteiner $ */ public abstract class SVGFontUtilities implements SVGConstants { public static List getFontFaces(Document doc, BridgeContext ctx) { // check fontFamilyMap to see if we have already created an // FontFamily that matches Map fontFamilyMap = ctx.getFontFamilyMap(); List ret = (List)fontFamilyMap.get(doc); if (ret != null) return ret; ret = new LinkedList(); NodeList fontFaceElements = doc.getElementsByTagNameNS (SVG_NAMESPACE_URI, SVG_FONT_FACE_TAG); SVGFontFaceElementBridge fontFaceBridge; fontFaceBridge = (SVGFontFaceElementBridge)ctx.getBridge (SVG_NAMESPACE_URI, SVG_FONT_FACE_TAG); for (int i = 0; i < fontFaceElements.getLength(); i++) { Element fontFaceElement = (Element)fontFaceElements.item(i); ret.add(fontFaceBridge.createFontFace (ctx, fontFaceElement)); } CSSEngine engine = ((SVGOMDocument)doc).getCSSEngine(); List sms = engine.getFontFaces(); for (Object sm : sms) { FontFaceRule ffr = (FontFaceRule) sm; ret.add(CSSFontFace.createCSSFontFace(engine, ffr)); } return ret; } /** * Given a font family name tries to find a matching SVG font * object. If finds one, returns an SVGFontFamily otherwise * returns an UnresolvedFontFamily. * * @param textElement The text element that the font family will * be attached to. * @param ctx The bridge context, used to search for a matching * SVG font element. * @param fontFamilyName The name of the font family to search * for. * @param fontWeight The weight of the font to use when trying to * match an SVG font family. * @param fontStyle The style of the font to use when trying to * match as SVG font family. * * @return A GVTFontFamily for the specified font attributes. This * will be unresolved unless a matching SVG font was found. */ public static GVTFontFamily getFontFamily(Element textElement, BridgeContext ctx, String fontFamilyName, String fontWeight, String fontStyle) { // TODO: should match against font-variant as well String fontKeyName = fontFamilyName.toLowerCase() + " " + // todo locale?? fontWeight + " " + fontStyle; // check fontFamilyMap to see if we have already created an // FontFamily that matches Map fontFamilyMap = ctx.getFontFamilyMap(); GVTFontFamily fontFamily = (GVTFontFamily)fontFamilyMap.get(fontKeyName); if (fontFamily != null) { return fontFamily; } // try to find a matching SVGFontFace element Document doc = textElement.getOwnerDocument(); List fontFaces = (List)fontFamilyMap.get(doc); if (fontFaces == null) { fontFaces = getFontFaces(doc, ctx); fontFamilyMap.put(doc, fontFaces); } Iterator iter = fontFaces.iterator(); List svgFontFamilies = new LinkedList(); while (iter.hasNext()) { FontFace fontFace = (FontFace)iter.next(); if (!fontFace.hasFamilyName(fontFamilyName)) { continue; } String fontFaceStyle = fontFace.getFontStyle(); if (fontFaceStyle.equals(SVG_ALL_VALUE) || fontFaceStyle.indexOf(fontStyle) != -1) { GVTFontFamily ffam = fontFace.getFontFamily(ctx); if (ffam != null) svgFontFamilies.add(ffam); } } if (svgFontFamilies.size() == 1) { // only found one matching svg font family fontFamilyMap.put(fontKeyName, svgFontFamilies.get(0)); return (GVTFontFamily)svgFontFamilies.get(0); } else if (svgFontFamilies.size() > 1) { // need to find font face that matches the font-weight closest String fontWeightNumber = getFontWeightNumberString(fontWeight); // create lists of font weight numbers for each font family List fontFamilyWeights = new ArrayList(svgFontFamilies.size()); for (Object svgFontFamily : svgFontFamilies) { GVTFontFace fontFace; fontFace = ((GVTFontFamily) svgFontFamily).getFontFace(); String fontFaceWeight = fontFace.getFontWeight(); fontFaceWeight = getFontWeightNumberString(fontFaceWeight); fontFamilyWeights.add(fontFaceWeight); } // make sure that each possible font-weight has been // assigned to a font-face, if not then need to "fill the // holes" List newFontFamilyWeights = new ArrayList(fontFamilyWeights); for (int i = 100; i <= 900; i+= 100) { String weightString = String.valueOf(i); boolean matched = false; int minDifference = 1000; int minDifferenceIndex = 0; for (int j = 0; j < fontFamilyWeights.size(); j++) { String fontFamilyWeight = (String)fontFamilyWeights.get(j); if (fontFamilyWeight.indexOf(weightString) > -1) { matched = true; break; } StringTokenizer st = new StringTokenizer(fontFamilyWeight, " ,"); while (st.hasMoreTokens()) { int weightNum = Integer.parseInt(st.nextToken()); int difference = Math.abs(weightNum - i); if (difference < minDifference) { minDifference = difference; minDifferenceIndex = j; } } } if (!matched) { String newFontFamilyWeight = newFontFamilyWeights.get(minDifferenceIndex) + ", " + weightString; newFontFamilyWeights.set(minDifferenceIndex, newFontFamilyWeight); } } // now find matching font weight for (int i = 0; i < svgFontFamilies.size(); i++) { String fontFaceWeight = (String)newFontFamilyWeights.get(i); if (fontFaceWeight.indexOf(fontWeightNumber) > -1) { fontFamilyMap.put(fontKeyName, svgFontFamilies.get(i)); return (GVTFontFamily)svgFontFamilies.get(i); } } // should not get here, just return the first svg font family fontFamilyMap.put(fontKeyName, svgFontFamilies.get(0)); return (GVTFontFamily) svgFontFamilies.get(0); } else { // couldn't find one so return an UnresolvedFontFamily object GVTFontFamily gvtFontFamily = new UnresolvedFontFamily(fontFamilyName); fontFamilyMap.put(fontKeyName, gvtFontFamily); return gvtFontFamily; } } /** * Returns a string that contains all of the font weight numbers for the * specified font weight attribute value. * * @param fontWeight The font-weight attribute value. * * @return The font weight expressed as font weight numbers. * e.g. "normal" becomes "400". */ protected static String getFontWeightNumberString(String fontWeight) { if (fontWeight.equals(SVG_NORMAL_VALUE)) { return SVG_400_VALUE; } else if (fontWeight.equals(SVG_BOLD_VALUE)) { return SVG_700_VALUE; } else if (fontWeight.equals(SVG_ALL_VALUE)) { return "100, 200, 300, 400, 500, 600, 700, 800, 900"; } return fontWeight; } }
/* * Copyright 2012-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.autoconfigure.security.servlet; import javax.servlet.DispatcherType; import org.assertj.core.api.InstanceOfAssertFactories; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.TestAutoConfigurationPackage; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; import org.springframework.boot.autoconfigure.orm.jpa.test.City; import org.springframework.boot.test.context.FilteredClassLoader; import org.springframework.boot.test.context.runner.WebApplicationContextRunner; import org.springframework.boot.web.servlet.DelegatingFilterProxyRegistrationBean; import org.springframework.boot.web.servlet.filter.OrderedFilter; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.security.authentication.AuthenticationEventPublisher; import org.springframework.security.authentication.DefaultAuthenticationEventPublisher; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.data.repository.query.SecurityEvaluationContextExtension; import org.springframework.security.web.FilterChainProxy; import org.springframework.security.web.SecurityFilterChain; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link SecurityAutoConfiguration}. * * @author Dave Syer * @author Rob Winch * @author Andy Wilkinson * @author Madhura Bhave */ class SecurityAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner().withConfiguration( AutoConfigurations.of(SecurityAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class)); @Test void testWebConfiguration() { this.contextRunner.run((context) -> { assertThat(context.getBean(AuthenticationManagerBuilder.class)).isNotNull(); assertThat(context.getBean(FilterChainProxy.class).getFilterChains()).hasSize(1); }); } @Test void enableWebSecurityIsConditionalOnClass() { this.contextRunner.withClassLoader(new FilteredClassLoader("org.springframework.security.config")) .run((context) -> assertThat(context).doesNotHaveBean("springSecurityFilterChain")); } @Test void securityConfigurerBacksOffWhenOtherSecurityFilterChainBeanPresent() { this.contextRunner.withUserConfiguration(TestSecurityFilterChainConfig.class).run((context) -> { assertThat(context.getBeansOfType(SecurityFilterChain.class).size()).isEqualTo(1); assertThat(context.containsBean("testSecurityFilterChain")).isTrue(); }); } @Test void securityConfigurerBacksOffWhenOtherWebSecurityAdapterBeanPresent() { this.contextRunner.withUserConfiguration(WebSecurity.class).run((context) -> { assertThat(context.getBeansOfType(WebSecurityConfigurerAdapter.class).size()).isEqualTo(1); assertThat(context.containsBean("securityAutoConfigurationTests.WebSecurity")).isTrue(); }); } @Test void testDefaultFilterOrderWithSecurityAdapter() { this.contextRunner .withConfiguration(AutoConfigurations.of(WebSecurity.class, SecurityFilterAutoConfiguration.class)) .run((context) -> assertThat( context.getBean("securityFilterChainRegistration", DelegatingFilterProxyRegistrationBean.class) .getOrder()).isEqualTo(OrderedFilter.REQUEST_WRAPPER_FILTER_MAX_ORDER - 100)); } @Test void testFilterIsNotRegisteredInNonWeb() { try (AnnotationConfigApplicationContext customContext = new AnnotationConfigApplicationContext()) { customContext.register(SecurityAutoConfiguration.class, SecurityFilterAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); customContext.refresh(); assertThat(customContext.containsBean("securityFilterChainRegistration")).isFalse(); } } @Test void defaultAuthenticationEventPublisherRegistered() { this.contextRunner.run((context) -> assertThat(context.getBean(AuthenticationEventPublisher.class)) .isInstanceOf(DefaultAuthenticationEventPublisher.class)); } @Test void defaultAuthenticationEventPublisherIsConditionalOnMissingBean() { this.contextRunner.withUserConfiguration(AuthenticationEventPublisherConfiguration.class) .run((context) -> assertThat(context.getBean(AuthenticationEventPublisher.class)).isInstanceOf( AuthenticationEventPublisherConfiguration.TestAuthenticationEventPublisher.class)); } @Test void testDefaultFilterOrder() { this.contextRunner.withConfiguration(AutoConfigurations.of(SecurityFilterAutoConfiguration.class)) .run((context) -> assertThat( context.getBean("securityFilterChainRegistration", DelegatingFilterProxyRegistrationBean.class) .getOrder()).isEqualTo(OrderedFilter.REQUEST_WRAPPER_FILTER_MAX_ORDER - 100)); } @Test void testCustomFilterOrder() { this.contextRunner.withConfiguration(AutoConfigurations.of(SecurityFilterAutoConfiguration.class)) .withPropertyValues("spring.security.filter.order:12345") .run((context) -> assertThat( context.getBean("securityFilterChainRegistration", DelegatingFilterProxyRegistrationBean.class) .getOrder()).isEqualTo(12345)); } @Test void testJpaCoexistsHappily() { this.contextRunner .withPropertyValues("spring.datasource.url:jdbc:hsqldb:mem:testsecdb", "spring.datasource.initialization-mode:never") .withUserConfiguration(EntityConfiguration.class) .withConfiguration( AutoConfigurations.of(HibernateJpaAutoConfiguration.class, DataSourceAutoConfiguration.class)) .run((context) -> assertThat(context.getBean(JpaTransactionManager.class)).isNotNull()); // This can fail if security @Conditionals force early instantiation of the // HibernateJpaAutoConfiguration (e.g. the EntityManagerFactory is not found) } @Test void testSecurityEvaluationContextExtensionSupport() { this.contextRunner .run((context) -> assertThat(context).getBean(SecurityEvaluationContextExtension.class).isNotNull()); } @Test void defaultFilterDispatcherTypes() { this.contextRunner.withConfiguration(AutoConfigurations.of(SecurityFilterAutoConfiguration.class)) .run((context) -> { DelegatingFilterProxyRegistrationBean bean = context.getBean("securityFilterChainRegistration", DelegatingFilterProxyRegistrationBean.class); assertThat(bean) .extracting("dispatcherTypes", InstanceOfAssertFactories.iterable(DispatcherType.class)) .containsOnly(DispatcherType.ASYNC, DispatcherType.ERROR, DispatcherType.REQUEST); }); } @Test void customFilterDispatcherTypes() { this.contextRunner.withPropertyValues("spring.security.filter.dispatcher-types:INCLUDE,ERROR") .withConfiguration(AutoConfigurations.of(SecurityFilterAutoConfiguration.class)).run((context) -> { DelegatingFilterProxyRegistrationBean bean = context.getBean("securityFilterChainRegistration", DelegatingFilterProxyRegistrationBean.class); assertThat(bean) .extracting("dispatcherTypes", InstanceOfAssertFactories.iterable(DispatcherType.class)) .containsOnly(DispatcherType.INCLUDE, DispatcherType.ERROR); }); } @Test void emptyFilterDispatcherTypesDoNotThrowException() { this.contextRunner.withPropertyValues("spring.security.filter.dispatcher-types:") .withConfiguration(AutoConfigurations.of(SecurityFilterAutoConfiguration.class)).run((context) -> { DelegatingFilterProxyRegistrationBean bean = context.getBean("securityFilterChainRegistration", DelegatingFilterProxyRegistrationBean.class); assertThat(bean) .extracting("dispatcherTypes", InstanceOfAssertFactories.iterable(DispatcherType.class)) .isEmpty(); }); } @Configuration(proxyBeanMethods = false) @TestAutoConfigurationPackage(City.class) static class EntityConfiguration { } @Configuration(proxyBeanMethods = false) static class AuthenticationEventPublisherConfiguration { @Bean AuthenticationEventPublisher authenticationEventPublisher() { return new TestAuthenticationEventPublisher(); } class TestAuthenticationEventPublisher implements AuthenticationEventPublisher { @Override public void publishAuthenticationSuccess(Authentication authentication) { } @Override public void publishAuthenticationFailure(AuthenticationException exception, Authentication authentication) { } } } @Configuration(proxyBeanMethods = false) @EnableWebSecurity static class WebSecurity extends WebSecurityConfigurerAdapter { } @Configuration(proxyBeanMethods = false) static class TestSecurityFilterChainConfig { @Bean SecurityFilterChain testSecurityFilterChain(HttpSecurity http) throws Exception { return http.antMatcher("/**").authorizeRequests((authorize) -> authorize.anyRequest().authenticated()) .build(); } } }
/* ** Copyright 2005 Huxtable.com. All rights reserved. */ package com.jhlabs.image; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.Kernel; /** * A filter which applies a convolution kernel to an image. * * @author Jerry Huxtable */ public class ConvolveFilter extends AbstractBufferedImageOp { static final long serialVersionUID = 2239251672685254626L; public static int ZERO_EDGES = 0; public static int CLAMP_EDGES = 1; public static int WRAP_EDGES = 2; protected Kernel kernel = null; public boolean alpha = true; private int edgeAction = CLAMP_EDGES; /** * Construct a filter with a null kernel. This is only useful if you're * going to change the kernel later on. */ public ConvolveFilter() { this(new float[9]); } /** * Construct a filter with the given 3x3 kernel. * * @param matrix * an array of 9 floats containing the kernel */ public ConvolveFilter(float[] matrix) { this(new Kernel(3, 3, matrix)); } /** * Construct a filter with the given kernel. * * @param rows * the number of rows in the kernel * @param cols * the number of columns in the kernel * @param matrix * an array of rows*cols floats containing the kernel */ public ConvolveFilter(int rows, int cols, float[] matrix) { this(new Kernel(cols, rows, matrix)); } /** * Construct a filter with the given 3x3 kernel. * * @param kernel * the kernel this filter applies */ public ConvolveFilter(Kernel kernel) { this.kernel = kernel; } public void setKernel(Kernel kernel) { this.kernel = kernel; } public Kernel getKernel() { return kernel; } public void setEdgeAction(int edgeAction) { this.edgeAction = edgeAction; } public int getEdgeAction() { return edgeAction; } public BufferedImage filter(BufferedImage src, BufferedImage dst) { int width = src.getWidth(); int height = src.getHeight(); if (dst == null) dst = createCompatibleDestImage(src, null); int[] inPixels = new int[width * height]; int[] outPixels = new int[width * height]; getRGB(src, 0, 0, width, height, inPixels); convolve(kernel, inPixels, outPixels, width, height, alpha, edgeAction); setRGB(dst, 0, 0, width, height, outPixels); return dst; } public BufferedImage createCompatibleDestImage(BufferedImage src, ColorModel dstCM) { if (dstCM == null) dstCM = src.getColorModel(); return new BufferedImage(dstCM, dstCM.createCompatibleWritableRaster( src.getWidth(), src.getHeight()), dstCM.isAlphaPremultiplied(), null); } public Rectangle2D getBounds2D(BufferedImage src) { return new Rectangle(0, 0, src.getWidth(), src.getHeight()); } public Point2D getPoint2D(Point2D srcPt, Point2D dstPt) { if (dstPt == null) dstPt = new Point2D.Double(); dstPt.setLocation(srcPt.getX(), srcPt.getY()); return dstPt; } public RenderingHints getRenderingHints() { return null; } public static void convolve(Kernel kernel, int[] inPixels, int[] outPixels, int width, int height, int edgeAction) { convolve(kernel, inPixels, outPixels, width, height, true, edgeAction); } public static void convolve(Kernel kernel, int[] inPixels, int[] outPixels, int width, int height, boolean alpha, int edgeAction) { if (kernel.getHeight() == 1) convolveH(kernel, inPixels, outPixels, width, height, alpha, edgeAction); else if (kernel.getWidth() == 1) convolveV(kernel, inPixels, outPixels, width, height, alpha, edgeAction); else convolveHV(kernel, inPixels, outPixels, width, height, alpha, edgeAction); } /** * Convolve with a 2D kernel * * @param kernel * the kernel to apply * @param inPixels * the input pixels * @param outPixels * the output pixels * @param width * the width of the image * @param height * the height of the image * @param alpha * whether alpha is present * @param edgeAction * one of the edge constants */ public static void convolveHV(Kernel kernel, int[] inPixels, int[] outPixels, int width, int height, boolean alpha, int edgeAction) { int index = 0; float[] matrix = kernel.getKernelData(null); int rows = kernel.getHeight(); int cols = kernel.getWidth(); int rows2 = rows / 2; int cols2 = cols / 2; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { float r = 0, g = 0, b = 0, a = 0; for (int row = -rows2; row <= rows2; row++) { int iy = y + row; int ioffset; if (0 <= iy && iy < height) ioffset = iy * width; else if (edgeAction == CLAMP_EDGES) ioffset = y * width; else if (edgeAction == WRAP_EDGES) ioffset = ((iy + height) % height) * width; else continue; int moffset = cols * (row + rows2) + cols2; for (int col = -cols2; col <= cols2; col++) { float f = matrix[moffset + col]; if (f != 0) { int ix = x + col; if (!(0 <= ix && ix < width)) { if (edgeAction == CLAMP_EDGES) ix = x; else if (edgeAction == WRAP_EDGES) ix = (x + width) % width; else continue; } int rgb = inPixels[ioffset + ix]; a += f * ((rgb >> 24) & 0xff); r += f * ((rgb >> 16) & 0xff); g += f * ((rgb >> 8) & 0xff); b += f * (rgb & 0xff); } } } int ia = alpha ? PixelUtils.clamp((int) (a + 0.5)) : 0xff; int ir = PixelUtils.clamp((int) (r + 0.5)); int ig = PixelUtils.clamp((int) (g + 0.5)); int ib = PixelUtils.clamp((int) (b + 0.5)); outPixels[index++] = (ia << 24) | (ir << 16) | (ig << 8) | ib; } } } /** * Convolve with a kernel consisting of one row * * @param kernel * the kernel to apply * @param inPixels * the input pixels * @param outPixels * the output pixels * @param width * the width of the image * @param height * the height of the image * @param alpha * whether alpha is present * @param edgeAction * one of the edge constants */ public static void convolveH(Kernel kernel, int[] inPixels, int[] outPixels, int width, int height, boolean alpha, int edgeAction) { int index = 0; float[] matrix = kernel.getKernelData(null); int cols = kernel.getWidth(); int cols2 = cols / 2; for (int y = 0; y < height; y++) { int ioffset = y * width; for (int x = 0; x < width; x++) { float r = 0, g = 0, b = 0, a = 0; int moffset = cols2; for (int col = -cols2; col <= cols2; col++) { float f = matrix[moffset + col]; if (f != 0) { int ix = x + col; if (ix < 0) { if (edgeAction == CLAMP_EDGES) ix = 0; else if (edgeAction == WRAP_EDGES) ix = (x + width) % width; } else if (ix >= width) { if (edgeAction == CLAMP_EDGES) ix = width - 1; else if (edgeAction == WRAP_EDGES) ix = (x + width) % width; } int rgb = inPixels[ioffset + ix]; a += f * ((rgb >> 24) & 0xff); r += f * ((rgb >> 16) & 0xff); g += f * ((rgb >> 8) & 0xff); b += f * (rgb & 0xff); } } int ia = alpha ? PixelUtils.clamp((int) (a + 0.5)) : 0xff; int ir = PixelUtils.clamp((int) (r + 0.5)); int ig = PixelUtils.clamp((int) (g + 0.5)); int ib = PixelUtils.clamp((int) (b + 0.5)); outPixels[index++] = (ia << 24) | (ir << 16) | (ig << 8) | ib; } } } /** * Convolve with a kernel consisting of one column * * @param kernel * the kernel to apply * @param inPixels * the input pixels * @param outPixels * the output pixels * @param width * the width of the image * @param height * the height of the image * @param alpha * whether alpha is present * @param edgeAction * one of the edge constants */ public static void convolveV(Kernel kernel, int[] inPixels, int[] outPixels, int width, int height, boolean alpha, int edgeAction) { int index = 0; float[] matrix = kernel.getKernelData(null); int rows = kernel.getHeight(); int rows2 = rows / 2; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { float r = 0, g = 0, b = 0, a = 0; for (int row = -rows2; row <= rows2; row++) { int iy = y + row; int ioffset; if (iy < 0) { if (edgeAction == CLAMP_EDGES) ioffset = 0; else if (edgeAction == WRAP_EDGES) ioffset = ((y + height) % height) * width; else ioffset = iy * width; } else if (iy >= height) { if (edgeAction == CLAMP_EDGES) ioffset = (height - 1) * width; else if (edgeAction == WRAP_EDGES) ioffset = ((y + height) % height) * width; else ioffset = iy * width; } else ioffset = iy * width; float f = matrix[row + rows2]; if (f != 0) { int rgb = inPixels[ioffset + x]; a += f * ((rgb >> 24) & 0xff); r += f * ((rgb >> 16) & 0xff); g += f * ((rgb >> 8) & 0xff); b += f * (rgb & 0xff); } } int ia = alpha ? PixelUtils.clamp((int) (a + 0.5)) : 0xff; int ir = PixelUtils.clamp((int) (r + 0.5)); int ig = PixelUtils.clamp((int) (g + 0.5)); int ib = PixelUtils.clamp((int) (b + 0.5)); outPixels[index++] = (ia << 24) | (ir << 16) | (ig << 8) | ib; } } } public String toString() { return "Blur/Convolve..."; } }
package com.tma.tt.api.repository; import com.tma.tt.api.model.TaskDetail; import io.katharsis.repository.ResourceRepositoryV2; public interface TaskDetailRepository extends ResourceRepositoryV2<TaskDetail, Long> { }
package events; import api.ILevel; import javax.script.ScriptEngine; import javax.script.ScriptException; import java.util.Map; @Deprecated /** * Created by cyao42 on 4/24/2016. */ public class LevelAction extends Action { public LevelAction (String scriptPath) { super(scriptPath); } public LevelAction (String scriptPath, Map<String, Object> parameters) { super(scriptPath, parameters); } public void activate (ScriptEngine engine, ILevel level) { getParameters().put("level", level); try { engine.eval(getScript(), getParameters()); } catch (ScriptException e) { //e.printStackTrace(); System.out.println("Groovy engine could not run script."); } } }
// Copyright 2015-2021 Swim 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 swim.math; public interface R3ToZ3Function { long transformX(double x, double y, double z); long transformY(double x, double y, double z); long transformZ(double x, double y, double z); }
package org.motechproject.scheduler.contract; public enum JobType { CRON, REPEATING, DAY_OF_WEEK, RUN_ONCE, REPEATING_PERIOD }
/** * */ package graphql.mavenplugin_notscannedbyspring; import java.util.ArrayList; import java.util.List; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScan.Filter; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.FilterType; import com.graphql_java_generator.plugin.conf.CustomScalarDefinition; import com.graphql_java_generator.plugin.conf.PluginMode; import com.graphql_java_generator.plugin.test.helper.GraphQLConfigurationTestHelper; @Configuration @ComponentScan(basePackages = "com.graphql_java_generator", excludeFilters = { @Filter(type = FilterType.REGEX, pattern = ".*\\.GenerateRelaySchema.*"), @Filter(type = FilterType.REGEX, pattern = ".*\\.GenerateGraphQLSchema.*"), @Filter(type = FilterType.REGEX, pattern = "com.graphql_java_generator.client.graphqlrepository.*") }) public class Github_Client_SpringConfiguration extends AbstractSpringConfiguration { static List<CustomScalarDefinition> customScalars; static { customScalars = new ArrayList<>(); customScalars.add(new CustomScalarDefinition("Date", "java.util.Date", null, "com.graphql_java_generator.customscalars.GraphQLScalarTypeDate.Date", null)); customScalars.add(new CustomScalarDefinition("DateTime", "java.util.Date", null, "com.graphql_java_generator.customscalars.GraphQLScalarTypeDateTime.DateTime", null)); customScalars.add(new CustomScalarDefinition("GitObjectID", "java.lang.String", null, "com.graphql_java_generator.customscalars.GraphQLScalarTypeString.String", null)); customScalars.add(new CustomScalarDefinition("GitRefname", "java.lang.String", null, "com.graphql_java_generator.customscalars.GraphQLScalarTypeString.String", null)); customScalars.add(new CustomScalarDefinition("GitSSHRemote", "java.lang.String", null, "com.graphql_java_generator.customscalars.GraphQLScalarTypeString.String", null)); customScalars.add(new CustomScalarDefinition("GitTimestamp", "java.lang.String", null, "com.graphql_java_generator.customscalars.GraphQLScalarTypeString.String", null)); customScalars.add(new CustomScalarDefinition("HTML", "java.lang.String", null, "com.graphql_java_generator.customscalars.GraphQLScalarTypeString.String", null)); customScalars.add(new CustomScalarDefinition("PreciseDateTime", "java.lang.String", null, "com.graphql_java_generator.customscalars.GraphQLScalarTypeString.String", null)); customScalars.add(new CustomScalarDefinition("URI", "java.lang.String", null, "com.graphql_java_generator.customscalars.GraphQLScalarTypeString.String", null)); customScalars.add(new CustomScalarDefinition("X509Certificate", "java.lang.String", null, "com.graphql_java_generator.customscalars.GraphQLScalarTypeString.String", null)); } @Override protected void addSpecificConfigurationParameterValue(GraphQLConfigurationTestHelper configuration) { configuration.schemaFilePattern = "github.schema.public.graphqls"; configuration.mode = PluginMode.client; configuration.schemaPersonalizationFile = null; configuration.customScalars = customScalars; configuration.separateUtilityClasses = true; } }
import java.util.*; public class Test { public static void main(String args[]) { // Creating object of the // class linked list LinkedList<String> ll = new LinkedList<String>(); // Adding elements to the linked list ll.add("A"); ll.add("B"); ll.addLast("C"); ll.addFirst("D"); ll.add(2, "E"); System.out.println(ll); ll.remove("B"); ll.remove(3); ll.removeFirst(); ll.removeLast(); System.out.println(ll); } }
/** */ package org.afplib.afplib.impl; import java.util.Collection; import org.afplib.afplib.AfplibPackage; import org.afplib.afplib.BRG; import org.afplib.base.Triplet; import org.afplib.base.impl.SFImpl; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.util.EObjectContainmentEList; import org.eclipse.emf.ecore.util.InternalEList; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>BRG</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link org.afplib.afplib.impl.BRGImpl#getRGrpName <em>RGrp Name</em>}</li> * <li>{@link org.afplib.afplib.impl.BRGImpl#getTriplets <em>Triplets</em>}</li> * </ul> * * @generated */ public class BRGImpl extends SFImpl implements BRG { /** * The default value of the '{@link #getRGrpName() <em>RGrp Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getRGrpName() * @generated * @ordered */ protected static final String RGRP_NAME_EDEFAULT = null; /** * The cached value of the '{@link #getRGrpName() <em>RGrp Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getRGrpName() * @generated * @ordered */ protected String rGrpName = RGRP_NAME_EDEFAULT; /** * The cached value of the '{@link #getTriplets() <em>Triplets</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTriplets() * @generated * @ordered */ protected EList<Triplet> triplets; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected BRGImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return AfplibPackage.eINSTANCE.getBRG(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getRGrpName() { return rGrpName; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setRGrpName(String newRGrpName) { String oldRGrpName = rGrpName; rGrpName = newRGrpName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.BRG__RGRP_NAME, oldRGrpName, rGrpName)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<Triplet> getTriplets() { if (triplets == null) { triplets = new EObjectContainmentEList.Resolving<Triplet>(Triplet.class, this, AfplibPackage.BRG__TRIPLETS); } return triplets; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case AfplibPackage.BRG__TRIPLETS: return ((InternalEList<?>)getTriplets()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case AfplibPackage.BRG__RGRP_NAME: return getRGrpName(); case AfplibPackage.BRG__TRIPLETS: return getTriplets(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case AfplibPackage.BRG__RGRP_NAME: setRGrpName((String)newValue); return; case AfplibPackage.BRG__TRIPLETS: getTriplets().clear(); getTriplets().addAll((Collection<? extends Triplet>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case AfplibPackage.BRG__RGRP_NAME: setRGrpName(RGRP_NAME_EDEFAULT); return; case AfplibPackage.BRG__TRIPLETS: getTriplets().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case AfplibPackage.BRG__RGRP_NAME: return RGRP_NAME_EDEFAULT == null ? rGrpName != null : !RGRP_NAME_EDEFAULT.equals(rGrpName); case AfplibPackage.BRG__TRIPLETS: return triplets != null && !triplets.isEmpty(); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (RGrpName: "); result.append(rGrpName); result.append(')'); return result.toString(); } } //BRGImpl
/* * Copyright 2019 GridGain Systems, Inc. and Contributors. * * Licensed under the GridGain Community Edition License (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.gridgain.com/products/software/community-edition/gridgain-community-edition-license * * 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.ignite.internal.processors.cache; import java.io.Serializable; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import javax.cache.Cache; import org.apache.ignite.Ignite; import org.apache.ignite.IgniteCache; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.cache.CachePeekMode; import org.apache.ignite.cache.eviction.lru.LruEvictionPolicy; import org.apache.ignite.cache.query.ScanQuery; import org.apache.ignite.cache.query.SqlFieldsQuery; import org.apache.ignite.cache.query.SqlQuery; import org.apache.ignite.cache.query.annotations.QuerySqlField; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.internal.IgniteInternalFuture; import org.apache.ignite.internal.IgniteKernal; import org.apache.ignite.internal.processors.cache.index.AbstractIndexingCommonTest; import org.apache.ignite.internal.processors.cache.query.GridCacheQueryManager; import org.apache.ignite.internal.util.typedef.CAX; import org.apache.ignite.internal.util.typedef.internal.U; import org.junit.Test; import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL; import static org.apache.ignite.cache.CacheMode.PARTITIONED; import static org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC; /** * Multi-threaded tests for cache queries. */ public class IgniteCacheQueryMultiThreadedSelfTest extends AbstractIndexingCommonTest { /** */ private static final boolean TEST_INFO = true; /** Number of test grids (nodes). Should not be less than 2. */ private static final int GRID_CNT = 3; /** */ private static AtomicInteger idxSwapCnt = new AtomicInteger(); /** */ private static AtomicInteger idxUnswapCnt = new AtomicInteger(); /** */ private static final long DURATION = 30 * 1000; /** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName); cfg.setCacheConfiguration(cacheConfiguration()); return cfg; } /** * @return Cache configuration. */ protected CacheConfiguration cacheConfiguration() { CacheConfiguration<?,?> cacheCfg = defaultCacheConfiguration(); cacheCfg.setCacheMode(PARTITIONED); cacheCfg.setAtomicityMode(TRANSACTIONAL); cacheCfg.setWriteSynchronizationMode(FULL_SYNC); cacheCfg.setBackups(1); LruEvictionPolicy plc = null; if (evictsEnabled()) { plc = new LruEvictionPolicy(); plc.setMaxSize(100); } cacheCfg.setEvictionPolicy(plc); cacheCfg.setOnheapCacheEnabled(plc != null); return cacheCfg; } /** * @param clsK Key class. * @param clsV Value class. * @return Cache. */ protected <K, V> IgniteCache<K, V> cache(Class<K> clsK, Class<V> clsV) { return jcache(grid(0), cacheConfiguration(), clsK, clsV); } /** {@inheritDoc} */ @Override protected long getTestTimeout() { return DURATION + 60_000; } /** @return {@code true} If evictions enabled. */ protected boolean evictsEnabled() { return false; } /** {@inheritDoc} */ @Override protected void beforeTest() throws Exception { super.beforeTest(); // Clean up all caches. for (int i = 0; i < GRID_CNT; i++) { IgniteCache<Object, Object> c = grid(i).cache(DEFAULT_CACHE_NAME); assertEquals(0, c.size()); } } /** {@inheritDoc} */ @Override protected void beforeTestsStarted() throws Exception { assert GRID_CNT >= 2 : "Constant GRID_CNT must be greater than or equal to 2."; startGridsMultiThreaded(GRID_CNT); } /** {@inheritDoc} */ @Override protected void afterTest() throws Exception { super.afterTest(); // Clean up all caches. for (int i = 0; i < GRID_CNT; i++) { for(String cacheName : grid(i).cacheNames()) { IgniteCache<Object, Object> c = grid(i).cache(cacheName); c.removeAll(); // Fix for tests where mapping was removed at primary node // but was not removed at others. // removeAll() removes mapping only when it presents at a primary node. // To remove all mappings used force remove by key. if (c.size() > 0) { for (Cache.Entry<Object, Object> e : c.localEntries()) c.remove(e.getKey()); } } } U.sleep(5000); for (int i = 0; i < GRID_CNT; i++) { for(String cacheName : grid(i).cacheNames()) { IgniteCache<Object, Object> c = grid(i).cache(cacheName); assertEquals(0, c.size(CachePeekMode.OFFHEAP)); assertEquals(0, c.size(CachePeekMode.PRIMARY)); assertEquals(0, c.size()); } } } /** {@inheritDoc} */ @Override protected void info(String msg) { if (TEST_INFO) super.info(msg); } /** * @param entries Entries. * @param g Grid. * @return Affinity nodes. */ private Set<UUID> affinityNodes(Iterable<Cache.Entry<Integer, Integer>> entries, Ignite g) { Set<UUID> nodes = new HashSet<>(); for (Cache.Entry<Integer, Integer> entry : entries) nodes.add(g.affinity(DEFAULT_CACHE_NAME).mapKeyToPrimaryAndBackups(entry.getKey()).iterator().next().id()); return nodes; } /** * JUnit. * * @throws Exception If failed. */ @SuppressWarnings({"TooBroadScope"}) @Test public void testMultiThreadedSwapUnswapString() throws Exception { int threadCnt = 50; final int keyCnt = 2000; final int valCnt = 10000; final Ignite g = grid(0); // Put test values into cache. final IgniteCache<Integer, String> c = cache(Integer.class, String.class); assertEquals(0, g.cache(DEFAULT_CACHE_NAME).localSize()); assertEquals(0, c.query(new SqlQuery(String.class, "1 = 1")).getAll().size()); Random rnd = new Random(); for (int i = 0; i < keyCnt; i += 1 + rnd.nextInt(3)) { c.put(i, String.valueOf(rnd.nextInt(valCnt))); if (evictsEnabled() && rnd.nextBoolean()) c.localEvict(Arrays.asList(i)); } final AtomicBoolean done = new AtomicBoolean(); IgniteInternalFuture<?> fut = multithreadedAsync(new CAX() { @Override public void applyx() throws IgniteCheckedException { Random rnd = new Random(); while (!done.get()) { switch (rnd.nextInt(5)) { case 0: c.put(rnd.nextInt(keyCnt), String.valueOf(rnd.nextInt(valCnt))); break; case 1: if (evictsEnabled()) c.localEvict(Arrays.asList(rnd.nextInt(keyCnt))); break; case 2: c.remove(rnd.nextInt(keyCnt)); break; case 3: c.get(rnd.nextInt(keyCnt)); break; case 4: int from = rnd.nextInt(valCnt); c.query(new SqlQuery(String.class, "_val between ? and ?").setArgs( String.valueOf(from), String.valueOf(from + 250))).getAll(); } } } }, threadCnt); Thread.sleep(DURATION); done.set(true); fut.get(); } /** * JUnit. * * @throws Exception If failed. */ @SuppressWarnings({"TooBroadScope"}) @Test public void testMultiThreadedSwapUnswapLong() throws Exception { int threadCnt = 50; final int keyCnt = 2000; final int valCnt = 10000; final Ignite g = grid(0); // Put test values into cache. final IgniteCache<Integer, Long> c = cache(Integer.class, Long.class); assertEquals(0, g.cache(DEFAULT_CACHE_NAME).localSize()); assertEquals(0, c.query(new SqlQuery(Long.class, "1 = 1")).getAll().size()); Random rnd = new Random(); for (int i = 0; i < keyCnt; i += 1 + rnd.nextInt(3)) { c.put(i, (long)rnd.nextInt(valCnt)); if (evictsEnabled() && rnd.nextBoolean()) c.localEvict(Arrays.asList(i)); } final AtomicBoolean done = new AtomicBoolean(); IgniteInternalFuture<?> fut = multithreadedAsync(new CAX() { @Override public void applyx() throws IgniteCheckedException { Random rnd = new Random(); while (!done.get()) { int key = rnd.nextInt(keyCnt); switch (rnd.nextInt(5)) { case 0: c.put(key, (long)rnd.nextInt(valCnt)); break; case 1: if (evictsEnabled()) c.localEvict(Arrays.asList(key)); break; case 2: c.remove(key); break; case 3: c.get(key); break; case 4: int from = rnd.nextInt(valCnt); c.query(new SqlQuery(Long.class, "_val between ? and ?").setArgs(from, from + 250)).getAll(); } } } }, threadCnt); Thread.sleep(DURATION); done.set(true); fut.get(); } /** * JUnit. * * @throws Exception If failed. */ @SuppressWarnings({"TooBroadScope"}) @Test public void testMultiThreadedSwapUnswapLongString() throws Exception { int threadCnt = 50; final int keyCnt = 2000; final int valCnt = 10000; final Ignite g = grid(0); // Put test values into cache. final IgniteCache<Integer, Object> c = cache(Integer.class, Object.class); assertEquals(0, g.cache(DEFAULT_CACHE_NAME).size()); assertEquals(0, c.query(new SqlQuery(Object.class, "1 = 1")).getAll().size()); Random rnd = new Random(); for (int i = 0; i < keyCnt; i += 1 + rnd.nextInt(3)) { c.put(i, rnd.nextBoolean() ? (long)rnd.nextInt(valCnt) : String.valueOf(rnd.nextInt(valCnt))); if (evictsEnabled() && rnd.nextBoolean()) c.localEvict(Arrays.asList(i)); } final AtomicBoolean done = new AtomicBoolean(); IgniteInternalFuture<?> fut = multithreadedAsync(new CAX() { @Override public void applyx() throws IgniteCheckedException { Random rnd = new Random(); while (!done.get()) { int key = rnd.nextInt(keyCnt); switch (rnd.nextInt(5)) { case 0: c.put(key, rnd.nextBoolean() ? (long)rnd.nextInt(valCnt) : String.valueOf(rnd.nextInt(valCnt))); break; case 1: if (evictsEnabled()) c.localEvict(Arrays.asList(key)); break; case 2: c.remove(key); break; case 3: c.get(key); break; case 4: int from = rnd.nextInt(valCnt); c.query(new SqlQuery(Object.class, "_val between ? and ?").setArgs(from, from + 250)) .getAll(); } } } }, threadCnt); Thread.sleep(DURATION); done.set(true); fut.get(); } /** * @throws Exception If failed. */ @SuppressWarnings({"TooBroadScope"}) @Test public void testMultiThreadedSwapUnswapObject() throws Exception { int threadCnt = 50; final int keyCnt = 4000; final int valCnt = 10000; final Ignite g = grid(0); // Put test values into cache. final IgniteCache<Integer, TestValue> c = cache(Integer.class, TestValue.class); assertEquals(0, g.cache(DEFAULT_CACHE_NAME).localSize()); assertEquals(0, c.query(new SqlQuery(TestValue.class, "1 = 1")).getAll().size()); Random rnd = new Random(); for (int i = 0; i < keyCnt; i += 1 + rnd.nextInt(3)) { c.put(i, new TestValue(rnd.nextInt(valCnt))); if (evictsEnabled() && rnd.nextBoolean()) c.localEvict(Arrays.asList(i)); } final AtomicBoolean done = new AtomicBoolean(); IgniteInternalFuture<?> fut = multithreadedAsync(new CAX() { @Override public void applyx() throws IgniteCheckedException { Random rnd = new Random(); while (!done.get()) { int key = rnd.nextInt(keyCnt); switch (rnd.nextInt(5)) { case 0: c.put(key, new TestValue(rnd.nextInt(valCnt))); break; case 1: if (evictsEnabled()) c.localEvict(Arrays.asList(key)); break; case 2: c.remove(key); break; case 3: c.get(key); break; case 4: int from = rnd.nextInt(valCnt); c.query(new SqlQuery(TestValue.class, "TestValue.val between ? and ?") .setArgs(from, from + 250)).getAll(); } } } }, threadCnt); Thread.sleep(DURATION); done.set(true); fut.get(); } /** * JUnit. * * @throws Exception If failed. */ @SuppressWarnings({"TooBroadScope"}) @Test public void testMultiThreadedSameQuery() throws Exception { int threadCnt = 50; final int keyCnt = 10; final int logMod = 5000; final Ignite g = grid(0); // Put test values into cache. final IgniteCache<Integer, Integer> c = cache(Integer.class, Integer.class); for (int i = 0; i < keyCnt; i++) { c.put(i, i); c.localEvict(Arrays.asList(i)); } final AtomicInteger cnt = new AtomicInteger(); final AtomicBoolean done = new AtomicBoolean(); IgniteInternalFuture<?> fut = multithreadedAsync( new CAX() { @Override public void applyx() throws IgniteCheckedException { int iter = 0; while (!done.get() && !Thread.currentThread().isInterrupted()) { iter++; Collection<Cache.Entry<Integer, Integer>> entries = c.query(new SqlQuery(Integer.class, "_val >= 0")).getAll(); assert entries != null; assertEquals("Query results [entries=" + entries + ", aff=" + affinityNodes(entries, g) + ", iteration=" + iter + ']', keyCnt, entries.size()); if (cnt.incrementAndGet() % logMod == 0) { GridCacheQueryManager<Object, Object> qryMgr = ((IgniteKernal)g).internalCache(c.getName()).context().queries(); assert qryMgr != null; qryMgr.printMemoryStats(); } } } }, threadCnt); Thread.sleep(DURATION); info("Finishing test..."); done.set(true); fut.get(); } /** * JUnit. * * @throws Exception If failed. */ @SuppressWarnings({"TooBroadScope"}) @Test public void testMultiThreadedNewQueries() throws Exception { int threadCnt = 50; final int keyCnt = 10; final int logMod = 5000; final Ignite g = grid(0); // Put test values into cache. final IgniteCache<Integer, Integer> c = cache(Integer.class, Integer.class); for (int i = 0; i < keyCnt; i++) { c.put(i, i); c.localEvict(Arrays.asList(i)); } final AtomicInteger cnt = new AtomicInteger(); final AtomicBoolean done = new AtomicBoolean(); IgniteInternalFuture<?> fut = multithreadedAsync(new CAX() { @Override public void applyx() throws IgniteCheckedException { int iter = 0; while (!done.get() && !Thread.currentThread().isInterrupted()) { iter++; Collection<Cache.Entry<Integer, Integer>> entries = c.query(new SqlQuery(Integer.class, "_val >= 0")).getAll(); assert entries != null; assertEquals("Entries count is not as expected on iteration: " + iter, keyCnt, entries.size()); if (cnt.incrementAndGet() % logMod == 0) { GridCacheQueryManager<Object, Object> qryMgr = ((IgniteKernal)g).internalCache(c.getName()).context().queries(); assert qryMgr != null; qryMgr.printMemoryStats(); } } } }, threadCnt); Thread.sleep(DURATION); done.set(true); fut.get(); } /** * JUnit. * * @throws Exception If failed. */ @SuppressWarnings({"TooBroadScope"}) @Test public void testMultiThreadedScanQuery() throws Exception { int threadCnt = 50; final int keyCnt = 500; final int logMod = 5000; final Ignite g = grid(0); // Put test values into cache. final IgniteCache<Integer, Integer> c = cache(Integer.class, Integer.class); for (int i = 0; i < keyCnt; i++) c.put(i, i); final AtomicInteger cnt = new AtomicInteger(); final AtomicBoolean done = new AtomicBoolean(); IgniteInternalFuture<?> fut = multithreadedAsync( new CAX() { @Override public void applyx() throws IgniteCheckedException { int iter = 0; while (!done.get() && !Thread.currentThread().isInterrupted()) { iter++; // Scan query. Collection<Cache.Entry<Integer, Integer>> entries = c.query(new ScanQuery<Integer, Integer>()).getAll(); assert entries != null; assertEquals("Entries count is not as expected on iteration: " + iter, keyCnt, entries.size()); if (cnt.incrementAndGet() % logMod == 0) { GridCacheQueryManager<Object, Object> qryMgr = ((IgniteKernal)g).internalCache(c.getName()).context().queries(); assert qryMgr != null; qryMgr.printMemoryStats(); } } } }, threadCnt); Thread.sleep(DURATION); done.set(true); fut.get(); } /** * SqlFieldsQuery paging mechanics stress test * * @throws Exception If failed. */ @SuppressWarnings({"TooBroadScope"}) @Test public void testMultiThreadedSqlFieldsQuery() throws Throwable { int threadCnt = 16; final int keyCnt = 1100; // set resultSet size bigger than page size final int logMod = 5000; final Ignite g = grid(0); // Put test values into cache. final IgniteCache<Integer, TestValue> c = cache(Integer.class, TestValue.class); for (int i = 0; i < keyCnt; i++) c.put(i, new TestValue(i)); final AtomicInteger cnt = new AtomicInteger(); final AtomicBoolean done = new AtomicBoolean(); IgniteInternalFuture<?> fut = multithreadedAsync( new CAX() { @Override public void applyx() throws IgniteCheckedException { int iter = 0; while (!done.get() && !Thread.currentThread().isInterrupted()) { iter++; List<List<?>> entries = c.query(new SqlFieldsQuery("SELECT * from TestValue").setPageSize(100)).getAll(); assert entries != null; assertEquals("Entries count is not as expected on iteration: " + iter, keyCnt, entries.size()); if (cnt.incrementAndGet() % logMod == 0) { GridCacheQueryManager<Object, Object> qryMgr = ((IgniteKernal)g).internalCache(DEFAULT_CACHE_NAME).context().queries(); assert qryMgr != null; qryMgr.printMemoryStats(); } } } }, threadCnt); Thread.sleep(DURATION); done.set(true); fut.get(); } /** * Test value. */ private static class TestValue implements Serializable { /** Value. */ @QuerySqlField(index = true) private int val; /** * @param val Value. */ private TestValue(int val) { this.val = val; } /** * @return Value. */ public int value() { return val; } } }
package org.mightyfish.crypto.test; import org.mightyfish.crypto.Mac; import org.mightyfish.crypto.engines.GOST28147Engine; import org.mightyfish.crypto.macs.GOST28147Mac; import org.mightyfish.crypto.params.KeyParameter; import org.mightyfish.crypto.params.ParametersWithSBox; import org.mightyfish.util.Arrays; import org.mightyfish.util.encoders.Hex; import org.mightyfish.util.test.SimpleTestResult; import org.mightyfish.util.test.Test; import org.mightyfish.util.test.TestResult; /** * GOST 28147 MAC tester */ public class GOST28147MacTest implements Test { // // these GOSTMac for testing. // static byte[] gkeyBytes1 = Hex.decode("6d145dc993f4019e104280df6fcd8cd8e01e101e4c113d7ec4f469ce6dcd9e49"); static byte[] gkeyBytes2 = Hex.decode("6d145dc993f4019e104280df6fcd8cd8e01e101e4c113d7ec4f469ce6dcd9e49"); static byte[] input3 = Hex.decode("7768617420646f2079612077616e7420666f72206e6f7468696e673f"); static byte[] input4 = Hex.decode("7768617420646f2079612077616e7420666f72206e6f7468696e673f"); static byte[] output7 = Hex.decode("93468a46"); static byte[] output8 = Hex.decode("93468a46"); public GOST28147MacTest() { } public TestResult perform() { // test1 Mac mac = new GOST28147Mac(); KeyParameter key = new KeyParameter(gkeyBytes1); mac.init(key); mac.update(input3, 0, input3.length); byte[] out = new byte[4]; mac.doFinal(out, 0); if (!Arrays.areEqual(out, output7)) { return new SimpleTestResult(false, getName() + ": Failed test 1 - expected " + new String(Hex.encode(output7)) + " got " + new String(Hex.encode(out))); } // test2 key = new KeyParameter(gkeyBytes2); ParametersWithSBox gparam = new ParametersWithSBox(key, GOST28147Engine.getSBox("E-A")); mac.init(gparam); mac.update(input4, 0, input4.length); out = new byte[4]; mac.doFinal(out, 0); if (!Arrays.areEqual(out, output8)) { return new SimpleTestResult(false, getName() + ": Failed test 2 - expected " + new String(Hex.encode(output8)) + " got " + new String(Hex.encode(out))); } return new SimpleTestResult(true, getName() + ": Okay"); } public String getName() { return "GOST28147Mac"; } public static void main( String[] args) { GOST28147MacTest test = new GOST28147MacTest(); TestResult result = test.perform(); System.out.println(result); } }
/** * Copyright &copy; 2016-2017 HZC All rights reserved. */ package com.hzc.aams.modules.sys.service; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.List; import com.hzc.aams.common.persistence.Page; import com.hzc.aams.common.security.Digests; import com.hzc.aams.common.security.shiro.session.SessionDAO; import com.hzc.aams.common.service.ServiceException; import com.hzc.aams.common.utils.CacheUtils; import com.hzc.aams.common.utils.Encodes; import com.hzc.aams.modules.sys.dao.MenuDao; import com.hzc.aams.modules.sys.dao.RoleDao; import com.hzc.aams.modules.sys.dao.UserDao; import com.hzc.aams.modules.sys.entity.Menu; import com.hzc.aams.modules.sys.entity.Role; import org.activiti.engine.IdentityService; import org.activiti.engine.identity.Group; import org.apache.shiro.session.Session; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.hzc.aams.common.config.Global; import com.hzc.aams.common.service.BaseService; import com.hzc.aams.common.utils.StringUtils; import com.hzc.aams.common.web.Servlets; import com.hzc.aams.modules.sys.entity.Office; import com.hzc.aams.modules.sys.entity.User; import com.hzc.aams.modules.sys.security.SystemAuthorizingRealm; import com.hzc.aams.modules.sys.utils.LogUtils; import com.hzc.aams.modules.sys.utils.UserUtils; /** * 系统管理,安全相关实体的管理类,包括用户、角色、菜单. * @author ThinkGem * @version 2013-12-05 */ @Service @Transactional(readOnly = true) public class SystemService extends BaseService implements InitializingBean { public static final String HASH_ALGORITHM = "SHA-1"; public static final int HASH_INTERATIONS = 1024; public static final int SALT_SIZE = 8; @Autowired private UserDao userDao; @Autowired private RoleDao roleDao; @Autowired private MenuDao menuDao; @Autowired private SessionDAO sessionDao; @Autowired private SystemAuthorizingRealm systemRealm; public SessionDAO getSessionDao() { return sessionDao; } @Autowired private IdentityService identityService; //-- User Service --// /** * 获取用户 * @param id * @return */ public User getUser(String id) { return UserUtils.get(id); } /** * 根据登录名获取用户 * @param loginName * @return */ public User getUserByLoginName(String loginName) { return UserUtils.getByLoginName(loginName); } public Page<User> findUser(Page<User> page, User user) { // 生成数据权限过滤条件(dsf为dataScopeFilter的简写,在xml中使用 ${sqlMap.dsf}调用权限SQL) user.getSqlMap().put("dsf", dataScopeFilter(user.getCurrentUser(), "o", "a")); // 设置分页参数 user.setPage(page); // 执行分页查询 page.setList(userDao.findList(user)); return page; } /** * 无分页查询人员列表 * @param user * @return */ public List<User> findUser(User user){ // 生成数据权限过滤条件(dsf为dataScopeFilter的简写,在xml中使用 ${sqlMap.dsf}调用权限SQL) user.getSqlMap().put("dsf", dataScopeFilter(user.getCurrentUser(), "o", "a")); List<User> list = userDao.findList(user); return list; } /** * 通过部门ID获取用户列表,仅返回用户id和name(树查询用户时用) * @param user * @return */ @SuppressWarnings("unchecked") public List<User> findUserByOfficeId(String officeId) { List<User> list = (List<User>) CacheUtils.get(UserUtils.USER_CACHE, UserUtils.USER_CACHE_LIST_BY_OFFICE_ID_ + officeId); if (list == null){ User user = new User(); user.setOffice(new Office(officeId)); list = userDao.findUserByOfficeId(user); CacheUtils.put(UserUtils.USER_CACHE, UserUtils.USER_CACHE_LIST_BY_OFFICE_ID_ + officeId, list); } return list; } @Transactional(readOnly = false) public void saveUser(User user) { if (StringUtils.isBlank(user.getId())){ user.preInsert(); userDao.insert(user); }else{ // 清除原用户机构用户缓存 User oldUser = userDao.get(user.getId()); if (oldUser.getOffice() != null && oldUser.getOffice().getId() != null){ CacheUtils.remove(UserUtils.USER_CACHE, UserUtils.USER_CACHE_LIST_BY_OFFICE_ID_ + oldUser.getOffice().getId()); } // 更新用户数据 user.preUpdate(); userDao.update(user); } if (StringUtils.isNotBlank(user.getId())){ // 更新用户与角色关联 userDao.deleteUserRole(user); if (user.getRoleList() != null && user.getRoleList().size() > 0){ userDao.insertUserRole(user); }else{ throw new ServiceException(user.getLoginName() + "没有设置角色!"); } // 将当前用户同步到Activiti saveActivitiUser(user); // 清除用户缓存 UserUtils.clearCache(user); // // 清除权限缓存 // systemRealm.clearAllCachedAuthorizationInfo(); } } @Transactional(readOnly = false) public void updateUserInfo(User user) { user.preUpdate(); userDao.updateUserInfo(user); // 清除用户缓存 UserUtils.clearCache(user); // // 清除权限缓存 // systemRealm.clearAllCachedAuthorizationInfo(); } @Transactional(readOnly = false) public void deleteUser(User user) { userDao.delete(user); // 同步到Activiti deleteActivitiUser(user); // 清除用户缓存 UserUtils.clearCache(user); // // 清除权限缓存 // systemRealm.clearAllCachedAuthorizationInfo(); } @Transactional(readOnly = false) public void updatePasswordById(String id, String loginName, String newPassword) { User user = new User(id); user.setPassword(entryptPassword(newPassword)); userDao.updatePasswordById(user); // 清除用户缓存 user.setLoginName(loginName); UserUtils.clearCache(user); // // 清除权限缓存 // systemRealm.clearAllCachedAuthorizationInfo(); } @Transactional(readOnly = false) public void updateUserLoginInfo(User user) { // 保存上次登录信息 user.setOldLoginIp(user.getLoginIp()); user.setOldLoginDate(user.getLoginDate()); // 更新本次登录信息 user.setLoginIp(StringUtils.getRemoteAddr(Servlets.getRequest())); user.setLoginDate(new Date()); userDao.updateLoginInfo(user); } /** * 生成安全的密码,生成随机的16位salt并经过1024次 sha-1 hash */ public static String entryptPassword(String plainPassword) { String plain = Encodes.unescapeHtml(plainPassword); byte[] salt = Digests.generateSalt(SALT_SIZE); byte[] hashPassword = Digests.sha1(plain.getBytes(), salt, HASH_INTERATIONS); return Encodes.encodeHex(salt)+Encodes.encodeHex(hashPassword); } /** * 验证密码 * @param plainPassword 明文密码 * @param password 密文密码 * @return 验证成功返回true */ public static boolean validatePassword(String plainPassword, String password) { String plain = Encodes.unescapeHtml(plainPassword); byte[] salt = Encodes.decodeHex(password.substring(0,16)); byte[] hashPassword = Digests.sha1(plain.getBytes(), salt, HASH_INTERATIONS); return password.equals(Encodes.encodeHex(salt)+Encodes.encodeHex(hashPassword)); } /** * 获得活动会话 * @return */ public Collection<Session> getActiveSessions(){ return sessionDao.getActiveSessions(false); } //-- Role Service --// public Role getRole(String id) { return roleDao.get(id); } public Role getRoleByName(String name) { Role r = new Role(); r.setName(name); return roleDao.getByName(r); } public Role getRoleByEnname(String enname) { Role r = new Role(); r.setEnname(enname); return roleDao.getByEnname(r); } public List<Role> findRole(Role role){ return roleDao.findList(role); } public List<Role> findAllRole(){ return UserUtils.getRoleList(); } @Transactional(readOnly = false) public void saveRole(Role role) { if (StringUtils.isBlank(role.getId())){ role.preInsert(); roleDao.insert(role); // 同步到Activiti saveActivitiGroup(role); }else{ role.preUpdate(); roleDao.update(role); } // 更新角色与菜单关联 roleDao.deleteRoleMenu(role); if (role.getMenuList().size() > 0){ roleDao.insertRoleMenu(role); } // 更新角色与部门关联 roleDao.deleteRoleOffice(role); if (role.getOfficeList().size() > 0){ roleDao.insertRoleOffice(role); } // 同步到Activiti saveActivitiGroup(role); // 清除用户角色缓存 UserUtils.removeCache(UserUtils.CACHE_ROLE_LIST); // // 清除权限缓存 // systemRealm.clearAllCachedAuthorizationInfo(); } @Transactional(readOnly = false) public void deleteRole(Role role) { roleDao.delete(role); // 同步到Activiti deleteActivitiGroup(role); // 清除用户角色缓存 UserUtils.removeCache(UserUtils.CACHE_ROLE_LIST); // // 清除权限缓存 // systemRealm.clearAllCachedAuthorizationInfo(); } @Transactional(readOnly = false) public Boolean outUserInRole(Role role, User user) { List<Role> roles = user.getRoleList(); for (Role e : roles){ if (e.getId().equals(role.getId())){ roles.remove(e); saveUser(user); return true; } } return false; } @Transactional(readOnly = false) public User assignUserToRole(Role role, User user) { if (user == null){ return null; } List<String> roleIds = user.getRoleIdList(); if (roleIds.contains(role.getId())) { return null; } user.getRoleList().add(role); saveUser(user); return user; } //-- Menu Service --// public Menu getMenu(String id) { return menuDao.get(id); } public List<Menu> findAllMenu(){ return UserUtils.getMenuList(); } @Transactional(readOnly = false) public void saveMenu(Menu menu) { // 获取父节点实体 menu.setParent(this.getMenu(menu.getParent().getId())); // 获取修改前的parentIds,用于更新子节点的parentIds String oldParentIds = menu.getParentIds(); // 设置新的父节点串 menu.setParentIds(menu.getParent().getParentIds()+menu.getParent().getId()+","); // 保存或更新实体 if (StringUtils.isBlank(menu.getId())){ menu.preInsert(); menuDao.insert(menu); }else{ menu.preUpdate(); menuDao.update(menu); } // 更新子节点 parentIds Menu m = new Menu(); m.setParentIds("%,"+menu.getId()+",%"); List<Menu> list = menuDao.findByParentIdsLike(m); for (Menu e : list){ e.setParentIds(e.getParentIds().replace(oldParentIds, menu.getParentIds())); menuDao.updateParentIds(e); } // 清除用户菜单缓存 UserUtils.removeCache(UserUtils.CACHE_MENU_LIST); // // 清除权限缓存 // systemRealm.clearAllCachedAuthorizationInfo(); // 清除日志相关缓存 CacheUtils.remove(LogUtils.CACHE_MENU_NAME_PATH_MAP); } @Transactional(readOnly = false) public void updateMenuSort(Menu menu) { menuDao.updateSort(menu); // 清除用户菜单缓存 UserUtils.removeCache(UserUtils.CACHE_MENU_LIST); // // 清除权限缓存 // systemRealm.clearAllCachedAuthorizationInfo(); // 清除日志相关缓存 CacheUtils.remove(LogUtils.CACHE_MENU_NAME_PATH_MAP); } @Transactional(readOnly = false) public void deleteMenu(Menu menu) { menuDao.delete(menu); // 清除用户菜单缓存 UserUtils.removeCache(UserUtils.CACHE_MENU_LIST); // // 清除权限缓存 // systemRealm.clearAllCachedAuthorizationInfo(); // 清除日志相关缓存 CacheUtils.remove(LogUtils.CACHE_MENU_NAME_PATH_MAP); } /** * 获取Key加载信息 */ public static boolean printKeyLoadMessage(){ StringBuilder sb = new StringBuilder(); sb.append("\r\n======================================================================\r\n"); sb.append("\r\n 欢迎使用 "+Global.getConfig("productName")+" - Powered By HZC\r\n"); sb.append("\r\n======================================================================\r\n"); System.out.println(sb.toString()); return true; } ///////////////// Synchronized to the Activiti ////////////////// // 已废弃,同步见:ActGroupEntityServiceFactory.java、ActUserEntityServiceFactory.java /** * 是需要同步Activiti数据,如果从未同步过,则同步数据。 */ private static boolean isSynActivitiIndetity = true; public void afterPropertiesSet() throws Exception { if (!Global.isSynActivitiIndetity()){ return; } if (isSynActivitiIndetity){ isSynActivitiIndetity = false; // 同步角色数据 List<Group> groupList = identityService.createGroupQuery().list(); if (groupList.size() == 0){ Iterator<Role> roles = roleDao.findAllList(new Role()).iterator(); while(roles.hasNext()) { Role role = roles.next(); saveActivitiGroup(role); } } // 同步用户数据 List<org.activiti.engine.identity.User> userList = identityService.createUserQuery().list(); if (userList.size() == 0){ Iterator<User> users = userDao.findAllList(new User()).iterator(); while(users.hasNext()) { saveActivitiUser(users.next()); } } } } private void saveActivitiGroup(Role role) { if (!Global.isSynActivitiIndetity()){ return; } String groupId = role.getEnname(); // 如果修改了英文名,则删除原Activiti角色 if (StringUtils.isNotBlank(role.getOldEnname()) && !role.getOldEnname().equals(role.getEnname())){ identityService.deleteGroup(role.getOldEnname()); } Group group = identityService.createGroupQuery().groupId(groupId).singleResult(); if (group == null) { group = identityService.newGroup(groupId); } group.setName(role.getName()); group.setType(role.getRoleType()); identityService.saveGroup(group); // 删除用户与用户组关系 List<org.activiti.engine.identity.User> activitiUserList = identityService.createUserQuery().memberOfGroup(groupId).list(); for (org.activiti.engine.identity.User activitiUser : activitiUserList){ identityService.deleteMembership(activitiUser.getId(), groupId); } // 创建用户与用户组关系 List<User> userList = findUser(new User(new Role(role.getId()))); for (User e : userList){ String userId = e.getLoginName();//ObjectUtils.toString(user.getId()); // 如果该用户不存在,则创建一个 org.activiti.engine.identity.User activitiUser = identityService.createUserQuery().userId(userId).singleResult(); if (activitiUser == null){ activitiUser = identityService.newUser(userId); activitiUser.setFirstName(e.getName()); activitiUser.setLastName(StringUtils.EMPTY); activitiUser.setEmail(e.getEmail()); activitiUser.setPassword(StringUtils.EMPTY); identityService.saveUser(activitiUser); } identityService.createMembership(userId, groupId); } } public void deleteActivitiGroup(Role role) { if (!Global.isSynActivitiIndetity()){ return; } if(role!=null) { String groupId = role.getEnname(); identityService.deleteGroup(groupId); } } private void saveActivitiUser(User user) { if (!Global.isSynActivitiIndetity()){ return; } String userId = user.getLoginName();//ObjectUtils.toString(user.getId()); org.activiti.engine.identity.User activitiUser = identityService.createUserQuery().userId(userId).singleResult(); if (activitiUser == null) { activitiUser = identityService.newUser(userId); } activitiUser.setFirstName(user.getName()); activitiUser.setLastName(StringUtils.EMPTY); activitiUser.setEmail(user.getEmail()); activitiUser.setPassword(StringUtils.EMPTY); identityService.saveUser(activitiUser); // 删除用户与用户组关系 List<Group> activitiGroups = identityService.createGroupQuery().groupMember(userId).list(); for (Group group : activitiGroups) { identityService.deleteMembership(userId, group.getId()); } // 创建用户与用户组关系 for (Role role : user.getRoleList()) { String groupId = role.getEnname(); // 如果该用户组不存在,则创建一个 Group group = identityService.createGroupQuery().groupId(groupId).singleResult(); if(group == null) { group = identityService.newGroup(groupId); group.setName(role.getName()); group.setType(role.getRoleType()); identityService.saveGroup(group); } identityService.createMembership(userId, role.getEnname()); } } private void deleteActivitiUser(User user) { if (!Global.isSynActivitiIndetity()){ return; } if(user!=null) { String userId = user.getLoginName();//ObjectUtils.toString(user.getId()); identityService.deleteUser(userId); } } ///////////////// Synchronized to the Activiti end ////////////////// }
/* SPDX-License-Identifier: Apache 2.0 */ /* Copyright Contributors to the ODPi Egeria project. */ package org.odpi.openmetadata.platformservices.server.spring; import io.swagger.v3.oas.annotations.ExternalDocumentation; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import org.odpi.openmetadata.commonservices.ffdc.rest.BooleanResponse; import org.odpi.openmetadata.commonservices.ffdc.rest.RegisteredOMAGServicesResponse; import org.odpi.openmetadata.platformservices.rest.ServerListResponse; import org.odpi.openmetadata.platformservices.rest.ServerServicesListResponse; import org.odpi.openmetadata.platformservices.rest.ServerStatusResponse; import org.odpi.openmetadata.platformservices.server.OMAGServerPlatformActiveServices; 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.RestController; /** * OMAGServerPlatformActiveResource allow an external caller to determine which servers are active on the * platform and the services that are active within them. */ @Tag(name="Platform Services", description="The platform services provides the APIs for querying the Open Metadata and Governance (OMAG) " + "Server Platform and discovering information about the OMAG Servers that it is hosting.", externalDocs=@ExternalDocumentation(description="Platform Services",url="https://egeria-project.org/services/platform-services/overview")) @RestController @RequestMapping("/open-metadata/platform-services/users/{userId}/server-platform") public class OMAGServerPlatformActiveResource { OMAGServerPlatformActiveServices platformAPI = new OMAGServerPlatformActiveServices(); /** * Return the list of access services that are registered (supported) in this OMAG Server Platform * and can be configured for a metadata server. * * @param userId calling user * @return list of service descriptions */ @GetMapping(path = "/registered-services/access-services") @Operation( summary = "Get registered access services", description="Retrieve a list of access services registered on this platform", responses = { @ApiResponse(responseCode = "200", description="list of service descriptions", content = @Content( mediaType ="application/json", schema = @Schema(implementation=RegisteredOMAGServicesResponse.class) ) ) }) public RegisteredOMAGServicesResponse getRegisteredAccessServices(@Parameter(description="calling user") @PathVariable String userId) { return platformAPI.getRegisteredAccessServices(userId); } /** * Return the list of engine services that are implemented in this OMAG Server Platform * and can be configured for an engine host server. * * @param userId calling user * @return list of service descriptions */ @GetMapping(path = "/registered-services/engine-services") @Operation( summary = "Get registered engine services", description="Retrieve a list of engine services implemented in this platform", responses = { @ApiResponse(responseCode = "200", description="list of service descriptions", content = @Content( mediaType ="application/json", schema = @Schema(implementation=RegisteredOMAGServicesResponse.class) ) ) }) public RegisteredOMAGServicesResponse getRegisteredEngineServices(@Parameter(description="calling user") @PathVariable String userId) { return platformAPI.getRegisteredEngineServices(userId); } /** * Return the list of integration services that are implemented in this OMAG Server Platform * and can be configured for a integration daemon server. * * @param userId calling user * @return list of service descriptions */ @GetMapping(path = "/registered-services/integration-services") @Operation( summary = "Get registered integration services", description="Retrieve a list of integration services implemented in this platform", responses = { @ApiResponse(responseCode = "200", description="list of service descriptions", content = @Content( mediaType ="application/json", schema = @Schema(implementation=RegisteredOMAGServicesResponse.class) ) ) }) public RegisteredOMAGServicesResponse getRegisteredIntegrationServices(@Parameter(description="calling user") @PathVariable String userId) { return platformAPI.getRegisteredIntegrationServices(userId); } /** * Return the list of view services that are registered (supported) in this OMAG Server Platform * and can be configured for a view server. * * @param userId calling user * @return list of service descriptions */ @GetMapping(path = "/registered-services/view-services") @Operation( summary = "Get registered view services", description="Retrieve a list of view services registered on this platform", responses = { @ApiResponse(responseCode = "200", description="list of service descriptions", content = @Content( mediaType ="application/json", schema = @Schema(implementation=RegisteredOMAGServicesResponse.class) ) ) }) public RegisteredOMAGServicesResponse getRegisteredViewServices(@Parameter(description="calling user") @PathVariable String userId) { return platformAPI.getRegisteredViewServices(userId); } /** * Return the list of governance services that are registered (supported) in this OMAG Server Platform * and can be configured as part of a governance server. * * @param userId calling user * @return list of service descriptions */ @GetMapping(path = "/registered-services/governance-services") @Operation( summary = "Get registered governance services", description="Retrieve a list of governance services registered on this platform", responses = { @ApiResponse(responseCode = "200", description="list of service descriptions", content = @Content( mediaType ="application/json", schema = @Schema(implementation=RegisteredOMAGServicesResponse.class) ) ) }) public RegisteredOMAGServicesResponse getRegisteredGovernanceServices(@Parameter(description="calling user") @PathVariable String userId) { return platformAPI.getRegisteredGovernanceServices(userId); } /** * Return the list of common services that are registered (supported) in this OMAG Server Platform * and can be configured as part of any server. * * @param userId calling user * @return list of service descriptions */ @GetMapping(path = "/registered-services/common-services") @Operation( summary = "Get registered common services", description="Retrieve a list of common services registered on this platform", responses = { @ApiResponse(responseCode = "200",description="list of service descriptions", content = @Content( mediaType ="application/json", schema = @Schema(implementation=RegisteredOMAGServicesResponse.class) ) ) }) public RegisteredOMAGServicesResponse getRegisteredCommonServices(@Parameter(description="calling user") @PathVariable String userId) { return platformAPI.getRegisteredCommonServices(userId); } /** * Return the list of all services that are registered (supported) in this OMAG Server Platform. * * @param userId calling user * @return list of service descriptions */ @GetMapping(path = "/registered-services") @Operation( summary = "Get all registered services", description="Retrieve a list of all services registered on this platform", responses = { @ApiResponse(responseCode = "200",description="list of service descriptions", content = @Content( mediaType ="application/json", schema = @Schema(implementation=RegisteredOMAGServicesResponse.class) ) ) }) public RegisteredOMAGServicesResponse getAllRegisteredServices(@Parameter(description="calling user") @PathVariable String userId) { return platformAPI.getAllRegisteredServices(userId); } /** * Return a flag to indicate if this server has ever run on this OMAG Server Platform. * * @param userId calling user * @param serverName server of interest * @return flag */ @GetMapping(path = "/servers/{serverName}/is-known") @Operation( summary = "Is server known", description="Return a boolean indication if this server has ever run on this platform", responses = { @ApiResponse(responseCode = "200",description="boolean flag", content = @Content( mediaType ="application/json", schema = @Schema(implementation=RegisteredOMAGServicesResponse.class) ) ) }) public BooleanResponse isServerKnown(@Parameter(description="calling user") @PathVariable String userId, @Parameter(description="server name") @PathVariable String serverName) { return platformAPI.isServerKnown(userId, serverName); } /** * Return the list of OMAG Servers that have run or are running in this OMAG Server Platform. * * @param userId calling user * @return list of OMAG server names */ @GetMapping(path = "/servers") @Operation( summary = "Get list of known servers", description="Return the list of servers that have run or are running on this platform", responses = { @ApiResponse(responseCode = "200",description="list of servers", content = @Content( mediaType ="application/json", schema = @Schema(implementation=ServerListResponse.class) ) ) }) public ServerListResponse getKnownServerList(@Parameter(description="calling user") @PathVariable String userId) { return platformAPI.getKnownServerList(userId); } /** * Return the list of OMAG Servers that are active on this OMAG Server Platform. * * @param userId name of the user making the request * @return list of server names */ @GetMapping(path = "/servers/active") @Operation( summary = "Get list of active servers", description="Return the list of servers that are active on this platform", responses = { @ApiResponse(responseCode = "200",description="list of servers", content = @Content( mediaType ="application/json", schema = @Schema(implementation= ServerListResponse.class) ) ) }) public ServerListResponse getActiveServerList(@Parameter(description="calling user") @PathVariable String userId) { return platformAPI.getActiveServerList(userId); } /** * Return information about when the server has been active. * * @param userId name of the user making the request * @param serverName name of the server of interest * @return details of the server status */ @GetMapping(path = "/servers/{serverName}/status") @Operation( summary = "Get server status", description="Return information about when the server has been active", responses = { @ApiResponse(responseCode = "200",description="details of server status", content = @Content( mediaType ="application/json", schema = @Schema(implementation=ServerStatusResponse.class) ) ) }) public ServerStatusResponse getServerStatus(@Parameter(description="calling user") @PathVariable String userId, @Parameter(description="server name") @PathVariable String serverName) { return platformAPI.getServerStatus(userId, serverName); } /** * Return the list of services that are active on a specific OMAG Server that is active on this OMAG Server Platform. * * @param userId name of the user making the request * @param serverName name of the server of interest * @return server name and list od services running within */ @GetMapping(path = "/servers/{serverName}/services") @Operation( summary = "Get active services for server", description="Return the list of services that are active on the server on this platform", responses = { @ApiResponse(responseCode = "200",description="details of server status", content = @Content( mediaType ="application/json", schema = @Schema(implementation=ServerServicesListResponse.class) ) ) }) public ServerServicesListResponse getActiveServiceListForServer(@Parameter(description="calling user") @PathVariable String userId, @Parameter(description="server name") @PathVariable String serverName) { return platformAPI.getActiveServiceListForServer(userId, serverName); } }
package pugbot.core.entities; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import net.dv8tion.jda.core.Permission; import net.dv8tion.jda.core.entities.Member; import net.dv8tion.jda.core.entities.TextChannel; import pugbot.core.Database; import pugbot.core.entities.timers.QueueFinishTimer; public class QueueManager { private List<Queue> queueList = new ArrayList<>(); private ConcurrentHashMap<QueueFinishTimer, Game> finishedGameMap = new ConcurrentHashMap<>(); private Server server; public QueueManager(Server server) { this.server = server; Database.loadServerQueues(this); } public void addQueue(Queue queue){ queueList.add(queue); } public void removeQueue(Queue queue){ queueList.remove(queue); } /** * Returns the queue list. * * @return List containing all the queues */ public List<Queue> getQueueList() { return queueList; } public List<Queue> getListOfQueuesFromStringArgs(String[] args){ List<Queue> queues = new ArrayList<Queue>(); Queue queue; for(String arg : args){ queue = getQueue(arg); if(queue != null && !queues.contains(queue)){ queues.add(queue); } } return queues; } public Queue getQueue(String queueVal){ Queue queue; try{ queue = getQueueByIndex(Integer.valueOf(queueVal)); }catch(NumberFormatException ex){ queue = getQueueByName(queueVal); } return queue; } /** * Returns a boolean result based on if the queue list is empty or not. * * @return returns true if empty, false if not empty */ public boolean isQueueListEmpty() { return queueList.isEmpty(); } /** * Returns a String containing compiled basic queue information. * * @return String containing compiled basic queue information */ public String getHeader() { if (isQueueListEmpty()) { return "NO ACTIVE QUEUES"; } else { String header = ""; for (Queue q : queueList) { String games = ""; if (q.getNumberOfGames() > 0) { games = String.format(" (In game)"); } header += String.format("%s [%d/%d]%s ", q.getName(), q.getCurrentPlayersCount(), q.getMaxPlayers(), games); } header = header.substring(0, header.lastIndexOf(" ")); return header; } } /** * Removes a list of players from all queues * * @param players List of Member to be removed */ public void purgeQueue(List<Member> players) { for (Queue q : queueList) { q.purge(players); } } /** * Removes a specified player from all queues. * * @param player the player to be removed */ public void purgeQueue(Member player) { for (Queue q : queueList) { q.delete(player); } } /** * Sets the topic of the server's pug channel and saves the queue to file. */ public void updateTopic() { Member self = getServer().getGuild().getSelfMember(); TextChannel pugChannel = getServer().getPugChannel(); if(self.hasPermission(pugChannel, Permission.MANAGE_CHANNEL)) { pugChannel.getManager().setTopic(getHeader()).queue(); } } /** * Returns a boolean based on if the player is in-game or not. * * @param player the player to check * @return true if the player is in-game, false if not */ public boolean isPlayerIngame(Member player) { for (Queue q : queueList) { for (Game g : q.getGames()) { if (g.getPlayers().contains(player)) { return true; } } } return false; } public Game getPlayersGame(Member player){ for (Queue q : queueList) { for (Game g : q.getGames()) { if (g.getPlayers().contains(player)) { return g; } } } return null; } private void addToJustFinished(Game game) { QueueFinishTimer timer = new QueueFinishTimer(this); finishedGameMap.put(timer, game); timer.start(); } public void queueFinishTimerEnd(QueueFinishTimer timer) { Game g = finishedGameMap.get(timer); for (Queue q : queueList) { q.addPlayersWaiting(g.getPlayers()); } g.cleanup(); finishedGameMap.remove(timer); updateTopic(); } public int getWaitTimeRemaining(Member player){ for(QueueFinishTimer timer : finishedGameMap.keySet()){ Game g = finishedGameMap.get(timer); if(g.containsPlayer(player)){ return timer.getTimeRemaining(); } } return 0; } /** * Checks if a player is currently in a queue or not. * * @param player the player to be checked * @return true if the player is in a queue, false of not */ public boolean isPlayerInQueue(Member player) { for (Queue q : queueList) { if (q.getPlayersInQueue().contains(player) || q.isPlayerInWaitlist(player)) { return true; } } return false; } public boolean hasPlayerJustFinished(Member player) { for(QueueFinishTimer timer : finishedGameMap.keySet()){ Game g = finishedGameMap.get(timer); if(g.containsPlayer(player)){ return true; } } return false; } /** * Gets the id of the guild associated with this instance of QueueManager. * * @return the guild id associated with this QueueManager instance */ public long getServerId() { return server.getId(); } /** * Gets the Server object associated with this instance of QueueManager. * * @return the Server instance associated with this QueueManager instance */ public Server getServer() { return server; } /** * Checks if the specified queue exists. * * @param name the name of the queue to check * @return true if the queue exists */ public boolean doesQueueExist(String name) { for (Queue q : queueList) { if (q.getName().equalsIgnoreCase(name)) { return true; } } return false; } /** * Checks if the specified queue exists. * * @param index the one-based index of the queue to check * @return true if the queue exists */ public boolean doesQueueExist(Integer index) { if (index >= 0 && index < queueList.size()) { return true; } else { return false; } } /** * Returns a specific queue. * * @param queueName the name of the queue to return * @return Queue object matching the name param, null if no matches */ public Queue getQueueByName(String queueName){ for(Queue q : queueList){ if(q.getName().equalsIgnoreCase(queueName)){ return q; } } return null; } /** * Returns a specific queue. * * @param index the one-based index of the queue to return * @return Queue object at the specified index, null if no matches */ public Queue getQueueByIndex(Integer index){ index--; if(doesQueueExist(index)){ return queueList.get(index); }else{ return null; } } /** * Returns boolean based on if the player is in a queue's wait list. * * @param player the player to check * @return true if the player is in a queue's wait list * @see Queue */ public boolean isPlayerWaiting(Member player){ for(Queue q : queueList){ if(q.isPlayerInWaitlist(player)){ return true; } } return false; } public void finishAllGames(){ for(Queue queue : queueList){ for(Game game : queue.getGames()){ game.cleanup(); } } } public void finishGame(Game game, Integer winningTeam){ Queue queue = game.getParentQueue(); game.finish(); queue.removeGame(game); Database.updateGameInfo(game.getTimestamp(), queue.getId(), getServerId(), System.currentTimeMillis(), winningTeam); if(winningTeam == null){ game.cleanup(); updateTopic(); return; } addToJustFinished(game); } }
package com.linkedinlearning.learning_lil; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class LearningLilApplicationTests { @Test void contextLoads() { } }
package com.google.firebase.example.fireeats.java.activities; import android.Manifest; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.PorterDuff; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.StringRes; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.core.view.MenuItemCompat; import androidx.lifecycle.ViewModelProvider; import com.firebase.ui.auth.AuthUI; import com.firebase.ui.auth.ErrorCodes; import com.firebase.ui.auth.IdpResponse; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.android.libraries.places.api.Places; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.example.fireeats.R; import com.google.firebase.example.fireeats.java.adapter.BottomBarAdapter; import com.google.firebase.example.fireeats.java.adapter.NoSwipePager; import com.google.firebase.example.fireeats.java.fragment.home.CategoryFragment; import com.google.firebase.example.fireeats.java.model.PaymentDetail; import com.google.firebase.example.fireeats.java.fragment.home.HomeFragment; import com.google.firebase.example.fireeats.java.fragment.home.OrderFragment; import com.google.firebase.example.fireeats.java.fragment.home.UserFragment; import com.google.firebase.example.fireeats.java.utils.Tools; import com.google.firebase.example.fireeats.java.viewmodel.MainActivityViewModel; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.messaging.FirebaseMessaging; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Map; public class HomeActivity extends AppCompatActivity { private ImageView[] menu_nav; private View notif_badge; private NoSwipePager viewPager; private BottomBarAdapter pagerAdapter; private int notification_count = -1; private ActionBar actionBar; private Toolbar toolbar; private FirebaseFirestore mFirestore; HomeFragment frag1 = new HomeFragment(); CategoryFragment frag2 = new CategoryFragment(); OrderFragment frag3 = new OrderFragment(); UserFragment fragmentProfile = new UserFragment(); private static final String TAG = "HomeActivity"; private static final int RC_SIGN_IN = 9001; private MainActivityViewModel mViewModel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_bottom_navigation_small); FirebaseMessaging.getInstance().getToken() .addOnCompleteListener(new OnCompleteListener<String>() { @Override public void onComplete(@NonNull Task<String> task) { if (!task.isSuccessful()) { Log.w(TAG, "Fetching FCM registration token failed", task.getException()); return; } // Get new FCM registration token String token = task.getResult(); // Log and toast Log.d("FIREBASE TOKEN FUCK YOU", token); // Toast.makeText(HomeActivity.this, token, Toast.LENGTH_SHORT).show(); } }); int permissionCheck = ContextCompat.checkSelfPermission(HomeActivity.this, Manifest.permission.ACCESS_FINE_LOCATION); if(permissionCheck != PackageManager.PERMISSION_GRANTED) { // ask permissions here using below code ActivityCompat.requestPermissions(HomeActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 99); } Places.initialize(getApplicationContext(), "AIzaSyCr2k5mtuFQSSS753K-If6OFXInjMYKhi4"); Places.createClient(this); // Enable Firestore logging FirebaseFirestore.setLoggingEnabled(true); //optimisation viewPager = findViewById(R.id.viewPager); viewPager.setOffscreenPageLimit(3); viewPager.setPagingEnabled(false); pagerAdapter = new BottomBarAdapter(getSupportFragmentManager()); pagerAdapter.addFragments(frag1); pagerAdapter.addFragments(frag2); pagerAdapter.addFragments(frag3); pagerAdapter.addFragments(fragmentProfile); viewPager.setAdapter(pagerAdapter); // View model mViewModel = new ViewModelProvider(this).get(MainActivityViewModel.class); fragmentProfile.setmViewModel(mViewModel); // Firestore mFirestore = FirebaseFirestore.getInstance(); initToolbar(); initComponent(); } @Override public void onStart() { super.onStart(); // Start sign in if necessary if (shouldStartSignIn()) { startSignIn(); return; } else { FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); DocumentReference cartRef = mFirestore.collection("carts").document(user.getUid()); cartRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { @Override public void onComplete(@NonNull Task<DocumentSnapshot> task) { if (task.isSuccessful()) { DocumentSnapshot document = task.getResult(); if (document.exists()) { Log.d(TAG, "DocumentSnapshot data: " + document.getData()); } else { Map<String, Object> dataInit = new HashMap<>(); dataInit.put("total", 0); dataInit.put("cartObjectList", new ArrayList<>()); mFirestore.collection("carts").document(FirebaseAuth.getInstance().getCurrentUser().getUid()) .set(dataInit); Log.d(TAG, "No such document"); } } else { Log.d(TAG, "get failed with ", task.getException()); } } }); DocumentReference paymentDetailRef = mFirestore.collection("paymentDetails").document(user.getUid()); paymentDetailRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { @Override public void onComplete(@NonNull Task<DocumentSnapshot> task) { if (task.isSuccessful()) { DocumentSnapshot document = task.getResult(); if (document.exists()) { Log.d(TAG, "DocumentSnapshot data: " + document.getData()); } else { PaymentDetail paymentDetail = new PaymentDetail(); mFirestore .collection("paymentDetails") .document(FirebaseAuth.getInstance().getCurrentUser().getUid()) .set(paymentDetail); Log.d(TAG, "No such document"); } } else { Log.d(TAG, "get failed with ", task.getException()); } } }); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RC_SIGN_IN) { IdpResponse response = IdpResponse.fromResultIntent(data); mViewModel.setIsSigningIn(false); if (resultCode != RESULT_OK) { if (response == null) { // User pressed the back button. finish(); } else if (response.getError() != null && response.getError().getErrorCode() == ErrorCodes.NO_NETWORK) { showSignInErrorDialog(R.string.message_no_network); } else { showSignInErrorDialog(R.string.message_unknown); } } } } private void initToolbar() { toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(false); actionBar.setHomeButtonEnabled(true); Tools.setSystemBarColor(this, R.color.grey_5); Tools.setSystemBarLight(this); } private void initComponent() { menu_nav = new ImageView[4]; menu_nav[0] = findViewById(R.id.menu_nav_1); menu_nav[1] = findViewById(R.id.menu_nav_2); menu_nav[2] = findViewById(R.id.menu_nav_3); menu_nav[3] = findViewById(R.id.menu_nav_5); // display image Tools.displayImageOriginal(this, (ImageView) findViewById(R.id.image_1), R.drawable.image_18); Tools.displayImageOriginal(this, (ImageView) findViewById(R.id.image_2), R.drawable.image_30); Tools.displayImageOriginal(this, (ImageView) findViewById(R.id.image_3), R.drawable.image_21); Tools.displayImageOriginal(this, (ImageView) findViewById(R.id.image_5), R.drawable.image_19); for (ImageView iv : menu_nav) { if (iv.getId() == R.id.menu_nav_1) { iv.setColorFilter(getResources().getColor(R.color.colorPrimary), PorterDuff.Mode.SRC_IN); break; } } } public void onNavigationClick(View view) { for (ImageView iv : menu_nav) { iv.setColorFilter(getResources().getColor(R.color.grey_20), PorterDuff.Mode.SRC_IN); if (iv.getId() == view.getId()) { switch (iv.getId()) { case R.id.menu_nav_1: System.out.println("First tab"); viewPager.setCurrentItem(0); break; case R.id.menu_nav_2: System.out.println("2nd tab"); viewPager.setCurrentItem(1); break; case R.id.menu_nav_3: System.out.println("3rd tab"); viewPager.setCurrentItem(2); frag3.loadOrder(); break; case R.id.menu_nav_5: System.out.println("4th tab"); viewPager.setCurrentItem(3); break; } iv.setColorFilter(getResources().getColor(R.color.colorPrimary), PorterDuff.Mode.SRC_IN); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_activity_main, menu); Tools.changeMenuIconColor(menu, getResources().getColor(R.color.grey_60)); Tools.changeOverflowMenuIconColor(toolbar, getResources().getColor(R.color.grey_60)); final MenuItem menu_notif = menu.findItem(R.id.action_cart); View actionView = MenuItemCompat.getActionView(menu_notif); actionView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onOptionsItemSelected(menu_notif); } }); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int item_id = item.getItemId(); if (item_id == R.id.action_cart) { //go to cart Intent intent = new Intent(this, ShoppingCartActivity.class); intent.putExtra("fuck you", "fuck"); startActivity(intent); } return super.onOptionsItemSelected(item); } private boolean shouldStartSignIn() { return (!mViewModel.getIsSigningIn() && FirebaseAuth.getInstance().getCurrentUser() == null); } private void startSignIn() { // Sign in with FirebaseUI Intent intent = AuthUI.getInstance().createSignInIntentBuilder() .setAvailableProviders(Collections.singletonList( new AuthUI.IdpConfig.EmailBuilder().build())) .setIsSmartLockEnabled(false) .build(); startActivityForResult(intent, RC_SIGN_IN); mViewModel.setIsSigningIn(true); } private void showSignInErrorDialog(@StringRes int message) { AlertDialog dialog = new AlertDialog.Builder(this) .setTitle(R.string.title_sign_in_error) .setMessage(message) .setCancelable(false) .setPositiveButton(R.string.option_retry, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { startSignIn(); } }) .setNegativeButton(R.string.option_exit, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { finish(); } }).create(); dialog.show(); } }
/** * Copyright 2018 Institute of Computing Technology, Chinese Academy of Sciences. * Licensed under the terms of the Apache 2.0 license. * Please see LICENSE file in the project root for terms */ package eml.studio.server.visual.service; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import eml.studio.server.visual.charts.BarChart; import eml.studio.server.visual.statics.ThreadDataParser; import eml.studio.server.visual.statics.ThreadUtils; import eml.studio.shared.util.DataTools; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; /** * Service for generate bar chart */ public class BarChartService extends ChartService { private static final Logger logger = Logger.getLogger(ChartService.class.getName()); private static final int MAX_GROUP_SIZE = 16; /** * Get bar chart data option string to draw the chart * * @param filePath data file path * @param dataType data type * @param columns data all columns * @param gByCol group by column * @param valCol value column * @param aggCol aggregation column * @param logScale value column log scale * @return * @throws IllegalArgumentException */ public BarChart barChartGen(String filePath, String dataType, List<String> columns, String gByCol, String valCol, String aggCol, boolean logScale) throws IllegalArgumentException { // TODO Auto-generated method stub //Read data from hdfs List<String> results = readAllData(filePath, true); //Only read limited line data(if the data length over max length) //Prepare selected column list and init result list List<String> selectedCols = new ArrayList<String>(); selectedCols.add(gByCol); selectedCols.add(valCol); List<List<String>> selectedColsDatas = new ArrayList<List<String>>(); initiaColResults(selectedColsDatas, selectedCols); //Use Multithread to parse specific column data ExecutorService exec = Executors.newCachedThreadPool(); int threadNum = ThreadUtils.THREAD_NUM; int countNum = (int) Math.ceil(results.size() / threadNum); for (int i = 0; i < threadNum; i++) { int startInx = i * countNum; int endInx = startInx + countNum; if (i == threadNum - 1) endInx = results.size(); exec.execute(new ThreadDataParser(results.subList(startInx, endInx), selectedCols, columns, dataType, selectedColsDatas)); } exec.shutdown(); // wait until sum-process is over try { exec.awaitTermination(5, TimeUnit.MINUTES); } catch (InterruptedException e) { logger.info("exec.awaitTermination(1, TimeUnit.HOURS) occurs error : " + e); } List<String> gByDatas = selectedColsDatas.get(0); List<String> valDatas = selectedColsDatas.get(1); logger.info("【BarChart】Parse group column=" + gByCol + ", size = " + gByDatas.size()); logger.info("【BarChart】Parse value column=" + valCol + ", size = " + valDatas.size()); //Use group column to group value column data HashMap<String, List<String>> groupDatas = new HashMap<String, List<String>>(); for (int k = 0; k < gByDatas.size(); k++) { String key = gByDatas.get(k); String value = valDatas.get(k); if (groupDatas.containsKey(key)) groupDatas.get(key).add(value); else { List<String> values = new ArrayList<String>(); values.add(value); groupDatas.put(key, values); } } // If the group over MAX_GROUP_SIZE, then return barChart with null category, tell user this column can not group data if (groupDatas.keySet().size() > MAX_GROUP_SIZE) { double[] datas = new double[groupDatas.keySet().size()]; BarChart barChart = new BarChart(null, datas); return barChart; } else { HashMap<String, Double> statRets = new HashMap<String, Double>(); switch (aggCol) { case "average": computAvg(groupDatas, statRets); break; case "stand_deviation": computStand(groupDatas, statRets); break; case "count": computCount(groupDatas, statRets); break; case "minimum": computMin(groupDatas, statRets); break; case "maximum": computMax(groupDatas, statRets); break; } if (statRets.size() == 0) //If the data is not numerical, the return barChart with null values, tell user this column is not numerical { String[] categories = new String[MAX_GROUP_SIZE]; return new BarChart(categories, null); } String[] categories = new String[statRets.keySet().size()]; double[] values = new double[statRets.keySet().size()]; Iterator<Entry<String, Double>> dataIter = statRets.entrySet().iterator(); int k = 0; while (dataIter.hasNext()) { Entry<String, Double> entry = dataIter.next(); categories[k] = entry.getKey(); if (logScale) values[k] = m3(Math.log(entry.getValue())); else values[k] = entry.getValue(); k++; } BarChart barChart = new BarChart(categories, values); return barChart; } } /** * Compute data average * * @param groupDatas group list datas * @param statRets group average values */ private void computAvg(HashMap<String, List<String>> groupDatas, HashMap<String, Double> statRets) { Iterator<Entry<String, List<String>>> dataIter = groupDatas.entrySet().iterator(); while (dataIter.hasNext()) { Entry<String, List<String>> entry = dataIter.next(); String key = entry.getKey(); List<String> datas = entry.getValue(); double sum = 0; int count = 0; for (String data : datas) { if (data.equals("")) continue; if (DataTools.isNumeric(data)) { count = count + 1; sum = sum + Double.valueOf(data); } else { // As long as one is not numeric, it returns null statRets = new HashMap<String, Double>(); return; } } if (count != 0) statRets.put(key, sum / count); } } /** * Compute standard deviation * * @param groupDatas group list datas * @param statRets group standard deviation values */ private void computStand(HashMap<String, List<String>> groupDatas, HashMap<String, Double> statRets) { Iterator<Entry<String, List<String>>> dataIter = groupDatas.entrySet().iterator(); while (dataIter.hasNext()) { Entry<String, List<String>> entry = dataIter.next(); String key = entry.getKey(); List<String> datas = entry.getValue(); double sum = 0; int count = 0; for (String data : datas) { if (DataTools.isNumeric(data)) { count = count + 1; sum = sum + Double.valueOf(data); } else { // As long as one is not numeric, it returns null statRets = new HashMap<String, Double>(); return; } } if (count != 0) { double avg = sum / count; double stdSum = 0; for (String data : datas) { if (DataTools.isNumeric(data)) { double numData = Double.valueOf(data); stdSum = stdSum + Math.pow(numData - avg, 2); } } statRets.put(key, Math.sqrt(stdSum / count)); } } } /** * Compute data count * * @param groupDatas group list datas * @param statRets group count values */ private void computCount(HashMap<String, List<String>> groupDatas, HashMap<String, Double> statRets) { Iterator<Entry<String, List<String>>> dataIter = groupDatas.entrySet().iterator(); while (dataIter.hasNext()) { Entry<String, List<String>> entry = dataIter.next(); String key = entry.getKey(); List<String> datas = entry.getValue(); int count = 0; for (String data : datas) { if (DataTools.isNumeric(data)) { count = count + 1; } else { // As long as one is not numeric, it returns null statRets = new HashMap<String, Double>(); return; } } if (count != 0) statRets.put(key, Double.valueOf(count)); } } /** * Compute minimum value * * @param groupDatas group list datas * @param statRets group minimum values */ private void computMin(HashMap<String, List<String>> groupDatas, HashMap<String, Double> statRets) { Iterator<Entry<String, List<String>>> dataIter = groupDatas.entrySet().iterator(); while (dataIter.hasNext()) { Entry<String, List<String>> entry = dataIter.next(); String key = entry.getKey(); List<String> datas = entry.getValue(); double min = Double.MAX_VALUE; int count = 0; for (String data : datas) { if (DataTools.isNumeric(data)) { if (Double.valueOf(data) < min) min = Double.valueOf(data); count = count + 1; } else { // As long as one is not numeric, it returns null statRets = new HashMap<String, Double>(); return; } } if (count != 0) statRets.put(key, min); } } /** * Compute maximal value * * @param groupDatas group list datas * @param statRets group maximal values */ private void computMax(HashMap<String, List<String>> groupDatas, HashMap<String, Double> statRets) { Iterator<Entry<String, List<String>>> dataIter = groupDatas.entrySet().iterator(); while (dataIter.hasNext()) { Entry<String, List<String>> entry = dataIter.next(); String key = entry.getKey(); List<String> datas = entry.getValue(); double max = Double.MIN_VALUE; int count = 0; for (String data : datas) { if (DataTools.isNumeric(data)) { if (Double.valueOf(data) > max) max = Double.valueOf(data); count = count + 1; } else { // As long as one is not numeric, it returns null statRets = new HashMap<String, Double>(); return; } } if (count != 0) statRets.put(key, max); } } }
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.imagepipeline.cache; import android.graphics.Bitmap; import com.facebook.common.internal.Preconditions; import com.facebook.common.references.CloseableReference; import com.facebook.infer.annotation.Nullsafe; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.annotation.Nullable; /** Inspects values cached in bitmap memory cache. */ @Nullsafe(Nullsafe.Mode.LOCAL) public class CountingMemoryCacheInspector<K, V> { /** Cache entry info for use by dumpers. */ public static class DumpInfoEntry<K, V> { // The key is immutable, so it's safe to store that directly public final K key; // The value public final @Nullable CloseableReference<V> value; public DumpInfoEntry(final K key, final CloseableReference<V> valueRef) { this.key = Preconditions.checkNotNull(key); this.value = CloseableReference.cloneOrNull(valueRef); } public void release() { CloseableReference.closeSafely(value); } } /** Info about the status of the cache for use by dumpers. */ public static class DumpInfo<K, V> { public final int maxSize; public final int maxEntriesCount; public final int maxEntrySize; public final int size; public final int lruSize; public final List<DumpInfoEntry<K, V>> lruEntries; public final List<DumpInfoEntry<K, V>> sharedEntries; public final Map<Bitmap, Object> otherEntries; public DumpInfo(int size, int lruSize, MemoryCacheParams params) { maxSize = params.maxCacheSize; maxEntriesCount = params.maxCacheEntries; maxEntrySize = params.maxCacheEntrySize; this.size = size; this.lruSize = lruSize; lruEntries = new ArrayList<>(); sharedEntries = new ArrayList<>(); otherEntries = new HashMap<>(); } public void release() { for (DumpInfoEntry entry : lruEntries) { entry.release(); } for (DumpInfoEntry entry : sharedEntries) { entry.release(); } } } private final CountingMemoryCache<K, V> mCountingBitmapCache; public CountingMemoryCacheInspector(CountingMemoryCache<K, V> countingBitmapCache) { mCountingBitmapCache = countingBitmapCache; } /** * Iterates through all entries cached in counting cache and builds snapshot of its content. This * should be used by tools that need to know current content of given cache. * * <p>Caller should call release method on returned DumpInfo after it is done with examining cache * contents */ public DumpInfo dumpCacheContent() { synchronized (mCountingBitmapCache) { DumpInfo<K, V> dumpInfo = new DumpInfo<>( mCountingBitmapCache.getSizeInBytes(), mCountingBitmapCache.getEvictionQueueSizeInBytes(), mCountingBitmapCache.getMemoryCacheParams()); @Nullable CountingLruMap<K, CountingMemoryCache.Entry<K, V>> maybeCachedEntries = mCountingBitmapCache.getCachedEntries(); if (maybeCachedEntries == null) { return dumpInfo; } final List<LinkedHashMap.Entry<K, CountingMemoryCache.Entry<K, V>>> cachedEntries = maybeCachedEntries.getMatchingEntries(null); for (LinkedHashMap.Entry<K, CountingMemoryCache.Entry<K, V>> cachedEntry : cachedEntries) { CountingMemoryCache.Entry<K, V> entry = cachedEntry.getValue(); DumpInfoEntry<K, V> dumpEntry = new DumpInfoEntry<>(entry.key, entry.valueRef); if (entry.clientCount > 0) { dumpInfo.sharedEntries.add(dumpEntry); } else { dumpInfo.lruEntries.add(dumpEntry); } } Map<Bitmap, Object> otherEntries = mCountingBitmapCache.getOtherEntries(); if (otherEntries != null) { for (Map.Entry<Bitmap, Object> entry : otherEntries.entrySet()) { if (entry != null && !entry.getKey().isRecycled()) { dumpInfo.otherEntries.put(entry.getKey(), entry.getValue()); } } } return dumpInfo; } } }
package com.foresee.echarts.model; public class BarModel extends AxisModel{ }
/** * Description: * 网站: <a href="http://www.crazyit.org">疯狂Java联盟</a><br> * Copyright (C), 2001-2018, Yeeku.H.Lee<br> * This program is protected by copyright laws.<br> * Program Name:<br> * Date:<br> * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ class Account { /* 定义一个ThreadLocal类型的变量,该变量将是一个线程局部变量 每个线程都会保留该变量的一个副本 */ private ThreadLocal<String> name = new ThreadLocal<>(); // 定义一个初始化name成员变量的构造器 public Account(String str) { this.name.set(str); // 下面代码用于访问当前线程的name副本的值 System.out.println("---" + this.name.get()); } // name的setter和getter方法 public String getName() { return name.get(); } public void setName(String str) { this.name.set(str); } } class MyTest extends Thread { // 定义一个Account类型的成员变量 private Account account; public MyTest(Account account, String name) { super(name); this.account = account; } public void run() { // 循环10次 for (int i = 0 ; i < 10 ; i++) { // 当i == 6时输出将账户名替换成当前线程名 if (i == 6) { account.setName(getName()); } // 输出同一个账户的账户名和循环变量 System.out.println(account.getName() + " 账户的i值:" + i); } } } public class ThreadLocalTest { public static void main(String[] args) { // 启动两条线程,两条线程共享同一个Account Account at = new Account("初始名"); /* 虽然两条线程共享同一个账户,即只有一个账户名 但由于账户名是ThreadLocal类型的,所以每条线程 都完全拥有各自的账户名副本,所以从i == 6之后,将看到两条 线程访问同一个账户时看到不同的账户名。 */ new MyTest(at , "线程甲").start(); new MyTest(at , "线程乙").start (); } }
package com.project1.meetday; import com.project1.http.Const; import com.project1.http.FileAccess; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.EditText; import android.widget.ImageButton; import android.widget.Toast; public class RegisterPage extends Activity { private static ImageButton Registerbutton; private static EditText login_email, login_pwd, login_checkpwd, login_phone; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); //Do not show title setContentView(R.layout.register_page); //String mystring = settingsActivity.getString("mystring", ""); login_email = (EditText) findViewById(R.id.register_useremail_edit); login_pwd = (EditText) findViewById(R.id.register_userpassword_edit); login_checkpwd = (EditText) findViewById(R.id.register_checkuserpassword_edit); login_email.addTextChangedListener(new TextWatcher(){ public void afterTextChanged(Editable s){ // Abstract Method of TextWatcher Interface. } public void beforeTextChanged(CharSequence s,int start, int count, int after){ // Abstract Method of TextWatcher Interface. } public void onTextChanged(CharSequence s,int start, int before, int count){ if(login_email.getText().length() == 0){ login_email.setBackgroundResource(R.drawable.box_email); }else{ login_email.setBackgroundResource(R.drawable.box_select); } } }); login_pwd.addTextChangedListener(new TextWatcher(){ public void afterTextChanged(Editable s){ // Abstract Method of TextWatcher Interface. } public void beforeTextChanged(CharSequence s,int start, int count, int after){ // Abstract Method of TextWatcher Interface. } public void onTextChanged(CharSequence s,int start, int before, int count){ if(login_pwd.getText().length() == 0){ login_pwd.setBackgroundResource(R.drawable.box_password); }else{ login_pwd.setBackgroundResource(R.drawable.box_select); } } }); login_checkpwd.addTextChangedListener(new TextWatcher(){ public void afterTextChanged(Editable s){ // Abstract Method of TextWatcher Interface. } public void beforeTextChanged(CharSequence s,int start, int count, int after){ // Abstract Method of TextWatcher Interface. } public void onTextChanged(CharSequence s,int start, int before, int count){ if(login_checkpwd.getText().length() == 0){ login_checkpwd.setBackgroundResource(R.drawable.box_check); }else{ login_checkpwd.setBackgroundResource(R.drawable.box_select); } } }); Registerbutton = (ImageButton) findViewById(R.id.register_gotomainpage_btn); Registerbutton.setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0) { Toast.makeText(getApplicationContext(), //"Name :" + login_firstname.getText().toString() + login_lastname.getText().toString() + "\r\n" + "Email :" + login_email.getText().toString() + "\r\n" + "Password:" + login_pwd.getText().toString() + "\r\n" + "CheckPassword:" + login_checkpwd.getText().toString(), Toast.LENGTH_SHORT).show(); String pwdstring = login_pwd.getText().toString(); String checkpwdstring = login_checkpwd.getText().toString(); if(pwdstring.compareTo(checkpwdstring)==0){ if(login_email != null && login_pwd !=null){ ConnectToServer con = new ConnectToServer(getBaseContext()); con.DoRegister(login_email.getEditableText().toString(), login_pwd.getEditableText().toString()); } while(Const.lastcmdret.equals("")){ ; } Log.e("REG", "lastcmdret: " + Const.lastcmdret); String[] data = FileAccess.parseDataToPara(Const.lastcmdret, "%"); if(data[0].equals(Const.Command.Cmd_Register.toString())&&data[1].equals(Const.RRet.RRET_SUCCESS.toString())){ Intent i = new Intent(); i.setClass(RegisterPage.this, SignUpPage.class); //con.DoGetPhoto(personPhotoUrl); i.putExtra(SignUpPage.USERID, data[2]); i.putExtra(SignUpPage.NICKNAME, login_email.getEditableText().toString()); startActivity(i); RegisterPage.this.finish(); } else if(data[0].equals(Const.Command.Cmd_Register.toString())&&data[1].equals(Const.RRet.RRET_USER_EXIST_FAIL.toString())){ AlertDialog.Builder dialog = new AlertDialog.Builder(RegisterPage.this); dialog.setTitle("Register Failed!!!"); dialog.setMessage("User Exist or Format Fail"); dialog.setPositiveButton(R.string.ok_label,new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialoginterface, int i){ } }); dialog.show(); } Const.lastcmdret = ""; }else{ AlertDialog.Builder dialog = new AlertDialog.Builder(RegisterPage.this); dialog.setTitle("Register Failed!!!"); dialog.setMessage("your password entered incorrectly"); dialog.setPositiveButton(R.string.ok_label,new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialoginterface, int i){ } }); dialog.show(); } } }); } }
package com.brijesh.microservices.limitsservice; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; @SpringBootApplication @EnableDiscoveryClient public class LimitsServiceApplication { public static void main(String[] args) { SpringApplication.run(LimitsServiceApplication.class, args); } }
/* * 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 baseClasses.enterprise; import baseClasses.network.Network; import baseClasses.roles.Role; import baseClasses.userAccount.UserAccountDirectory; import java.util.ArrayList; /** * * @author Abhishek */ public class CountryEnterprise extends Enterprise { private Network countryNetwork; // To add country level login details for Government Panels private UserAccountDirectory userAccountDirectory; public Network getCountryNetwork() { return countryNetwork; } public void setCountryNetwork(Network countryNetwork) { this.countryNetwork = countryNetwork; } @Override public ArrayList<Role> getSupportedRole() { return null; } public CountryEnterprise(String name) { super(name, EnterpriseType.Country); countryNetwork = new Network(); } @Override public String toString() { return name; //To change body of generated methods, choose Tools | Templates. } }
/* ******************************************************************************* * Copyright (c) 2017 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * 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. ******************************************************************************/ /** * <p> * CDI Support for Microprofile OpenTracing. * * * * @author <a href="mailto:steve.m.fontes@gmail.com">Steve Fontes</a> */ @org.osgi.annotation.versioning.Version("2.0") package org.eclipse.microprofile.opentracing;
/***************************************************************** JADE - Java Agent DEvelopment Framework is a framework to develop multi-agent systems in compliance with the FIPA specifications. Copyright (C) 2000 CSELT S.p.A. GNU Lesser General Public License This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, version 2.1 of the License. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *****************************************************************/ package jade.mtp.http.https; //#PJAVA_EXCLUDE_FILE import jade.core.Profile; import java.io.FileInputStream; import java.security.KeyStore; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; /** * This class implements a concrete behaviour for HTTPS Trust decisions. If * we configure the platform to use this TrustManager, we must also specify * two configuration properties: * * <b>jade_mtp_http_https_firendListFile</b>: This property must indicate * the location of a java KeyStore in the disc. * * <b>jade_mtp_http_https_friendListFilePass</b> Password for this KeyStore. * * The KeyStore must contain a list of Trusted Certificates. When a new HTTPS * connection is stablished, trust decisions will be made in terms of * the certificates inside the KeyStore. If the Certificate sent by the remote * peer is inside of the KeyStore or signed by one of the issuers of the * inside the KeyStore, the connection will be stablished. Otherwise the * connection will not be possible. * * @author <a href="mailto:Joan.Ametller@uab.es">Joan Ametller Esquerra</a> * */ public class FriendListAuthentication implements HTTPSTrustManager { public X509Certificate[] getAcceptedIssuers() { return _tm.getAcceptedIssuers(); } public void checkClientTrusted(X509Certificate[] cert, String authType) throws CertificateException { _tm.checkClientTrusted(cert, authType); } public void checkServerTrusted(X509Certificate[] cert, String authType) throws CertificateException { _tm.checkServerTrusted(cert, authType); } public void init(Profile profile) throws Exception{ KeyStore ks = KeyStore.getInstance("JKS"); String filename = profile.getParameter("jade_mtp_http_https_friendListFile", ""); char[] pass = profile.getParameter("jade_mtp_http_https_friendListFilePass", "").toCharArray(); ks.load(new FileInputStream(filename), null); TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); tmf.init(ks); _tm = (X509TrustManager)tmf.getTrustManagers()[0]; } private X509TrustManager _tm; }
package com.faust; import android.content.SharedPreferences; import android.util.Log; class ParametersInfo { final String VERSION = "0.11"; // Saved Parameters String[] address; float[] values; int zoom; int[] accgyrType; int[] accgyrCurve; float[] accgyrMin; float[] accgyrMax; float[] accgyrCenter; int[] accgyrItemFocus; // Multi interface parameters int nMultiParams; int[] order; String[] label; float[] min; float[] max; float[] step; // Other Parameters int[] parameterType; int[] localId; int nParams = 0; int saved = 1; boolean locked = true; //OSC SETTING String ipAddress = "192.168.1.5"; int inPort = 5510; int outPort = 5511; int xmit = 1; public void init(int numberOfParams){ nParams = numberOfParams; address = new String[nParams]; values = new float[nParams]; accgyrType = new int[nParams]; accgyrCurve = new int[nParams]; accgyrMin = new float[nParams]; accgyrMax = new float[nParams]; accgyrCenter = new float[nParams]; accgyrItemFocus = new int[nParams]; parameterType = new int[nParams]; //0: hslider, 1: vslider localId = new int[nParams]; order = new int[nParams]; label = new String[nParams]; min = new float[nParams]; max = new float[nParams]; step = new float[nParams]; // assigning default values for(int i=0; i<nParams; i++){ accgyrType[i] = 0; accgyrMin[i] = -100.0f; accgyrMax[i] = 100.0f; accgyrCenter[i] = 0.0f; accgyrCurve[i] = 0; accgyrItemFocus[i] = 0; order[i] = -1; min[i] = 0; max[i] = 0; step[i] = 0; } } public void saveParameters(SharedPreferences settings){ SharedPreferences.Editor editor = settings.edit(); editor.putInt("wasSaved" + VERSION,saved); editor.putInt("zoom", zoom); editor.putBoolean("locked", locked); editor.putInt("nMultiParams", nMultiParams); editor.putString("ipAddress",ipAddress); editor.putInt("inPort",inPort); editor.putInt("outPort",outPort); editor.putInt("xMit",xmit); Log.d("FaustJava", "saveParameters : nParams " + nParams); for (int i = 0; i < nParams; i++){ editor.putFloat("value"+i, values[i]); editor.putInt("accgyrType"+i, accgyrType[i]); editor.putFloat("accgyrMin"+i, accgyrMin[i]); editor.putFloat("accgyrMax"+i, accgyrMax[i]); editor.putFloat("accgyrCenter"+i, accgyrCenter[i]); editor.putInt("accgyrCurve"+i, accgyrCurve[i]); //Log.d("FaustJava", "saveParameters accgyrCurve "+i + " " + accgyrCurve[i]); Log.d("FaustJava", "saveParameters accgyrType "+i + " " + accgyrType[i]); editor.putInt("order"+i, order[i]); editor.putString("label"+i, label[i]); editor.putFloat("min"+i, min[i]); editor.putFloat("max"+i, max[i]); editor.putFloat("step"+i, step[i]); } editor.commit(); } public boolean loadParameters(SharedPreferences settings){ if(settings.getInt("wasSaved" + VERSION,0) == 1){ zoom = settings.getInt("zoom", 0); locked = settings.getBoolean("locked",true); nMultiParams = settings.getInt("nMultiParams", 0); ipAddress = settings.getString("ipAddress","192.168.1.5"); inPort = settings.getInt("inPort",5510); outPort = settings.getInt("outPort",5511); xmit = settings.getInt("xMit", 1); Log.d("FaustJava", "loadParameters : nParams " + nParams); for (int i = 0; i < nParams; i++){ values[i] = settings.getFloat("value"+i,0.0f); accgyrType[i] = settings.getInt("accgyrType"+i, 0); //TODO: should be done only for controlled parameters accgyrMin[i] = settings.getFloat("accgyrMin"+i, 0); accgyrMax[i] = settings.getFloat("accgyrMax"+i, 0); accgyrCenter[i] = settings.getFloat("accgyrCenter"+i, 0); accgyrCurve[i] = settings.getInt("accgyrCurve"+i, 0); //Log.d("FaustJava", "loadParameters accgyrCurve "+i + " " + accgyrCurve[i]); Log.d("FaustJava", "loadParameters accgyrType "+i + " " + accgyrType[i]); // TODO perhaps this should be in a separate function for optimization saic... order[i] = settings.getInt("order"+i, 0); label[i] = settings.getString("label"+i, null); min[i] = settings.getFloat("min"+i, 0f); max[i] = settings.getFloat("max"+i, 0f); step[i] = settings.getFloat("step"+i, 0f); } return true; } else return false; } }
/* GraphicsConfiguration.java -- describes characteristics of graphics Copyright (C) 2000, 2001, 2002 Free Software Foundation This file is part of GNU Classpath. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Classpath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package java.awt; import gnu.classpath.NotImplementedException; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.VolatileImage; /** * This class describes the configuration of various graphics devices, such * as a monitor or printer. Different configurations may exist for the same * device, according to the different native modes supported. * * <p>Virtual devices are supported (for example, in a multiple screen * environment, a virtual device covers all screens simultaneously); the * configuration will have a non-zero relative coordinate system in such * a case. * * @author Eric Blake (ebb9@email.byu.edu) * @see Window * @see Frame * @see GraphicsEnvironment * @see GraphicsDevice * @since 1.0 * @status updated to 1.4 */ public abstract class GraphicsConfiguration { /** The cached image capabilities. */ private ImageCapabilities imageCapabilities; /** The cached buffer capabilities. */ private BufferCapabilities bufferCapabilities; /** * The default constructor. * * @see GraphicsDevice#getConfigurations() * @see GraphicsDevice#getDefaultConfiguration() * @see GraphicsDevice#getBestConfiguration(GraphicsConfigTemplate) * @see Graphics2D#getDeviceConfiguration() */ protected GraphicsConfiguration () { } /** * Gets the associated device that this configuration describes. * * @return the device */ public abstract GraphicsDevice getDevice(); /** * Returns a buffered image optimized to this device, so that blitting can * be supported in the buffered image. * * @param w the width of the buffer * @param h the height of the buffer * @return the buffered image, or null if none is supported */ public abstract BufferedImage createCompatibleImage(int w, int h); /** * Returns a buffered volatile image optimized to this device, so that * blitting can be supported in the buffered image. Because the buffer is * volatile, it can be optimized by native graphics accelerators. * * @param w the width of the buffer * @param h the height of the buffer * @return the buffered image, or null if none is supported * @see Component#createVolatileImage(int, int) * @since 1.4 */ public abstract VolatileImage createCompatibleVolatileImage(int w, int h); /** * Returns a buffered volatile image optimized to this device, and with the * given capabilities, so that blitting can be supported in the buffered * image. Because the buffer is volatile, it can be optimized by native * graphics accelerators. * * @param w the width of the buffer * @param h the height of the buffer * @param caps the desired capabilities of the image buffer * @return the buffered image, or null if none is supported * @throws AWTException if the capabilities cannot be met * @since 1.4 */ public VolatileImage createCompatibleVolatileImage(int w, int h, ImageCapabilities caps) throws AWTException { throw new AWTException("not implemented"); } /** * Returns a buffered volatile image optimized to this device, and * with the given transparency. Because the buffer is volatile, it * can be optimized by native graphics accelerators. * * @param width the width of the buffer * @param height the height of the buffer * @param transparency the transparency value for the buffer * @return the buffered image, or null if none is supported * @since 1.5 */ public abstract VolatileImage createCompatibleVolatileImage(int width, int height, int transparency); /** * Returns a buffered image optimized to this device, and with the specified * transparency, so that blitting can be supported in the buffered image. * * @param w the width of the buffer * @param h the height of the buffer * @param transparency the transparency of the buffer * @return the buffered image, or null if none is supported * @see Transparency#OPAQUE * @see Transparency#BITMASK * @see Transparency#TRANSLUCENT */ public abstract BufferedImage createCompatibleImage(int w, int h, int transparency); /** * Gets the color model of the corresponding device. * * @return the color model */ public abstract ColorModel getColorModel(); /** * Gets a color model for the corresponding device which supports the desired * transparency level. * * @param transparency the transparency of the model * @return the color model, with transparency * @see Transparency#OPAQUE * @see Transparency#BITMASK * @see Transparency#TRANSLUCENT */ public abstract ColorModel getColorModel(int transparency); /** * Returns a transform that maps user coordinates to device coordinates. The * preferred mapping is about 72 user units to 1 inch (2.54 cm) of physical * space. This is often the identity transform. The device coordinates have * the origin at the upper left, with increasing x to the right, and * increasing y to the bottom. * * @return the transformation from user space to device space * @see #getNormalizingTransform() */ public abstract AffineTransform getDefaultTransform(); /** * Returns a transform that maps user coordinates to device coordinates. The * exact mapping is 72 user units to 1 inch (2.54 cm) of physical space. * This is often the identity transform. The device coordinates have the * origin at the upper left, with increasing x to the right, and increasing * y to the bottom. Note that this is more accurate (and thus, sometimes more * costly) than the default transform. * * @return the normalized transformation from user space to device space * @see #getDefaultTransform() */ public abstract AffineTransform getNormalizingTransform(); /** * Returns the bounds of the configuration, in device coordinates. If this * is a virtual device (for example, encompassing several screens), the * bounds may have a non-zero origin. * * @return the device bounds * @since 1.3 */ public abstract Rectangle getBounds(); /** * Returns the buffering capabilities of this configuration. * * @return the buffer capabilities * @since 1.4 */ public BufferCapabilities getBufferCapabilities() { if (imageCapabilities == null) getImageCapabilities(); if (bufferCapabilities == null) bufferCapabilities = new BufferCapabilities(imageCapabilities, imageCapabilities, null); return bufferCapabilities; } /** * Returns the imaging capabilities of this configuration. * * @return the image capabilities * @since 1.4 */ public ImageCapabilities getImageCapabilities() { if (imageCapabilities == null) imageCapabilities = new ImageCapabilities(false); return imageCapabilities; } } // class GraphicsConfiguration
/* * 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.commons.betwixt.recursion; /** * Test bean for resursion * @author <a href='http://commons.apache.org/'>Apache Commons Team</a> * @version $Revision: 561314 $ */ public class SouthWind { private WestWind west; public SouthWind() {} /** * @return */ public WestWind getNextWindClockwise() { return west; } /** * @param east */ public void setNextWindClockwise(WestWind west) { this.west = west; } }
/** * Copyright (C) 2016 - 2030 youtongluan. * * 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.yx.rpc.client; import java.util.Objects; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.function.Supplier; import org.apache.mina.core.future.ConnectFuture; import org.apache.mina.core.future.WriteFuture; import org.apache.mina.core.session.IoSession; import org.apache.mina.transport.socket.SocketConnector; import org.yx.common.Host; import org.yx.log.Logs; import org.yx.rpc.client.route.HostChecker; public final class ReqSession { protected volatile IoSession session; private static Supplier<SocketConnector> connectorSupplier = new SocketConnectorSupplier(); private final Host addr; private final Lock lock = new ReentrantLock(); public static void setConnectorSupplier(Supplier<SocketConnector> connectorSupplier) { ReqSession.connectorSupplier = Objects.requireNonNull(connectorSupplier); } public static Supplier<SocketConnector> getConnectorSupplier() { return connectorSupplier; } public ReqSession(Host host) { this.addr = Objects.requireNonNull(host); } public SocketConnector getConnector() { return connectorSupplier.get(); } private boolean ensureSession() { if (session != null && !session.isClosing()) { return true; } try { SocketConnector connector = this.getConnector(); if (lock.tryLock(connector.getConnectTimeoutMillis() + 2000, TimeUnit.MILLISECONDS)) { try { if (session != null && !session.isClosing()) { return true; } connect(connector); } finally { lock.unlock(); } } } catch (Exception e1) { Logs.rpc().error(this.addr + " - " + e1.toString(), e1); } if (session == null || session.isClosing()) { HostChecker.get().addDownUrl(addr); return false; } return true; } private void connect(SocketConnector connector) throws InterruptedException { if (session == null || session.isClosing()) { Logs.rpc().debug("create session for {}", addr); ConnectFuture cf = connector.connect(addr.toInetSocketAddress()); cf.await(connector.getConnectTimeoutMillis() + 20); IoSession se = cf.getSession(); if (se != null) { this.session = se; return; } cf.cancel(); } } public WriteFuture write(Req req) { if (!this.ensureSession()) { return null; } return this.session.write(req); } public void close() { IoSession s = this.session; if (s != null && s.isConnected()) { this.session.closeNow(); } } public static void init() { connectorSupplier.get(); } }
package com.petOcare.security; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; @SpringBootApplication @EnableResourceServer public class AuthServiceApplication { public static void main(String[] args) { SpringApplication.run(AuthServiceApplication.class, args); } }
package io.katharsis.jpa.internal; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Arrays; public class TypeUtils { private TypeUtils() { } public static final ParameterizedType parameterize(final Class<?> raw, final Type... typeArguments) { final Type useOwner; if (raw.getEnclosingClass() == null) { useOwner = null; } else { useOwner = raw.getEnclosingClass(); } return new ParameterizedTypeImpl(raw, useOwner, typeArguments); } private static final class ParameterizedTypeImpl implements ParameterizedType { private final Class<?> raw; private final Type useOwner; private final Type[] typeArguments; private ParameterizedTypeImpl(final Class<?> raw, final Type useOwner, final Type[] typeArguments) { this.raw = raw; this.useOwner = useOwner; this.typeArguments = typeArguments; } @Override public Type getRawType() { return raw; } @Override public Type getOwnerType() { return useOwner; } @Override public Type[] getActualTypeArguments() { return typeArguments.clone(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((raw == null) ? 0 : raw.hashCode()); result = prime * result + Arrays.hashCode(typeArguments); result = prime * result + ((useOwner == null) ? 0 : useOwner.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ParameterizedTypeImpl other = (ParameterizedTypeImpl) obj; if (raw == null) { if (other.raw != null) return false; } else if (!raw.equals(other.raw)) return false; if (!Arrays.equals(typeArguments, other.typeArguments)) return false; if (useOwner == null) { if (other.useOwner != null) return false; } else if (!useOwner.equals(other.useOwner)) return false; return true; } } }
/* * Copyright 2018 Dennis Neufeld * * 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 space.npstr.magma.processing; import com.iwebpp.crypto.TweetNaclFast; import net.dv8tion.jda.core.audio.AudioPacket; import space.npstr.magma.EncryptionMode; import java.nio.ByteBuffer; import java.util.concurrent.ThreadLocalRandom; import java.util.function.Supplier; /** * Created by napster on 23.06.18. */ public class PacketUtil { private PacketUtil() { } //this may reallocate the passed bytebuffer if it is too small public static ByteBuffer encryptPacket(final AudioPacket audioPacket, final ByteBuffer packetBuffer, final EncryptionMode encryptionMode, final byte[] secretKey, final Supplier<Long> nonceSupplier, final byte[] nonceBuffer) { final int nonceLength; switch (encryptionMode) { case XSALSA20_POLY1305: nonceLength = 0; break; case XSALSA20_POLY1305_LITE: PacketUtil.writeNonce(nonceSupplier.get(), nonceBuffer); nonceLength = 4; break; case XSALSA20_POLY1305_SUFFIX: ThreadLocalRandom.current().nextBytes(nonceBuffer); nonceLength = TweetNaclFast.SecretBox.nonceLength; break; default: throw new IllegalStateException("Encryption mode [" + encryptionMode + "] is not supported!"); } return audioPacket.asEncryptedPacket(packetBuffer, secretKey, nonceBuffer, nonceLength); } //@formatter:off public static void writeNonce(final long nonce, final byte[] nonceBuffer) { nonceBuffer[0] = (byte) ((nonce >>> 24) & 0xFF); nonceBuffer[1] = (byte) ((nonce >>> 16) & 0xFF); nonceBuffer[2] = (byte) ((nonce >>> 8) & 0xFF); nonceBuffer[3] = (byte) ( nonce & 0xFF); } //@formatter:on }
/* * Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.cognitoidp.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * A resource server scope. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/ResourceServerScopeType" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ResourceServerScopeType implements Serializable, Cloneable, StructuredPojo { /** * <p> * The name of the scope. * </p> */ private String scopeName; /** * <p> * A description of the scope. * </p> */ private String scopeDescription; /** * <p> * The name of the scope. * </p> * * @param scopeName * The name of the scope. */ public void setScopeName(String scopeName) { this.scopeName = scopeName; } /** * <p> * The name of the scope. * </p> * * @return The name of the scope. */ public String getScopeName() { return this.scopeName; } /** * <p> * The name of the scope. * </p> * * @param scopeName * The name of the scope. * @return Returns a reference to this object so that method calls can be chained together. */ public ResourceServerScopeType withScopeName(String scopeName) { setScopeName(scopeName); return this; } /** * <p> * A description of the scope. * </p> * * @param scopeDescription * A description of the scope. */ public void setScopeDescription(String scopeDescription) { this.scopeDescription = scopeDescription; } /** * <p> * A description of the scope. * </p> * * @return A description of the scope. */ public String getScopeDescription() { return this.scopeDescription; } /** * <p> * A description of the scope. * </p> * * @param scopeDescription * A description of the scope. * @return Returns a reference to this object so that method calls can be chained together. */ public ResourceServerScopeType withScopeDescription(String scopeDescription) { setScopeDescription(scopeDescription); return this; } /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getScopeName() != null) sb.append("ScopeName: ").append(getScopeName()).append(","); if (getScopeDescription() != null) sb.append("ScopeDescription: ").append(getScopeDescription()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ResourceServerScopeType == false) return false; ResourceServerScopeType other = (ResourceServerScopeType) obj; if (other.getScopeName() == null ^ this.getScopeName() == null) return false; if (other.getScopeName() != null && other.getScopeName().equals(this.getScopeName()) == false) return false; if (other.getScopeDescription() == null ^ this.getScopeDescription() == null) return false; if (other.getScopeDescription() != null && other.getScopeDescription().equals(this.getScopeDescription()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getScopeName() == null) ? 0 : getScopeName().hashCode()); hashCode = prime * hashCode + ((getScopeDescription() == null) ? 0 : getScopeDescription().hashCode()); return hashCode; } @Override public ResourceServerScopeType clone() { try { return (ResourceServerScopeType) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.cognitoidp.model.transform.ResourceServerScopeTypeMarshaller.getInstance().marshall(this, protocolMarshaller); } }
package com.likya.tlossw.web; import java.util.HashMap; import java.util.ResourceBundle; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedProperty; import javax.faces.context.FacesContext; import org.apache.log4j.Logger; import com.likya.tlossw.model.DocMetaDataHolder; import com.likya.tlossw.model.auth.WebAppUser; import com.likya.tlossw.web.appmng.SessionMediator; import com.likya.tlossw.web.db.DBOperations; import com.likya.tlossw.web.utils.BeanUtils; public abstract class TlosSWBaseBean { private static final Logger logger = Logger.getLogger(TlosSWBaseBean.class); @ManagedProperty(value = "#{sessionMediator}") private SessionMediator sessionMediator; @ManagedProperty(value = "#{dbOperations}") private DBOperations dbOperations; @ManagedProperty(value = "#{sessionMediator.webAppUser}") private WebAppUser webAppUser; public String resolveMessage(String message) { ResourceBundle messages = sessionMediator.getMessageBundle(); message = BeanUtils.resolveMessage(messages, message); return message; } protected void setPassedParameters() { int firstColumn = 0; int secondColumn = 0; String doc1Id = getPassedParameter().get("doc1Id"); String doc2Id = getPassedParameter().get("doc2Id"); if( doc1Id != null && getPassedParameter().get("firstColumn") != null ) { firstColumn = Integer.parseInt(getPassedParameter().get("firstColumn")); sessionMediator.setDocumentScope( doc1Id, firstColumn); sessionMediator.setCurrentDoc( DocMetaDataHolder.FIRST_COLUMN, doc1Id); } if( doc2Id != null && getPassedParameter().get("secondColumn") != null ) { secondColumn = Integer.parseInt(getPassedParameter().get("secondColumn")); sessionMediator.setDocumentScope( doc2Id, secondColumn); sessionMediator.setCurrentDoc( DocMetaDataHolder.SECOND_COLUMN, doc2Id); } } public String getDocId(Integer columnId) { //setPassedParameters(); String docId = getSessionMediator().getWebSpaceWideRegistery().getDocMetaDataInfo().getCurrentDocs()[columnId-1]; return docId; } public void addMessage(String formName, String fieldName, String errorMessage, String miscText) { ResourceBundle messages = sessionMediator.getMessageBundle(); BeanUtils.addMessage(messages, formName, fieldName, errorMessage, miscText); return; } public HashMap<String, String> getPassedParameter() { HashMap<String, String> parameterMap = new HashMap<String, String>(); FacesContext facesContext = FacesContext.getCurrentInstance(); parameterMap.putAll(facesContext.getExternalContext().getRequestParameterMap()); return parameterMap; } public void addMessage(String fieldName, FacesMessage.Severity severity, String message, String miscText) { ResourceBundle messages = sessionMediator.getMessageBundle(); BeanUtils.addMessage(messages, fieldName, severity, message, miscText); } public void addSuccessMessage(String fieldName, String successMessage, String miscText) { ResourceBundle messages = sessionMediator.getMessageBundle(); BeanUtils.addSuccessMessage(messages, fieldName, successMessage, miscText); } public void addFailMessage(String fieldName, String errorMessage, String miscText) { ResourceBundle messages = sessionMediator.getMessageBundle(); BeanUtils.addFailMessage(messages, fieldName, errorMessage, miscText); } public final SessionMediator getSessionMediator() { return sessionMediator; } public final void setSessionMediator(SessionMediator sessionMediator) { this.sessionMediator = sessionMediator; } public DBOperations getDbOperations() { return dbOperations; } public void setDbOperations(DBOperations dbOperations) { this.dbOperations = dbOperations; } public int getDocumentScope(String documentId) { return getSessionMediator().getDocumentScope(documentId); } public WebAppUser getWebAppUser() { return webAppUser; } public void setWebAppUser(WebAppUser webAppUser) { this.webAppUser = webAppUser; } public static Logger getLogger() { return logger; } }
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.uiDesigner.make; import com.intellij.uiDesigner.lw.LwComponent; public class ToolBarLayoutSourceGenerator extends LayoutSourceGenerator { @Override public void generateComponentLayout(final LwComponent component, final FormSourceCodeGenerator generator, final String variable, final String parentVariable) { generator.startMethodCall(parentVariable, "add"); generator.pushVar(variable); generator.endMethod(); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.runtime.dispatcher; import org.apache.flink.runtime.metrics.groups.JobManagerMetricGroup; /** * Factory interface for {@link JobManagerMetricGroup}. */ public interface JobManagerMetricGroupFactory { /** * @return newly created {@link JobManagerMetricGroup} */ JobManagerMetricGroup create(); }
package Interfaces; import Classes.Funcionario; import Classes.Turma; import DAO.AlunoDAO; import DAO.CursoDAO; import DAO.FunDAO; import DAO.TurmaDAO; import DAO.VendaDAO; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.filechooser.FileNameExtensionFilter; public class Turma_Cadastro extends javax.swing.JFrame implements KeyListener { Funcionario funLog; BufferedReader txt; Turma turma; String[] dadosTurma; FileReader arqReader; ArrayList<Turma> listaTurma; TurmaDAO turmaDao; CursoDAO cursoDao; AlunoDAO alunoDao; VendaDAO vendaDao; FunDAO funDao; private Turma_Cadastro() { initComponents(); this.setLocationRelativeTo(null); txtArea.setEditable(false); txtArea.addKeyListener(this); btnSalvar.setEnabled(false); } public Turma_Cadastro(Funcionario fun) { initComponents(); listaTurma = new ArrayList(); cursoDao = new CursoDAO(); turmaDao = new TurmaDAO(); txtArea.addKeyListener(this); txtNomeArquivo.addKeyListener(this); funLog = fun; txtArea.setEditable(false); this.setLocationRelativeTo(null); turmaDao = new TurmaDAO(); cursoDao = new CursoDAO(); alunoDao = new AlunoDAO(); vendaDao = new VendaDAO(); funDao = new FunDAO(); btnSalvar.setEnabled(false); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPopupMenu1 = new javax.swing.JPopupMenu(); jMenu1 = new javax.swing.JMenu(); jMenuItem1 = new javax.swing.JMenuItem(); jPanel1 = new javax.swing.JPanel(); filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 90), new java.awt.Dimension(0, 90), new java.awt.Dimension(32767, 90)); jLabel1 = new javax.swing.JLabel(); txtLogo = new javax.swing.JLabel(); btnVoltar = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); txtNomeArquivo = new javax.swing.JTextField(); lblEscolherArquivo = new javax.swing.JLabel(); btnSalvar = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); txtArea = new javax.swing.JTextArea(); jMenuBar1 = new javax.swing.JMenuBar(); jMenu2 = new javax.swing.JMenu(); jMenuItem11 = new javax.swing.JMenuItem(); jMenuItem10 = new javax.swing.JMenuItem(); jMenu3 = new javax.swing.JMenu(); jMenuItem20 = new javax.swing.JMenuItem(); jMenu4 = new javax.swing.JMenu(); jMenuItem4 = new javax.swing.JMenuItem(); jMenuItem12 = new javax.swing.JMenuItem(); jMenuItem15 = new javax.swing.JMenuItem(); jMenuItem16 = new javax.swing.JMenuItem(); jMenuItem18 = new javax.swing.JMenuItem(); jMenu5 = new javax.swing.JMenu(); jMenuItem7 = new javax.swing.JMenuItem(); jMenuItem21 = new javax.swing.JMenuItem(); jMenuItem3 = new javax.swing.JMenuItem(); jMenu6 = new javax.swing.JMenu(); jMenuItem2 = new javax.swing.JMenuItem(); jMenu7 = new javax.swing.JMenu(); jMenuItem14 = new javax.swing.JMenuItem(); jMenu8 = new javax.swing.JMenu(); jMenuItem17 = new javax.swing.JMenuItem(); jMenu1.setText("jMenu1"); jMenuItem1.setText("jMenuItem1"); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Cadastrar Turmas"); setResizable(false); txtLogo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/LOGO_150px.png"))); // NOI18N btnVoltar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/backward-arrow.png"))); // NOI18N btnVoltar.setToolTipText("Voltar"); btnVoltar.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnVoltarMouseClicked(evt); } }); jLabel4.setFont(new java.awt.Font("Simplified Arabic", 0, 18)); // NOI18N jLabel4.setForeground(new java.awt.Color(53, 72, 112)); jLabel4.setText("Selecione um arquivo:"); lblEscolherArquivo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/btn_EscolherArquivo.png"))); // NOI18N lblEscolherArquivo.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { lblEscolherArquivoMouseClicked(evt); } }); btnSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/btn_Salvar.png"))); // NOI18N btnSalvar.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnSalvarMouseClicked(evt); } }); txtArea.setColumns(20); txtArea.setRows(5); jScrollPane1.setViewportView(txtArea); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(199, 199, 199) .addComponent(txtLogo) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel1) .addGap(178, 178, 178)) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(lblEscolherArquivo, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(27, 27, 27) .addComponent(btnSalvar) .addGap(60, 60, 60)) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(36, 36, 36) .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txtNomeArquivo, javax.swing.GroupLayout.PREFERRED_SIZE, 292, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(btnVoltar))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 303, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(61, 61, 61) .addComponent(filler1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(164, 164, 164)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel1) .addGap(125, 125, 125)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(20, 20, 20) .addComponent(txtLogo) .addGap(28, 28, 28) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtNomeArquivo, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4)))) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(filler1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(12, 12, 12) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(btnSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lblEscolherArquivo, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGap(142, 142, 142) .addComponent(btnVoltar) .addGap(63, 63, 63)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(42, 42, 42) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 421, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jMenu2.setBorder(null); jMenu2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/wallet.png"))); // NOI18N jMenu2.setText("Venda"); jMenu2.setFont(new java.awt.Font("Simplified Arabic", 0, 18)); // NOI18N jMenu2.setMargin(new java.awt.Insets(10, 10, 10, 10)); jMenu2.setPreferredSize(new java.awt.Dimension(110, 25)); jMenuItem11.setText("Ticket"); jMenuItem11.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { jMenuItem11MouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { jMenuItem11MouseExited(evt); } }); jMenuItem11.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem11ActionPerformed(evt); } }); jMenu2.add(jMenuItem11); jMenuItem10.setText("Créditos"); jMenuItem10.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem10ActionPerformed(evt); } }); jMenu2.add(jMenuItem10); jMenuBar1.add(jMenu2); jMenu3.setBorder(null); jMenu3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/ticket.png"))); // NOI18N jMenu3.setText("Ficha"); jMenu3.setFont(new java.awt.Font("Simplified Arabic", 0, 18)); // NOI18N jMenu3.setMargin(new java.awt.Insets(10, 10, 10, 10)); jMenuItem20.setText("Alterar"); jMenuItem20.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem20ActionPerformed(evt); } }); jMenu3.add(jMenuItem20); jMenuBar1.add(jMenu3); jMenu4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/icon.png"))); // NOI18N jMenu4.setText("Aluno"); jMenu4.setFont(new java.awt.Font("Simplified Arabic", 0, 18)); // NOI18N jMenu4.setMargin(new java.awt.Insets(10, 10, 10, 10)); jMenu4.setPreferredSize(new java.awt.Dimension(110, 52)); jMenuItem4.setText("Adicionar listagem"); jMenuItem4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem4ActionPerformed(evt); } }); jMenu4.add(jMenuItem4); jMenuItem12.setText("Adicionar listagem beneficente"); jMenuItem12.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem12ActionPerformed(evt); } }); jMenu4.add(jMenuItem12); jMenuItem15.setText("Buscar Aluno"); jMenuItem15.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem15ActionPerformed(evt); } }); jMenu4.add(jMenuItem15); jMenuItem16.setText("Adicionar foto"); jMenuItem16.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem16ActionPerformed(evt); } }); jMenu4.add(jMenuItem16); jMenuItem18.setText("Consultar Histórico"); jMenuItem18.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem18ActionPerformed(evt); } }); jMenu4.add(jMenuItem18); jMenuBar1.add(jMenu4); jMenu5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/users.png"))); // NOI18N jMenu5.setText("Funcionário"); jMenu5.setFont(new java.awt.Font("Simplified Arabic", 0, 18)); // NOI18N jMenu5.setMargin(new java.awt.Insets(10, 10, 10, 10)); jMenu5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenu5ActionPerformed(evt); } }); jMenuItem7.setText("Cadastro"); jMenuItem7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem7ActionPerformed(evt); } }); jMenu5.add(jMenuItem7); jMenuItem21.setText("Criar login"); jMenuItem21.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem21ActionPerformed(evt); } }); jMenu5.add(jMenuItem21); jMenuItem3.setText("[ADMINISTRADOR]"); jMenuItem3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem3ActionPerformed(evt); } }); jMenu5.add(jMenuItem3); jMenuBar1.add(jMenu5); jMenu6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/padnote.png"))); // NOI18N jMenu6.setText("Relatório"); jMenu6.setFont(new java.awt.Font("Simplified Arabic", 0, 18)); // NOI18N jMenu6.setMargin(new java.awt.Insets(10, 10, 10, 10)); jMenuItem2.setText("Gerar"); jMenuItem2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem2ActionPerformed(evt); } }); jMenu6.add(jMenuItem2); jMenuBar1.add(jMenu6); jMenu7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/curso_1.png"))); // NOI18N jMenu7.setText("Curso"); jMenu7.setFont(new java.awt.Font("Simplified Arabic", 0, 18)); // NOI18N jMenu7.setMargin(new java.awt.Insets(10, 10, 10, 10)); jMenu7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenu7ActionPerformed(evt); } }); jMenuItem14.setText("Cadastrar"); jMenuItem14.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem14ActionPerformed(evt); } }); jMenu7.add(jMenuItem14); jMenuBar1.add(jMenu7); jMenu8.setBorder(null); jMenu8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/turma.png"))); // NOI18N jMenu8.setText("Turma"); jMenu8.setFont(new java.awt.Font("Simplified Arabic", 0, 18)); // NOI18N jMenu8.setMargin(new java.awt.Insets(10, 35, 10, 35)); jMenu8.setPreferredSize(new java.awt.Dimension(150, 33)); jMenu8.setRequestFocusEnabled(false); jMenu8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenu8ActionPerformed(evt); } }); jMenuItem17.setText("Cadastrar"); jMenuItem17.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem17ActionPerformed(evt); } }); jMenu8.add(jMenuItem17); jMenuBar1.add(jMenu8); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 879, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 10, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnVoltarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnVoltarMouseClicked dispose(); Inicio newInicio = new Inicio(funLog); newInicio.setVisible(true); }//GEN-LAST:event_btnVoltarMouseClicked public void escolherArquivo() { txtArea.setText(""); txtNomeArquivo.setText(""); //VARIÁVEIS JFileChooser fileChooser = new JFileChooser(); File arq; FileNameExtensionFilter filtro = new FileNameExtensionFilter("Texto", "txt"); int retornoFileChooser; //Configuração do JFileChooser fileChooser.setDialogTitle("Escolher Arquivo..."); fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); fileChooser.setFileFilter(filtro); //Aviso sobre a formatação do arquivo. JOptionPane.showMessageDialog(null, "Certifique-se que o formato do arquivo está no padrão solicitado para executar o cadastro:\n" + "(Dados separados por '#' e na seguinte ordem:\n" + "-Código da turma\n" + "-Curso ao qual a turma pertence", "Aviso!", JOptionPane.WARNING_MESSAGE); //Abre a janela JFileChooser e guarda a resposta na variável 'retornoFileChooser' retornoFileChooser = fileChooser.showOpenDialog(this); if (retornoFileChooser == JFileChooser.APPROVE_OPTION) { arq = fileChooser.getSelectedFile(); txtNomeArquivo.setText(arq.getName()); try { System.out.println(arq.getPath()); txt = new BufferedReader(new InputStreamReader(new FileInputStream(arq.getPath()), "UTF8")); } catch (FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } try { String linha = txt.readLine(); while (linha != null) { String novaLinha = txtArea.getText() + linha + "\n"; txtArea.setText(novaLinha); dadosTurma = linha.split("#"); turma = new Turma(); turma.setCodigo(dadosTurma[0]); turma.setCurso("" + cursoDao.getCodigoByNome(dadosTurma[1])); listaTurma.add(turma); linha = txt.readLine(); } } catch (IOException e) { e.printStackTrace(); } btnSalvar.setEnabled(false); } } private void salvar() { if (txt == null) { JOptionPane.showMessageDialog(null, "Selecione um arquivo.", "AVISO!", JOptionPane.WARNING_MESSAGE); } else { for (Turma t : listaTurma) { if (turmaDao.addTurma(t) == false) { JOptionPane.showMessageDialog(null, "Erro.", "ERRO!", JOptionPane.ERROR_MESSAGE); break; } } int resposta = JOptionPane.showConfirmDialog(null, "Turmas cadastradas com sucesso. Deseja voltar ao menu principal?", null, JOptionPane.YES_NO_OPTION); if (resposta == JOptionPane.YES_OPTION) { dispose(); Inicio newInicio = new Inicio(funLog); newInicio.setVisible(true); } } } private void lblEscolherArquivoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblEscolherArquivoMouseClicked escolherArquivo(); }//GEN-LAST:event_lblEscolherArquivoMouseClicked private void btnSalvarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnSalvarMouseClicked if (btnSalvar.isEnabled()) { salvar(); } }//GEN-LAST:event_btnSalvarMouseClicked private void jMenuItem11MouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jMenuItem11MouseEntered // TODO add your handling code here: }//GEN-LAST:event_jMenuItem11MouseEntered private void jMenuItem11MouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jMenuItem11MouseExited }//GEN-LAST:event_jMenuItem11MouseExited private void jMenuItem11ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem11ActionPerformed if (!alunoDao.verificaBD()) { JOptionPane.showMessageDialog(null, "Não há alunos cadastrados.", "Erro!", JOptionPane.ERROR_MESSAGE); } else if (!funDao.verificaBD()) { JOptionPane.showMessageDialog(null, "Não há funcionários cadastrados.", "Erro!", JOptionPane.ERROR_MESSAGE); } else { dispose(); Venda_Ficha newVenda = new Venda_Ficha(funLog); newVenda.setVisible(true); } }//GEN-LAST:event_jMenuItem11ActionPerformed private void jMenuItem10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem10ActionPerformed if (!alunoDao.verificaBD()) { JOptionPane.showMessageDialog(null, "Não há alunos cadastrados.", "Erro!", JOptionPane.ERROR_MESSAGE); } else if (!funDao.verificaBD()) { JOptionPane.showMessageDialog(null, "Não há funcionários cadastrados.", "Erro!", JOptionPane.ERROR_MESSAGE); } else { dispose(); Venda_Creditos newVenda = new Venda_Creditos(funLog); newVenda.setVisible(true); } }//GEN-LAST:event_jMenuItem10ActionPerformed private void jMenuItem20ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem20ActionPerformed dispose(); Ficha_AlterarValor alt = new Ficha_AlterarValor(funLog); alt.setVisible(true); }//GEN-LAST:event_jMenuItem20ActionPerformed private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem4ActionPerformed dispose(); Aluno_Cadastro newCD = new Aluno_Cadastro(funLog); newCD.setVisible(true); }//GEN-LAST:event_jMenuItem4ActionPerformed private void jMenuItem12ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem12ActionPerformed if (!alunoDao.verificaBD()) { JOptionPane.showMessageDialog(null, "Não há alunos cadastrados.", "Erro!", JOptionPane.ERROR_MESSAGE); } else { dispose(); Aluno_Cadastro_Beneficiarios newCD = new Aluno_Cadastro_Beneficiarios(funLog); newCD.setVisible(true); } }//GEN-LAST:event_jMenuItem12ActionPerformed private void jMenuItem15ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem15ActionPerformed if (!alunoDao.verificaBD()) { JOptionPane.showMessageDialog(null, "Não há alunos cadastrados.", "Erro!", JOptionPane.ERROR_MESSAGE); } else { dispose(); Aluno_Buscar newBuscar = new Aluno_Buscar(funLog); newBuscar.setVisible(true); } }//GEN-LAST:event_jMenuItem15ActionPerformed private void jMenuItem16ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem16ActionPerformed if (!alunoDao.verificaBD()) { JOptionPane.showMessageDialog(null, "Não há alunos cadastrados.", "Erro!", JOptionPane.ERROR_MESSAGE); } else { dispose(); Aluno_Foto newFoto = new Aluno_Foto(funLog); newFoto.setVisible(true); } }//GEN-LAST:event_jMenuItem16ActionPerformed private void jMenuItem18ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem18ActionPerformed if (!alunoDao.verificaBD()) { JOptionPane.showMessageDialog(null, "Não há alunos cadastrados.", "Erro!", JOptionPane.ERROR_MESSAGE); } else { dispose(); Aluno_ConsultarHistorico consulta = new Aluno_ConsultarHistorico(funLog); consulta.setVisible(true); } }//GEN-LAST:event_jMenuItem18ActionPerformed private void jMenuItem7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem7ActionPerformed dispose(); Funcionario_Cadastro newCD = new Funcionario_Cadastro(funLog); newCD.setVisible(true); }//GEN-LAST:event_jMenuItem7ActionPerformed private void jMenuItem21ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem21ActionPerformed if (!funDao.verificaBD()) { JOptionPane.showMessageDialog(null, "Não há funcionários cadastrados.", "Erro!", JOptionPane.ERROR_MESSAGE); } else { dispose(); Login_Cadastro newCD = new Login_Cadastro(funLog); newCD.setVisible(true); } }//GEN-LAST:event_jMenuItem21ActionPerformed private void jMenu5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu5ActionPerformed dispose(); Login_Cadastro newCD = new Login_Cadastro(funLog); newCD.setVisible(true); }//GEN-LAST:event_jMenu5ActionPerformed private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed if (!vendaDao.verificaBD()) { JOptionPane.showMessageDialog(null, "Não há vendas.", "Erro!", JOptionPane.ERROR_MESSAGE); } else { dispose(); Relatório_Gerar gerarRelatorio = new Relatório_Gerar(funLog); gerarRelatorio.setVisible(true); } }//GEN-LAST:event_jMenuItem2ActionPerformed private void jMenuItem14ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem14ActionPerformed dispose(); Curso_Cadastro c = new Curso_Cadastro(funLog); c.setVisible(true); }//GEN-LAST:event_jMenuItem14ActionPerformed private void jMenu7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu7ActionPerformed dispose(); Curso_Cadastro newCD = new Curso_Cadastro(funLog); newCD.setVisible(true); }//GEN-LAST:event_jMenu7ActionPerformed private void jMenuItem17ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem17ActionPerformed dispose(); Turma_Cadastro c = new Turma_Cadastro(funLog); c.setVisible(true); }//GEN-LAST:event_jMenuItem17ActionPerformed private void jMenu8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu8ActionPerformed dispose(); Turma_Cadastro newCD = new Turma_Cadastro(funLog); newCD.setVisible(true); }//GEN-LAST:event_jMenu8ActionPerformed private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed String senha = JOptionPane.showInputDialog(null, "Digite a senha do administrador:", null, JOptionPane.QUESTION_MESSAGE); if (funDao.validaSenhaAdm(senha)) { dispose(); Administrador_Menu admMenu = new Administrador_Menu(funLog); admMenu.setVisible(true); } else { JOptionPane.showMessageDialog(null, "Senha inválida.", "Erro!", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_jMenuItem3ActionPerformed public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Turma_Cadastro.class .getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Turma_Cadastro.class .getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Turma_Cadastro.class .getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Turma_Cadastro.class .getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Turma_Cadastro().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel btnSalvar; private javax.swing.JLabel btnVoltar; private javax.swing.Box.Filler filler1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel4; private javax.swing.JMenu jMenu1; private javax.swing.JMenu jMenu2; private javax.swing.JMenu jMenu3; private javax.swing.JMenu jMenu4; private javax.swing.JMenu jMenu5; private javax.swing.JMenu jMenu6; private javax.swing.JMenu jMenu7; private javax.swing.JMenu jMenu8; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JMenuItem jMenuItem1; private javax.swing.JMenuItem jMenuItem10; private javax.swing.JMenuItem jMenuItem11; private javax.swing.JMenuItem jMenuItem12; private javax.swing.JMenuItem jMenuItem14; private javax.swing.JMenuItem jMenuItem15; private javax.swing.JMenuItem jMenuItem16; private javax.swing.JMenuItem jMenuItem17; private javax.swing.JMenuItem jMenuItem18; private javax.swing.JMenuItem jMenuItem2; private javax.swing.JMenuItem jMenuItem20; private javax.swing.JMenuItem jMenuItem21; private javax.swing.JMenuItem jMenuItem3; private javax.swing.JMenuItem jMenuItem4; private javax.swing.JMenuItem jMenuItem7; private javax.swing.JPanel jPanel1; private javax.swing.JPopupMenu jPopupMenu1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JLabel lblEscolherArquivo; private javax.swing.JTextArea txtArea; private javax.swing.JLabel txtLogo; private javax.swing.JTextField txtNomeArquivo; // End of variables declaration//GEN-END:variables @Override public void keyTyped(KeyEvent ke) { //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void keyPressed(KeyEvent ke) { int codigo = ke.getKeyCode(); if (codigo == KeyEvent.VK_ENTER) { if (txtNomeArquivo.getText().length() == 0) { escolherArquivo(); } else { salvar(); } } } @Override public void keyReleased(KeyEvent ke) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
/* * Copyright (C) 2008 ZXing 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 com.ewgvip.buyer.android.zxing.view; import java.util.Collection; import java.util.HashSet; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Typeface; import android.graphics.drawable.BitmapDrawable; import android.util.AttributeSet; import android.view.View; import com.google.zxing.ResultPoint; import com.ewgvip.buyer.android.zxing.camera.CameraManager; import com.ewgvip.buyer.android.R; /** * This view is overlaid on top of the camera preview. It adds the viewfinder * rectangle and partial transparency outside it, as well as the laser scanner * animation and result points. * */ public final class ViewfinderView extends View { /** * ˢ�½����ʱ�� */ private static final long ANIMATION_DELAY = 10L; private static final int OPAQUE = 0xFF; /** * �ĸ���ɫ�߽Ƕ�Ӧ�ij��� */ private int ScreenRate; /** * �ĸ���ɫ�߽Ƕ�Ӧ�Ŀ�� */ private static final int CORNER_WIDTH = 5; /** * ɨ����е��м��ߵĿ�� */ private static final int MIDDLE_LINE_WIDTH = 6; /** * ɨ����е��м��ߵ���ɨ������ҵļ�϶ */ private static final int MIDDLE_LINE_PADDING = 5; /** * �м�������ÿ��ˢ���ƶ��ľ��� */ private static final int SPEEN_DISTANCE = 5; /** * �ֻ����Ļ�ܶ� */ private static float density; /** * �����С */ private static final int TEXT_SIZE = 16; /** * �������ɨ�������ľ��� */ private static final int TEXT_PADDING_TOP = 30; /** * ���ʶ�������� */ private Paint paint; /** * �м们���ߵ����λ�� */ private int slideTop; /** * �м们���ߵ���׶�λ�� */ private int slideBottom; /** * ��ɨ��Ķ�ά��������������û��������ܣ���ʱ������ */ private Bitmap resultBitmap; private final int maskColor; private final int resultColor; private final int resultPointColor; private Collection<ResultPoint> possibleResultPoints; private Collection<ResultPoint> lastPossibleResultPoints; boolean isFirst; public ViewfinderView(Context context, AttributeSet attrs) { super(context, attrs); density = context.getResources().getDisplayMetrics().density; //������ת����dp ScreenRate = (int)(15 * density); paint = new Paint(); Resources resources = getResources(); maskColor = resources.getColor(R.color.viewfinder_mask); resultColor = resources.getColor(R.color.result_view); resultPointColor = resources.getColor(R.color.possible_result_points); possibleResultPoints = new HashSet<ResultPoint>(5); } @Override public void onDraw(Canvas canvas) { //�м��ɨ�����Ҫ�޸�ɨ���Ĵ�С��ȥCameraManager�����޸� Rect frame = CameraManager.get().getFramingRect(); if (frame == null) { return; } //��ʼ���м��߻��������ϱߺ����±� if(!isFirst){ isFirst = true; slideTop = frame.top; slideBottom = frame.bottom; } //��ȡ��Ļ�Ŀ�͸� int width = canvas.getWidth(); int height = canvas.getHeight(); paint.setColor(resultBitmap != null ? resultColor : maskColor); //����ɨ����������Ӱ���֣����ĸ����֣�ɨ�������浽��Ļ���棬ɨ�������浽��Ļ���� //ɨ��������浽��Ļ��ߣ�ɨ�����ұߵ���Ļ�ұ� canvas.drawRect(0, 0, width, frame.top, paint); canvas.drawRect(0, frame.top, frame.left, frame.bottom + 1, paint); canvas.drawRect(frame.right + 1, frame.top, width, frame.bottom + 1, paint); canvas.drawRect(0, frame.bottom + 1, width, height, paint); if (resultBitmap != null) { // Draw the opaque result bitmap over the scanning rectangle paint.setAlpha(OPAQUE); canvas.drawBitmap(resultBitmap, frame.left, frame.top, paint); } else { //��ɨ�����ϵĽǣ��ܹ�8������ paint.setColor(Color.GREEN); canvas.drawRect(frame.left, frame.top, frame.left + ScreenRate, frame.top + CORNER_WIDTH, paint); canvas.drawRect(frame.left, frame.top, frame.left + CORNER_WIDTH, frame.top + ScreenRate, paint); canvas.drawRect(frame.right - ScreenRate, frame.top, frame.right, frame.top + CORNER_WIDTH, paint); canvas.drawRect(frame.right - CORNER_WIDTH, frame.top, frame.right, frame.top + ScreenRate, paint); canvas.drawRect(frame.left, frame.bottom - CORNER_WIDTH, frame.left + ScreenRate, frame.bottom, paint); canvas.drawRect(frame.left, frame.bottom - ScreenRate, frame.left + CORNER_WIDTH, frame.bottom, paint); canvas.drawRect(frame.right - ScreenRate, frame.bottom - CORNER_WIDTH, frame.right, frame.bottom, paint); canvas.drawRect(frame.right - CORNER_WIDTH, frame.bottom - ScreenRate, frame.right, frame.bottom, paint); //�����м����,ÿ��ˢ�½��棬�м���������ƶ�SPEEN_DISTANCE slideTop += SPEEN_DISTANCE; if(slideTop >= frame.bottom){ slideTop = frame.top; } Rect lineRect = new Rect(); lineRect.left = frame.left; lineRect.right = frame.right; lineRect.top = slideTop; lineRect.bottom = slideTop + 18; canvas.drawBitmap(((BitmapDrawable)(getResources().getDrawable(R.mipmap.qrcode_scan_line))).getBitmap(), null, lineRect, paint); //��ɨ���������� paint.setColor(Color.WHITE); paint.setTextSize(TEXT_SIZE * density); paint.setAlpha(0x40); paint.setTypeface(Typeface.create("System", Typeface.BOLD)); String text = getResources().getString(R.string.scan_text); float textWidth = paint.measureText(text); canvas.drawText(text, (width - textWidth)/2, frame.bottom + (float)TEXT_PADDING_TOP *density, paint); Collection<ResultPoint> currentPossible = possibleResultPoints; Collection<ResultPoint> currentLast = lastPossibleResultPoints; if (currentPossible.isEmpty()) { lastPossibleResultPoints = null; } else { possibleResultPoints = new HashSet<ResultPoint>(5); lastPossibleResultPoints = currentPossible; paint.setAlpha(OPAQUE); paint.setColor(resultPointColor); for (ResultPoint point : currentPossible) { canvas.drawCircle(frame.left + point.getX(), frame.top + point.getY(), 6.0f, paint); } } if (currentLast != null) { paint.setAlpha(OPAQUE / 2); paint.setColor(resultPointColor); for (ResultPoint point : currentLast) { canvas.drawCircle(frame.left + point.getX(), frame.top + point.getY(), 3.0f, paint); } } //ֻˢ��ɨ�������ݣ�����ط���ˢ�� postInvalidateDelayed(ANIMATION_DELAY, frame.left, frame.top, frame.right, frame.bottom); } } public void drawViewfinder() { resultBitmap = null; invalidate(); } /** * Draw a bitmap with the result points highlighted instead of the live * scanning display. * * @param barcode * An image of the decoded barcode. */ public void drawResultBitmap(Bitmap barcode) { resultBitmap = barcode; invalidate(); } public void addPossibleResultPoint(ResultPoint point) { possibleResultPoints.add(point); } }
/** * Copyright 2009-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ibatis.scripting.xmltags; import java.util.Arrays; import java.util.List; import org.apache.ibatis.session.Configuration; /** * where标签是基于trim标签来实现的 * @author Clinton Begin */ public class WhereSqlNode extends TrimSqlNode { private static List<String> prefixList = Arrays.asList("AND ","OR ","AND\n", "OR\n", "AND\r", "OR\r", "AND\t", "OR\t"); public WhereSqlNode(Configuration configuration, SqlNode contents) { super(configuration, contents, "WHERE", prefixList, null, null); } }
package com.ucar.datalink.common.utils; import java.util.concurrent.*; public abstract class ConvertingFutureCallback<U, T> implements Callback<U>, Future<T> { private Callback<T> underlying; private CountDownLatch finishedLatch; private T result = null; private Throwable exception = null; public ConvertingFutureCallback(Callback<T> underlying) { this.underlying = underlying; this.finishedLatch = new CountDownLatch(1); } public abstract T convert(U result); @Override public void onCompletion(Throwable error, U result) { this.exception = error; this.result = convert(result); if (underlying != null) underlying.onCompletion(error, this.result); finishedLatch.countDown(); } @Override public boolean cancel(boolean b) { return false; } @Override public boolean isCancelled() { return false; } @Override public boolean isDone() { return finishedLatch.getCount() == 0; } @Override public T get() throws InterruptedException, ExecutionException { finishedLatch.await(); return result(); } @Override public T get(long l, TimeUnit timeUnit) throws InterruptedException, ExecutionException, TimeoutException { if (!finishedLatch.await(l, timeUnit)) throw new TimeoutException("Timed out waiting for future"); return result(); } private T result() throws ExecutionException { if (exception != null) { throw new ExecutionException(exception); } return result; } }
/* * Copyright (c) CovertJaguar, 2014 http://railcraft.info * * This code is the property of CovertJaguar * and may only be used with explicit written * permission unless otherwise specified on the * license page at http://railcraft.info/wiki/info:license. */ package mods.railcraft.common.blocks.machine.beta; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.IIcon; import net.minecraftforge.common.util.ForgeDirection; import mods.railcraft.common.blocks.machine.IEnumMachine; import mods.railcraft.common.fluids.FluidHelper; import mods.railcraft.common.fluids.TankManager; import mods.railcraft.common.fluids.tanks.FakeTank; import mods.railcraft.common.fluids.tanks.StandardTank; import mods.railcraft.common.util.misc.Game; import mods.railcraft.common.util.misc.ITileFilter; import mods.railcraft.common.util.misc.MiscTools; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTankInfo; import net.minecraftforge.fluids.IFluidHandler; /** * * @author CovertJaguar <http://www.railcraft.info> */ public class TileTankIronValve extends TileTankBase implements IFluidHandler { private final static ITileFilter FLUID_OUTPUT_FILTER = new ITileFilter() { @Override public boolean matches(TileEntity tile) { if (tile instanceof TileTankBase) return false; else if (tile instanceof IFluidHandler) return true; return false; } }; private final static ForgeDirection[] FLUID_OUTPUTS = {ForgeDirection.DOWN}; private static final int FLOW_RATE = 250; private static final byte FILL_INCREMENT = 1; private StandardTank fillTank = new StandardTank(20); public TileTankIronValve() { tankManager.add(fillTank); } private void setFilling(FluidStack resource) { boolean needsUpdate = fillTank.isEmpty(); resource = resource.copy(); resource.amount = 20; fillTank.fill(resource, true); if (needsUpdate) sendUpdateToClient(); } private void decrementFilling() { if (!fillTank.isEmpty()) { fillTank.drain(FILL_INCREMENT, true); if (fillTank.isEmpty()) sendUpdateToClient(); } } public boolean isFilling() { return !fillTank.isEmpty(); } public StandardTank getFillTank() { return fillTank; } @Override public IEnumMachine getMachineType() { return EnumMachineBeta.TANK_IRON_VALVE; } @Override public void updateEntity() { super.updateEntity(); if (Game.isNotHost(worldObj)) return; decrementFilling(); if (isMaster) { TileEntity tileBelow = tileCache.getTileOnSide(ForgeDirection.DOWN); TileTankIronValve valveBelow = null; if (tileBelow instanceof TileTankIronValve) { valveBelow = (TileTankIronValve) tileBelow; if (valveBelow.isStructureValid() && valveBelow.getPatternMarker() == 'T') { StandardTank tankBelow = valveBelow.getTankManager().get(0); FluidStack liquid = tankBelow.getFluid(); if (liquid != null && liquid.amount >= tankBelow.getCapacity() - FluidHelper.BUCKET_VOLUME) { valveBelow = null; FluidStack fillStack = liquid.copy(); fillStack.amount = FluidHelper.BUCKET_VOLUME - (tankBelow.getCapacity() - liquid.amount); if (fillStack.amount > 0) { int used = tank.fill(fillStack, false); if (used > 0) { fillStack = tankBelow.drain(used, true); tank.fill(fillStack, true); } } } } else valveBelow = null; } if (valveBelow != null) { FluidStack available = tankManager.drain(0, FluidHelper.BUCKET_VOLUME, false); if (available != null && available.amount > 0) { int used = valveBelow.fill(ForgeDirection.UP, available, true); tankManager.drain(0, used, true); } } } if (getPatternPositionY() - getPattern().getMasterOffsetY() == 0) { TankManager tMan = getTankManager(); if (tMan != null) tMan.outputLiquid(tileCache, FLUID_OUTPUT_FILTER, FLUID_OUTPUTS, 0, FLOW_RATE); } } @Override public IIcon getIcon(int side) { if (!isStructureValid() || getPattern() == null) return getMachineType().getTexture(side); ForgeDirection s = ForgeDirection.getOrientation(side); char markerSide = getPattern().getPatternMarkerChecked(MiscTools.getXOnSide(getPatternPositionX(), s), MiscTools.getYOnSide(getPatternPositionY(), s), MiscTools.getZOnSide(getPatternPositionZ(), s)); if (!isMapPositionOtherBlock(markerSide)) { if (side == ForgeDirection.UP.ordinal() || side == ForgeDirection.DOWN.ordinal()) return getMachineType().getTexture(6); return getMachineType().getTexture(7); } return getMachineType().getTexture(side); } @Override public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { if (!canFill(from, null)) return 0; if (resource == null || resource.amount <= 0) return 0; TankManager tMan = getTankManager(); if (tMan == null) return 0; resource = resource.copy(); resource.amount = Math.min(resource.amount, FLOW_RATE); int filled = tMan.fill(0, resource, doFill); if (filled > 0 && doFill) setFilling(resource.copy()); return filled; } @Override public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { if (getPatternPositionY() - getPattern().getMasterOffsetY() != 1) return null; TankManager tMan = getTankManager(); if (tMan != null) { maxDrain = Math.min(maxDrain, FLOW_RATE); return tMan.drain(0, maxDrain, doDrain); } return null; } @Override public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { if (resource == null) return null; TankManager tMan = getTankManager(); if (tMan != null && tMan.get(0).getFluidType() == resource.getFluid()) return drain(from, resource.amount, doDrain); return null; } @Override public boolean canFill(ForgeDirection from, Fluid fluid) { return getPatternPositionY() - getPattern().getMasterOffsetY() > 0; } @Override public boolean canDrain(ForgeDirection from, Fluid fluid) { return getPatternPositionY() - getPattern().getMasterOffsetY() <= 1; } @Override public FluidTankInfo[] getTankInfo(ForgeDirection side) { TankManager tMan = getTankManager(); if (tMan != null) return tMan.getTankInfo(); return FakeTank.INFO; } }
package org.pushingpixels.demo.flamingo.svg.tango.transcoded; import java.awt.*; import java.awt.geom.*; import java.awt.image.BufferedImage; import java.io.*; import java.lang.ref.WeakReference; import java.util.Base64; import java.util.Stack; import javax.imageio.ImageIO; import javax.swing.SwingUtilities; import javax.swing.plaf.UIResource; import org.pushingpixels.neon.api.icon.ResizableIcon; import org.pushingpixels.neon.api.icon.ResizableIconUIResource; /** * This class has been automatically generated using <a * href="https://github.com/kirill-grouchnikov/radiance">Photon SVG transcoder</a>. */ public class Document_new implements ResizableIcon { private Shape shape = null; private GeneralPath generalPath = null; private Paint paint = null; private Stroke stroke = null; private Shape clip = null; private Stack<AffineTransform> transformsStack = new Stack<>(); private void _paint0(Graphics2D g,float origAlpha) { transformsStack.push(g.getTransform()); // g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f)); // _0 g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f)); // _0_0 g.setComposite(AlphaComposite.getInstance(3, 0.56725144f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(1.167598009109497f, 0.0f, 0.0f, 1.0f, -4.692486763000488f, 0.6187170147895813f)); // _0_0_0 if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(40.128307f, 42.07798f); generalPath.curveTo(40.15366f, 43.693268f, 37.143654f, 45.188953f, 32.23805f, 45.998688f); generalPath.curveTo(27.332438f, 46.808426f, 21.28115f, 46.808426f, 16.375542f, 45.998688f); generalPath.curveTo(11.469933f, 45.188953f, 8.459927f, 43.693268f, 8.485281f, 42.07798f); generalPath.curveTo(8.459927f, 40.462692f, 11.469933f, 38.967007f, 16.375542f, 38.157272f); generalPath.curveTo(21.28115f, 37.347534f, 27.332438f, 37.347534f, 32.23805f, 38.157272f); generalPath.curveTo(37.143654f, 38.967007f, 40.15366f, 40.462692f, 40.128307f, 42.07798f); generalPath.closePath(); shape = generalPath; paint = new RadialGradientPaint(new Point2D.Double(24.306795120239258, 42.077980041503906), 15.821514f, new Point2D.Double(24.306795120239258, 42.077980041503906), new float[] {0.0f,1.0f}, new Color[] {new Color(0, 0, 0, 255),new Color(0, 0, 0, 0)}, MultipleGradientPaint.CycleMethod.NO_CYCLE, MultipleGradientPaint.ColorSpaceType.SRGB, new AffineTransform(1.0f, 0.0f, 0.0f, 0.2849160134792328f, -6.310056114470044E-16f, 30.089279174804688f)); g.setPaint(paint); g.fill(shape); g.setTransform(transformsStack.pop()); g.setTransform(transformsStack.pop()); g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f)); // _0_1 g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f)); // _0_1_0 shape = new RoundRectangle2D.Double(6.60355281829834, 3.6464462280273438, 34.875, 40.920494079589844, 2.2980971336364746, 2.2980971336364746); paint = new RadialGradientPaint(new Point2D.Double(33.966678619384766, 35.736915588378906), 86.70845f, new Point2D.Double(33.966678619384766, 35.736915588378906), new float[] {0.0f,1.0f}, new Color[] {new Color(250, 250, 250, 255),new Color(187, 187, 187, 255)}, MultipleGradientPaint.CycleMethod.NO_CYCLE, MultipleGradientPaint.ColorSpaceType.SRGB, new AffineTransform(0.9604930281639099f, 0.0f, 0.0f, 1.0411319732666016f, 0.0f, 0.0f)); g.setPaint(paint); g.fill(shape); paint = new RadialGradientPaint(new Point2D.Double(8.824419021606445, 3.7561285495758057), 37.751713f, new Point2D.Double(8.824419021606445, 3.7561285495758057), new float[] {0.0f,1.0f}, new Color[] {new Color(163, 163, 163, 255),new Color(76, 76, 76, 255)}, MultipleGradientPaint.CycleMethod.NO_CYCLE, MultipleGradientPaint.ColorSpaceType.SRGB, new AffineTransform(0.9682729840278625f, 0.0f, 0.0f, 1.0327670574188232f, 3.353553056716919f, 0.6464470028877258f)); stroke = new BasicStroke(1.0f,1,1,4.0f,null,0.0f); shape = new RoundRectangle2D.Double(6.60355281829834, 3.6464462280273438, 34.875, 40.920494079589844, 2.2980971336364746, 2.2980971336364746); g.setPaint(paint); g.setStroke(stroke); g.draw(shape); g.setTransform(transformsStack.pop()); g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f)); // _0_1_1 paint = new RadialGradientPaint(new Point2D.Double(8.143556594848633, 7.26789665222168), 38.158695f, new Point2D.Double(8.143556594848633, 7.26789665222168), new float[] {0.0f,1.0f}, new Color[] {new Color(255, 255, 255, 255),new Color(248, 248, 248, 255)}, MultipleGradientPaint.CycleMethod.NO_CYCLE, MultipleGradientPaint.ColorSpaceType.SRGB, new AffineTransform(0.9682729840278625f, 0.0f, 0.0f, 1.0327670574188232f, 3.353553056716919f, 0.6464470028877258f)); stroke = new BasicStroke(1.0f,1,1,4.0f,null,0.0f); shape = new RoundRectangle2D.Double(7.666053771972656, 4.583946228027344, 32.77588653564453, 38.94638442993164, 0.2980971336364746, 0.2980971336364746); g.setPaint(paint); g.setStroke(stroke); g.draw(shape); g.setTransform(transformsStack.pop()); g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.6464470028877258f, -0.03798932954668999f)); // _0_1_2 g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(0.22970299422740936f, 0.0f, 0.0f, 0.22970299422740936f, 4.967081069946289f, 4.244972229003906f)); // _0_1_2_0 g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f)); // _0_1_2_0_0 if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(23.428f, 113.07f); generalPath.curveTo(23.428f, 115.043f, 21.828f, 116.642f, 19.855f, 116.642f); generalPath.curveTo(17.881f, 116.642f, 16.282f, 115.042f, 16.282f, 113.07f); generalPath.curveTo(16.282f, 111.096f, 17.882f, 109.497f, 19.855f, 109.497f); generalPath.curveTo(21.828f, 109.497f, 23.428f, 111.097f, 23.428f, 113.07f); generalPath.closePath(); shape = generalPath; paint = new Color(255, 255, 255, 255); g.setPaint(paint); g.fill(shape); g.setTransform(transformsStack.pop()); g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f)); // _0_1_2_0_1 if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(23.428f, 63.07f); generalPath.curveTo(23.428f, 65.043f, 21.828f, 66.643f, 19.855f, 66.643f); generalPath.curveTo(17.881f, 66.643f, 16.282f, 65.043f, 16.282f, 63.07f); generalPath.curveTo(16.282f, 61.096f, 17.882f, 59.497f, 19.855f, 59.497f); generalPath.curveTo(21.828f, 59.497f, 23.428f, 61.097f, 23.428f, 63.07f); generalPath.closePath(); shape = generalPath; paint = new Color(255, 255, 255, 255); g.setPaint(paint); g.fill(shape); g.setTransform(transformsStack.pop()); g.setTransform(transformsStack.pop()); g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f)); // _0_1_2_1 if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(9.995011f, 29.952326f); generalPath.curveTo(9.995011f, 30.40553f, 9.627486f, 30.772825f, 9.174282f, 30.772825f); generalPath.curveTo(8.720848f, 30.772825f, 8.353554f, 30.4053f, 8.353554f, 29.952326f); generalPath.curveTo(8.353554f, 29.498892f, 8.721078f, 29.131598f, 9.174282f, 29.131598f); generalPath.curveTo(9.627486f, 29.131598f, 9.995011f, 29.499123f, 9.995011f, 29.952326f); generalPath.closePath(); shape = generalPath; paint = new RadialGradientPaint(new Point2D.Double(20.892099380493164, 114.56839752197266), 5.256f, new Point2D.Double(20.892099380493164, 114.56839752197266), new float[] {0.0f,1.0f}, new Color[] {new Color(240, 240, 240, 255),new Color(154, 154, 154, 255)}, MultipleGradientPaint.CycleMethod.NO_CYCLE, MultipleGradientPaint.ColorSpaceType.SRGB, new AffineTransform(0.22970299422740936f, 0.0f, 0.0f, 0.22970299422740936f, 4.613529205322266f, 3.9798080921173096f)); g.setPaint(paint); g.fill(shape); g.setTransform(transformsStack.pop()); g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f)); // _0_1_2_2 if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(9.995011f, 18.467176f); generalPath.curveTo(9.995011f, 18.92038f, 9.627486f, 19.287905f, 9.174282f, 19.287905f); generalPath.curveTo(8.720848f, 19.287905f, 8.353554f, 18.92038f, 8.353554f, 18.467176f); generalPath.curveTo(8.353554f, 18.013742f, 8.721078f, 17.646446f, 9.174282f, 17.646446f); generalPath.curveTo(9.627486f, 17.646446f, 9.995011f, 18.013971f, 9.995011f, 18.467176f); generalPath.closePath(); shape = generalPath; paint = new RadialGradientPaint(new Point2D.Double(20.892099380493164, 64.56790161132812), 5.257f, new Point2D.Double(20.892099380493164, 64.56790161132812), new float[] {0.0f,1.0f}, new Color[] {new Color(240, 240, 240, 255),new Color(154, 154, 154, 255)}, MultipleGradientPaint.CycleMethod.NO_CYCLE, MultipleGradientPaint.ColorSpaceType.SRGB, new AffineTransform(0.22970299422740936f, 0.0f, 0.0f, 0.22970299422740936f, 4.613529205322266f, 3.9798080921173096f)); g.setPaint(paint); g.fill(shape); g.setTransform(transformsStack.pop()); g.setTransform(transformsStack.pop()); g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f)); // _0_1_3 paint = new Color(0, 0, 0, 4); stroke = new BasicStroke(0.9885531f,0,0,4.0f,null,0.0f); if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(11.505723f, 5.4942765f); generalPath.lineTo(11.505723f, 43.400867f); shape = generalPath; g.setPaint(paint); g.setStroke(stroke); g.draw(shape); g.setTransform(transformsStack.pop()); g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f)); // _0_1_4 paint = new Color(255, 255, 255, 52); stroke = new BasicStroke(1.0f,0,0,4.0f,null,0.0f); if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(12.5f, 5.0205154f); generalPath.lineTo(12.5f, 43.038227f); shape = generalPath; g.setPaint(paint); g.setStroke(stroke); g.draw(shape); g.setTransform(transformsStack.pop()); g.setTransform(transformsStack.pop()); g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f)); // _0_2 g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(0.7832919955253601f, 0.0f, 0.0f, 0.7832919955253601f, -6.340882778167725f, -86.65167999267578f)); // _0_2_0 if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(69.375f, 125.0f); generalPath.curveTo(69.39803f, 130.151f, 66.66322f, 134.92062f, 62.206123f, 137.50279f); generalPath.curveTo(57.74902f, 140.08498f, 52.25098f, 140.08498f, 47.793877f, 137.50279f); generalPath.curveTo(43.336773f, 134.92062f, 40.601963f, 130.151f, 40.625f, 125.0f); generalPath.curveTo(40.601963f, 119.84899f, 43.336773f, 115.07938f, 47.793877f, 112.4972f); generalPath.curveTo(52.25098f, 109.91502f, 57.74902f, 109.91502f, 62.206123f, 112.4972f); generalPath.curveTo(66.66322f, 115.07938f, 69.39803f, 119.84899f, 69.375f, 125.0f); generalPath.closePath(); shape = generalPath; paint = new RadialGradientPaint(new Point2D.Double(55.0, 125.0), 14.375f, new Point2D.Double(55.0, 125.0), new float[] {0.0f,0.5f,1.0f}, new Color[] {new Color(255, 255, 255, 255),new Color(255, 245, 32, 227),new Color(255, 243, 0, 0)}, MultipleGradientPaint.CycleMethod.NO_CYCLE, MultipleGradientPaint.ColorSpaceType.SRGB, new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f)); g.setPaint(paint); g.fill(shape); g.setTransform(transformsStack.pop()); g.setTransform(transformsStack.pop()); g.setTransform(transformsStack.pop()); g.setTransform(transformsStack.pop()); } @SuppressWarnings("unused") private void innerPaint(Graphics2D g) { float origAlpha = 1.0f; Composite origComposite = g.getComposite(); if (origComposite instanceof AlphaComposite) { AlphaComposite origAlphaComposite = (AlphaComposite)origComposite; if (origAlphaComposite.getRule() == AlphaComposite.SRC_OVER) { origAlpha = origAlphaComposite.getAlpha(); } } _paint0(g, origAlpha); shape = null; generalPath = null; paint = null; stroke = null; clip = null; transformsStack.clear(); } /** * Returns the X of the bounding box of the original SVG image. * * @return The X of the bounding box of the original SVG image. */ public static double getOrigX() { return 5.185306549072266; } /** * Returns the Y of the bounding box of the original SVG image. * * @return The Y of the bounding box of the original SVG image. */ public static double getOrigY() { return 0.0; } /** * Returns the width of the bounding box of the original SVG image. * * @return The width of the bounding box of the original SVG image. */ public static double getOrigWidth() { return 42.814693450927734; } /** * Returns the height of the bounding box of the original SVG image. * * @return The height of the bounding box of the original SVG image. */ public static double getOrigHeight() { return 47.42714309692383; } /** The current width of this resizable icon. */ private int width; /** The current height of this resizable icon. */ private int height; /** * Creates a new transcoded SVG image. This is marked as private to indicate that app * code should be using the {@link #of(int, int)} method to obtain a pre-configured instance. */ private Document_new() { this.width = (int) getOrigWidth(); this.height = (int) getOrigHeight(); } @Override public int getIconHeight() { return height; } @Override public int getIconWidth() { return width; } @Override public synchronized void setDimension(Dimension newDimension) { this.width = newDimension.width; this.height = newDimension.height; } @Override public synchronized void paintIcon(Component c, Graphics g, int x, int y) { Graphics2D g2d = (Graphics2D) g.create(); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); g2d.translate(x, y); double coef1 = (double) this.width / getOrigWidth(); double coef2 = (double) this.height / getOrigHeight(); double coef = Math.min(coef1, coef2); g2d.clipRect(0, 0, this.width, this.height); g2d.scale(coef, coef); g2d.translate(-getOrigX(), -getOrigY()); if (coef1 != coef2) { if (coef1 < coef2) { int extraDy = (int) ((getOrigWidth() - getOrigHeight()) / 2.0); g2d.translate(0, extraDy); } else { int extraDx = (int) ((getOrigHeight() - getOrigWidth()) / 2.0); g2d.translate(extraDx, 0); } } Graphics2D g2ForInner = (Graphics2D) g2d.create(); innerPaint(g2ForInner); g2ForInner.dispose(); g2d.dispose(); } /** * Returns a new instance of this icon with specified dimensions. * * @param width Required width of the icon * @param height Required height of the icon * @return A new instance of this icon with specified dimensions. */ public static ResizableIcon of(int width, int height) { Document_new base = new Document_new(); base.width = width; base.height = height; return base; } /** * Returns a new {@link UIResource} instance of this icon with specified dimensions. * * @param width Required width of the icon * @param height Required height of the icon * @return A new {@link UIResource} instance of this icon with specified dimensions. */ public static ResizableIconUIResource uiResourceOf(int width, int height) { Document_new base = new Document_new(); base.width = width; base.height = height; return new ResizableIconUIResource(base); } /** * Returns a factory that returns instances of this icon on demand. * * @return Factory that returns instances of this icon on demand. */ public static Factory factory() { return Document_new::new; } }
package io.flutter.plugins.share; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import io.flutter.app.FlutterActivity; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugin.common.EventChannel; import static io.flutter.plugins.share.SharePlugin.IS_MULTIPLE; import static io.flutter.plugins.share.SharePlugin.PATH; import static io.flutter.plugins.share.SharePlugin.TEXT; import static io.flutter.plugins.share.SharePlugin.TITLE; import static io.flutter.plugins.share.SharePlugin.TYPE; /** * main activity super, handles eventChannel sink creation * , share intent parsing and redirecting to eventChannel sink stream * * @author Duarte Silveira * @version 1 * @since 25/05/18 */ public class FlutterShareReceiverActivity extends FlutterActivity { public static final String STREAM = "plugins.flutter.io/receiveshare"; private EventChannel.EventSink eventSink = null; private boolean inited = false; private List<Intent> backlog = new ArrayList<>(); private boolean ignoring = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (!inited) { init(getFlutterView(), this); } } public void init(BinaryMessenger flutterView, Context context) { Log.i(getClass().getSimpleName(), "initializing eventChannel"); context.startActivity(new Intent(context, ShareReceiverActivityWorker.class)); // Handle other intents, such as being started from the home screen new EventChannel(flutterView, STREAM).setStreamHandler(new EventChannel.StreamHandler() { @Override public void onListen(Object args, EventChannel.EventSink events) { Log.i(getClass().getSimpleName(), "adding listener"); eventSink = events; ignoring = false; for (int i = 0; i < backlog.size(); i++) { handleIntent(backlog.remove(i)); } } @Override public void onCancel(Object args) { Log.i(getClass().getSimpleName(), "cancelling listener"); ignoring = true; eventSink = null; } }); inited = true; handleIntent(getIntent()); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); handleIntent(intent); } public void handleIntent(Intent intent) { // Get intent, action and MIME type String action = intent.getAction(); String type = intent.getType(); if (Intent.ACTION_SEND.equals(action) && type != null) { if ("text/plain".equals(type)) { String sharedTitle = intent.getStringExtra(Intent.EXTRA_SUBJECT); Log.i(getClass().getSimpleName(), "receiving shared title: " + sharedTitle); String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT); Log.i(getClass().getSimpleName(), "receiving shared text: " + sharedText); if (eventSink != null) { Map<String, String> params = new HashMap<>(); params.put(TYPE, type); params.put(TEXT, sharedText); if (!TextUtils.isEmpty(sharedTitle)) { params.put(TITLE, sharedTitle); } eventSink.success(params); } else if (!ignoring && !backlog.contains(intent)) { backlog.add(intent); } } else { String sharedTitle = intent.getStringExtra(Intent.EXTRA_SUBJECT); Log.i(getClass().getSimpleName(), "receiving shared title: " + sharedTitle); Uri sharedUri = intent.getParcelableExtra(Intent.EXTRA_STREAM); Log.i(getClass().getSimpleName(), "receiving shared file: " + sharedUri); if (eventSink != null) { Map<String, String> params = new HashMap<>(); params.put(TYPE, type); params.put(PATH, sharedUri.toString()); if (!TextUtils.isEmpty(sharedTitle)) { params.put(TITLE, sharedTitle); } if (!intent.hasExtra(Intent.EXTRA_TEXT)) { params.put(TEXT, intent.getStringExtra(Intent.EXTRA_TEXT)); } eventSink.success(params); } else if (!ignoring && !backlog.contains(intent)) { backlog.add(intent); } } } else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) { Log.i(getClass().getSimpleName(), "receiving shared files!"); ArrayList<Uri> uris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM); if (eventSink != null) { Map<String, String> params = new HashMap<>(); params.put(TYPE, type); params.put(IS_MULTIPLE, "true"); for (int i = 0; i < uris.size(); i++) { params.put(Integer.toString(i), uris.get(i).toString()); } eventSink.success(params); } else if (!ignoring && !backlog.contains(intent)) { backlog.add(intent); } } } }
package com.fyp.baigktk.cuifr; import android.app.Activity; import android.content.Intent; import android.graphics.Color; import android.os.Handler; import androidx.viewpager.widget.PagerAdapter; import androidx.viewpager.widget.ViewPager; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import devlight.io.library.ntb.NavigationTabBar; public class NavBar{ private Activity activity; private NavigationTabBar navigationTabBar; private static NavBar instance = null; private boolean initialized = false; private int INDEX; Runnable mDelay; Handler mHandler; private NavBar(){ } public static NavBar getInstance(){ if(instance == null){ instance = new NavBar(); } return instance; } public void initializeTab(Activity a){ this.activity = a; navigationTabBar = (NavigationTabBar) activity.findViewById(R.id.ntb); ViewPager viewPager = (ViewPager) activity.findViewById(R.id.vp_horizontal_ntb); viewPager.setAdapter(new PagerAdapter() { @Override public int getCount() { return 3; } @Override public boolean isViewFromObject(View view, Object object) { return view.equals(object); } @Override public void destroyItem(final View container, final int position, final Object object) { ((ViewPager) container).removeView((View) object); } @Override public Object instantiateItem(final ViewGroup container, final int position) { return null; } }); final String[] colors = activity.getResources().getStringArray(R.array.ntb_colors); final ArrayList<NavigationTabBar.Model> models = new ArrayList<>(); models.add( new NavigationTabBar.Model.Builder(activity.getResources().getDrawable(R.drawable.ic_home_white_24dp), Color.parseColor(colors[0])).title("Heart").badgeTitle("NTB").build() ); models.add( new NavigationTabBar.Model.Builder(activity.getResources().getDrawable(R.drawable.ic_person_white_24dp),Color.parseColor(colors[1])).title("Cup").badgeTitle("with").build() ); // models.add(new NavigationTabBar.Model.Builder(activity.getResources().getDrawable(R.drawable.ic_account_balance_white_24dp),Color.parseColor(colors[2])).title("Diploma").badgeTitle("state").build() // ); navigationTabBar.setModels(models); if(activity instanceof MainActivity) { navigationTabBar.setViewPager(viewPager, 0); }else if(activity instanceof ProfilePageActivity){ navigationTabBar.setViewPager(viewPager, 1); } // else if(activity instanceof ShowOrganizationsActivity){ // navigationTabBar.setViewPager(viewPager, 2); // } navigationTabBar.setTitleMode(NavigationTabBar.TitleMode.ACTIVE); navigationTabBar.setBadgeGravity(NavigationTabBar.BadgeGravity.BOTTOM); navigationTabBar.setBadgePosition(NavigationTabBar.BadgePosition.CENTER); navigationTabBar.setTypeface("fonts/OpenSans-Regular.ttf"); navigationTabBar.setIsBadged(true); navigationTabBar.setIsTitled(true); navigationTabBar.setIsTinted(true); navigationTabBar.setIsBadgeUseTypeface(true); navigationTabBar.setBadgeBgColor(Color.RED); navigationTabBar.setBadgeTitleColor(Color.WHITE); navigationTabBar.setIsSwiped(true); navigationTabBar.setBadgeSize(10); navigationTabBar.setTitleSize(10); navigationTabBar.setIconSizeFraction(0.5f); } public void tabListener(final Activity current){ mHandler = new Handler(); mDelay = new Runnable() { @Override public void run() { int index = NavBar.this.INDEX; if(index==0 && !(current instanceof MainActivity)){ Intent intent = new Intent(current, MainActivity.class); current.startActivity(intent); } if(index==1 && !(current instanceof ProfilePageActivity)){ Intent intent = new Intent(current, ProfilePageActivity.class); current.startActivity(intent); } // if(index==2 && !(current instanceof ShowOrganizationsActivity)){ // Intent intent = new Intent(current, ShowOrganizationsActivity.class); // current.startActivity(intent); // } } }; navigationTabBar.setOnTabBarSelectedIndexListener(new NavigationTabBar.OnTabBarSelectedIndexListener() { @Override public void onStartTabSelected(NavigationTabBar.Model model, int index) { NavBar.this.INDEX = index; System.out.println(index); mHandler.postDelayed(mDelay, 250); } @Override public void onEndTabSelected(NavigationTabBar.Model model, int index) { } }); } }
package com.regitiny.catiny.advance.repository; import com.regitiny.catiny.advance.repository.base.MessageContentBaseRepository; import org.springframework.stereotype.Repository; /** * Spring Data SQL repository for the {@link com.regitiny.catiny.domain.MessageContent} entity. * <p> * here contains complex queries with pure SQL or HQL syntax. * if you want to write simple query then you should write to : * {@link MessageContentBaseRepository} */ @Repository @SuppressWarnings("unused") public interface MessageContentAdvanceRepository extends MessageContentBaseRepository { }
/* Copyright 2013 Nationale-Nederlanden 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 nl.nn.adapterframework.extensions.ifsa.ejb; import com.ing.ifsa.api.FireForgetService; import javax.ejb.EJBLocalObject; /** * * @author Tim van der Leeuw */ public interface IfsaFFSessionBeanLocal extends FireForgetService, EJBLocalObject { }
/*- * #%L * Elastic APM Java agent * %% * Copyright (C) 2018 - 2020 Elastic and contributors * %% * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. 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. * #L% */ /** * Contains the public API of the Elastic APM Java agent. */ package co.elastic.apm.api;
package com.nimbusds.oauth2.sdk.assertions.jwt; import java.util.Set; import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.jwt.proc.BadJWTException; import com.nimbusds.jwt.proc.DefaultJWTClaimsVerifier; import com.nimbusds.oauth2.sdk.id.Audience; import net.jcip.annotations.Immutable; import org.apache.commons.collections4.CollectionUtils; /** * JSON Web Token (JWT) bearer assertion details (claims set) verifier for * OAuth 2.0 client authentication and authorisation grants. Intended for * initial validation of JWT assertions: * * <ul> * <li>Audience check * <li>Expiration time check * <li>Not-before time check (is set) * <li>Subject and issuer presence check * </ul> * * <p>Related specifications: * * <ul> * <li>JSON Web Token (JWT) Profile for OAuth 2.0 Client Authentication and * Authorization Grants (RFC 7523). * </ul> */ @Immutable public class JWTAssertionDetailsVerifier extends DefaultJWTClaimsVerifier { // Cache JWT exceptions for quick processing of bad claims sets /** * Missing JWT expiration claim. */ private static final BadJWTException MISSING_EXP_CLAIM_EXCEPTION = new BadJWTException("Missing JWT expiration claim"); /** * Missing JWT audience claim. */ private static final BadJWTException MISSING_AUD_CLAIM_EXCEPTION = new BadJWTException("Missing JWT audience claim"); /** * Missing JWT subject claim. */ private static final BadJWTException MISSING_SUB_CLAIM_EXCEPTION = new BadJWTException("Missing JWT subject claim"); /** * Missing JWT issuer claim. */ private static final BadJWTException MISSING_ISS_CLAIM_EXCEPTION = new BadJWTException("Missing JWT issuer claim"); /** * The expected audience. */ private final Set<Audience> expectedAudience; /** * Cached unexpected JWT audience claim exception. */ private final BadJWTException unexpectedAudClaimException; /** * Creates a new JWT bearer assertion details (claims set) verifier. * * @param expectedAudience The expected audience (aud) claim values. * Must not be empty or {@code null}. Should * typically contain the token endpoint URI and * for OpenID provider it may also include the * issuer URI. */ public JWTAssertionDetailsVerifier(final Set<Audience> expectedAudience) { if (CollectionUtils.isEmpty(expectedAudience)) { throw new IllegalArgumentException("The expected audience set must not be null or empty"); } this.expectedAudience = expectedAudience; unexpectedAudClaimException = new BadJWTException("Invalid JWT audience claim, expected " + expectedAudience); } /** * Returns the expected audience values. * * @return The expected audience (aud) claim values. */ public Set<Audience> getExpectedAudience() { return expectedAudience; } @Override public void verify(final JWTClaimsSet claimsSet) throws BadJWTException { super.verify(claimsSet); if (claimsSet.getExpirationTime() == null) { throw MISSING_EXP_CLAIM_EXCEPTION; } if (claimsSet.getAudience() == null || claimsSet.getAudience().isEmpty()) { throw MISSING_AUD_CLAIM_EXCEPTION; } boolean audMatch = false; for (String aud: claimsSet.getAudience()) { if (aud == null || aud.isEmpty()) { continue; // skip } if (expectedAudience.contains(new Audience(aud))) { audMatch = true; } } if (! audMatch) { throw unexpectedAudClaimException; } if (claimsSet.getIssuer() == null) { throw MISSING_ISS_CLAIM_EXCEPTION; } if (claimsSet.getSubject() == null) { throw MISSING_SUB_CLAIM_EXCEPTION; } } }
package org.swtk.commons.dict.wordnet.frames.instance.p0.p1; import java.util.Map; import java.util.TreeMap; import org.swtk.common.dict.dto.wordnet.DataNoun; import com.trimc.blogger.commons.utils.GsonUtils; public final class WordnetNounFrame0167 { private static Map<String, DataNoun> map = new TreeMap<String, DataNoun>(); static { add("{\"id\":\"01670073\", \"upperType\":\"NOUN\", \"term\":\"musk_turtle\", \"synonyms\":[\"stinkpot\"], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01669755\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01669943\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01670211\", \"upperType\":\"NOUN\", \"term\":\"Emydidae\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01659454\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01664915\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01670419\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01670600\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01670898\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01671709\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01672168\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01670419\", \"upperType\":\"NOUN\", \"term\":\"terrapin\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01665425\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01670211\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"01670732\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01670600\", \"upperType\":\"NOUN\", \"term\":\"Malaclemys\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01660364\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01670211\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01670732\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01670732\", \"upperType\":\"NOUN\", \"term\":\"diamondback_terrapin\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01670419\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01670600\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01670898\", \"upperType\":\"NOUN\", \"term\":\"Pseudemys\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01660364\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01670211\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01671077\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01671306\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01671533\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01671077\", \"upperType\":\"NOUN\", \"term\":\"red-bellied_terrapin\", \"synonyms\":[\"redbelly\"], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01665425\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01670898\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01671306\", \"upperType\":\"NOUN\", \"term\":\"slider\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01665425\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01670898\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01671533\", \"upperType\":\"NOUN\", \"term\":\"cooter\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01665425\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01670898\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01671709\", \"upperType\":\"NOUN\", \"term\":\"Terrapene\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01660364\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01670211\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01671832\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01671832\", \"upperType\":\"NOUN\", \"term\":\"box_turtle\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01665425\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01671709\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"01672013\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01672013\", \"upperType\":\"NOUN\", \"term\":\"Western_box_turtle\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01671832\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01672168\", \"upperType\":\"NOUN\", \"term\":\"Chrysemys\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01660364\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01670211\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01672295\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01672295\", \"upperType\":\"NOUN\", \"term\":\"painted_turtle\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01665425\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01672168\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01672524\", \"upperType\":\"NOUN\", \"term\":\"Testudinidae\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01659454\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01664915\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01672733\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01673019\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01673314\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01673602\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01673953\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01672733\", \"upperType\":\"NOUN\", \"term\":\"tortoise\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01665425\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01672524\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"01673176\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"01673443\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"01673766\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"01674120\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"01674346\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01673019\", \"upperType\":\"NOUN\", \"term\":\"Testudo\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01660364\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01672524\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01673176\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01673443\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01673176\", \"upperType\":\"NOUN\", \"term\":\"European_tortoise\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01672733\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01673019\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01673314\", \"upperType\":\"NOUN\", \"term\":\"Geochelone\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01660364\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01672524\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01673443\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01673443\", \"upperType\":\"NOUN\", \"term\":\"giant_tortoise\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01672733\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01673019\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01673314\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01673602\", \"upperType\":\"NOUN\", \"term\":\"Gopherus\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01660364\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01672524\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01673766\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01674120\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01674346\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01673766\", \"upperType\":\"NOUN\", \"term\":\"gopher_tortoise\", \"synonyms\":[\"gopher\"], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01672733\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01673602\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01673953\", \"upperType\":\"NOUN\", \"term\":\"Xerobates\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01660364\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01672524\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01674120\", \"upperType\":\"NOUN\", \"term\":\"desert_tortoise\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01672733\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01673602\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01674346\", \"upperType\":\"NOUN\", \"term\":\"Texas_tortoise\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01672733\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01673602\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01674515\", \"upperType\":\"NOUN\", \"term\":\"Trionychidae\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01659454\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01664915\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01674673\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01674916\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01674673\", \"upperType\":\"NOUN\", \"term\":\"soft-shelled_turtle\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01665425\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01674515\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"01675073\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"01675252\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01674916\", \"upperType\":\"NOUN\", \"term\":\"Trionyx\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01660364\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01674515\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01675073\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01675252\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01675073\", \"upperType\":\"NOUN\", \"term\":\"spiny_softshell\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01674673\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01674916\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01675252\", \"upperType\":\"NOUN\", \"term\":\"smooth_softshell\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01674673\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01674916\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01675408\", \"upperType\":\"NOUN\", \"term\":\"Lepidosauria\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"08120743\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01663360\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01675591\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01676144\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01675591\", \"upperType\":\"NOUN\", \"term\":\"Rhynchocephalia\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01345170\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01675408\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01675759\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01675759\", \"upperType\":\"NOUN\", \"term\":\"Sphenodon\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01660364\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01675591\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01675923\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01675923\", \"upperType\":\"NOUN\", \"term\":\"tuatara\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01664459\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01675759\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01676144\", \"upperType\":\"NOUN\", \"term\":\"Squamata\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01345170\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01675408\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01676309\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01729031\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01676309\", \"upperType\":\"NOUN\", \"term\":\"Sauria\", \"synonyms\":[\"Lacertilia\"], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01345170\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01676144\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"ACTION\", \"id\":\"02864625\", \"semPointer\":\"0302\", \"upperType\":\"ADJECTIVE\"},{\"frameType\":\"ACTION\", \"id\":\"02864625\", \"semPointer\":\"0101\", \"upperType\":\"ADJECTIVE\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01676857\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01677491\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01678605\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01678954\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01685561\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01686069\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01686365\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01687582\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01687918\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01690082\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01691867\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01693344\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01693726\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01694025\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01694423\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01695354\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01696113\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01697071\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01676857\", \"upperType\":\"NOUN\", \"term\":\"saurian\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01664459\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01676309\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"ACTION\", \"id\":\"02864625\", \"semPointer\":\"0101\", \"upperType\":\"ADJECTIVE\"},{\"frameType\":\"SYNONYM\", \"id\":\"01677105\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01677105\", \"upperType\":\"NOUN\", \"term\":\"lizard\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01676857\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"01677631\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"01679396\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"01685842\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"01686199\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"01686774\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"01688080\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"01690306\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"01692052\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"01693858\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"01694293\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"01694592\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"01695505\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"01696424\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"01697350\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01677491\", \"upperType\":\"NOUN\", \"term\":\"Gekkonidae\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01659454\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01676309\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01677866\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01678240\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01677631\", \"upperType\":\"NOUN\", \"term\":\"gecko\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01677105\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"01677993\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"01678363\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01677866\", \"upperType\":\"NOUN\", \"term\":\"Ptychozoon\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01660364\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01677491\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01677993\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01677993\", \"upperType\":\"NOUN\", \"term\":\"flying_gecko\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01677631\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01677866\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01678240\", \"upperType\":\"NOUN\", \"term\":\"Coleonyx\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01660364\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01677491\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01678363\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01678363\", \"upperType\":\"NOUN\", \"term\":\"banded_gecko\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01677631\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01678240\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01678605\", \"upperType\":\"NOUN\", \"term\":\"Pygopodidae\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01659454\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01676309\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01678754\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01678754\", \"upperType\":\"NOUN\", \"term\":\"Pygopus\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01660364\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01678605\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01678954\", \"upperType\":\"NOUN\", \"term\":\"Iguanidae\", \"synonyms\":[\"Iguania\"], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01659454\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01676309\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01679396\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01679883\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01680254\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01680554\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01680878\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01681163\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01681528\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01681819\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01682135\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01682478\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01682778\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01683841\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01684154\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01684453\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01684934\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01685229\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01679396\", \"upperType\":\"NOUN\", \"term\":\"iguanid\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01677105\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01678954\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"01680007\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"01680388\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"01680684\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"01680984\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"01681298\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"01681646\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"01681948\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"01682267\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"01682603\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"01682905\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"01683969\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"01684294\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"01684581\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"01685076\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"01685355\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"01679883\", \"upperType\":\"NOUN\", \"term\":\"genus_Iguana\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"01660364\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_15\", \"id\":\"01678954\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_12\", \"id\":\"01680007\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); } private static void add(final String JSON) { DataNoun bean = GsonUtils.toObject(JSON, DataNoun.class); map.put(bean.getId(), bean); } public static DataNoun get(final String ID) { return map.get(ID); } public static boolean has(final String ID) { return map.containsKey(ID); } }
/** * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. */ package com.yitong.weixin.modules.wechat.dao; import com.yitong.weixin.common.persistence.CrudDao; import com.yitong.weixin.common.persistence.annotation.MyBatisDao; import com.yitong.weixin.modules.wechat.entity.WeixinAccessToken; /** * access_token配置DAO接口 * @author hf * @version 2016-01-15 */ @MyBatisDao public interface WeixinAccessTokenDao extends CrudDao<WeixinAccessToken> { public WeixinAccessToken getAccessTokenByOpenId(String AcctOpenId); }
/* * 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.iotdb.cluster.exception; import org.apache.iotdb.cluster.log.Log; /** * Raised when a request times out before reaching an agreement in a group. */ public class RequestTimeOutException extends Exception { public RequestTimeOutException(Log log) { super("Request \"" + log + "\" timeout"); } public RequestTimeOutException(String request) { super("Request \"" + request + "\" timeout"); } }
/** * Copyright 2019 Huawei Technologies Co.,Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of the * License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.obs.services.internal; import java.io.BufferedInputStream; import java.io.Closeable; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.lang.reflect.Method; import java.security.NoSuchAlgorithmException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.Set; import java.util.TreeMap; import com.obs.log.ILogger; import com.obs.log.LoggerBuilder; import com.obs.services.internal.Constants.CommonHeaders; import com.obs.services.internal.Constants.ObsRequestParams; import com.obs.services.internal.handler.XmlResponsesSaxParser.AccessControlListHandler; import com.obs.services.internal.handler.XmlResponsesSaxParser.BucketCorsHandler; import com.obs.services.internal.handler.XmlResponsesSaxParser.BucketDirectColdAccessHandler; import com.obs.services.internal.handler.XmlResponsesSaxParser.BucketEncryptionHandler; import com.obs.services.internal.handler.XmlResponsesSaxParser.BucketLifecycleConfigurationHandler; import com.obs.services.internal.handler.XmlResponsesSaxParser.BucketLocationHandler; import com.obs.services.internal.handler.XmlResponsesSaxParser.BucketLoggingHandler; import com.obs.services.internal.handler.XmlResponsesSaxParser.BucketNotificationConfigurationHandler; import com.obs.services.internal.handler.XmlResponsesSaxParser.BucketQuotaHandler; import com.obs.services.internal.handler.XmlResponsesSaxParser.BucketReplicationConfigurationHandler; import com.obs.services.internal.handler.XmlResponsesSaxParser.BucketStorageInfoHandler; import com.obs.services.internal.handler.XmlResponsesSaxParser.BucketStoragePolicyHandler; import com.obs.services.internal.handler.XmlResponsesSaxParser.BucketTagInfoHandler; import com.obs.services.internal.handler.XmlResponsesSaxParser.BucketVersioningHandler; import com.obs.services.internal.handler.XmlResponsesSaxParser.BucketWebsiteConfigurationHandler; import com.obs.services.internal.handler.XmlResponsesSaxParser.CompleteMultipartUploadHandler; import com.obs.services.internal.handler.XmlResponsesSaxParser.CopyObjectResultHandler; import com.obs.services.internal.handler.XmlResponsesSaxParser.CopyPartResultHandler; import com.obs.services.internal.handler.XmlResponsesSaxParser.DeleteObjectsHandler; import com.obs.services.internal.handler.XmlResponsesSaxParser.InitiateMultipartUploadHandler; import com.obs.services.internal.handler.XmlResponsesSaxParser.ListBucketsHandler; import com.obs.services.internal.handler.XmlResponsesSaxParser.ListMultipartUploadsHandler; import com.obs.services.internal.handler.XmlResponsesSaxParser.ListObjectsHandler; import com.obs.services.internal.handler.XmlResponsesSaxParser.ListPartsHandler; import com.obs.services.internal.handler.XmlResponsesSaxParser.ListVersionsHandler; import com.obs.services.internal.io.HttpMethodReleaseInputStream; import com.obs.services.internal.io.ProgressInputStream; import com.obs.services.internal.task.BlockRejectedExecutionHandler; import com.obs.services.internal.task.DefaultTaskProgressStatus; import com.obs.services.internal.utils.AbstractAuthentication; import com.obs.services.internal.utils.JSONChange; import com.obs.services.internal.utils.Mimetypes; import com.obs.services.internal.utils.RestUtils; import com.obs.services.internal.utils.ServiceUtils; import com.obs.services.internal.utils.V2Authentication; import com.obs.services.internal.utils.V4Authentication; import com.obs.services.model.AbstractBulkRequest; import com.obs.services.model.AccessControlList; import com.obs.services.model.AppendObjectRequest; import com.obs.services.model.AppendObjectResult; import com.obs.services.model.AuthTypeEnum; import com.obs.services.model.AvailableZoneEnum; import com.obs.services.model.BucketCors; import com.obs.services.model.BucketDirectColdAccess; import com.obs.services.model.BucketEncryption; import com.obs.services.model.BucketLocationResponse; import com.obs.services.model.BucketLoggingConfiguration; import com.obs.services.model.BucketMetadataInfoRequest; import com.obs.services.model.BucketMetadataInfoResult; import com.obs.services.model.BucketNotificationConfiguration; import com.obs.services.model.BucketPolicyResponse; import com.obs.services.model.BucketQuota; import com.obs.services.model.BucketStorageInfo; import com.obs.services.model.BucketStoragePolicyConfiguration; import com.obs.services.model.BucketTagInfo; import com.obs.services.model.BucketVersioningConfiguration; import com.obs.services.model.CompleteMultipartUploadRequest; import com.obs.services.model.CompleteMultipartUploadResult; import com.obs.services.model.CopyObjectRequest; import com.obs.services.model.CopyObjectResult; import com.obs.services.model.CopyPartRequest; import com.obs.services.model.CopyPartResult; import com.obs.services.model.CreateBucketRequest; import com.obs.services.model.DeleteObjectResult; import com.obs.services.model.DeleteObjectsRequest; import com.obs.services.model.DeleteObjectsResult; import com.obs.services.model.ExtensionBucketPermissionEnum; import com.obs.services.model.ExtensionObjectPermissionEnum; import com.obs.services.model.GetObjectMetadataRequest; import com.obs.services.model.GetObjectRequest; import com.obs.services.model.GrantAndPermission; import com.obs.services.model.GroupGrantee; import com.obs.services.model.HeaderResponse; import com.obs.services.model.InitiateMultipartUploadRequest; import com.obs.services.model.InitiateMultipartUploadResult; import com.obs.services.model.LifecycleConfiguration; import com.obs.services.model.ListBucketsRequest; import com.obs.services.model.ListBucketsResult; import com.obs.services.model.ListMultipartUploadsRequest; import com.obs.services.model.ListObjectsRequest; import com.obs.services.model.ListPartsRequest; import com.obs.services.model.ListPartsResult; import com.obs.services.model.ListVersionsRequest; import com.obs.services.model.ListVersionsResult; import com.obs.services.model.MultipartUploadListing; import com.obs.services.model.ObjectListing; import com.obs.services.model.ObjectMetadata; import com.obs.services.model.ObsBucket; import com.obs.services.model.ObsObject; import com.obs.services.model.OptionsInfoRequest; import com.obs.services.model.Permission; import com.obs.services.model.PolicyTempSignatureRequest; import com.obs.services.model.PostSignatureRequest; import com.obs.services.model.PostSignatureResponse; import com.obs.services.model.ProgressListener; import com.obs.services.model.PutObjectBasicRequest; import com.obs.services.model.PutObjectRequest; import com.obs.services.model.ReadAheadQueryResult; import com.obs.services.model.ReadAheadRequest; import com.obs.services.model.ReadAheadResult; import com.obs.services.model.AbstractTemporarySignatureRequest; import com.obs.services.model.ReplicationConfiguration; import com.obs.services.model.RestoreObjectRequest; import com.obs.services.model.RestoreObjectRequest.RestoreObjectStatus; import com.obs.services.model.RestoreObjectResult; import com.obs.services.model.SetObjectMetadataRequest; import com.obs.services.model.SpecialParamEnum; import com.obs.services.model.SseCHeader; import com.obs.services.model.SseKmsHeader; import com.obs.services.model.StorageClassEnum; import com.obs.services.model.TaskCallback; import com.obs.services.model.TaskProgressListener; import com.obs.services.model.TemporarySignatureRequest; import com.obs.services.model.TemporarySignatureResponse; import com.obs.services.model.UploadPartRequest; import com.obs.services.model.UploadPartResult; import com.obs.services.model.V4PostSignatureResponse; import com.obs.services.model.VersionOrDeleteMarker; import com.obs.services.model.VersioningStatusEnum; import com.obs.services.model.WebsiteConfiguration; import com.obs.services.model.fs.DropFileResult; import com.obs.services.model.fs.FSStatusEnum; import com.obs.services.model.fs.GetBucketFSStatusResult; import com.obs.services.model.fs.NewBucketRequest; import com.obs.services.model.fs.ObsFSAttribute; import com.obs.services.model.fs.ObsFSFile; import com.obs.services.model.fs.ReadFileResult; import com.obs.services.model.fs.RenameRequest; import com.obs.services.model.fs.RenameResult; import com.obs.services.model.fs.SetBucketFSStatusRequest; import com.obs.services.model.fs.TruncateFileRequest; import com.obs.services.model.fs.TruncateFileResult; import com.obs.services.model.fs.WriteFileRequest; import com.oef.services.model.CreateAsynchFetchJobsResult; import com.oef.services.model.DisPolicy; import com.oef.services.model.GetDisPolicyResult; import com.oef.services.model.QueryExtensionPolicyResult; import com.oef.services.model.QueryAsynchFetchJobsResult; import com.oef.services.model.RequestParamEnum; import okhttp3.Headers; import okhttp3.MediaType; import okhttp3.RequestBody; import okhttp3.Response; public class ObsService extends RestStorageService { private static final ILogger log = LoggerBuilder.getLogger("com.obs.services.ObsClient"); protected ObsService() { } private static class TransResult { private Map<String, String> headers; private Map<String, String> params; private RequestBody body; TransResult(Map<String, String> headers) { this(headers, null, null); } TransResult(Map<String, String> headers, RequestBody body) { this(headers, null, body); } TransResult(Map<String, String> headers, Map<String, String> params, RequestBody body) { this.headers = headers; this.params = params; this.body = body; } Map<String, String> getHeaders() { if (this.headers == null) { headers = new HashMap<String, String>(); } return this.headers; } Map<String, String> getParams() { if (this.params == null) { params = new HashMap<String, String>(); } return this.params; } } protected HeaderResponse setBucketVersioningImpl(String bucketName, VersioningStatusEnum status) throws ServiceException { Map<String, String> requestParams = new HashMap<String, String>(); requestParams.put(SpecialParamEnum.VERSIONING.getOriginalStringCode(), ""); Map<String, String> metadata = new HashMap<String, String>(); metadata.put(CommonHeaders.CONTENT_TYPE, Mimetypes.MIMETYPE_XML); String xml = this.getIConvertor().transVersioningConfiguration(bucketName, status != null ? status.getCode() : null); Response response = performRestPut(bucketName, null, metadata, requestParams, createRequestBody(Mimetypes.MIMETYPE_XML, xml), true); return this.build(response); } protected RequestBody createRequestBody(String mimeType, String content) throws ServiceException { try { if (log.isTraceEnabled()) { try { log.trace("Entity Content:" + content); } catch (Exception e) { } } return RequestBody.create(MediaType.parse(mimeType), content.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new ServiceException(e); } } protected void verifyResponseContentType(Response response) throws ServiceException { if (this.obsProperties.getBoolProperty(ObsConstraint.VERIFY_RESPONSE_CONTENT_TYPE, true)) { String contentType = response.header(Constants.CommonHeaders.CONTENT_TYPE); if (!Mimetypes.MIMETYPE_XML.equalsIgnoreCase(contentType) && !Mimetypes.MIMETYPE_TEXT_XML.equalsIgnoreCase(contentType)) { throw new ServiceException( "Expected XML document response from OBS but received content type " + contentType); } } } protected BucketVersioningConfiguration getBucketVersioningImpl(String bucketName) throws ServiceException { Map<String, String> requestParams = new HashMap<String, String>(); requestParams.put(SpecialParamEnum.VERSIONING.getOriginalStringCode(), ""); Response response = performRestGet(bucketName, null, requestParams, null); this.verifyResponseContentType(response); BucketVersioningConfiguration ret = getXmlResponseSaxParser() .parse(new HttpMethodReleaseInputStream(response), BucketVersioningHandler.class, false) .getVersioningStatus(); setResponseHeaders(ret, this.cleanResponseHeaders(response)); setStatusCode(ret, response.code()); return ret; } TransResult transListVersionsRequest(ListVersionsRequest request) { Map<String, String> params = new HashMap<String, String>(); params.put(SpecialParamEnum.VERSIONS.getOriginalStringCode(), ""); if (request.getPrefix() != null) { params.put(ObsRequestParams.PREFIX, request.getPrefix()); } if (request.getDelimiter() != null) { params.put(ObsRequestParams.DELIMITER, request.getDelimiter()); } if (request.getMaxKeys() > 0) { params.put(ObsRequestParams.MAX_KEYS, String.valueOf(request.getMaxKeys())); } if (request.getKeyMarker() != null) { params.put(ObsRequestParams.KEY_MARKER, request.getKeyMarker()); } if (request.getVersionIdMarker() != null) { params.put(ObsRequestParams.VERSION_ID_MARKER, request.getVersionIdMarker()); } Map<String, String> headers = new HashMap<String, String>(); if (request.getListTimeout() > 0) { putHeader(headers, this.getIHeaders().listTimeoutHeader(), String.valueOf(request.getListTimeout())); } return new TransResult(headers, params, null); } protected ListVersionsResult listVersionsImpl(ListVersionsRequest request) throws ServiceException { TransResult result = this.transListVersionsRequest(request); Response response = performRestGet(request.getBucketName(), null, result.getParams(), null); this.verifyResponseContentType(response); ListVersionsHandler handler = getXmlResponseSaxParser().parse(new HttpMethodReleaseInputStream(response), ListVersionsHandler.class, true); List<VersionOrDeleteMarker> partialItems = handler.getItems(); ListVersionsResult listVersionsResult = new ListVersionsResult(handler.getBucketName() == null ? request.getBucketName() : handler.getBucketName(), handler.getRequestPrefix() == null ? request.getPrefix() : handler.getRequestPrefix(), handler.getKeyMarker() == null ? request.getKeyMarker() : handler.getKeyMarker(), handler.getNextKeyMarker(), handler.getVersionIdMarker() == null ? request.getVersionIdMarker() : handler.getVersionIdMarker(), handler.getNextVersionIdMarker(), String.valueOf(handler.getRequestMaxKeys()), handler.isListingTruncated(), partialItems.toArray(new VersionOrDeleteMarker[partialItems.size()]), handler.getCommonPrefixes(), response.header(this.getIHeaders().bucketRegionHeader()), handler.getDelimiter() == null ? request.getDelimiter() : handler.getDelimiter()); setResponseHeaders(listVersionsResult, this.cleanResponseHeaders(response)); setStatusCode(listVersionsResult, response.code()); return listVersionsResult; } protected BucketPolicyResponse getBucketPolicyImpl(String bucketName) throws ServiceException { try { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.POLICY.getOriginalStringCode(), ""); Response response = performRestGet(bucketName, null, requestParameters, null); BucketPolicyResponse ret = new BucketPolicyResponse(response.body().string()); setResponseHeaders(ret, this.cleanResponseHeaders(response)); setStatusCode(ret, response.code()); return ret; } catch (IOException e) { throw new ServiceException(e); } } protected BucketNotificationConfiguration getBucketNotificationConfigurationImpl(String bucketName) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.NOTIFICATION.getOriginalStringCode(), ""); Response httpResponse = performRestGet(bucketName, null, requestParameters, null); this.verifyResponseContentType(httpResponse); BucketNotificationConfiguration result = getXmlResponseSaxParser() .parse(new HttpMethodReleaseInputStream(httpResponse), BucketNotificationConfigurationHandler.class, false) .getBucketNotificationConfiguration(); setResponseHeaders(result, this.cleanResponseHeaders(httpResponse)); setStatusCode(result, httpResponse.code()); return result; } protected HeaderResponse setBucketNotificationImpl(String bucketName, BucketNotificationConfiguration bucketNotificationConfiguration) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.NOTIFICATION.getOriginalStringCode(), ""); Map<String, String> metadata = new HashMap<String, String>(); metadata.put(CommonHeaders.CONTENT_TYPE, Mimetypes.MIMETYPE_XML); String xml = this.getIConvertor().transBucketNotificationConfiguration(bucketNotificationConfiguration); Response response = performRestPut(bucketName, null, metadata, requestParameters, createRequestBody(Mimetypes.MIMETYPE_XML, xml), true); HeaderResponse ret = build(this.cleanResponseHeaders(response)); setStatusCode(ret, response.code()); return ret; } protected HeaderResponse setBucketPolicyImpl(String bucketName, String policyDocument) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.POLICY.getOriginalStringCode(), ""); Map<String, String> metadata = new HashMap<String, String>(); metadata.put(CommonHeaders.CONTENT_TYPE, Mimetypes.MIMETYPE_TEXT_PLAIN); Response response = performRestPut(bucketName, null, metadata, requestParameters, createRequestBody(Mimetypes.MIMETYPE_TEXT_PLAIN, policyDocument), true); HeaderResponse ret = build(this.cleanResponseHeaders(response)); setStatusCode(ret, response.code()); return ret; } protected HeaderResponse deleteBucketPolicyImpl(String bucketName) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.POLICY.getOriginalStringCode(), ""); Response response = performRestDelete(bucketName, null, requestParameters); HeaderResponse ret = build(this.cleanResponseHeaders(response)); setStatusCode(ret, response.code()); return ret; } TransResult transInitiateMultipartUploadRequest(InitiateMultipartUploadRequest request) throws ServiceException { Map<String, String> headers = new HashMap<String, String>(); IHeaders iheaders = this.getIHeaders(); IConvertor iconvertor = this.getIConvertor(); ObjectMetadata objectMetadata = request.getMetadata() == null ? new ObjectMetadata() : request.getMetadata(); for (Map.Entry<String, Object> entry : objectMetadata.getMetadata().entrySet()) { String key = entry.getKey(); if (!ServiceUtils.isValid(key)) { continue; } key = key.trim(); if (Constants.ALLOWED_REQUEST_HTTP_HEADER_METADATA_NAMES.contains(key.toLowerCase())) { continue; } headers.put(key, entry.getValue() == null ? "" : entry.getValue().toString()); } if (objectMetadata.getObjectStorageClass() != null) { putHeader(headers, iheaders.storageClassHeader(), iconvertor.transStorageClass(objectMetadata.getObjectStorageClass())); } if (request.getExpires() > 0) { putHeader(headers, iheaders.expiresHeader(), String.valueOf(request.getExpires())); } if (ServiceUtils.isValid(objectMetadata.getWebSiteRedirectLocation())) { putHeader(headers, iheaders.websiteRedirectLocationHeader(), objectMetadata.getWebSiteRedirectLocation()); } if (ServiceUtils.isValid(request.getSuccessRedirectLocation())) { putHeader(headers, iheaders.successRedirectLocationHeader(), request.getSuccessRedirectLocation()); } if (ServiceUtils.isValid(objectMetadata.getContentEncoding())) { headers.put(CommonHeaders.CONTENT_ENCODING, objectMetadata.getContentEncoding().trim()); } transExtensionPermissions(request, headers); transSseHeaders(request, headers, iheaders); Object contentType = objectMetadata.getContentType() == null ? objectMetadata.getValue(CommonHeaders.CONTENT_TYPE) : objectMetadata.getContentType(); if (contentType == null) { contentType = Mimetypes.getInstance().getMimetype(request.getObjectKey()); } String _contentType = contentType.toString().trim(); headers.put(CommonHeaders.CONTENT_TYPE, _contentType); Map<String, String> params = new HashMap<String, String>(); params.put(SpecialParamEnum.UPLOADS.getOriginalStringCode(), ""); return new TransResult(headers, params, null); } protected InitiateMultipartUploadResult initiateMultipartUploadImpl(InitiateMultipartUploadRequest request) throws ServiceException { TransResult result = this.transInitiateMultipartUploadRequest(request); this.prepareRESTHeaderAcl(result.getHeaders(), request.getAcl()); Response httpResponse = performRestPost(request.getBucketName(), request.getObjectKey(), result.getHeaders(), result.getParams(), null, false); this.verifyResponseContentType(httpResponse); InitiateMultipartUploadResult multipartUpload = getXmlResponseSaxParser() .parse(new HttpMethodReleaseInputStream(httpResponse), InitiateMultipartUploadHandler.class, true) .getInitiateMultipartUploadResult(); setResponseHeaders(multipartUpload, this.cleanResponseHeaders(httpResponse)); setStatusCode(multipartUpload, httpResponse.code()); return multipartUpload; } protected HeaderResponse abortMultipartUploadImpl(String uploadId, String bucketName, String objectKey) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(ObsRequestParams.UPLOAD_ID, uploadId); Response response = performRestDelete(bucketName, objectKey, requestParameters); HeaderResponse ret = build(this.cleanResponseHeaders(response)); setStatusCode(ret, response.code()); return ret; } protected CompleteMultipartUploadResult completeMultipartUploadImpl(CompleteMultipartUploadRequest request) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(ObsRequestParams.UPLOAD_ID, request.getUploadId()); Map<String, String> metadata = new HashMap<String, String>(); metadata.put(CommonHeaders.CONTENT_TYPE, Mimetypes.MIMETYPE_XML); Response response = performRestPost(request.getBucketName(), request.getObjectKey(), metadata, requestParameters, createRequestBody(Mimetypes.MIMETYPE_XML, this.getIConvertor().transCompleteMultipartUpload(request.getPartEtag())), false); this.verifyResponseContentType(response); CompleteMultipartUploadHandler handler = getXmlResponseSaxParser() .parse(new HttpMethodReleaseInputStream(response), CompleteMultipartUploadHandler.class, true); String versionId = response.header(this.getIHeaders().versionIdHeader()); CompleteMultipartUploadResult ret = new CompleteMultipartUploadResult(handler.getBucketName(), handler.getObjectKey(), handler.getEtag(), handler.getLocation(), versionId, this.getObjectUrl(handler.getBucketName(), handler.getObjectKey())); setResponseHeaders(ret, this.cleanResponseHeaders(response)); setStatusCode(ret, response.code()); return ret; } protected MultipartUploadListing listMultipartUploadsImpl(ListMultipartUploadsRequest request) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.UPLOADS.getOriginalStringCode(), ""); if (request.getPrefix() != null) { requestParameters.put(ObsRequestParams.PREFIX, request.getPrefix()); } if (request.getDelimiter() != null) { requestParameters.put(ObsRequestParams.DELIMITER, request.getDelimiter()); } if (request.getMaxUploads() != null) { requestParameters.put(ObsRequestParams.MAX_UPLOADS, request.getMaxUploads().toString()); } if (request.getKeyMarker() != null) { requestParameters.put(ObsRequestParams.KEY_MARKER, request.getKeyMarker()); } if (request.getUploadIdMarker() != null) { requestParameters.put(ObsRequestParams.UPLOAD_ID_MARKER, request.getUploadIdMarker()); } Response httpResponse = performRestGet(request.getBucketName(), null, requestParameters, null); this.verifyResponseContentType(httpResponse); ListMultipartUploadsHandler handler = getXmlResponseSaxParser() .parse(new HttpMethodReleaseInputStream(httpResponse), ListMultipartUploadsHandler.class, true); MultipartUploadListing listResult = new MultipartUploadListing(handler.getBucketName() == null ? request.getBucketName() : handler.getBucketName(), handler.getKeyMarker() == null ? request.getKeyMarker() : handler.getKeyMarker(), handler.getUploadIdMarker() == null ? request.getUploadIdMarker() : handler.getUploadIdMarker(), handler.getNextKeyMarker(), handler.getNextUploadIdMarker(), handler.getPrefix() == null ? request.getPrefix() : handler.getPrefix(), handler.getMaxUploads(), handler.isTruncated(), handler.getMultipartUploadList(), handler.getDelimiter() == null ? request.getDelimiter() : handler.getDelimiter(), handler.getCommonPrefixes().toArray(new String[handler.getCommonPrefixes().size()])); setResponseHeaders(listResult, this.cleanResponseHeaders(httpResponse)); setStatusCode(listResult, httpResponse.code()); return listResult; } protected ListPartsResult listPartsImpl(ListPartsRequest request) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(ObsRequestParams.UPLOAD_ID, request.getUploadId()); if (null != request.getMaxParts()) { requestParameters.put(ObsRequestParams.MAX_PARTS, request.getMaxParts().toString()); } if (null != request.getPartNumberMarker()) { requestParameters.put(ObsRequestParams.PART_NUMBER_MARKER, request.getPartNumberMarker().toString()); } Response httpResponse = performRestGet(request.getBucketName(), request.getKey(), requestParameters, null); this.verifyResponseContentType(httpResponse); ListPartsHandler handler = getXmlResponseSaxParser().parse(new HttpMethodReleaseInputStream(httpResponse), ListPartsHandler.class, true); ListPartsResult result = new ListPartsResult(handler.getBucketName() == null ? request.getBucketName() : handler.getBucketName(), handler.getObjectKey() == null ? request.getKey() : handler.getObjectKey(), handler.getUploadId() == null ? request.getUploadId() : handler.getUploadId(), handler.getInitiator(), handler.getOwner(), StorageClassEnum.getValueFromCode(handler.getStorageClass()), handler.getMultiPartList(), handler.getMaxParts(), handler.isTruncated(), handler.getPartNumberMarker() == null ? (request.getPartNumberMarker() == null ? null : request.getPartNumberMarker().toString()) : handler.getPartNumberMarker(), handler.getNextPartNumberMarker()); setResponseHeaders(result, this.cleanResponseHeaders(httpResponse)); setStatusCode(result, httpResponse.code()); return result; } protected WebsiteConfiguration getBucketWebsiteConfigurationImpl(String bucketName) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.WEBSITE.getOriginalStringCode(), ""); Response httpResponse = performRestGet(bucketName, null, requestParameters, null); this.verifyResponseContentType(httpResponse); WebsiteConfiguration ret = getXmlResponseSaxParser() .parse(new HttpMethodReleaseInputStream(httpResponse), BucketWebsiteConfigurationHandler.class, false) .getWebsiteConfig(); setResponseHeaders(ret, this.cleanResponseHeaders(httpResponse)); setStatusCode(ret, httpResponse.code()); return ret; } protected HeaderResponse setBucketWebsiteConfigurationImpl(String bucketName, WebsiteConfiguration config) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.WEBSITE.getOriginalStringCode(), ""); Map<String, String> metadata = new HashMap<String, String>(); metadata.put(CommonHeaders.CONTENT_TYPE, Mimetypes.MIMETYPE_XML); String xml = this.getIConvertor().transWebsiteConfiguration(config); Response response = performRestPut(bucketName, null, metadata, requestParameters, createRequestBody(Mimetypes.MIMETYPE_XML, xml), true); HeaderResponse ret = build(this.cleanResponseHeaders(response)); setStatusCode(ret, response.code()); return ret; } protected HeaderResponse deleteBucketWebsiteConfigurationImpl(String bucketName) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.WEBSITE.getOriginalStringCode(), ""); Response response = performRestDelete(bucketName, null, requestParameters); HeaderResponse ret = build(this.cleanResponseHeaders(response)); setStatusCode(ret, response.code()); return ret; } protected LifecycleConfiguration getBucketLifecycleConfigurationImpl(String bucketName) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.LIFECYCLE.getOriginalStringCode(), ""); Response response = performRestGet(bucketName, null, requestParameters, null); this.verifyResponseContentType(response); LifecycleConfiguration ret = getXmlResponseSaxParser() .parse(new HttpMethodReleaseInputStream(response), BucketLifecycleConfigurationHandler.class, false) .getLifecycleConfig(); setResponseHeaders(ret, this.cleanResponseHeaders(response)); setStatusCode(ret, response.code()); return ret; } protected HeaderResponse setBucketLifecycleConfigurationImpl(String bucketName, LifecycleConfiguration config) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.LIFECYCLE.getOriginalStringCode(), ""); Map<String, String> metadata = new HashMap<String, String>(); String xml = this.getIConvertor().transLifecycleConfiguration(config); metadata.put(CommonHeaders.CONTENT_MD5, ServiceUtils.computeMD5(xml)); metadata.put(CommonHeaders.CONTENT_TYPE, Mimetypes.MIMETYPE_XML); Response response = performRestPut(bucketName, null, metadata, requestParameters, createRequestBody(Mimetypes.MIMETYPE_XML, xml), true); HeaderResponse ret = build(this.cleanResponseHeaders(response)); setStatusCode(ret, response.code()); return ret; } protected HeaderResponse deleteBucketLifecycleConfigurationImpl(String bucketName) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.LIFECYCLE.getOriginalStringCode(), ""); Response response = performRestDelete(bucketName, null, requestParameters); HeaderResponse ret = build(this.cleanResponseHeaders(response)); setStatusCode(ret, response.code()); return ret; } protected DeleteObjectsResult deleteObjectsImpl(DeleteObjectsRequest deleteObjectsRequest) throws ServiceException { String xml = this.getIConvertor().transKeyAndVersion(deleteObjectsRequest.getKeyAndVersions(), deleteObjectsRequest.isQuiet()); Map<String, String> metadata = new HashMap<String, String>(); metadata.put(CommonHeaders.CONTENT_MD5, ServiceUtils.computeMD5(xml)); metadata.put(CommonHeaders.CONTENT_TYPE, Mimetypes.MIMETYPE_XML); Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.DELETE.getOriginalStringCode(), ""); Response httpResponse = performRestPost(deleteObjectsRequest.getBucketName(), null, metadata, requestParameters, createRequestBody(Mimetypes.MIMETYPE_XML, xml), false); this.verifyResponseContentType(httpResponse); DeleteObjectsResult ret = getXmlResponseSaxParser() .parse(new HttpMethodReleaseInputStream(httpResponse), DeleteObjectsHandler.class, true) .getMultipleDeleteResult(); setResponseHeaders(ret, this.cleanResponseHeaders(httpResponse)); setStatusCode(ret, httpResponse.code()); return ret; } protected boolean headBucketImpl(String bucketName) throws ServiceException { try { performRestHead(bucketName, null, null, null); return true; } catch (ServiceException e) { if (e.getResponseCode() == 404) { return false; } throw e; } } protected HeaderResponse setBucketFSStatusImpl(SetBucketFSStatusRequest request) throws ServiceException{ Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.FILEINTERFACE.getOriginalStringCode(), ""); String xml = this.getIConvertor().transBucketFileInterface(request.getStatus()); Response response = performRestPut(request.getBucketName(), null, null, requestParameters, createRequestBody(Mimetypes.MIMETYPE_XML, xml), true); HeaderResponse ret = build(this.cleanResponseHeaders(response)); setStatusCode(ret, response.code()); return ret; } protected TruncateFileResult truncateFileImpl(TruncateFileRequest request) throws ServiceException{ Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.TRUNCATE.getOriginalStringCode(), ""); requestParameters.put(Constants.ObsRequestParams.LENGTH, String.valueOf(request.getNewLength())); Response response = performRestPut(request.getBucketName(), request.getObjectKey(), null, requestParameters, null, true); TruncateFileResult result = new TruncateFileResult(); setResponseHeaders(result, this.cleanResponseHeaders(response)); setStatusCode(result, response.code()); return result; } protected RenameResult renameObjectImpl(RenameRequest request) throws ServiceException{ Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.RENAME.getOriginalStringCode(), ""); requestParameters.put(Constants.ObsRequestParams.NAME, request.getNewObjectKey()); Response response = performRestPost(request.getBucketName(), request.getObjectKey(), null, requestParameters, null, true); RenameResult result = new RenameResult(); setResponseHeaders(result, this.cleanResponseHeaders(response)); setStatusCode(result, response.code()); return result; } protected GetBucketFSStatusResult getBucketMetadataImpl(BucketMetadataInfoRequest bucketMetadataInfoRequest) throws ServiceException { GetBucketFSStatusResult output = null; String origin = bucketMetadataInfoRequest.getOrigin(); List<String> requestHeaders = bucketMetadataInfoRequest.getRequestHeaders(); if (origin != null && requestHeaders != null && requestHeaders.size() > 0) { for (int i = 0; i < requestHeaders.size(); i++) { String value = requestHeaders.get(i); Map<String, String> headers = new HashMap<String, String>(); headers.put(Constants.CommonHeaders.ORIGIN, origin); headers.put(Constants.CommonHeaders.ACCESS_CONTROL_REQUEST_HEADERS, value); Response response = performRestHead(bucketMetadataInfoRequest.getBucketName(), null, null, headers); if (output == null) { output = this.getOptionInfoResult(response); } else { String header = response.header(Constants.CommonHeaders.ACCESS_CONTROL_ALLOW_HEADERS); if (header != null) { if (!output.getAllowHeaders().contains(header)) { output.getAllowHeaders().add(header); } } } response.close(); } } else { Map<String, String> headers = new HashMap<String, String>(); if (origin != null) { headers.put(Constants.CommonHeaders.ORIGIN, origin); } Response response = performRestHead(bucketMetadataInfoRequest.getBucketName(), null, null, headers); output = this.getOptionInfoResult(response); response.close(); } return output; } protected RestoreObjectStatus restoreObjectImpl(RestoreObjectRequest restoreObjectRequest) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.RESTORE.getOriginalStringCode(), ""); if (restoreObjectRequest.getVersionId() != null) { requestParameters.put(ObsRequestParams.VERSION_ID, restoreObjectRequest.getVersionId()); } Map<String, String> metadata = new HashMap<String, String>(); String requestXmlElement = this.getIConvertor().transRestoreObjectRequest(restoreObjectRequest); metadata.put(CommonHeaders.CONTENT_MD5, ServiceUtils.computeMD5(requestXmlElement)); metadata.put(CommonHeaders.CONTENT_TYPE, Mimetypes.MIMETYPE_XML); Response response = this.performRestPost(restoreObjectRequest.getBucketName(), restoreObjectRequest.getObjectKey(), metadata, requestParameters, createRequestBody(Mimetypes.MIMETYPE_XML, requestXmlElement), true); RestoreObjectStatus ret = RestoreObjectStatus.valueOf(response.code()); setResponseHeaders(ret, this.cleanResponseHeaders(response)); setStatusCode(ret, response.code()); return ret; } protected RestoreObjectResult restoreObjectV2Impl(RestoreObjectRequest restoreObjectRequest) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.RESTORE.getOriginalStringCode(), ""); if (restoreObjectRequest.getVersionId() != null) { requestParameters.put(ObsRequestParams.VERSION_ID, restoreObjectRequest.getVersionId()); } Map<String, String> metadata = new HashMap<String, String>(); String requestXmlElement = this.getIConvertor().transRestoreObjectRequest(restoreObjectRequest); metadata.put(CommonHeaders.CONTENT_MD5, ServiceUtils.computeMD5(requestXmlElement)); metadata.put(CommonHeaders.CONTENT_TYPE, Mimetypes.MIMETYPE_XML); Response response = this.performRestPost(restoreObjectRequest.getBucketName(), restoreObjectRequest.getObjectKey(), metadata, requestParameters, createRequestBody(Mimetypes.MIMETYPE_XML, requestXmlElement), true); RestoreObjectResult ret = new RestoreObjectResult(restoreObjectRequest.getBucketName(), restoreObjectRequest.getObjectKey(), restoreObjectRequest.getVersionId()); setResponseHeaders(ret, this.cleanResponseHeaders(response)); setStatusCode(ret, response.code()); return ret; } protected BucketTagInfo getBucketTaggingImpl(String bucketName) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.TAGGING.getOriginalStringCode(), ""); Response httpResponse = this.performRestGet(bucketName, null, requestParameters, null); this.verifyResponseContentType(httpResponse); BucketTagInfo result = getXmlResponseSaxParser() .parse(new HttpMethodReleaseInputStream(httpResponse), BucketTagInfoHandler.class, false) .getBucketTagInfo(); setResponseHeaders(result, this.cleanResponseHeaders(httpResponse)); setStatusCode(result, httpResponse.code()); return result; } protected HeaderResponse setBucketTaggingImpl(String bucketName, BucketTagInfo bucketTagInfo) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.TAGGING.getOriginalStringCode(), ""); Map<String, String> headers = new HashMap<String, String>(); String requestXmlElement = this.getIConvertor().transBucketTagInfo(bucketTagInfo); headers.put(CommonHeaders.CONTENT_MD5, ServiceUtils.computeMD5(requestXmlElement)); headers.put(CommonHeaders.CONTENT_TYPE, Mimetypes.MIMETYPE_XML); Response response = this.performRestPut(bucketName, null, headers, requestParameters, createRequestBody(Mimetypes.MIMETYPE_XML, requestXmlElement), true); HeaderResponse ret = build(this.cleanResponseHeaders(response)); setStatusCode(ret, response.code()); return ret; } protected HeaderResponse deleteBucketTaggingImpl(String bucketName) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.TAGGING.getOriginalStringCode(), ""); Response response = performRestDelete(bucketName, null, requestParameters); HeaderResponse ret = build(this.cleanResponseHeaders(response)); setStatusCode(ret, response.code()); return ret; } protected BucketEncryption getBucketEncryptionImpl(String bucketName) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.ENCRYPTION.getOriginalStringCode(), ""); Response httpResponse = performRestGet(bucketName, null, requestParameters, null); this.verifyResponseContentType(httpResponse); BucketEncryption ret = getXmlResponseSaxParser() .parse(new HttpMethodReleaseInputStream(httpResponse), BucketEncryptionHandler.class, false).getEncryption(); setResponseHeaders(ret, this.cleanResponseHeaders(httpResponse)); setStatusCode(ret, httpResponse.code()); return ret; } protected HeaderResponse setBucketEncryptionImpl(String bucketName, BucketEncryption encryption) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.ENCRYPTION.getOriginalStringCode(), ""); Map<String, String> metadata = new HashMap<String, String>(); metadata.put(CommonHeaders.CONTENT_TYPE, Mimetypes.MIMETYPE_XML); String encryptAsXml = encryption == null ? "" : this.getIConvertor().transBucketEcryption(encryption); metadata.put(CommonHeaders.CONTENT_LENGTH, String.valueOf(encryptAsXml.length())); Response response = performRestPut(bucketName, null, metadata, requestParameters, createRequestBody(Mimetypes.MIMETYPE_XML, encryptAsXml), true); HeaderResponse ret = build(this.cleanResponseHeaders(response)); setStatusCode(ret, response.code()); return ret; } protected HeaderResponse deleteBucketEncryptionImpl(String bucketName) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.ENCRYPTION.getOriginalStringCode(), ""); Response response = performRestDelete(bucketName, null, requestParameters); HeaderResponse ret = build(this.cleanResponseHeaders(response)); setStatusCode(ret, response.code()); return ret; } protected ReplicationConfiguration getBucketReplicationConfigurationImpl(String bucketName) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.REPLICATION.getOriginalStringCode(), ""); Response httpResponse = this.performRestGet(bucketName, null, requestParameters, null); this.verifyResponseContentType(httpResponse); ReplicationConfiguration result = getXmlResponseSaxParser() .parse(new HttpMethodReleaseInputStream(httpResponse), BucketReplicationConfigurationHandler.class, false) .getReplicationConfiguration(); setResponseHeaders(result, this.cleanResponseHeaders(httpResponse)); setStatusCode(result, httpResponse.code()); return result; } protected HeaderResponse setBucketReplicationConfigurationImpl(String bucketName, ReplicationConfiguration replicationConfiguration) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.REPLICATION.getOriginalStringCode(), ""); Map<String, String> headers = new HashMap<String, String>(); String requestXmlElement = this.getIConvertor().transReplicationConfiguration(replicationConfiguration); headers.put(CommonHeaders.CONTENT_MD5, ServiceUtils.computeMD5(requestXmlElement)); headers.put(CommonHeaders.CONTENT_TYPE, Mimetypes.MIMETYPE_XML); Response response = this.performRestPut(bucketName, null, headers, requestParameters, createRequestBody(Mimetypes.MIMETYPE_XML, requestXmlElement), true); HeaderResponse ret = build(this.cleanResponseHeaders(response)); setStatusCode(ret, response.code()); return ret; } protected HeaderResponse deleteBucketReplicationConfigurationImpl(String bucketName) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.REPLICATION.getOriginalStringCode(), ""); Response response = performRestDelete(bucketName, null, requestParameters); HeaderResponse ret = build(this.cleanResponseHeaders(response)); setStatusCode(ret, response.code()); return ret; } protected TemporarySignatureResponse _createTemporarySignature(AbstractTemporarySignatureRequest request) throws Exception { String requestMethod = request.getMethod() != null ? request.getMethod().getOperationType() : "GET"; Map<String, Object> queryParams = new TreeMap<String, Object>(); queryParams.putAll(request.getQueryParams()); if (!queryParams.containsKey(this.getIHeaders().securityTokenHeader())) { String securityToken = this.getProviderCredentials().getSecurityToken(); if (ServiceUtils.isValid(securityToken)) { queryParams.put(this.getIHeaders().securityTokenHeader(), securityToken); } } String endpoint = this.getEndpoint(); String bucketName = request.getBucketName(); String objectKey = request.getObjectKey(); String hostname = ServiceUtils.generateHostnameForBucket(bucketName, this.isPathStyle(), endpoint); String virtualBucketPath = ""; String uriPath = ""; String objectKeyPath = (objectKey != null) ? RestUtils.encodeUrlPath(objectKey, "/") : ""; if (!endpoint.equals(hostname)) { int subdomainOffset = hostname.lastIndexOf("." + endpoint); if (subdomainOffset > 0) { virtualBucketPath = hostname.substring(0, subdomainOffset) + "/"; } uriPath = objectKeyPath; } else { uriPath = (((!ServiceUtils.isValid(bucketName)) ? "" : bucketName.trim()) + "/" + objectKeyPath); } if(this.isCname()) { hostname = endpoint; uriPath = objectKeyPath; virtualBucketPath = endpoint + "/"; } uriPath += "?"; if (request.getSpecialParam() != null) { if(request.getSpecialParam() == SpecialParamEnum.STORAGECLASS || request.getSpecialParam() == SpecialParamEnum.STORAGEPOLICY) { request.setSpecialParam(this.getSpecialParamForStorageClass()); } uriPath += request.getSpecialParam().getOriginalStringCode() + "&"; } String accessKeyIdPrefix = this.getProviderCredentials().getAuthType() == AuthTypeEnum.OBS ? "AccessKeyId=" : "AWSAccessKeyId="; uriPath += accessKeyIdPrefix + this.getProviderCredentials().getAccessKey(); String expiresOrPolicy = ""; String uriExpiresOrPolicy = ""; if (request instanceof TemporarySignatureRequest) { TemporarySignatureRequest tempRequest = (TemporarySignatureRequest)request; long secondsSinceEpoch = tempRequest.getExpires() <= 0 ? ObsConstraint.DEFAULT_EXPIRE_SECONEDS : tempRequest.getExpires(); secondsSinceEpoch += System.currentTimeMillis() / 1000; expiresOrPolicy = String.valueOf(secondsSinceEpoch); uriExpiresOrPolicy = "&Expires=" + expiresOrPolicy; } else if(request instanceof PolicyTempSignatureRequest) { PolicyTempSignatureRequest policyRequest = (PolicyTempSignatureRequest)request; String policy = policyRequest.generatePolicy(); expiresOrPolicy = ServiceUtils.toBase64(policy.getBytes(Constants.DEFAULT_ENCODING)); uriExpiresOrPolicy = "&Policy=" + expiresOrPolicy; } uriPath += uriExpiresOrPolicy; for (Map.Entry<String, Object> entry : queryParams.entrySet()) { if (entry.getKey() != null && entry.getValue() != null) { String key = RestUtils.uriEncode(entry.getKey(), false); uriPath += "&"; uriPath += key; uriPath += "="; String value = RestUtils.uriEncode(entry.getValue().toString(), false); uriPath += value; } } Map<String, String> headers = new HashMap<String, String>(); headers.putAll(request.getHeaders()); headers.put(CommonHeaders.HOST, hostname + ":" + (this.getHttpsOnly() ? this.getHttpsPort() : this.getHttpPort())); Map<String, String> actualSignedRequestHeaders = new TreeMap<String, String>(); for (Map.Entry<String, String> entry : headers.entrySet()) { if (ServiceUtils.isValid(entry.getKey())) { String key = entry.getKey().toLowerCase().trim(); boolean validKey = false; if (Constants.ALLOWED_REQUEST_HTTP_HEADER_METADATA_NAMES.contains(key) || key.startsWith(this.getRestHeaderPrefix()) || key.startsWith(Constants.OBS_HEADER_PREFIX)) { validKey = true; } else if (requestMethod.equals("PUT") || requestMethod.equals("POST")) { key = this.getRestMetadataPrefix() + key; validKey = true; } if (validKey) { String value = entry.getValue() == null ? "" : entry.getValue().trim(); if (key.startsWith(this.getRestMetadataPrefix())) { value = RestUtils.uriEncode(value, true); } actualSignedRequestHeaders.put(entry.getKey().trim(), value); } } } String resource = ""; if (request instanceof TemporarySignatureRequest) { resource = "/" + virtualBucketPath + uriPath; } AbstractAuthentication authentication = this.getAuthentication(); if (authentication == null) { authentication = V2Authentication.getInstance(); } String canonicalString = authentication.makeServiceCanonicalString(requestMethod, resource, actualSignedRequestHeaders, expiresOrPolicy, Constants.ALLOWED_RESOURCE_PARAMTER_NAMES); if (log.isDebugEnabled()) { log.debug("CanonicalString is :" + canonicalString); } String signedCanonical = ServiceUtils.signWithHmacSha1(credentials.getSecretKey(), canonicalString); String encodedCanonical = RestUtils.encodeUrlString(signedCanonical); uriPath += "&Signature=" + encodedCanonical; String signedUrl; if (this.getHttpsOnly()) { signedUrl = "https://"; } else { signedUrl = "http://"; } signedUrl += headers.get(CommonHeaders.HOST) + "/" + uriPath; TemporarySignatureResponse response = new TemporarySignatureResponse(signedUrl); response.getActualSignedRequestHeaders().putAll(actualSignedRequestHeaders); return response; } protected PostSignatureResponse _createPostSignature(PostSignatureRequest request, boolean isV4) throws Exception { Date requestDate = request.getRequestDate() != null ? request.getRequestDate() : new Date(); SimpleDateFormat expirationDateFormat = ServiceUtils.getExpirationDateFormat(); Date expiryDate = request.getExpiryDate() == null ? new Date(requestDate.getTime() + (request.getExpires() <=0 ? ObsConstraint.DEFAULT_EXPIRE_SECONEDS : request.getExpires()) * 1000) : request.getExpiryDate(); String expiration = expirationDateFormat.format(expiryDate); StringBuilder originPolicy = new StringBuilder(); originPolicy.append("{\"expiration\":").append("\"").append(expiration).append("\",") .append("\"conditions\":["); String shortDate = ServiceUtils.getShortDateFormat().format(requestDate); String longDate = ServiceUtils.getLongDateFormat().format(requestDate); String credential = this.getCredential(shortDate); if (request.getConditions() != null && !request.getConditions().isEmpty()) { originPolicy.append(ServiceUtils.join(request.getConditions(), ",")).append(","); } else { Map<String, Object> params = new TreeMap<String, Object>(); if(isV4) { params.put(Constants.V2_HEADER_PREFIX_CAMEL + "Algorithm", Constants.V4_ALGORITHM); params.put(Constants.V2_HEADER_PREFIX_CAMEL + "Date", longDate); params.put(Constants.V2_HEADER_PREFIX_CAMEL + "Credential", credential); } params.putAll(request.getFormParams()); if (!params.containsKey(this.getIHeaders().securityTokenHeader())) { String securityToken = this.getProviderCredentials().getSecurityToken(); if (ServiceUtils.isValid(securityToken)) { params.put(this.getIHeaders().securityTokenHeader(), securityToken); } } if (ServiceUtils.isValid(request.getBucketName())) { params.put("bucket", request.getBucketName()); } if (ServiceUtils.isValid(request.getObjectKey())) { params.put("key", request.getObjectKey()); } boolean matchAnyBucket = true; boolean matchAnyKey = true; for (Map.Entry<String, Object> entry : params.entrySet()) { if (ServiceUtils.isValid(entry.getKey())) { String key = entry.getKey().toLowerCase().trim(); if (key.equals("bucket")) { matchAnyBucket = false; } else if (key.equals("key")) { matchAnyKey = false; } if (!Constants.ALLOWED_REQUEST_HTTP_HEADER_METADATA_NAMES.contains(key) && !key.startsWith(this.getRestHeaderPrefix()) && !key.startsWith(Constants.OBS_HEADER_PREFIX) && !key.equals("acl") && !key.equals("bucket") && !key.equals("key") && !key.equals("success_action_redirect") && !key.equals("redirect") && !key.equals("success_action_status")) { continue; } String value = entry.getValue() == null ? "" : entry.getValue().toString(); originPolicy.append("{\"").append(key).append("\":").append("\"").append(value).append("\"},"); } } if (matchAnyBucket) { originPolicy.append("[\"starts-with\", \"$bucket\", \"\"],"); } if (matchAnyKey) { originPolicy.append("[\"starts-with\", \"$key\", \"\"],"); } } originPolicy.append("]}"); String policy = ServiceUtils.toBase64(originPolicy.toString().getBytes(Constants.DEFAULT_ENCODING)); if(isV4) { String signature = V4Authentication.caculateSignature(policy, shortDate, this.getProviderCredentials().getSecretKey()); return new V4PostSignatureResponse(policy, originPolicy.toString(), Constants.V4_ALGORITHM, credential, longDate, signature, expiration); }else { String signature = AbstractAuthentication.caculateSignature(policy, this.getProviderCredentials().getSecretKey()); return new PostSignatureResponse(policy, originPolicy.toString(), signature, expiration, this.getProviderCredentials().getAccessKey()); } } protected TemporarySignatureResponse createV4TemporarySignature(TemporarySignatureRequest request) throws Exception { StringBuilder canonicalUri = new StringBuilder(); String bucketName = request.getBucketName(); String endpoint = this.getEndpoint(); String objectKey = request.getObjectKey(); if (!this.isCname()) { if (ServiceUtils.isValid(bucketName)) { if (this.isPathStyle() || !ServiceUtils.isBucketNameValidDNSName(bucketName)) { canonicalUri.append("/").append(bucketName.trim()); } else { endpoint = bucketName.trim() + "." + endpoint; } if (ServiceUtils.isValid(objectKey)) { canonicalUri.append("/").append(RestUtils.uriEncode(objectKey, false)); } } } else { if (ServiceUtils.isValid(objectKey)) { canonicalUri.append("/").append(RestUtils.uriEncode(objectKey, false)); } } if(this.isCname()) { endpoint = this.getEndpoint(); } Map<String, String> headers = new TreeMap<String, String>(); headers.putAll(request.getHeaders()); Map<String, Object> queryParams = new TreeMap<String, Object>(); queryParams.putAll(request.getQueryParams()); Date requestDate = request.getRequestDate(); if (requestDate == null) { requestDate = new Date(); } if((this.getHttpsOnly() && this.getHttpsPort() == 443) || (!this.getHttpsOnly() && this.getHttpPort() == 80)) { headers.put(CommonHeaders.HOST, endpoint); }else { headers.put(CommonHeaders.HOST, endpoint + ":" + (this.getHttpsOnly() ? this.getHttpsPort() : this.getHttpPort())); } if (!queryParams.containsKey(this.getIHeaders().securityTokenHeader())) { String securityToken = this.getProviderCredentials().getSecurityToken(); if (ServiceUtils.isValid(securityToken)) { queryParams.put(this.getIHeaders().securityTokenHeader(), securityToken); } } String requestMethod = request.getMethod() != null ? request.getMethod().getOperationType() : "GET"; StringBuilder signedHeaders = new StringBuilder(); StringBuilder canonicalHeaders = new StringBuilder(); int index = 0; Map<String, String> actualSignedRequestHeaders = new TreeMap<String, String>(); for (Map.Entry<String, String> entry : headers.entrySet()) { if (ServiceUtils.isValid(entry.getKey())) { String key = entry.getKey().toLowerCase().trim(); boolean validKey = false; if (Constants.ALLOWED_REQUEST_HTTP_HEADER_METADATA_NAMES.contains(key) || key.startsWith(this.getRestHeaderPrefix()) || key.startsWith(Constants.OBS_HEADER_PREFIX)) { validKey = true; } else if (requestMethod.equals("PUT") || requestMethod.equals("POST")) { key = this.getRestMetadataPrefix() + key; validKey = true; } if (validKey) { String value = entry.getValue() == null ? "" : entry.getValue().trim(); if (key.startsWith(this.getRestMetadataPrefix())) { value = RestUtils.uriEncode(value, true); } signedHeaders.append(key); canonicalHeaders.append(key).append(":").append(value).append("\n"); if (index++ != headers.size() - 1) { signedHeaders.append(";"); } actualSignedRequestHeaders.put(entry.getKey().trim(), value); } } } String shortDate = ServiceUtils.getShortDateFormat().format(requestDate); String longDate = ServiceUtils.getLongDateFormat().format(requestDate); queryParams.put(Constants.V2_HEADER_PREFIX_CAMEL + "Algorithm", Constants.V4_ALGORITHM); queryParams.put(Constants.V2_HEADER_PREFIX_CAMEL + "Credential", this.getCredential(shortDate)); queryParams.put(Constants.V2_HEADER_PREFIX_CAMEL + "Date", longDate); queryParams.put(Constants.V2_HEADER_PREFIX_CAMEL + "Expires", request.getExpires() <= 0 ? ObsConstraint.DEFAULT_EXPIRE_SECONEDS : request.getExpires()); queryParams.put(Constants.V2_HEADER_PREFIX_CAMEL + "SignedHeaders", signedHeaders.toString()); StringBuilder canonicalQueryString = new StringBuilder(); StringBuilder signedUrl = new StringBuilder(); if (this.getHttpsOnly()) { String securePortStr = this.getHttpsPort() == 443 ? "" : ":" + this.getHttpsPort(); signedUrl.append("https://").append(endpoint).append(securePortStr); } else { String insecurePortStr = this.getHttpPort() == 80 ? "" : ":" + this.getHttpPort(); signedUrl.append("http://").append(endpoint).append(insecurePortStr); } signedUrl.append(canonicalUri).append("?"); if (request.getSpecialParam() != null) { if(request.getSpecialParam() == SpecialParamEnum.STORAGECLASS || request.getSpecialParam() == SpecialParamEnum.STORAGEPOLICY) { request.setSpecialParam(this.getSpecialParamForStorageClass()); } queryParams.put(request.getSpecialParam().getOriginalStringCode(), null); } index = 0; for (Map.Entry<String, Object> entry : queryParams.entrySet()) { if (ServiceUtils.isValid(entry.getKey())) { String key = RestUtils.uriEncode(entry.getKey(), false); canonicalQueryString.append(key).append("="); signedUrl.append(key); if (entry.getValue() != null) { String value = RestUtils.uriEncode(entry.getValue().toString(), false); canonicalQueryString.append(value); signedUrl.append("=").append(value); } else { canonicalQueryString.append(""); } if (index++ != queryParams.size() - 1) { canonicalQueryString.append("&"); signedUrl.append("&"); } } } StringBuilder canonicalRequest = new StringBuilder(requestMethod).append("\n") .append(canonicalUri.length() == 0 ? "/" : canonicalUri).append("\n").append(canonicalQueryString) .append("\n").append(canonicalHeaders).append("\n").append(signedHeaders).append("\n") .append("UNSIGNED-PAYLOAD"); StringBuilder stringToSign = new StringBuilder(Constants.V4_ALGORITHM).append("\n").append(longDate) .append("\n").append(shortDate).append("/").append(ObsConstraint.DEFAULT_BUCKET_LOCATION_VALUE) .append("/").append(Constants.SERVICE).append("/").append(Constants.REQUEST_TAG).append("\n") .append(V4Authentication.byteToHex((V4Authentication.sha256encode(canonicalRequest.toString())))); signedUrl.append("&").append(Constants.V2_HEADER_PREFIX_CAMEL).append("Signature=") .append(V4Authentication.caculateSignature(stringToSign.toString(), shortDate, this.getProviderCredentials().getSecretKey())); TemporarySignatureResponse response = new TemporarySignatureResponse(signedUrl.toString()); response.getActualSignedRequestHeaders().putAll(actualSignedRequestHeaders); return response; } protected String getCredential(String shortDate) { return new StringBuilder(this.getProviderCredentials().getAccessKey()).append("/").append(shortDate).append("/") .append(ObsConstraint.DEFAULT_BUCKET_LOCATION_VALUE).append("/").append(Constants.SERVICE).append("/") .append(Constants.REQUEST_TAG).toString(); } GetBucketFSStatusResult getOptionInfoResult(Response response) { Headers headers = response.headers(); Map<String, List<String>> map = headers.toMultimap(); String maxAge = headers.get(Constants.CommonHeaders.ACCESS_CONTROL_MAX_AGE); IHeaders iheaders = this.getIHeaders(); FSStatusEnum status = FSStatusEnum.getValueFromCode(headers.get(iheaders.fsFileInterfaceHeader())); GetBucketFSStatusResult output = new GetBucketFSStatusResult(headers.get(Constants.CommonHeaders.ACCESS_CONTROL_ALLOW_ORIGIN), map.get(Constants.CommonHeaders.ACCESS_CONTROL_ALLOW_HEADERS), maxAge == null ? 0 :Integer.parseInt(maxAge) , map.get(Constants.CommonHeaders.ACCESS_CONTROL_ALLOW_METHODS), map.get(Constants.CommonHeaders.ACCESS_CONTROL_EXPOSE_HEADERS), StorageClassEnum.getValueFromCode(headers.get(iheaders.defaultStorageClassHeader())), headers.get(iheaders.bucketRegionHeader()), headers.get(iheaders.serverVersionHeader()), status, AvailableZoneEnum.getValueFromCode(headers.get(iheaders.azRedundancyHeader())), headers.get(iheaders.epidHeader())); setResponseHeaders(output, this.cleanResponseHeaders(response)); setStatusCode(output, response.code()); return output; } protected BucketMetadataInfoResult optionsImpl(String bucketName, String ObjectName, OptionsInfoRequest option) throws ServiceException { Map<String, String> metadata = new IdentityHashMap<String, String>(); if (ServiceUtils.isValid(option.getOrigin())) { metadata.put(CommonHeaders.ORIGIN, option.getOrigin().trim()); } for (int i = 0; option.getRequestMethod() != null && i < option.getRequestMethod().size(); i++) { metadata.put(new String(CommonHeaders.ACCESS_CONTROL_REQUEST_METHOD), option.getRequestMethod().get(i)); } for (int i = 0; option.getRequestHeaders() != null && i < option.getRequestHeaders().size(); i++) { metadata.put(new String(CommonHeaders.ACCESS_CONTROL_REQUEST_HEADERS), option.getRequestHeaders().get(i)); } Response rsult = performRestOptions(bucketName, ObjectName, metadata, null, true); return getOptionInfoResult(rsult); } protected HeaderResponse deleteBucketCorsImpl(String bucketName) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.CORS.getOriginalStringCode(), ""); Response response = performRestDelete(bucketName, null, requestParameters); HeaderResponse ret = build(this.cleanResponseHeaders(response)); setStatusCode(ret, response.code()); return ret; } protected BucketCors getBucketCorsImpl(String bucketName) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.CORS.getOriginalStringCode(), ""); Response httpResponse = performRestGet(bucketName, null, requestParameters, null); this.verifyResponseContentType(httpResponse); BucketCors ret = getXmlResponseSaxParser() .parse(new HttpMethodReleaseInputStream(httpResponse), BucketCorsHandler.class, false) .getConfiguration(); setResponseHeaders(ret, this.cleanResponseHeaders(httpResponse)); setStatusCode(ret, httpResponse.code()); return ret; } protected HeaderResponse setBucketCorsImpl(String bucketName, BucketCors bucketCors) throws ServiceException { String corsXML = bucketCors == null ? "" : this.getIConvertor().transBucketCors(bucketCors); Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.CORS.getOriginalStringCode(), ""); Map<String, String> metadata = new HashMap<String, String>(); metadata.put(CommonHeaders.CONTENT_TYPE, Mimetypes.MIMETYPE_XML); metadata.put(CommonHeaders.CONTENT_MD5, ServiceUtils.computeMD5(corsXML)); metadata.put(CommonHeaders.CONTENT_LENGTH, String.valueOf(corsXML.length())); Response response = performRestPut(bucketName, null, metadata, requestParameters, createRequestBody(Mimetypes.MIMETYPE_XML, corsXML), true); HeaderResponse ret = build(this.cleanResponseHeaders(response)); setStatusCode(ret, response.code()); return ret; } protected HeaderResponse setBucketQuotaImpl(String bucketName, BucketQuota quota) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.QUOTA.getOriginalStringCode(), ""); Map<String, String> metadata = new HashMap<String, String>(); metadata.put(CommonHeaders.CONTENT_TYPE, Mimetypes.MIMETYPE_XML); String quotaAsXml = quota == null ? "" : this.getIConvertor().transBucketQuota(quota); metadata.put(CommonHeaders.CONTENT_LENGTH, String.valueOf(quotaAsXml.length())); Response response = performRestPut(bucketName, null, metadata, requestParameters, createRequestBody(Mimetypes.MIMETYPE_XML, quotaAsXml), true); HeaderResponse ret = build(this.cleanResponseHeaders(response)); setStatusCode(ret, response.code()); return ret; } protected HeaderResponse setBucketStorageImpl(String bucketName, BucketStoragePolicyConfiguration storagePolicy) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(this.getSpecialParamForStorageClass().getOriginalStringCode(), ""); Map<String, String> metadata = new HashMap<String, String>(); metadata.put(CommonHeaders.CONTENT_TYPE, Mimetypes.MIMETYPE_XML); String xml = storagePolicy == null ? "" : this.getIConvertor().transStoragePolicy(storagePolicy); metadata.put(CommonHeaders.CONTENT_LENGTH, String.valueOf(xml.length())); Response response = performRestPut(bucketName, null, metadata, requestParameters, createRequestBody(Mimetypes.MIMETYPE_XML, xml), true); HeaderResponse ret = build(this.cleanResponseHeaders(response)); setStatusCode(ret, response.code()); return ret; } void putAclImpl(String bucketName, String objectKey, AccessControlList acl, String versionId) throws ServiceException { if (acl != null) { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.ACL.getOriginalStringCode(), ""); if (versionId != null) { requestParameters.put(Constants.ObsRequestParams.VERSION_ID, versionId); } Map<String, String> metadata = new HashMap<String, String>(); metadata.put(Constants.CommonHeaders.CONTENT_TYPE, Mimetypes.MIMETYPE_XML); String aclAsXml = this.getIConvertor().transAccessControlList(acl, !ServiceUtils.isValid(objectKey)); metadata.put(Constants.CommonHeaders.CONTENT_LENGTH, String.valueOf(aclAsXml.length())); performRestPut(bucketName, objectKey, metadata, requestParameters, createRequestBody(Mimetypes.MIMETYPE_XML, aclAsXml), true); } } protected HeaderResponse setObjectAclImpl(String bucketName, String objectKey, String cannedACL, AccessControlList acl, String versionId) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.ACL.getOriginalStringCode(), ""); if (versionId != null) { requestParameters.put(ObsRequestParams.VERSION_ID, versionId); } RequestBody entity = null; if (ServiceUtils.isValid(cannedACL)) { acl = this.getIConvertor().transCannedAcl(cannedACL.trim()); } Map<String, String> metadata = new HashMap<String, String>(); metadata.put(CommonHeaders.CONTENT_TYPE, Mimetypes.MIMETYPE_XML); boolean isExtraAclPutRequired = !prepareRESTHeaderAclObject(metadata, acl); if (isExtraAclPutRequired) { String aclAsXml = acl == null ? "" : this.getIConvertor().transAccessControlList(acl, false); metadata.put(CommonHeaders.CONTENT_LENGTH, String.valueOf(aclAsXml.length())); entity = createRequestBody(Mimetypes.MIMETYPE_XML, aclAsXml); } Response response = performRestPut(bucketName, objectKey, metadata, requestParameters, entity, true); HeaderResponse ret = build(this.cleanResponseHeaders(response)); setStatusCode(ret, response.code()); return ret; } protected HeaderResponse setBucketAclImpl(String bucketName, String cannedACL, AccessControlList acl) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.ACL.getOriginalStringCode(), ""); RequestBody entity = null; if (ServiceUtils.isValid(cannedACL)) { acl = this.getIConvertor().transCannedAcl(cannedACL.trim()); } Map<String, String> metadata = new HashMap<String, String>(); metadata.put(CommonHeaders.CONTENT_TYPE, Mimetypes.MIMETYPE_XML); boolean isExtraAclPutRequired = !prepareRESTHeaderAcl(metadata, acl); if (isExtraAclPutRequired) { String aclAsXml = acl == null ? "" : this.getIConvertor().transAccessControlList(acl, true); metadata.put(CommonHeaders.CONTENT_LENGTH, String.valueOf(aclAsXml.length())); entity = createRequestBody(Mimetypes.MIMETYPE_XML, aclAsXml); } Response response = performRestPut(bucketName, null, metadata, requestParameters, entity, true); HeaderResponse ret = build(this.cleanResponseHeaders(response)); setStatusCode(ret, response.code()); return ret; } AbstractAuthentication getAuthentication() { return Constants.AUTHTICATION_MAP.get(this.getProviderCredentials().getAuthType()); } SpecialParamEnum getSpecialParamForStorageClass() { return this.getProviderCredentials().getAuthType() == AuthTypeEnum.OBS ? SpecialParamEnum.STORAGECLASS : SpecialParamEnum.STORAGEPOLICY; } void putHeader(Map<String, String> headers, String key, String value) { if (ServiceUtils.isValid(key)) { headers.put(key, value); } } TransResult transCreateBucketRequest(CreateBucketRequest request) throws ServiceException { Map<String, String> headers = new HashMap<String, String>(); IConvertor convertor = this.getIConvertor(); if (request.getBucketStorageClass() != null) { putHeader(headers, getIHeaders().defaultStorageClassHeader(), convertor.transStorageClass(request.getBucketStorageClass())); } if (request.getEpid() != null) { putHeader(headers, getIHeaders().epidHeader(), request.getEpid()); } if (request instanceof NewBucketRequest) { putHeader(headers, getIHeaders().fsFileInterfaceHeader(), Constants.ENABLED); } if(request.getAvailableZone() != null) { putHeader(headers, getIHeaders().azRedundancyHeader(), request.getAvailableZone().getCode()); } Set<ExtensionBucketPermissionEnum> extensionPermissionEnums = request.getAllGrantPermissions(); if (!extensionPermissionEnums.isEmpty()) { for (ExtensionBucketPermissionEnum extensionPermissionEnum : extensionPermissionEnums) { Set<String> domainIds = request.getDomainIdsByGrantPermission(extensionPermissionEnum); List<String> domainIdList = new ArrayList<String>(domainIds.size()); for (String domainId : domainIds) { domainIdList.add("id=" + domainId); } putHeader(headers, getHeaderByMethodName(extensionPermissionEnum.getCode()), ServiceUtils.join(domainIdList, ",")); } } if (request.getExtensionHeaderMap() != null) { for (Entry<String, String> kv : request.getExtensionHeaderMap().entrySet()) { putHeader(headers, kv.getKey(), kv.getValue()); } } String contentType = Mimetypes.MIMETYPE_XML; headers.put(Constants.CommonHeaders.CONTENT_TYPE, contentType); TransResult result = new TransResult(headers); if (ServiceUtils.isValid(request.getLocation())) { String configXml = convertor.transBucketLoction(request.getLocation()); headers.put(Constants.CommonHeaders.CONTENT_LENGTH, String.valueOf(configXml.length())); RequestBody requestEntity = createRequestBody(contentType, configXml); result.body = requestEntity; } return result; } String getHeaderByMethodName(String code) { try { IHeaders iheaders = this.getIHeaders(); Method m = iheaders.getClass().getMethod(code); Object result = m.invoke(iheaders); return result == null ? "" : result.toString(); } catch (Exception e) { if (log.isWarnEnabled()) { log.warn("Invoke getHeaderByMethodName error", e); } } return null; } protected ObsBucket createBucketImpl(CreateBucketRequest request) throws ServiceException { TransResult result = this.transCreateBucketRequest(request); String bucketName = request.getBucketName(); AccessControlList acl = request.getAcl(); boolean isExtraAclPutRequired = !prepareRESTHeaderAcl(result.getHeaders(), acl); Response response = performRestPut(bucketName, null, result.getHeaders(), null, result.body, true); if (isExtraAclPutRequired && acl != null) { if (log.isDebugEnabled()) { log.debug("Creating bucket with a non-canned ACL using REST, so an extra ACL Put is required"); } try { putAclImpl(bucketName, null, acl, null); } catch (Exception e) { if (log.isWarnEnabled()) { log.warn("Try to set bucket acl error", e); } } } Map<String, Object> map = this.cleanResponseHeaders(response); ObsBucket bucket = new ObsBucket(); bucket.setBucketName(bucketName); bucket.setLocation(request.getLocation()); bucket.setAcl(acl); bucket.setBucketStorageClass(request.getBucketStorageClass()); setResponseHeaders(bucket, map); setStatusCode(bucket, response.code()); return bucket; } boolean prepareRESTHeaderAclForV2(Map<String, String> metadata, AccessControlList acl) { String restHeaderAclValue = null; if (acl == AccessControlList.REST_CANNED_PRIVATE) { restHeaderAclValue = Constants.ACL_PRIVATE; } else if (acl == AccessControlList.REST_CANNED_PUBLIC_READ) { restHeaderAclValue = Constants.ACL_PUBLIC_READ; } else if (acl == AccessControlList.REST_CANNED_PUBLIC_READ_WRITE) { restHeaderAclValue = Constants.ACL_PUBLIC_READ_WRITE; } else if (acl == AccessControlList.REST_CANNED_PUBLIC_READ_DELIVERED) { restHeaderAclValue = Constants.ACL_PUBLIC_READ; } else if (acl == AccessControlList.REST_CANNED_PUBLIC_READ_WRITE_DELIVERED) { restHeaderAclValue = Constants.ACL_PUBLIC_READ_WRITE; } else if (acl == AccessControlList.REST_CANNED_AUTHENTICATED_READ) { restHeaderAclValue = Constants.ACL_AUTHENTICATED_READ; } else if (acl == AccessControlList.REST_CANNED_BUCKET_OWNER_READ) { restHeaderAclValue = Constants.ACL_BUCKET_OWNER_READ; } else if (acl == AccessControlList.REST_CANNED_BUCKET_OWNER_FULL_CONTROL) { restHeaderAclValue = Constants.ACL_BUCKET_OWNER_FULL_CONTROL; } else if (acl == AccessControlList.REST_CANNED_LOG_DELIVERY_WRITE) { restHeaderAclValue = Constants.ACL_LOG_DELIVERY_WRITE; } String aclHeader = this.getIHeaders().aclHeader(); if (restHeaderAclValue != null) { metadata.put(aclHeader, restHeaderAclValue); } return metadata.containsKey(aclHeader); } boolean prepareRESTHeaderAclForOBS(Map<String, String> metadata, AccessControlList acl) throws ServiceException { String restHeaderAclValue = null; boolean invalid = false; if (acl == AccessControlList.REST_CANNED_PRIVATE) { restHeaderAclValue = Constants.ACL_PRIVATE; } else if (acl == AccessControlList.REST_CANNED_PUBLIC_READ) { restHeaderAclValue = Constants.ACL_PUBLIC_READ; } else if (acl == AccessControlList.REST_CANNED_PUBLIC_READ_WRITE) { restHeaderAclValue = Constants.ACL_PUBLIC_READ_WRITE; } else if (acl == AccessControlList.REST_CANNED_PUBLIC_READ_DELIVERED) { restHeaderAclValue = Constants.ACL_PUBLIC_READ_DELIVERED; } else if (acl == AccessControlList.REST_CANNED_PUBLIC_READ_WRITE_DELIVERED) { restHeaderAclValue = Constants.ACL_PUBLIC_READ_WRITE_DELIVERED; } else if (acl == AccessControlList.REST_CANNED_AUTHENTICATED_READ) { restHeaderAclValue = Constants.ACL_AUTHENTICATED_READ; invalid = true; } else if (acl == AccessControlList.REST_CANNED_BUCKET_OWNER_READ) { restHeaderAclValue = Constants.ACL_BUCKET_OWNER_READ; invalid = true; } else if (acl == AccessControlList.REST_CANNED_BUCKET_OWNER_FULL_CONTROL) { restHeaderAclValue = Constants.ACL_BUCKET_OWNER_FULL_CONTROL; invalid = true; } else if (acl == AccessControlList.REST_CANNED_LOG_DELIVERY_WRITE) { restHeaderAclValue = Constants.ACL_LOG_DELIVERY_WRITE; invalid = true; } if (invalid) { log.info("Invalid Canned ACL:" + restHeaderAclValue); } String aclHeader = this.getIHeaders().aclHeader(); if (restHeaderAclValue != null) { metadata.put(aclHeader, restHeaderAclValue); } return metadata.containsKey(aclHeader); } boolean prepareRESTHeaderAclObject(Map<String, String> metadata, AccessControlList acl) throws ServiceException { return this.getProviderCredentials().getAuthType() == AuthTypeEnum.OBS ? this.prepareRESTHeaderAclForOBSObject(metadata, acl) : this.prepareRESTHeaderAclForV2(metadata, acl); } boolean prepareRESTHeaderAclForOBSObject(Map<String, String> metadata, AccessControlList acl) throws ServiceException { String restHeaderAclValue = null; boolean invalid = false; if (acl == AccessControlList.REST_CANNED_PRIVATE) { restHeaderAclValue = Constants.ACL_PRIVATE; } else if (acl == AccessControlList.REST_CANNED_PUBLIC_READ) { restHeaderAclValue = Constants.ACL_PUBLIC_READ; } else if (acl == AccessControlList.REST_CANNED_PUBLIC_READ_WRITE) { restHeaderAclValue = Constants.ACL_PUBLIC_READ_WRITE; } else if (acl == AccessControlList.REST_CANNED_PUBLIC_READ_DELIVERED) { restHeaderAclValue = Constants.ACL_PUBLIC_READ; } else if (acl == AccessControlList.REST_CANNED_PUBLIC_READ_WRITE_DELIVERED) { restHeaderAclValue = Constants.ACL_PUBLIC_READ_WRITE; } else if (acl == AccessControlList.REST_CANNED_AUTHENTICATED_READ) { restHeaderAclValue = Constants.ACL_AUTHENTICATED_READ; invalid = true; } else if (acl == AccessControlList.REST_CANNED_BUCKET_OWNER_READ) { restHeaderAclValue = Constants.ACL_BUCKET_OWNER_READ; invalid = true; } else if (acl == AccessControlList.REST_CANNED_BUCKET_OWNER_FULL_CONTROL) { restHeaderAclValue = Constants.ACL_BUCKET_OWNER_FULL_CONTROL; invalid = true; } else if (acl == AccessControlList.REST_CANNED_LOG_DELIVERY_WRITE) { restHeaderAclValue = Constants.ACL_LOG_DELIVERY_WRITE; invalid = true; } if (invalid) { log.info("Invalid Canned ACL:" + restHeaderAclValue); } String aclHeader = this.getIHeaders().aclHeader(); if (restHeaderAclValue != null) { metadata.put(aclHeader, restHeaderAclValue); } return metadata.containsKey(aclHeader); } boolean prepareRESTHeaderAcl(Map<String, String> metadata, AccessControlList acl) throws ServiceException { return this.getProviderCredentials().getAuthType() == AuthTypeEnum.OBS ? this.prepareRESTHeaderAclForOBS(metadata, acl) : this.prepareRESTHeaderAclForV2(metadata, acl); } protected BucketLocationResponse getBucketLocationImpl(String bucketName) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.LOCATION.getOriginalStringCode(), ""); Response httpResponse = performRestGet(bucketName, null, requestParameters, null); this.verifyResponseContentType(httpResponse); BucketLocationResponse ret = new BucketLocationResponse(getXmlResponseSaxParser() .parse(new HttpMethodReleaseInputStream(httpResponse), BucketLocationHandler.class, false) .getLocation()); setResponseHeaders(ret, this.cleanResponseHeaders(httpResponse)); setStatusCode(ret, httpResponse.code()); return ret; } protected BucketLoggingConfiguration getBucketLoggingConfigurationImpl(String bucketName) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.LOGGING.getOriginalStringCode(), ""); Response httpResponse = performRestGet(bucketName, null, requestParameters, null); this.verifyResponseContentType(httpResponse); BucketLoggingConfiguration ret = getXmlResponseSaxParser() .parse(new HttpMethodReleaseInputStream(httpResponse), BucketLoggingHandler.class, false) .getBucketLoggingStatus(); setResponseHeaders(ret, this.cleanResponseHeaders(httpResponse)); setStatusCode(ret, httpResponse.code()); return ret; } HeaderResponse setBucketLoggingConfigurationImpl(String bucketName, BucketLoggingConfiguration status) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.LOGGING.getOriginalStringCode(), ""); Map<String, String> metadata = new HashMap<String, String>(); metadata.put(CommonHeaders.CONTENT_TYPE, Mimetypes.MIMETYPE_XML); String statusAsXml = status == null ? "" : this.getIConvertor().transBucketLoggingConfiguration(status); Response response = performRestPut(bucketName, null, metadata, requestParameters, createRequestBody(Mimetypes.MIMETYPE_XML, statusAsXml), true); HeaderResponse ret = build(this.cleanResponseHeaders(response)); setStatusCode(ret, response.code()); return ret; } TransResult transPutObjectRequest(PutObjectRequest request) throws ServiceException { Map<String, String> headers = new HashMap<String, String>(); IConvertor iconvertor = this.getIConvertor(); IHeaders iheaders = this.getIHeaders(); ObjectMetadata objectMetadata = request.getMetadata() == null ? new ObjectMetadata() : request.getMetadata(); for (Map.Entry<String, Object> entry : objectMetadata.getMetadata().entrySet()) { String key = entry.getKey(); if (!ServiceUtils.isValid(key)) { continue; } key = key.trim(); if (Constants.ALLOWED_REQUEST_HTTP_HEADER_METADATA_NAMES.contains(key.toLowerCase())) { continue; } headers.put(key, entry.getValue() == null ? "" : entry.getValue().toString()); } if (ServiceUtils.isValid(objectMetadata.getContentMd5())) { headers.put(CommonHeaders.CONTENT_MD5, objectMetadata.getContentMd5().trim()); } if (ServiceUtils.isValid(objectMetadata.getContentEncoding())) { headers.put(CommonHeaders.CONTENT_ENCODING, objectMetadata.getContentEncoding().trim()); } if (objectMetadata.getObjectStorageClass() != null) { putHeader(headers, iheaders.storageClassHeader(), iconvertor.transStorageClass(objectMetadata.getObjectStorageClass())); } if (request.getExpires() >= 0) { putHeader(headers, iheaders.expiresHeader(), String.valueOf(request.getExpires())); } if (objectMetadata.getWebSiteRedirectLocation() != null) { putHeader(headers, iheaders.websiteRedirectLocationHeader(), objectMetadata.getWebSiteRedirectLocation()); } if (request.getSuccessRedirectLocation() != null) { putHeader(headers, iheaders.successRedirectLocationHeader(), request.getSuccessRedirectLocation()); } transExtensionPermissions(request, headers); transSseHeaders(request, headers, iheaders); Object contentType = objectMetadata.getContentType() == null ? objectMetadata.getValue(CommonHeaders.CONTENT_TYPE) : objectMetadata.getContentType(); if (contentType == null) { contentType = Mimetypes.getInstance().getMimetype(request.getObjectKey()); } Object contentLength = objectMetadata.getContentLength(); if (contentLength == null) { contentLength = objectMetadata.getValue(CommonHeaders.CONTENT_LENGTH); } long _contentLength = contentLength == null ? -1l : Long.parseLong(contentLength.toString()); InputStream input = null; if (request.getFile() != null) { if (Mimetypes.MIMETYPE_OCTET_STREAM.equals(contentType)) { contentType = Mimetypes.getInstance().getMimetype(request.getFile()); } try { input = new FileInputStream(request.getFile()); } catch (FileNotFoundException e) { throw new IllegalArgumentException("File doesnot exist"); } long fileSize = request.getFile().length(); if(request.getOffset() > 0 && request.getOffset() < fileSize) { _contentLength = (_contentLength > 0 && _contentLength <= fileSize - request.getOffset()) ? _contentLength : fileSize - request.getOffset(); try { input.skip(request.getOffset()); } catch (IOException e) { ServiceUtils.closeStream(input); throw new ServiceException(e); } }else if(_contentLength < 0 || _contentLength > fileSize) { _contentLength = fileSize; } if(request.getProgressListener() != null) { ProgressManager progressManager = new SimpleProgressManager(_contentLength, 0, request.getProgressListener(), request.getProgressInterval() > 0 ? request.getProgressInterval() : ObsConstraint.DEFAULT_PROGRESS_INTERVAL); input = new ProgressInputStream(input, progressManager); } } else { input = request.getInput(); if(input != null && request.getProgressListener() != null) { ProgressManager progressManager = new SimpleProgressManager(_contentLength, 0, request.getProgressListener(), request.getProgressInterval() > 0 ? request.getProgressInterval() : ObsConstraint.DEFAULT_PROGRESS_INTERVAL); input = new ProgressInputStream(input, progressManager); } } String _contentType = contentType.toString().trim(); headers.put(CommonHeaders.CONTENT_TYPE, _contentType); if(_contentLength > -1) { this.putHeader(headers, CommonHeaders.CONTENT_LENGTH, String.valueOf(_contentLength)); } RequestBody body = input == null ? null : new RepeatableRequestEntity(input, _contentType, _contentLength, this.obsProperties); return new TransResult(headers, body); } TransResult transWriteFileRequest(WriteFileRequest request) throws ServiceException { TransResult result = this.transPutObjectRequest(request); if(request.getPosition() > 0) { Map<String, String> params = new HashMap<String, String>(); params.put(SpecialParamEnum.MODIFY.getOriginalStringCode(), ""); params.put(ObsRequestParams.POSITION, String.valueOf(request.getPosition())); result.params = params; } return result; } TransResult transAppendObjectRequest(AppendObjectRequest request) throws ServiceException { TransResult result = this.transPutObjectRequest(request); Map<String, String> params = new HashMap<String, String>(); params.put(SpecialParamEnum.APPEND.getOriginalStringCode(), ""); params.put(ObsRequestParams.POSITION, String.valueOf(request.getPosition())); result.params = params; return result; } void transSseKmsHeaders(SseKmsHeader kmsHeader, Map<String, String> headers, IHeaders iheaders) { if (kmsHeader == null) { return; } String sseKmsEncryption = this.getProviderCredentials().getAuthType() != AuthTypeEnum.OBS ? "aws:" + kmsHeader.getSSEAlgorithm().getCode() : kmsHeader.getSSEAlgorithm().getCode(); putHeader(headers, iheaders.sseKmsHeader(), ServiceUtils.toValid(sseKmsEncryption)); if (ServiceUtils.isValid(kmsHeader.getKmsKeyId())) { putHeader(headers, iheaders.sseKmsKeyHeader(), kmsHeader.getKmsKeyId()); } if(ServiceUtils.isValid(kmsHeader.getProjectId())) { putHeader(headers, iheaders.sseKmsProjectIdHeader(), kmsHeader.getProjectId()); } } void transSseCHeaders(SseCHeader cHeader, Map<String, String> headers, IHeaders iheaders) throws ServiceException { if (cHeader == null) { return; } String sseCAlgorithm = cHeader.getSSEAlgorithm().getCode(); putHeader(headers, iheaders.sseCHeader(), ServiceUtils.toValid(sseCAlgorithm)); if(cHeader.getSseCKeyBase64() != null) { try { putHeader(headers, iheaders.sseCKeyHeader(), cHeader.getSseCKeyBase64()); putHeader(headers, iheaders.sseCKeyMd5Header(), ServiceUtils.toBase64(ServiceUtils.computeMD5Hash(ServiceUtils.fromBase64(cHeader.getSseCKeyBase64())))); } catch (IOException e) { throw new IllegalStateException("fail to read sseCkey", e); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("fail to read sseCkey", e); } }else if (null != cHeader.getSseCKey()) { try { byte[] data = cHeader.getSseCKey(); putHeader(headers, iheaders.sseCKeyHeader(), ServiceUtils.toBase64(data)); putHeader(headers, iheaders.sseCKeyMd5Header(), ServiceUtils.toBase64(ServiceUtils.computeMD5Hash(data))); } catch (IOException e) { throw new IllegalStateException("fail to read sseCkey", e); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("fail to read sseCkey", e); } } } void transSseHeaders(PutObjectBasicRequest request, Map<String, String> headers, IHeaders iheaders) throws ServiceException { if (null != request.getSseCHeader()) { this.transSseCHeaders(request.getSseCHeader(), headers, iheaders); } else if (null != request.getSseKmsHeader()) { this.transSseKmsHeaders(request.getSseKmsHeader(), headers, iheaders); } } void transExtensionPermissions(PutObjectBasicRequest request, Map<String, String> headers) { Set<ExtensionObjectPermissionEnum> extensionPermissionEnums = request.getAllGrantPermissions(); if (!extensionPermissionEnums.isEmpty()) { for (ExtensionObjectPermissionEnum extensionPermissionEnum : extensionPermissionEnums) { Set<String> domainIds = request.getDomainIdsByGrantPermission(extensionPermissionEnum); List<String> domainIdList = new ArrayList<String>(domainIds.size()); for (String domainId : domainIds) { domainIdList.add("id=" + domainId); } putHeader(headers, getHeaderByMethodName(extensionPermissionEnum.getCode()), ServiceUtils.join(domainIdList, ",")); } } } protected AppendObjectResult appendObjectImpl(AppendObjectRequest request) throws ServiceException { TransResult result = null; Response response; boolean isExtraAclPutRequired; AccessControlList acl = request.getAcl(); try { result = this.transAppendObjectRequest(request); isExtraAclPutRequired = !prepareRESTHeaderAcl(result.getHeaders(), acl); response = performRestPost(request.getBucketName(), request.getObjectKey(), result.getHeaders(), result.getParams(), result.body, true); } finally { if (result != null && result.body != null && request.isAutoClose()) { RepeatableRequestEntity entity = (RepeatableRequestEntity) result.body; ServiceUtils.closeStream(entity); } } String nextPosition = response.header(this.getIHeaders().nextPositionHeader()); AppendObjectResult ret = new AppendObjectResult(request.getBucketName(), request.getObjectKey(), response.header(CommonHeaders.ETAG), nextPosition != null ? Long.parseLong(nextPosition) : -1, StorageClassEnum.getValueFromCode(response.header(this.getIHeaders().storageClassHeader())), this.getObjectUrl(request.getBucketName(), request.getObjectKey())); Map<String, Object> map = this.cleanResponseHeaders(response); setResponseHeaders(ret, map); setStatusCode(ret, response.code()); if (isExtraAclPutRequired && acl != null) { try { putAclImpl(request.getBucketName(), request.getObjectKey(), acl, null); } catch (Exception e) { if (log.isWarnEnabled()) { log.warn("Try to set object acl error", e); } } } return ret; } protected ObsFSFile writeFileImpl(WriteFileRequest request) throws ServiceException { TransResult result = null; Response response; boolean isExtraAclPutRequired; AccessControlList acl = request.getAcl(); try { result = this.transWriteFileRequest(request); isExtraAclPutRequired = !prepareRESTHeaderAcl(result.getHeaders(), acl); response = performRestPut(request.getBucketName(), request.getObjectKey(), result.getHeaders(), result.getParams(), result.body, true); } finally { if (result != null && result.body != null && request.isAutoClose()) { if(result.body instanceof Closeable) { ServiceUtils.closeStream((Closeable)result.body); } } } ObsFSFile ret = new ObsFSFile(request.getBucketName(), request.getObjectKey(), response.header(CommonHeaders.ETAG), response.header(this.getIHeaders().versionIdHeader()), StorageClassEnum.getValueFromCode(response.header(this.getIHeaders().storageClassHeader())), this.getObjectUrl(request.getBucketName(), request.getObjectKey())); Map<String, Object> map = this.cleanResponseHeaders(response); setResponseHeaders(ret, map); setStatusCode(ret, response.code()); if (isExtraAclPutRequired && acl != null) { try { putAclImpl(request.getBucketName(), request.getObjectKey(), acl, null); } catch (Exception e) { if (log.isWarnEnabled()) { log.warn("Try to set object acl error", e); } } } return ret; } protected ObsFSFile putObjectImpl(PutObjectRequest request) throws ServiceException { TransResult result = null; Response response; boolean isExtraAclPutRequired; AccessControlList acl = request.getAcl(); try { result = this.transPutObjectRequest(request); isExtraAclPutRequired = !prepareRESTHeaderAcl(result.getHeaders(), acl); response = performRestPut(request.getBucketName(), request.getObjectKey(), result.getHeaders(), null, result.body, true); } finally { if (result != null && result.body != null && request.isAutoClose()) { if(result.body instanceof Closeable) { ServiceUtils.closeStream((Closeable)result.body); } } } ObsFSFile ret = new ObsFSFile(request.getBucketName(), request.getObjectKey(), response.header(CommonHeaders.ETAG), response.header(this.getIHeaders().versionIdHeader()), StorageClassEnum.getValueFromCode(response.header(this.getIHeaders().storageClassHeader())), this.getObjectUrl(request.getBucketName(), request.getObjectKey())); Map<String, Object> map = this.cleanResponseHeaders(response); setResponseHeaders(ret, map); setStatusCode(ret, response.code()); if (isExtraAclPutRequired && acl != null) { try { putAclImpl(request.getBucketName(), request.getObjectKey(), acl, null); } catch (Exception e) { if (log.isWarnEnabled()) { log.warn("Try to set object acl error", e); } } } return ret; } TransResult transCopyObjectRequest(CopyObjectRequest request) throws ServiceException { Map<String, String> headers = new HashMap<String, String>(); IConvertor iconvertor = this.getIConvertor(); IHeaders iheaders = this.getIHeaders(); ObjectMetadata objectMetadata = request.getNewObjectMetadata() == null ? new ObjectMetadata() : request.getNewObjectMetadata(); putHeader(headers, iheaders.metadataDirectiveHeader(), request.isReplaceMetadata() ? Constants.DERECTIVE_REPLACE : Constants.DERECTIVE_COPY); if (request.isReplaceMetadata()) { objectMetadata.getMetadata().remove(iheaders.requestIdHeader()); objectMetadata.getMetadata().remove(iheaders.requestId2Header()); for (Map.Entry<String, Object> entry : objectMetadata.getMetadata().entrySet()) { String key = entry.getKey(); if (!ServiceUtils.isValid(key)) { continue; } key = key.trim(); if (Constants.ALLOWED_REQUEST_HTTP_HEADER_METADATA_NAMES.contains(key.toLowerCase())) { continue; } headers.put(key, entry.getValue() == null ? "" : entry.getValue().toString()); } } if (objectMetadata.getContentType() != null) { headers.put(CommonHeaders.CONTENT_TYPE, objectMetadata.getContentType().trim()); } if (objectMetadata.getContentEncoding() != null) { headers.put(CommonHeaders.CONTENT_ENCODING, objectMetadata.getContentEncoding().trim()); } if (objectMetadata.getObjectStorageClass() != null) { putHeader(headers, iheaders.storageClassHeader(), iconvertor.transStorageClass(objectMetadata.getObjectStorageClass())); } if (objectMetadata.getWebSiteRedirectLocation() != null) { putHeader(headers, iheaders.websiteRedirectLocationHeader(), objectMetadata.getWebSiteRedirectLocation()); } if (request.getSuccessRedirectLocation() != null) { putHeader(headers, iheaders.successRedirectLocationHeader(), request.getSuccessRedirectLocation()); } this.transExtensionPermissions(request, headers); this.transSseHeaders(request, headers, iheaders); transSseCSourceHeaders(request.getSseCHeaderSource(), headers, iheaders); transConditionCopyHeaders(request, headers, iheaders); String sourceKey = RestUtils .encodeUrlString(request.getSourceBucketName()) + "/" + RestUtils .encodeUrlString(request.getSourceObjectKey()); if (ServiceUtils.isValid(request.getVersionId())) { sourceKey += "?versionId=" + request.getVersionId().trim(); } putHeader(headers, iheaders.copySourceHeader(), sourceKey); return new TransResult(headers); } void transSseCSourceHeaders(SseCHeader sseCHeader, Map<String, String> headers, IHeaders iheaders) throws ServiceException { if (sseCHeader != null) { String algorithm = sseCHeader.getSSEAlgorithm().getCode(); putHeader(headers, iheaders.copySourceSseCHeader(), ServiceUtils.toValid(algorithm)); if(sseCHeader.getSseCKeyBase64() != null) { try { putHeader(headers, iheaders.copySourceSseCKeyHeader(), sseCHeader.getSseCKeyBase64()); putHeader(headers, iheaders.copySourceSseCKeyMd5Header(), ServiceUtils.toBase64(ServiceUtils.computeMD5Hash(ServiceUtils.fromBase64(sseCHeader.getSseCKeyBase64())))); } catch (IOException e) { throw new IllegalStateException("fail to read sseCkey", e); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("fail to read sseCkey", e); } }else if (null != sseCHeader.getSseCKey()) { try { byte[] data = sseCHeader.getSseCKey(); putHeader(headers, iheaders.copySourceSseCKeyHeader(), ServiceUtils.toBase64(data)); putHeader(headers, iheaders.copySourceSseCKeyMd5Header(), ServiceUtils.toBase64(ServiceUtils.computeMD5Hash(data))); } catch (IOException e) { throw new IllegalStateException("fail to read sseCkey", e); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("fail to read sseCkey", e); } } } } void transConditionCopyHeaders(CopyObjectRequest request, Map<String, String> headers, IHeaders iheaders) { if (request.getIfModifiedSince() != null) { putHeader(headers, iheaders.copySourceIfModifiedSinceHeader(), ServiceUtils.formatRfc822Date(request.getIfModifiedSince())); } if (request.getIfUnmodifiedSince() != null) { putHeader(headers, iheaders.copySourceIfUnmodifiedSinceHeader(), ServiceUtils.formatRfc822Date(request.getIfUnmodifiedSince())); } if (ServiceUtils.isValid(request.getIfMatchTag())) { putHeader(headers, iheaders.copySourceIfMatchHeader(), request.getIfMatchTag().trim()); } if (ServiceUtils.isValid(request.getIfNoneMatchTag())) { putHeader(headers, iheaders.copySourceIfNoneMatchHeader(), request.getIfNoneMatchTag().trim()); } } protected CopyObjectResult copyObjectImpl(CopyObjectRequest request) throws ServiceException { TransResult result = this.transCopyObjectRequest(request); AccessControlList acl = request.getAcl(); boolean isExtraAclPutRequired = !prepareRESTHeaderAcl(result.getHeaders(), acl); Response response = performRestPut(request.getDestinationBucketName(), request.getDestinationObjectKey(), result.getHeaders(), null, null, false); this.verifyResponseContentType(response); CopyObjectResultHandler handler = getXmlResponseSaxParser().parse(new HttpMethodReleaseInputStream(response), CopyObjectResultHandler.class, false); CopyObjectResult copyRet = new CopyObjectResult(handler.getETag(), handler.getLastModified(), response.header(this.getIHeaders().versionIdHeader()), response.header(this.getIHeaders().copySourceVersionIdHeader()), StorageClassEnum.getValueFromCode(response.header(this.getIHeaders().storageClassHeader()))); Map<String, Object> map = this.cleanResponseHeaders(response); setResponseHeaders(copyRet, map); setStatusCode(copyRet, response.code()); if (isExtraAclPutRequired && acl != null) { if (log.isDebugEnabled()) { log.debug("Creating object with a non-canned ACL using REST, so an extra ACL Put is required"); } try { putAclImpl(request.getDestinationBucketName(), request.getDestinationObjectKey(), acl, null); } catch (Exception e) { if (log.isWarnEnabled()) { log.warn("Try to set object acl error", e); } } } return copyRet; } protected ObsFSAttribute getObjectMetadataImpl(GetObjectMetadataRequest request) throws ServiceException { Map<String, String> headers = new HashMap<String, String>(); this.transSseCHeaders(request.getSseCHeader(), headers, this.getIHeaders()); Map<String, String> params = new HashMap<String, String>(); if (request.getVersionId() != null) { params.put(ObsRequestParams.VERSION_ID, request.getVersionId()); } return (ObsFSAttribute) this.getObjectImpl(true, request.getBucketName(), request.getObjectKey(), headers, params, null, -1); } TransResult transSetObjectMetadataRequest(SetObjectMetadataRequest request) throws ServiceException { Map<String, String> headers = new HashMap<String, String>(); IHeaders iheaders = this.getIHeaders(); IConvertor iconvertor = this.getIConvertor(); for (Map.Entry<String, String> entry : request.getMetadata().entrySet()) { String key = entry.getKey(); if (!ServiceUtils.isValid(key)) { continue; } key = key.trim(); headers.put(key, entry.getValue() == null ? "" : entry.getValue().toString()); } if (request.getObjectStorageClass() != null) { putHeader(headers, iheaders.storageClassHeader(), iconvertor.transStorageClass(request.getObjectStorageClass())); } if (request.getWebSiteRedirectLocation() != null) { putHeader(headers, iheaders.websiteRedirectLocationHeader(), request.getWebSiteRedirectLocation()); } if(request.getContentDisposition() != null) { putHeader(headers, Constants.CommonHeaders.CONTENT_DISPOSITION, request.getContentDisposition()); } if(request.getContentEncoding() != null) { putHeader(headers, Constants.CommonHeaders.CONTENT_ENCODING, request.getContentEncoding()); } if(request.getContentLanguage() != null) { putHeader(headers, Constants.CommonHeaders.CONTENT_LANGUAGE, request.getContentLanguage()); } if(request.getContentType() != null) { putHeader(headers, Constants.CommonHeaders.CONTENT_TYPE, request.getContentType()); } if(request.getCacheControl() != null) { putHeader(headers, Constants.CommonHeaders.CACHE_CONTROL, request.getCacheControl()); } if(request.getExpires() != null) { putHeader(headers, Constants.CommonHeaders.EXPIRES, request.getExpires()); } putHeader(headers, iheaders.metadataDirectiveHeader(), request.isRemoveUnset() ? Constants.DERECTIVE_REPLACE : Constants.DERECTIVE_REPLACE_NEW); Map<String, String> params = new HashMap<String, String>(); params.put(SpecialParamEnum.METADATA.getOriginalStringCode(), ""); if (request.getVersionId() != null) { params.put(ObsRequestParams.VERSION_ID, request.getVersionId()); } return new TransResult(headers, params, null); } protected ObjectMetadata setObjectMetadataImpl(SetObjectMetadataRequest request) { TransResult result = this.transSetObjectMetadataRequest(request); Response response = performRestPut(request.getBucketName(), request.getObjectKey(), result.headers, result.params, result.body, true); return this.getObsFSAttributeFromResponse(response); } TransResult transGetObjectRequest(GetObjectRequest request) throws ServiceException { Map<String, String> headers = new HashMap<String, String>(); this.transSseCHeaders(request.getSseCHeader(), headers, this.getIHeaders()); this.transConditionGetObjectHeaders(request, headers); if (request.getRangeStart() != null) { String rangeEnd = request.getRangeEnd() != null ? String.valueOf(request.getRangeEnd()) : ""; String range = String.format("bytes=%s-%s", request.getRangeStart(), rangeEnd); headers.put(CommonHeaders.RANGE, range); } Map<String, String> params = new HashMap<String, String>(); this.transGetObjectParams(request, params); return new TransResult(headers, params, null); } void transGetObjectParams(GetObjectRequest request, Map<String, String> params) { if (null != request.getReplaceMetadata()) { if (ServiceUtils.isValid(request.getReplaceMetadata().getCacheControl())) { params.put(ObsRequestParams.RESPONSE_CACHE_CONTROL, request.getReplaceMetadata().getCacheControl()); } if (ServiceUtils.isValid(request.getReplaceMetadata().getContentDisposition())) { params.put(ObsRequestParams.RESPONSE_CONTENT_DISPOSITION, request.getReplaceMetadata().getContentDisposition()); } if (ServiceUtils.isValid(request.getReplaceMetadata().getContentEncoding())) { params.put(ObsRequestParams.RESPONSE_CONTENT_ENCODING, request.getReplaceMetadata().getContentEncoding()); } if (ServiceUtils.isValid(request.getReplaceMetadata().getContentLanguage())) { params.put(ObsRequestParams.RESPONSE_CONTENT_LANGUAGE, request.getReplaceMetadata().getContentLanguage()); } if (ServiceUtils.isValid(request.getReplaceMetadata().getContentType())) { params.put(ObsRequestParams.RESPONSE_CONTENT_TYPE, request.getReplaceMetadata().getContentType()); } if (ServiceUtils.isValid(request.getReplaceMetadata().getExpires())) { params.put(ObsRequestParams.RESPONSE_EXPIRES, request.getReplaceMetadata().getExpires()); } } if (ServiceUtils.isValid(request.getImageProcess())) { params.put(ObsRequestParams.X_IMAGE_PROCESS, request.getImageProcess()); } if (request.getVersionId() != null) { params.put(ObsRequestParams.VERSION_ID, request.getVersionId()); } if(request.getCacheOption() != null) { String cacheControl = request.getCacheOption().getCode() + ", ttl=" + request.getTtl(); params.put(ObsRequestParams.X_CACHE_CONTROL, cacheControl); } } void transConditionGetObjectHeaders(GetObjectRequest request, Map<String, String> headers) { if (request.getIfModifiedSince() != null) { headers.put(CommonHeaders.IF_MODIFIED_SINCE, ServiceUtils.formatRfc822Date(request.getIfModifiedSince())); } if (request.getIfUnmodifiedSince() != null) { headers.put(CommonHeaders.IF_UNMODIFIED_SINCE, ServiceUtils.formatRfc822Date(request.getIfUnmodifiedSince())); } if (ServiceUtils.isValid(request.getIfMatchTag())) { headers.put(CommonHeaders.IF_MATCH, request.getIfMatchTag().trim()); } if (ServiceUtils.isValid(request.getIfNoneMatchTag())) { headers.put(CommonHeaders.IF_NONE_MATCH, request.getIfNoneMatchTag().trim()); } } protected ObsObject getObjectImpl(GetObjectRequest request) throws ServiceException { TransResult result = this.transGetObjectRequest(request); if (request.getRequestParameters() != null) { result.getParams().putAll(request.getRequestParameters()); } return (ObsObject) this.getObjectImpl(false, request.getBucketName(), request.getObjectKey(), result.getHeaders(), result.getParams(), request.getProgressListener(), request.getProgressInterval()); } private ObsFSAttribute getObsFSAttributeFromResponse(Response response) { Date _lastModified = null; String lastModified = response.header(CommonHeaders.LAST_MODIFIED); if (lastModified != null) { try { _lastModified = ServiceUtils.parseRfc822Date(lastModified); } catch (ParseException e) { if (log.isWarnEnabled()) { log.warn("Response last-modified is not well-format", e); } } } ObsFSAttribute objMetadata = new ObsFSAttribute(); objMetadata.setLastModified(_lastModified); objMetadata.setContentEncoding(response.header(CommonHeaders.CONTENT_ENCODING)); objMetadata.setContentType(response.header(CommonHeaders.CONTENT_TYPE)); String contentLength = response.header(CommonHeaders.CONTENT_LENGTH); if (contentLength != null) { try { objMetadata.setContentLength(Long.parseLong(contentLength)); } catch (NumberFormatException e) { if (log.isWarnEnabled()) { log.warn("Response content-length is not well-format", e); } } } String fsMode; if((fsMode=response.header(this.getIHeaders().fsModeHeader())) != null) { objMetadata.setMode(Integer.parseInt(fsMode)); } objMetadata.setWebSiteRedirectLocation(response.header(this.getIHeaders().websiteRedirectLocationHeader())); objMetadata.setObjectStorageClass( StorageClassEnum.getValueFromCode(response.header(this.getIHeaders().storageClassHeader()))); String etag = response.header(CommonHeaders.ETAG); objMetadata.setEtag(etag); if (etag != null && !etag.contains("-")) { String md5 = etag; if (md5.startsWith("\"")) { md5 = md5.substring(1); } if (md5.endsWith("\"")) { md5 = md5.substring(0, md5.length() - 1); } try { objMetadata.setContentMd5(ServiceUtils.toBase64(ServiceUtils.fromHex(md5))); } catch (Exception e) { if (log.isDebugEnabled()) { log.debug(e.getMessage(), e); } } } objMetadata.setAppendable("Appendable".equals(response.header(this.getIHeaders().objectTypeHeader()))); String nextPosition = response.header(this.getIHeaders().nextPositionHeader(), "-1"); objMetadata.setNextPosition(Long.parseLong(nextPosition)); if(objMetadata.getNextPosition() == -1L) { objMetadata.setNextPosition(Long.parseLong(response.header(Constants.CommonHeaders.CONTENT_LENGTH, "-1"))); } objMetadata.getMetadata().putAll(this.cleanResponseHeaders(response)); setStatusCode(objMetadata, response.code()); return objMetadata; } protected Object getObjectImpl(boolean headOnly, String bucketName, String objectKey, Map<String, String> headers, Map<String, String> params, ProgressListener progressListener, long progressInterval) throws ServiceException { Response response; if (headOnly) { response = performRestHead(bucketName, objectKey, params, headers); } else { response = performRestGet(bucketName, objectKey, params, headers); } ObsFSAttribute objMetadata = this.getObsFSAttributeFromResponse(response); if (headOnly) { response.close(); return objMetadata; } ReadFileResult obsObject = new ReadFileResult(); obsObject.setObjectKey(objectKey); obsObject.setBucketName(bucketName); obsObject.setMetadata(objMetadata); InputStream input = response.body().byteStream(); if(progressListener != null) { ProgressManager progressManager = new SimpleProgressManager(objMetadata.getContentLength(), 0, progressListener, progressInterval > 0 ? progressInterval : ObsConstraint.DEFAULT_PROGRESS_INTERVAL); input = new ProgressInputStream(input, progressManager); } int readBufferSize = obsProperties.getIntProperty(ObsConstraint.READ_BUFFER_SIZE, ObsConstraint.DEFAULT_READ_BUFFER_STREAM); if(readBufferSize > 0) { input = new BufferedInputStream(input, readBufferSize); } obsObject.setObjectContent(input); return obsObject; } protected BucketQuota getBucketQuotaImpl(String bucketName) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.QUOTA.getOriginalStringCode(), ""); Response httpResponse = performRestGet(bucketName, null, requestParameters, null); this.verifyResponseContentType(httpResponse); BucketQuota ret = getXmlResponseSaxParser() .parse(new HttpMethodReleaseInputStream(httpResponse), BucketQuotaHandler.class, false).getQuota(); setResponseHeaders(ret, this.cleanResponseHeaders(httpResponse)); setStatusCode(ret, httpResponse.code()); return ret; } protected BucketStoragePolicyConfiguration getBucketStoragePolicyImpl(String bucketName) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(this.getSpecialParamForStorageClass().getOriginalStringCode(), ""); Response httpResponse = performRestGet(bucketName, null, requestParameters, null); this.verifyResponseContentType(httpResponse); BucketStoragePolicyConfiguration ret = getXmlResponseSaxParser() .parse(new HttpMethodReleaseInputStream(httpResponse), BucketStoragePolicyHandler.class, false) .getStoragePolicy(); setResponseHeaders(ret, this.cleanResponseHeaders(httpResponse)); setStatusCode(ret, httpResponse.code()); return ret; } protected BucketStorageInfo getBucketStorageInfoImpl(String bucketName) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.STORAGEINFO.getOriginalStringCode(), ""); Response httpResponse = performRestGet(bucketName, null, requestParameters, null); this.verifyResponseContentType(httpResponse); BucketStorageInfo ret = getXmlResponseSaxParser() .parse(new HttpMethodReleaseInputStream(httpResponse), BucketStorageInfoHandler.class, false) .getStorageInfo(); setResponseHeaders(ret, this.cleanResponseHeaders(httpResponse)); setStatusCode(ret, httpResponse.code()); return ret; } protected AccessControlList getBucketAclImpl(String bucketName) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.ACL.getOriginalStringCode(), ""); Response httpResponse = performRestGet(bucketName, null, requestParameters, null); this.verifyResponseContentType(httpResponse); AccessControlList ret = getXmlResponseSaxParser() .parse(new HttpMethodReleaseInputStream(httpResponse), AccessControlListHandler.class, false) .getAccessControlList(); setResponseHeaders(ret, this.cleanResponseHeaders(httpResponse)); setStatusCode(ret, httpResponse.code()); return ret; } protected AccessControlList getObjectAclImpl(String bucketName, String objectKey, String versionId) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.ACL.getOriginalStringCode(), ""); if (ServiceUtils.isValid(versionId)) { requestParameters.put(ObsRequestParams.VERSION_ID, versionId.trim()); } Response httpResponse = performRestGet(bucketName, objectKey, requestParameters, null); this.verifyResponseContentType(httpResponse); AccessControlList ret = getXmlResponseSaxParser() .parse(new HttpMethodReleaseInputStream(httpResponse), AccessControlListHandler.class, false) .getAccessControlList(); setResponseHeaders(ret, this.cleanResponseHeaders(httpResponse)); setStatusCode(ret, httpResponse.code()); return ret; } protected DeleteObjectResult deleteObjectImpl(String bucketName, String objectKey, String versionId) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); if (versionId != null) { requestParameters.put(ObsRequestParams.VERSION_ID, versionId); } Response response = performRestDelete(bucketName, objectKey, requestParameters); DropFileResult result = new DropFileResult(Boolean.valueOf(response.header(this.getIHeaders().deleteMarkerHeader())), objectKey, response.header(this.getIHeaders().versionIdHeader())); Map<String, Object> map = this.cleanResponseHeaders(response); setResponseHeaders(result, map); setStatusCode(result, response.code()); return result; } protected ReadAheadResult readAheadObjectsImpl(ReadAheadRequest request) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(Constants.ObsRequestParams.READAHEAD, ""); requestParameters.put(Constants.ObsRequestParams.PREFIX, request.getPrefix()); Map<String, String> metadata = new HashMap<String, String>(); String cacheControl = request.getCacheOption().getCode() + ", ttl=" + request.getTtl(); metadata.put(ObsRequestParams.X_CACHE_CONTROL, cacheControl); Response response = performRestPost(request.getBucketName(), null, metadata, requestParameters, null, false); this.verifyResponseContentTypeForJson(response); String body; try { body = response.body().string(); } catch (IOException e) { throw new ServiceException(e); } ReadAheadResult result = (ReadAheadResult) JSONChange.jsonToObj(new ReadAheadResult(), body); result.setResponseHeaders(this.cleanResponseHeaders(response)); setStatusCode(result, response.code()); return result; } protected ReadAheadResult DeleteReadAheadObjectsImpl(String bucketName, String prefix) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(Constants.ObsRequestParams.READAHEAD, ""); requestParameters.put(Constants.ObsRequestParams.PREFIX, prefix); Response response = performRestDelete(bucketName, null, requestParameters, false); this.verifyResponseContentTypeForJson(response); String body; try { body = response.body().string(); } catch (IOException e) { throw new ServiceException(e); } ReadAheadResult result = (ReadAheadResult) JSONChange.jsonToObj(new ReadAheadResult(), body); result.setResponseHeaders(this.cleanResponseHeaders(response)); setStatusCode(result, response.code()); return result; } protected ReadAheadQueryResult queryReadAheadObjectsTaskImpl(String bucketName, String taskId) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(Constants.ObsRequestParams.READAHEAD, ""); requestParameters.put(Constants.ObsRequestParams.TASKID, taskId); Response response = performRestGet(bucketName, null, requestParameters, null); this.verifyResponseContentTypeForJson(response); String body; try { body = response.body().string(); } catch (IOException e) { throw new ServiceException(e); } ReadAheadQueryResult result = (ReadAheadQueryResult) JSONChange.jsonToObj(new ReadAheadQueryResult(), body); result.setResponseHeaders(this.cleanResponseHeaders(response)); setStatusCode(result, response.code()); return result; } protected BucketDirectColdAccess getBucketDirectColdAccessImpl(String bucketName) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.DIRECTCOLDACCESS.getOriginalStringCode(), ""); Response httpResponse = this.performRestGet(bucketName, null, requestParameters, null); this.verifyResponseContentType(httpResponse); BucketDirectColdAccess result = getXmlResponseSaxParser() .parse(new HttpMethodReleaseInputStream(httpResponse), BucketDirectColdAccessHandler.class, false) .getBucketDirectColdAccess(); setResponseHeaders(result, this.cleanResponseHeaders(httpResponse)); setStatusCode(result, httpResponse.code()); return result; } protected HeaderResponse setBucketDirectColdAccessImpl(String bucketName, BucketDirectColdAccess access) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.DIRECTCOLDACCESS.getOriginalStringCode(), ""); Map<String, String> headers = new HashMap<String, String>(); String requestXmlElement = this.getIConvertor().transBucketDirectColdAccess(access); headers.put(CommonHeaders.CONTENT_MD5, ServiceUtils.computeMD5(requestXmlElement)); headers.put(CommonHeaders.CONTENT_TYPE, Mimetypes.MIMETYPE_XML); Response response = this.performRestPut(bucketName, null, headers, requestParameters, createRequestBody(Mimetypes.MIMETYPE_XML, requestXmlElement), true); HeaderResponse ret = build(this.cleanResponseHeaders(response)); setStatusCode(ret, response.code()); return ret; } protected HeaderResponse deleteBucketDirectColdAccessImpl(String bucketName) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(SpecialParamEnum.DIRECTCOLDACCESS.getOriginalStringCode(), ""); Response response = performRestDelete(bucketName, null, requestParameters); HeaderResponse ret = build(this.cleanResponseHeaders(response)); setStatusCode(ret, response.code()); return ret; } TransResult transListObjectsRequest(ListObjectsRequest listObjectsRequest) { Map<String, String> params = new HashMap<String, String>(); if (listObjectsRequest.getPrefix() != null) { params.put(ObsRequestParams.PREFIX, listObjectsRequest.getPrefix()); } if (listObjectsRequest.getDelimiter() != null) { params.put(ObsRequestParams.DELIMITER, listObjectsRequest.getDelimiter()); } if (listObjectsRequest.getMaxKeys() > 0) { params.put(ObsRequestParams.MAX_KEYS, String.valueOf(listObjectsRequest.getMaxKeys())); } if (listObjectsRequest.getMarker() != null) { params.put(ObsRequestParams.MARKER, listObjectsRequest.getMarker()); } Map<String, String> headers = new HashMap<String, String>(); if (listObjectsRequest.getListTimeout() > 0) { putHeader(headers, this.getIHeaders().listTimeoutHeader(), String.valueOf(listObjectsRequest.getListTimeout())); } return new TransResult(headers, params, null); } protected ObjectListing listObjectsImpl(ListObjectsRequest listObjectsRequest) throws ServiceException { TransResult result = this.transListObjectsRequest(listObjectsRequest); Response httpResponse = performRestGet(listObjectsRequest.getBucketName(), null, result.getParams(), null); this.verifyResponseContentType(httpResponse); ListObjectsHandler listObjectsHandler = getXmlResponseSaxParser() .parse(new HttpMethodReleaseInputStream(httpResponse), ListObjectsHandler.class, true); ObjectListing objList = new ObjectListing(listObjectsHandler.getObjects(), listObjectsHandler.getCommonPrefixes(), listObjectsHandler.getBucketName() == null ? listObjectsRequest.getBucketName() : listObjectsHandler.getBucketName(), listObjectsHandler.isListingTruncated(), listObjectsHandler.getRequestPrefix() == null ? listObjectsRequest.getPrefix() : listObjectsHandler.getRequestPrefix(), listObjectsHandler.getRequestMarker() == null ? listObjectsRequest.getMarker() : listObjectsHandler.getRequestMarker(), listObjectsHandler.getRequestMaxKeys(), listObjectsHandler.getRequestDelimiter() == null ? listObjectsRequest.getDelimiter() : listObjectsHandler.getRequestDelimiter(), listObjectsHandler.getMarkerForNextListing(), httpResponse.header(this.getIHeaders().bucketRegionHeader())); setResponseHeaders(objList, this.cleanResponseHeaders(httpResponse)); setStatusCode(objList, httpResponse.code()); return objList; } protected ListBucketsResult listAllBucketsImpl(ListBucketsRequest request) throws ServiceException { Map<String, String> headers = new HashMap<String, String>(); if (request != null && request.isQueryLocation()) { this.putHeader(headers, this.getIHeaders().locationHeader(), Constants.TRUE); } Response httpResponse = performRestGetForListBuckets("", null, null, headers); this.verifyResponseContentType(httpResponse); ListBucketsHandler handler = getXmlResponseSaxParser() .parse(new HttpMethodReleaseInputStream(httpResponse), ListBucketsHandler.class, true); Map<String, Object> responseHeaders = this.cleanResponseHeaders(httpResponse); ListBucketsResult result = new ListBucketsResult(handler.getBuckets(), handler.getOwner()); setResponseHeaders(result, responseHeaders); setStatusCode(result, httpResponse.code()); return result; } protected HeaderResponse setBucketLoggingConfigurationImpl(String bucketName, BucketLoggingConfiguration status, boolean updateTargetACLifRequired) throws ServiceException { if (status.isLoggingEnabled() && updateTargetACLifRequired && this.getProviderCredentials().getAuthType() != AuthTypeEnum.OBS) { boolean isSetLoggingGroupWrite = false; boolean isSetLoggingGroupReadACP = false; String groupIdentifier = Constants.LOG_DELIVERY_URI; AccessControlList logBucketACL = getBucketAclImpl(status.getTargetBucketName()); for (GrantAndPermission gap : logBucketACL.getGrantAndPermissions()) { if (gap.getGrantee() instanceof GroupGrantee) { GroupGrantee grantee = (GroupGrantee) gap.getGrantee(); if (groupIdentifier.equals(this.getIConvertor().transGroupGrantee(grantee.getGroupGranteeType()))) { if (Permission.PERMISSION_WRITE.equals(gap.getPermission())) { isSetLoggingGroupWrite = true; } else if (Permission.PERMISSION_READ_ACP.equals(gap.getPermission())) { isSetLoggingGroupReadACP = true; } } } } if (!isSetLoggingGroupWrite || !isSetLoggingGroupReadACP) { if (log.isWarnEnabled()) { log.warn("Target logging bucket '" + status.getTargetBucketName() + "' does not have the necessary ACL settings, updating ACL now"); } if (logBucketACL.getOwner() != null) { logBucketACL.getOwner().setDisplayName(null); } logBucketACL.grantPermission(GroupGrantee.LOG_DELIVERY, Permission.PERMISSION_WRITE); logBucketACL.grantPermission(GroupGrantee.LOG_DELIVERY, Permission.PERMISSION_READ_ACP); setBucketAclImpl(status.getTargetBucketName(), null, logBucketACL); } else { if (log.isDebugEnabled()) { log.debug("Target logging bucket '" + status.getTargetBucketName() + "' has the necessary ACL settings"); } } } return setBucketLoggingConfigurationImpl(bucketName, status); } protected HeaderResponse deleteBucketImpl(String bucketName) throws ServiceException { Response response = performRestDelete(bucketName, null, null); return this.build(response); } Map<String, Object> cleanResponseHeaders(Response response) { Map<String, List<String>> map = response.headers().toMultimap(); return ServiceUtils.cleanRestMetadataMap(map, this.getIHeaders().headerPrefix(), this.getIHeaders().headerMetaPrefix()); } TransResult transUploadPartRequest(UploadPartRequest request) throws ServiceException { Map<String, String> params = new HashMap<String, String>(); params.put(ObsRequestParams.PART_NUMBER, String.valueOf(request.getPartNumber())); params.put(ObsRequestParams.UPLOAD_ID, request.getUploadId()); Map<String, String> headers = new HashMap<String, String>(); IHeaders iheaders = this.getIHeaders(); if (ServiceUtils.isValid(request.getContentMd5())) { headers.put(CommonHeaders.CONTENT_MD5, request.getContentMd5().trim()); } this.transSseCHeaders(request.getSseCHeader(), headers, iheaders); InputStream input = null; long contentLength = -1L; if (null != request.getFile()) { long fileSize = request.getFile().length(); long offset = (request.getOffset() >= 0 && request.getOffset() < fileSize) ? request.getOffset() : 0; long partSize = (request.getPartSize() != null && request.getPartSize() > 0 && request.getPartSize() <= (fileSize - offset)) ? request.getPartSize() : fileSize - offset; contentLength = partSize; try { if (request.isAttachMd5() && !ServiceUtils.isValid(request.getContentMd5())) { headers.put(CommonHeaders.CONTENT_MD5, ServiceUtils.toBase64( ServiceUtils.computeMD5Hash(new FileInputStream(request.getFile()), partSize, offset))); } input = new FileInputStream(request.getFile()); input.skip(offset); } catch (Exception e) { ServiceUtils.closeStream(input); throw new ServiceException(e); } if(request.getProgressListener() != null) { ProgressManager progressManager = new SimpleProgressManager(contentLength, 0, request.getProgressListener(), request.getProgressInterval() > 0 ? request.getProgressInterval() : ObsConstraint.DEFAULT_PROGRESS_INTERVAL); input = new ProgressInputStream(input, progressManager); } } else if (null != request.getInput()) { if(request.getPartSize() != null && request.getPartSize() > 0){ contentLength = request.getPartSize(); } input = request.getInput(); if(input != null && request.getProgressListener() != null) { ProgressManager progressManager = new SimpleProgressManager(contentLength, 0, request.getProgressListener(), request.getProgressInterval() > 0 ? request.getProgressInterval() : ObsConstraint.DEFAULT_PROGRESS_INTERVAL); input = new ProgressInputStream(input, progressManager); } } String contentType = Mimetypes.getInstance().getMimetype(request.getObjectKey()); headers.put(CommonHeaders.CONTENT_TYPE, contentType); if(contentLength > -1) { this.putHeader(headers, CommonHeaders.CONTENT_LENGTH, String.valueOf(contentLength)); } RequestBody body = input == null ? null : new RepeatableRequestEntity(input, contentType, contentLength, this.obsProperties); return new TransResult(headers, params, body); } protected UploadPartResult uploadPartImpl(UploadPartRequest request) throws ServiceException { TransResult result = null; Response response; try { result = this.transUploadPartRequest(request); response = performRestPut(request.getBucketName(), request.getObjectKey(), result.getHeaders(), result.getParams(), result.body, true); } finally { if (result != null && result.body != null && request.isAutoClose()) { RepeatableRequestEntity entity = (RepeatableRequestEntity) result.body; ServiceUtils.closeStream(entity); } } UploadPartResult ret = new UploadPartResult(); ret.setEtag(response.header(CommonHeaders.ETAG)); ret.setPartNumber(request.getPartNumber()); setResponseHeaders(ret, this.cleanResponseHeaders(response)); setStatusCode(ret, response.code()); return ret; } TransResult transCopyPartRequest(CopyPartRequest request) throws ServiceException { Map<String, String> params = new HashMap<String, String>(); params.put(ObsRequestParams.PART_NUMBER, String.valueOf(request.getPartNumber())); params.put(ObsRequestParams.UPLOAD_ID, request.getUploadId()); Map<String, String> headers = new HashMap<String, String>(); IHeaders iheaders = this.getIHeaders(); String sourceKey = RestUtils .encodeUrlString(request.getSourceBucketName()) + "/" + RestUtils .encodeUrlString(request.getSourceObjectKey()); if (ServiceUtils.isValid(request.getVersionId())) { sourceKey += "?versionId=" + request.getVersionId().trim(); } putHeader(headers, iheaders.copySourceHeader(), sourceKey); if (request.getByteRangeStart() != null) { String rangeEnd = request.getByteRangeEnd() != null ? String.valueOf(request.getByteRangeEnd()) : ""; String range = String.format("bytes=%s-%s", request.getByteRangeStart(), rangeEnd); putHeader(headers, iheaders.copySourceRangeHeader(), range); } this.transSseCHeaders(request.getSseCHeaderDestination(), headers, iheaders); this.transSseCSourceHeaders(request.getSseCHeaderSource(), headers, iheaders); return new TransResult(headers, params, null); } protected CopyPartResult copyPartImpl(CopyPartRequest request) throws ServiceException { TransResult result = this.transCopyPartRequest(request); Response response = this.performRestPut(request.getDestinationBucketName(), request.getDestinationObjectKey(), result.getHeaders(), result.getParams(), null, false); this.verifyResponseContentType(response); CopyPartResult ret = getXmlResponseSaxParser() .parse(new HttpMethodReleaseInputStream(response), CopyPartResultHandler.class, true) .getCopyPartResult(request.getPartNumber()); setResponseHeaders(ret, this.cleanResponseHeaders(response)); setStatusCode(ret, response.code()); return ret; } HeaderResponse build(Response res){ HeaderResponse response = new HeaderResponse(); setResponseHeaders(response, this.cleanResponseHeaders(res)); setStatusCode(response, res.code()); return response; } static HeaderResponse build(Map<String,Object> responseHeaders){ HeaderResponse response = new HeaderResponse(); setResponseHeaders(response, responseHeaders); return response; } static void setStatusCode(HeaderResponse response, int statusCode) { response.setStatusCode(statusCode); } static void setResponseHeaders(HeaderResponse response, Map<String,Object> responseHeaders) { response.setResponseHeaders(responseHeaders); } private String getObjectUrl(String bucketName, String objectKey) { boolean pathStyle = this.isPathStyle(); boolean https = this.getHttpsOnly(); boolean isCname = this.isCname(); return new StringBuilder().append(https? "https://" : "http://") .append(pathStyle || isCname? "" : bucketName + ".") .append(this.getEndpoint()) .append(":").append(https? this.getHttpsPort(): this.getHttpPort()) .append("/") .append(pathStyle? bucketName + "/" : "") .append(RestUtils.uriEncode(objectKey, false)).toString(); } protected AuthTypeEnum getApiVersion(String bucketName) throws ServiceException { if (!ServiceUtils.isValid(bucketName)) { return parseAuthTypeInResponse(""); } AuthTypeEnum apiVersion = apiVersionCache.getApiVersionInCache(bucketName); if (apiVersion == null) { try { segmentLock.lock(bucketName); apiVersion = apiVersionCache.getApiVersionInCache(bucketName); if (apiVersion == null) { apiVersion = parseAuthTypeInResponse(bucketName); apiVersionCache.addApiVersion(bucketName, apiVersion); } } finally { segmentLock.unlock(bucketName); } } return apiVersion; } private AuthTypeEnum parseAuthTypeInResponse(String bucketName) throws ServiceException { Response response; try { response = getAuthTypeNegotiationResponseImpl(bucketName); } catch (ServiceException e) { if (e.getResponseCode() == 404 || e.getResponseCode() <= 0 || e.getResponseCode() == 408 || e.getResponseCode() >= 500) { throw e; } else { return AuthTypeEnum.V2; } } String apiVersion; return (response.code() == 200 && (apiVersion=response.headers().get("x-obs-api")) != null && apiVersion.compareTo("3.0") >= 0) ? AuthTypeEnum.OBS : AuthTypeEnum.V2; } private Response getAuthTypeNegotiationResponseImpl(String bucketName) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put("apiversion", ""); return performRestForApiVersion(bucketName, null, requestParameters, null); } protected ThreadPoolExecutor initThreadPool(AbstractBulkRequest request) { int taskThreadNum = request.getTaskThreadNum(); int workQueenLength = request.getTaskQueueNum(); ThreadPoolExecutor executor = new ThreadPoolExecutor(taskThreadNum, taskThreadNum, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(workQueenLength)); executor.setRejectedExecutionHandler(new BlockRejectedExecutionHandler()); return executor; } protected void recordBulkTaskStatus(DefaultTaskProgressStatus progressStatus, TaskCallback<DeleteObjectResult, String> callback, TaskProgressListener listener, int interval) { progressStatus.execTaskIncrement(); if (listener != null) { if (progressStatus.getExecTaskNum() % interval == 0) { listener.progressChanged(progressStatus); } if (progressStatus.getExecTaskNum() == progressStatus.getTotalTaskNum()) { listener.progressChanged(progressStatus); } } } protected HeaderResponse setExtensionPolicyImpl(String bucketName, String policyDocument) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(RequestParamEnum.EXTENSION_POLICY.getOriginalStringCode(), ""); Map<String, String> metadata = new HashMap<String, String>(); metadata.put(CommonHeaders.CONTENT_TYPE, Mimetypes.MIMETYPE_JSON); metadata.put((this.getProviderCredentials().getAuthType() != AuthTypeEnum.OBS ? Constants.V2_HEADER_PREFIX : Constants.OBS_HEADER_PREFIX) + Constants.OEF_MARKER, Constants.YES); Response response = performRestPut(bucketName, null, metadata, requestParameters, this.createRequestBody(Mimetypes.MIMETYPE_JSON, policyDocument), false, true); HeaderResponse ret = build(this.cleanResponseHeaders(response)); setStatusCode(ret, response.code()); return ret; } protected QueryExtensionPolicyResult queryExtensionPolicyImpl(String bucketName) throws ServiceException{ Map<String, String> requestParams = new HashMap<String, String>(); requestParams.put(RequestParamEnum.EXTENSION_POLICY.getOriginalStringCode(), ""); Map<String, String> metadata = new HashMap<String, String>(); metadata.put((this.getProviderCredentials().getAuthType() != AuthTypeEnum.OBS ? Constants.V2_HEADER_PREFIX : Constants.OBS_HEADER_PREFIX) + Constants.OEF_MARKER, Constants.YES); Response response = performRestGet(bucketName, null, requestParams, metadata, true); this.verifyResponseContentTypeForJson(response); String body; try { body = response.body().string(); } catch (IOException e) { throw new ServiceException(e); } QueryExtensionPolicyResult ret = (QueryExtensionPolicyResult) JSONChange.jsonToObj(new QueryExtensionPolicyResult(), body); ret.setResponseHeaders(this.cleanResponseHeaders(response)); setStatusCode(ret, response.code()); return ret; } protected HeaderResponse deleteExtensionPolicyImpl(String bucketName) throws ServiceException { Map<String, String> requestParams = new HashMap<String, String>(); requestParams.put(RequestParamEnum.EXTENSION_POLICY.getOriginalStringCode(), ""); Map<String, String> metadata = new HashMap<String, String>(); metadata.put((this.getProviderCredentials().getAuthType() != AuthTypeEnum.OBS ? Constants.V2_HEADER_PREFIX : Constants.OBS_HEADER_PREFIX) + Constants.OEF_MARKER, Constants.YES); Response response = performRestDelete(bucketName, null, requestParams, metadata, true); return this.build(response); } protected CreateAsynchFetchJobsResult createFetchJobImpl(String bucketName, String policyDocument) throws ServiceException{ Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(RequestParamEnum.ASYNC_FETCH_JOBS.getOriginalStringCode(), ""); Map<String, String> metadata = new HashMap<String, String>(); metadata.put(CommonHeaders.CONTENT_TYPE, Mimetypes.MIMETYPE_JSON); metadata.put((this.getProviderCredentials().getAuthType() != AuthTypeEnum.OBS ? Constants.V2_HEADER_PREFIX : Constants.OBS_HEADER_PREFIX) + Constants.OEF_MARKER, Constants.YES); Response response = performRestPost(bucketName, null, metadata, requestParameters, this.createRequestBody(Mimetypes.MIMETYPE_JSON, policyDocument), false, true); this.verifyResponseContentTypeForJson(response); String body; try { body = response.body().string(); } catch (IOException e) { throw new ServiceException(e); } CreateAsynchFetchJobsResult ret = (CreateAsynchFetchJobsResult) JSONChange.jsonToObj(new CreateAsynchFetchJobsResult(), body); ret.setResponseHeaders(this.cleanResponseHeaders(response)); setStatusCode(ret, response.code()); return ret; } protected QueryAsynchFetchJobsResult queryFetchJobImpl(String bucketName, String jobId) throws ServiceException{ Map<String, String> requestParams = new HashMap<String, String>(); requestParams.put(RequestParamEnum.ASYNC_FETCH_JOBS.getOriginalStringCode() + "/" +jobId, ""); Map<String, String> metadata = new HashMap<String, String>(); metadata.put(CommonHeaders.CONTENT_TYPE, Mimetypes.MIMETYPE_JSON); metadata.put((this.getProviderCredentials().getAuthType() != AuthTypeEnum.OBS ? Constants.V2_HEADER_PREFIX : Constants.OBS_HEADER_PREFIX) + Constants.OEF_MARKER, Constants.YES); Response response = performRestGet(bucketName, null, requestParams, metadata, true); this.verifyResponseContentTypeForJson(response); String body; try { body = response.body().string(); } catch (IOException e) { throw new ServiceException(e); } QueryAsynchFetchJobsResult ret = (QueryAsynchFetchJobsResult) JSONChange.jsonToObj(new QueryAsynchFetchJobsResult(), body); ret.setResponseHeaders(this.cleanResponseHeaders(response)); setStatusCode(ret, response.code()); return ret; } protected HeaderResponse putDisPolicyImpl(String bucketName, String policyDocument) throws ServiceException { Map<String, String> requestParameters = new HashMap<String, String>(); requestParameters.put(RequestParamEnum.DIS_POLICIES.getOriginalStringCode(), ""); Map<String, String> metadata = new HashMap<String, String>(); metadata.put(CommonHeaders.CONTENT_TYPE, Mimetypes.MIMETYPE_JSON); metadata.put((this.getProviderCredentials().getAuthType() != AuthTypeEnum.OBS ? Constants.V2_HEADER_PREFIX : Constants.OBS_HEADER_PREFIX) + Constants.OEF_MARKER, Constants.YES); Response response = performRestPut(bucketName, null, metadata, requestParameters, this.createRequestBody(Mimetypes.MIMETYPE_JSON, policyDocument), false, true); HeaderResponse ret = build(this.cleanResponseHeaders(response)); setStatusCode(ret, response.code()); return ret; } protected GetDisPolicyResult getDisPolicyImpl(String bucketName) throws ServiceException{ Map<String, String> requestParams = new HashMap<String, String>(); requestParams.put(RequestParamEnum.DIS_POLICIES.getOriginalStringCode(), ""); Map<String, String> metadata = new HashMap<String, String>(); metadata.put((this.getProviderCredentials().getAuthType() != AuthTypeEnum.OBS ? Constants.V2_HEADER_PREFIX : Constants.OBS_HEADER_PREFIX) + Constants.OEF_MARKER, Constants.YES); Response response = performRestGet(bucketName, null, requestParams, metadata, true); this.verifyResponseContentTypeForJson(response); String body; try { body = response.body().string(); } catch (IOException e) { throw new ServiceException(e); } DisPolicy policy = (DisPolicy) JSONChange.jsonToObj(new DisPolicy(), body); GetDisPolicyResult ret = new GetDisPolicyResult(policy); ret.setResponseHeaders(this.cleanResponseHeaders(response)); setStatusCode(ret, response.code()); return ret; } protected HeaderResponse deleteDisPolicyImpl(String bucketName) throws ServiceException { Map<String, String> requestParams = new HashMap<String, String>(); requestParams.put(RequestParamEnum.DIS_POLICIES.getOriginalStringCode(), ""); Map<String, String> metadata = new HashMap<String, String>(); metadata.put((this.getProviderCredentials().getAuthType() != AuthTypeEnum.OBS ? Constants.V2_HEADER_PREFIX : Constants.OBS_HEADER_PREFIX) + Constants.OEF_MARKER, Constants.YES); Response response = performRestDelete(bucketName, null, requestParams, metadata, true); return this.build(response); } protected void verifyResponseContentTypeForJson(Response response) throws ServiceException { if (this.obsProperties.getBoolProperty(ObsConstraint.VERIFY_RESPONSE_CONTENT_TYPE, true)) { String contentType = response.header(Constants.CommonHeaders.CONTENT_TYPE); if(null == contentType) { throw new ServiceException( "Expected JSON document response but received content type is null"); } else if(-1 == contentType.toString().indexOf(Mimetypes.MIMETYPE_JSON)) { throw new ServiceException( "Expected JSON document response but received content type is " + contentType); } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.ql.ddl.view.materialized.show; import java.io.DataOutputStream; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.ql.ErrorMsg; import org.apache.hadoop.hive.ql.ddl.DDLOperation; import org.apache.hadoop.hive.ql.ddl.DDLOperationContext; import org.apache.hadoop.hive.ql.ddl.DDLUtils; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.apache.hadoop.hive.ql.metadata.Table; /** * Operation process showing the materialized views. */ public class ShowMaterializedViewsOperation extends DDLOperation<ShowMaterializedViewsDesc> { public ShowMaterializedViewsOperation(DDLOperationContext context, ShowMaterializedViewsDesc desc) { super(context, desc); } @Override public int execute() throws HiveException { String dbName = desc.getDbName(); String pattern = desc.getPattern(); // if null, all tables/views are returned String resultsFile = desc.getResFile(); if (!context.getDb().databaseExists(dbName)) { throw new HiveException(ErrorMsg.DATABASE_NOT_EXISTS, dbName); } // the returned list is not sortable as it is immutable, thus it must be put into a new ArrayList List<Table> tableObjects = new ArrayList<>(context.getDb().getMaterializedViewObjectsByPattern(dbName, pattern)); LOG.debug("Found {} materialized view(s) matching the SHOW MATERIALIZED VIEWS statement.", tableObjects.size()); try (DataOutputStream os = DDLUtils.getOutputStream(new Path(resultsFile), context)) { Collections.sort(tableObjects, Comparator.comparing(Table::getTableName)); context.getFormatter().showMaterializedViews(os, tableObjects); } catch (Exception e) { throw new HiveException(e, ErrorMsg.GENERIC_ERROR, "in database" + dbName); } return 0; } }
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * gradle plugin from the resource data it found. It * should not be modified by hand. */ package android.support.compat; public final class R { public static final class attr { public static final int font = 0x7f010122; public static final int fontProviderAuthority = 0x7f01011b; public static final int fontProviderCerts = 0x7f01011e; public static final int fontProviderFetchStrategy = 0x7f01011f; public static final int fontProviderFetchTimeout = 0x7f010120; public static final int fontProviderPackage = 0x7f01011c; public static final int fontProviderQuery = 0x7f01011d; public static final int fontStyle = 0x7f010121; public static final int fontWeight = 0x7f010123; } public static final class bool { public static final int abc_action_bar_embed_tabs = 0x7f0b0000; } public static final class color { public static final int notification_action_color_filter = 0x7f0d0000; public static final int notification_icon_bg_color = 0x7f0d0041; public static final int ripple_material_light = 0x7f0d004c; public static final int secondary_text_default_material_light = 0x7f0d004e; } public static final class dimen { public static final int compat_button_inset_horizontal_material = 0x7f09005c; public static final int compat_button_inset_vertical_material = 0x7f09005d; public static final int compat_button_padding_horizontal_material = 0x7f09005e; public static final int compat_button_padding_vertical_material = 0x7f09005f; public static final int compat_control_corner_material = 0x7f090060; public static final int notification_action_icon_size = 0x7f09008f; public static final int notification_action_text_size = 0x7f090090; public static final int notification_big_circle_margin = 0x7f090091; public static final int notification_content_margin_start = 0x7f09001a; public static final int notification_large_icon_height = 0x7f090092; public static final int notification_large_icon_width = 0x7f090093; public static final int notification_main_column_padding_top = 0x7f09001b; public static final int notification_media_narrow_margin = 0x7f09001c; public static final int notification_right_icon_size = 0x7f090094; public static final int notification_right_side_padding_top = 0x7f090018; public static final int notification_small_icon_background_padding = 0x7f090095; public static final int notification_small_icon_size_as_large = 0x7f090096; public static final int notification_subtext_size = 0x7f090097; public static final int notification_top_pad = 0x7f090098; public static final int notification_top_pad_large_text = 0x7f090099; } public static final class drawable { public static final int notification_action_background = 0x7f020083; public static final int notification_bg = 0x7f020084; public static final int notification_bg_low = 0x7f020085; public static final int notification_bg_low_normal = 0x7f020086; public static final int notification_bg_low_pressed = 0x7f020087; public static final int notification_bg_normal = 0x7f020088; public static final int notification_bg_normal_pressed = 0x7f020089; public static final int notification_icon_background = 0x7f02008a; public static final int notification_template_icon_bg = 0x7f020090; public static final int notification_template_icon_low_bg = 0x7f020091; public static final int notification_tile_bg = 0x7f02008b; public static final int notify_panel_notification_icon_bg = 0x7f02008c; } public static final class id { public static final int action_container = 0x7f0f012c; public static final int action_divider = 0x7f0f0133; public static final int action_image = 0x7f0f012d; public static final int action_text = 0x7f0f012e; public static final int actions = 0x7f0f013c; public static final int async = 0x7f0f004f; public static final int blocking = 0x7f0f0050; public static final int chronometer = 0x7f0f0138; public static final int forever = 0x7f0f0051; public static final int icon = 0x7f0f0074; public static final int icon_group = 0x7f0f013d; public static final int info = 0x7f0f0139; public static final int italic = 0x7f0f0052; public static final int line1 = 0x7f0f0008; public static final int line3 = 0x7f0f0009; public static final int normal = 0x7f0f0028; public static final int notification_background = 0x7f0f013a; public static final int notification_main_column = 0x7f0f0135; public static final int notification_main_column_container = 0x7f0f0134; public static final int right_icon = 0x7f0f013b; public static final int right_side = 0x7f0f0136; public static final int tag_transition_group = 0x7f0f0011; public static final int text = 0x7f0f0012; public static final int text2 = 0x7f0f0013; public static final int time = 0x7f0f0137; public static final int title = 0x7f0f0016; } public static final class integer { public static final int status_bar_notification_info_maxnum = 0x7f0c000a; } public static final class layout { public static final int notification_action = 0x7f040043; public static final int notification_action_tombstone = 0x7f040044; public static final int notification_template_custom_big = 0x7f04004b; public static final int notification_template_icon_group = 0x7f04004c; public static final int notification_template_part_chronometer = 0x7f040050; public static final int notification_template_part_time = 0x7f040051; } public static final class string { public static final int status_bar_notification_info_overflow = 0x7f080024; } public static final class style { public static final int TextAppearance_Compat_Notification = 0x7f0a0076; public static final int TextAppearance_Compat_Notification_Info = 0x7f0a0077; public static final int TextAppearance_Compat_Notification_Line2 = 0x7f0a0105; public static final int TextAppearance_Compat_Notification_Time = 0x7f0a007a; public static final int TextAppearance_Compat_Notification_Title = 0x7f0a007c; public static final int Widget_Compat_NotificationActionContainer = 0x7f0a007e; public static final int Widget_Compat_NotificationActionText = 0x7f0a007f; } public static final class styleable { public static final int[] FontFamily = { 0x7f01011b, 0x7f01011c, 0x7f01011d, 0x7f01011e, 0x7f01011f, 0x7f010120 }; public static final int FontFamily_fontProviderAuthority = 0; public static final int FontFamily_fontProviderPackage = 1; public static final int FontFamily_fontProviderQuery = 2; public static final int FontFamily_fontProviderCerts = 3; public static final int FontFamily_fontProviderFetchStrategy = 4; public static final int FontFamily_fontProviderFetchTimeout = 5; public static final int[] FontFamilyFont = { 0x01010532, 0x01010533, 0x0101053f, 0x7f010121, 0x7f010122, 0x7f010123 }; public static final int FontFamilyFont_android_font = 0; public static final int FontFamilyFont_android_fontWeight = 1; public static final int FontFamilyFont_android_fontStyle = 2; public static final int FontFamilyFont_fontStyle = 3; public static final int FontFamilyFont_font = 4; public static final int FontFamilyFont_fontWeight = 5; } }
package pers.haoming.bigtalkdesignpattern.template; /** * @author haoming * @package pers.haoming.bigtalkdesignpattern.template * @class TestPaper * @description: 试卷 * @createDate 2019/2/16 16:23 */ public abstract class TestPaper { public void testQuestion() { testQuestion1(); testQuestion2(); testQuestion3(); } public void testQuestion1() { System.out.println("1. 杨过得到,后来给了郭靖,炼成倚天剑、屠龙刀的玄铁可能是【 】"); System.out.println("a. 球磨铸铁"); System.out.println("b. 马口铁"); System.out.println("c. 高速合金钢"); System.out.println("d. 碳素纤维"); System.out.println("答案:" + answer1()); } public void testQuestion2() { System.out.println("2. 杨过、程英、陆无双铲除了情花,造成【 】"); System.out.println("a. 使这种植物不再害人"); System.out.println("b. 使一种珍惜物种灭绝"); System.out.println("c. 破坏了那个生物圈的生态平衡"); System.out.println("d. 造成该地区沙漠化"); System.out.println("答案:" + answer2()); } public void testQuestion3() { System.out.println("3. 蓝凤凰致使华山师徒、桃谷六仙呕吐不止,如果你是大夫,会给他们开什么药【 】"); System.out.println("a. 阿司匹林"); System.out.println("b. 牛黄解毒片"); System.out.println("c. 氟哌酸"); System.out.println("d. 让他们喝大量的生牛奶"); System.out.println("e. 以上全不对"); System.out.println("答案:" + answer3()); } public abstract String answer1(); public abstract String answer2(); public abstract String answer3(); }
package org.minxc.emp.base.db.table.impl.h2; import org.apache.commons.lang3.StringUtils; import org.minxc.emp.base.api.Page; import org.minxc.emp.base.core.util.BeanUtils; import org.minxc.emp.base.db.api.table.IViewOperator; import org.minxc.emp.base.db.api.table.model.Column; import org.minxc.emp.base.db.api.table.model.Table; import org.minxc.emp.base.db.table.BaseViewOperator; import org.minxc.emp.base.db.table.colmap.H2ColumnMap; import org.minxc.emp.base.db.table.model.DefaultTable; import org.minxc.emp.base.db.table.util.SQLConst; import org.springframework.jdbc.core.RowMapper; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; /** * H2 视图操作的实现类。 * * <pre> * </pre> */ public class H2ViewOperator extends BaseViewOperator implements IViewOperator { // private static final String // sqlAllView="select view_name from user_views "; private static final String SQL_GET_ALL_VIEW = "SELECT " + "TABLE_NAME ," + "REMARKS " + "FROM " + "INFORMATION_SCHEMA.TABLES " + "WHERE " + "TABLE_TYPE = 'VIEW' " + "AND TABLE_SCHEMA=SCHEMA() "; private static final String SQL_GET_COLUMNS = "SELECT " + "A.TABLE_NAME, " + "A.COLUMN_NAME, " + "A.IS_NULLABLE, " + "A.DATA_TYPE, " + "A.CHARACTER_OCTET_LENGTH LENGTH, " + "A.NUMERIC_PRECISION PRECISIONS, " + "A.NUMERIC_SCALE SCALE, " + "B.COLUMN_LIST, " + "A.REMARKS " + "FROM " + "INFORMATION_SCHEMA.COLUMNS A " + "JOIN INFORMATION_SCHEMA.CONSTRAINTS B ON A.TABLE_NAME=B.TABLE_NAME " + "WHERE " + "A.TABLE_SCHEMA=SCHEMA() " + "AND UPPER(A.TABLE_NAME)='%s' "; static final String SQL_GET_COLUMNS_BATCH = "SELECT " + "A.TABLE_NAME, " + "A.COLUMN_NAME, " + "A.IS_NULLABLE, " + "A.DATA_TYPE, " + "A.CHARACTER_OCTET_LENGTH LENGTH, " + "A.NUMERIC_PRECISION PRECISIONS, " + "A.NUMERIC_SCALE SCALE, " + "B.COLUMN_LIST, " + "A.REMARKS " + "FROM " + "INFORMATION_SCHEMA.COLUMNS A " + "JOIN INFORMATION_SCHEMA.CONSTRAINTS B ON A.TABLE_NAME=B.TABLE_NAME " + "WHERE " + "A.TABLE_SCHEMA=SCHEMA() "; private static final String DB_TYPE = SQLConst.DB_H2; /* * (non-Javadoc) * * @see org.minxc.emp.base.api.db.IViewOperator#createOrRep(java.lang.String, * java.lang.String) */ @Override public void createOrRep(String viewName, String sql) throws Exception { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see org.minxc.emp.base.api.db.IViewOperator#getViews(java.lang.String) */ @Override public List<String> getViews(String viewName) throws SQLException { String sql = SQL_GET_ALL_VIEW; if (StringUtils.isNotEmpty(viewName)) { sql += " AND TABLE_NAME LIKE '%" + viewName + "%'"; } RowMapper<String> rowMapper = new RowMapper<String>() { @Override public String mapRow(ResultSet rs, int rowNum) throws SQLException { String name = rs.getString("TABLE_NAME"); return name; } }; return this.jdbcTemplate.query(sql, rowMapper); } /* * (non-Javadoc) * * @see org.minxc.emp.base.api.db.IViewOperator#getViews(java.lang.String, * org.minxc.emp.base.api.Page) */ @Override public List<String> getViews(String viewName, Page page) throws SQLException, Exception { String sql = SQL_GET_ALL_VIEW; if (StringUtils.isNotEmpty(viewName)) { sql += " AND TABLE_NAME LIKE '%" + viewName + "%'"; } RowMapper<String> rowMapper = new RowMapper<String>() { @Override public String mapRow(ResultSet rs, int rowNum) throws SQLException { String name = rs.getString("TABLE_NAME"); return name; } }; return this.jdbcTemplate.query(sql, rowMapper); } /* * (non-Javadoc) * * @see * org.minxc.emp.base.api.db.IViewOperator#getViewsByName(java.lang.String, * org.minxc.emp.base.api.Page) */ @Override public List<Table> getViewsByName(String viewName, Page page) throws Exception { String sql = SQL_GET_ALL_VIEW; if (StringUtils.isNotEmpty(viewName)) { sql += " AND TABLE_NAME LIKE '%" + viewName + "%'"; } RowMapper<Table> rowMapper = new RowMapper<Table>() { @Override public Table mapRow(ResultSet rs, int row) throws SQLException { Table tableModel = new DefaultTable(); tableModel.setTableName(rs.getString("table_name")); tableModel.setComment(tableModel.getTableName()); return tableModel; } }; List<Table> tableModels = getForList(sql, page, rowMapper, DB_TYPE); List<String> tableNames = new ArrayList<String>(); // get all table names for (Table model : tableModels) { tableNames.add(model.getTableName()); } // batch get table columns Map<String, List<Column>> tableColumnsMap = getColumnsByTableName(tableNames); // extract table columns from paraTypeMap by table name; for (Entry<String, List<Column>> entry : tableColumnsMap.entrySet()) { // set Table's columns for (Table model : tableModels) { if (model.getTableName().equalsIgnoreCase(entry.getKey())) { model.setColumnList(entry.getValue()); } } } return tableModels; } /** * 根据表名获取列。此方法使用批量查询方式。 * * @param tableName * @return */ @SuppressWarnings("unchecked") private Map<String, List<Column>> getColumnsByTableName( List<String> tableNames) { String sql = SQL_GET_COLUMNS_BATCH; Map<String, List<Column>> map = new HashMap<String, List<Column>>(); if (tableNames != null && tableNames.size() == 0) { return map; } else { StringBuffer buf = new StringBuffer(); for (String str : tableNames) { buf.append("'" + str + "',"); } buf.deleteCharAt(buf.length() - 1); sql += " AND A.TABLE_NAME IN (" + buf.toString() + ") "; } List<Column> columnModels = jdbcTemplate.query(sql, new H2ColumnMap()); for (Column columnModel : columnModels) { String tableName = columnModel.getTableName(); if (map.containsKey(tableName)) { map.get(tableName).add(columnModel); } else { List<Column> cols = new ArrayList<Column>(); cols.add(columnModel); map.put(tableName, cols); } } return map; } /* * (non-Javadoc) * * @see BaseViewOperator#getType(java.lang.String) */ @Override public String getType(String type) { type = type.toLowerCase(); if (type.indexOf("number") > -1) return Column.COLUMN_TYPE_NUMBER; else if (type.indexOf("date") > -1) { return Column.COLUMN_TYPE_DATE; } else if (type.indexOf("char") > -1) { return Column.COLUMN_TYPE_VARCHAR; } return Column.COLUMN_TYPE_VARCHAR; } /* * (non-Javadoc) * * @see * BaseViewOperator#getModelByViewName(java.lang * .String) */ @Override public Table getModelByViewName(String viewName) throws SQLException { String sql = SQL_GET_ALL_VIEW; sql += " AND UPPER(TABLE_NAME) = '" + viewName.toUpperCase() + "'"; // Table tableModel= (Table) jdbcTemplate.queryForObject(sql, null, // tableModelRowMapper); Table tableModel = null; List<Table> tableModels = jdbcTemplate.query(sql, tableRowMapper); if (BeanUtils.isEmpty(tableModels)) { return null; } else { tableModel = tableModels.get(0); } // 获取列对象 List<Column> columnList = getColumnsByTableName(viewName); tableModel.setColumnList(columnList); return tableModel; } /** * 根据表名获取列 * * @param tableName * @return */ @SuppressWarnings("unchecked") private List<Column> getColumnsByTableName(String tableName) { String sql = String.format(SQL_GET_COLUMNS, tableName); // jdbcHelper.setCurrentDb(currentDb); Map<String, Object> map = new HashMap<String, Object>(); // sqlColumns语句的column_key包含了column是否为primary List<Column> list = jdbcTemplate.query(sql, new H2ColumnMap()); for (Column model : list) { model.setTableName(tableName); } return list; } RowMapper<Table> tableRowMapper = new RowMapper<Table>() { @Override public Table mapRow(ResultSet rs, int row) throws SQLException { Table tableModel = new DefaultTable(); String tabName = rs.getString("TABLE_NAME"); String tabComment = rs.getString("REMARKS"); tableModel.setTableName(tabName); tableModel.setComment(tabComment); return tableModel; } }; }
/* * 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.sudoku.grid.tests; import com.sudoku.data.manager.UserManager; import com.sudoku.data.model.Grid; import com.sudoku.data.model.User; import com.sudoku.grid.editor.IhmGridEditorManuallyFilled; import com.sudoku.grid.gridcells.IhmCellEditable; import com.sudoku.grid.gridcells.IhmGridLines; import com.sudoku.grid.gridcells.IhmGridLinesCompleted; import com.sudoku.grid.player.IhmGridPlayer; import com.sudoku.grid.popups.IhmPopupsList; import com.sudoku.grid.preview.IhmGridPreview; import java.io.UnsupportedEncodingException; import java.net.UnknownHostException; import java.security.NoSuchAlgorithmException; import java.util.Calendar; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.scene.layout.HBox; import javafx.scene.layout.StackPane; import javafx.scene.paint.Color; import javafx.scene.paint.Paint; import javafx.scene.shape.Line; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; import javafx.stage.WindowEvent; /** * * @author Marc-Antoine */ public class GridTest extends Application { @Override public void start(Stage primaryStage) { HBox root = new HBox(); Scene scene = new Scene(root, 700, 500); primaryStage.setTitle("Sudoku Tests"); primaryStage.setScene(scene); /* IhmCellEditable ce = new IhmCellEditable(50, 50, 10, 20); root.getChildren().add(ce); //*/ /* TextField ce = new TextField("1"); ce.setMaxSize(50, 50); ce.setAlignment(Pos.CENTER); ce.setStyle("-fx-font-size: 20pt;"); root.getChildren().add(ce); //*/ //* Grid g = new Grid("blabla", UserManager.getInstance().getLoggedUser()); /*for (byte x = 0; x < 9; x++) { for (byte y = 0; y < 9; y++) { if (Math.random() > 0.5) { g.setFixedCell(x, y, (byte) (((x + y) % 9) + 1)); } else { g.setEmptyCell(x, y); } } }*/ /* Sudoku de test: |4 9|31 | |37 |4 5| 9 |8 5| |4 | 9 | |8 5 | |592| |1 3| | 7 | 6| |3 7 | 1 |2 3| 84 | | 81|9 6 Solution: | 6 | 8|752 | 1| 2 |6 8 | 2 |679| 31 |6 2|137| 4 |748| |163 | 5 |846|2 9 |28 |954| 1 |9 7| 6 |5 |534|7 | 2 */ g.setFixedCell((byte) 0, (byte) 0, (byte) 4); g.setFixedCell((byte) 0, (byte) 1, (byte) 3); g.setFixedCell((byte) 0, (byte) 2, (byte) 8); g.setFixedCell((byte) 0, (byte) 5, (byte) 1); g.setFixedCell((byte) 1, (byte) 1, (byte) 7); g.setFixedCell((byte) 1, (byte) 3, (byte) 9); g.setFixedCell((byte) 1, (byte) 7, (byte) 1); g.setFixedCell((byte) 2, (byte) 0, (byte) 9); g.setFixedCell((byte) 2, (byte) 2, (byte) 5); g.setFixedCell((byte) 2, (byte) 5, (byte) 3); g.setFixedCell((byte) 2, (byte) 6, (byte) 6); g.setFixedCell((byte) 3, (byte) 0, (byte) 3); g.setFixedCell((byte) 3, (byte) 1, (byte) 4); g.setFixedCell((byte) 3, (byte) 4, (byte) 5); g.setFixedCell((byte) 3, (byte) 7, (byte) 2); g.setFixedCell((byte) 4, (byte) 0, (byte) 1); g.setFixedCell((byte) 4, (byte) 4, (byte) 9); g.setFixedCell((byte) 4, (byte) 8, (byte) 8); g.setFixedCell((byte) 5, (byte) 1, (byte) 5); g.setFixedCell((byte) 5, (byte) 4, (byte) 2); g.setFixedCell((byte) 5, (byte) 7, (byte) 3); g.setFixedCell((byte) 5, (byte) 8, (byte) 1); g.setFixedCell((byte) 6, (byte) 2, (byte) 4); g.setFixedCell((byte) 6, (byte) 3, (byte) 8); g.setFixedCell((byte) 6, (byte) 6, (byte) 3); g.setFixedCell((byte) 6, (byte) 8, (byte) 9); g.setFixedCell((byte) 7, (byte) 1, (byte) 9); g.setFixedCell((byte) 7, (byte) 5, (byte) 7); g.setFixedCell((byte) 7, (byte) 7, (byte) 8); g.setFixedCell((byte) 8, (byte) 3, (byte) 5); g.setFixedCell((byte) 8, (byte) 6, (byte) 7); g.setFixedCell((byte) 8, (byte) 7, (byte) 4); g.setFixedCell((byte) 8, (byte) 8, (byte) 6); IhmGridLines glines = new IhmGridLines(g, 500, IhmGridLines.ALL_VIEW.add(IhmGridLines.FIXED_HIDABLE)); glines.addEventHandler(IhmGridLinesCompleted.GRID_COMPLETED, new EventHandler<IhmGridLinesCompleted>() { @Override public void handle(IhmGridLinesCompleted t) { //Grid completed System.out.println("\n########## Grid Completed! ##########"); } }); root.getChildren().add(glines); //* IhmPopupsList.init(200, 700, 6); IhmPopupsList plist = IhmPopupsList.getInstance(); primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() { @Override public void handle(WindowEvent t) { if (t.getEventType() == WindowEvent.WINDOW_CLOSE_REQUEST) { IhmPopupsList.getInstance().killAllTimers(); } } }); root.getChildren().add(plist); //*/ /* IhmGridPreview ce = new IhmGridPreview("Test Preview", 5); root.getChildren().add(ce); //*/ /* IhmGridEditorManuallyFilled ce = new IhmGridEditorManuallyFilled(); root.getChildren().add(ce); //*/ primaryStage.show(); } /** * @param args the command line arguments */ public static void main(String[] args) { launch(args); } }
package com.eoi.marayarn.logstash; import org.apache.commons.io.IOUtils; import org.junit.Assert; import org.junit.Test; public class LogstashStatsMetricsPickerTest { @Test public void LogstashStatsMetricsPickerTest_1() throws Exception { byte[] metrics = IOUtils.toByteArray(getClass().getResourceAsStream("/test.json")); LogstashStatsMetricsPicker logstashStatsMetricsPicker = new LogstashStatsMetricsPicker(new String(metrics)); logstashStatsMetricsPicker.visit(); Assert.assertEquals(1, logstashStatsMetricsPicker.metricValues.get(".process.cpu.percent")); Assert.assertFalse(logstashStatsMetricsPicker.metricValues.containsKey(".reloads.failures")); Assert.assertEquals(14, logstashStatsMetricsPicker.metricValues.size()); Assert.assertEquals(14, logstashStatsMetricsPicker.metricTypes.size()); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.bearsoft.org.netbeans.modules.form; // ---------- public interface ComponentReference<C> { RADComponent<C> getComponent(); }
package com.example.bozhilun.android.w30s.carema; import android.annotation.SuppressLint; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ActivityInfo; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.hardware.Camera; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.provider.MediaStore; import androidx.annotation.Nullable; import android.text.TextUtils; import android.util.Log; import android.view.Display; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.ImageView; import android.widget.RelativeLayout; import com.example.bozhilun.android.MyApp; import com.example.bozhilun.android.R; import com.example.bozhilun.android.bleutil.MyCommandManager; import com.example.bozhilun.android.siswatch.WatchBaseActivity; import com.example.bozhilun.android.siswatch.utils.WatchUtils; import com.example.bozhilun.android.w30s.activity.W30sAlbumActivity; import com.example.bozhilun.android.w30s.ble.W37BleOperateManager; import com.example.bozhilun.android.w30s.ble.W37DataAnalysis; import com.example.bozhilun.android.w30s.utils.CameraUtils; import com.example.bozhilun.android.xwatch.ble.XWatchBleAnalysis; import com.suchengkeji.android.w30sblelibrary.W30SBLEServices; import com.suchengkeji.android.w30sblelibrary.utils.SharedPreferencesUtils; import com.tjdL4.tjdmain.L4M; import com.tjdL4.tjdmain.contr.L4Command; import com.veepoo.protocol.listener.base.IBleWriteResponse; import com.veepoo.protocol.listener.data.ICameraDataListener; import com.veepoo.protocol.model.enums.ECameraStatus; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * @aboutContent: * @author: An * @crateTime: 2018/3/23 08:58 * @mailBox: an.****.life@gmail.com * @company: 东莞速成科技有限公司 */ public class W30sCameraActivity extends WatchBaseActivity implements View.OnClickListener { private static final String TAG = "W30sCameraActivity"; //开始拍照的指令 public static final String W37_CAMERA_TAKE_PHOTO = "com.example.bozhilun.android.w30s.ble.take_photo"; CameraPreview mCameraPreview; CameraLine mCameraLine; RelativeLayout id_rl_cp_view; //【重力感应处理】 app内锁定横屏 或用户锁定横屏时候获得方向 private ScreenSwitchUtils mScreenSwitchInstance; Camera mCamera; public static final int ZOOM_FACTOR = 5;//缩放因子 private int zoomValue = 0; public static final int FLAG_CHOOCE_PICTURE = 2001;//选择图片 private final int FLAG_AUTO_FOCUS = 1001;//自动对焦 private final int TAKE_PHOTO_FINISH = 1002;//拍完 private final int FOCUS_DURATION = 3000;//延迟聚焦 // private final int FOCUS_YAOYIYAO = 111000; private boolean safeToTakePicture = true; private boolean isPortrait = true; int cameraCurrentlyLocked; private int defaultCameraId = 1; //1为后置摄像头 int cameraPosition = 1; int tmpCamera = 0; private int orientationState = ScreenSwitchUtils.ORIENTATION_HEAD_IS_UP; private int mScreenHeight, mScreenWidth; private int viewHeight; boolean isShow = false; boolean isShowCamera = false; //是否是手动切换摄像头 boolean isChange = false; @SuppressLint("HandlerLeak") private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { Log.e(TAG, "-----hand=" + msg.what); switch (msg.what) { case FLAG_AUTO_FOCUS: //闪光灯 try { if (mCamera != null && safeToTakePicture && !TextUtils.isEmpty(mCamera.getParameters().getFlashMode())) { mCamera.startPreview(); mCamera.autoFocus(null); //Toast.makeText(CameraActivity.this, "auto focus", Toast.LENGTH_SHORT).show(); } handler.sendEmptyMessageDelayed(FLAG_AUTO_FOCUS, FOCUS_DURATION); }catch (Exception e){ e.printStackTrace(); } break; case TAKE_PHOTO_FINISH: //拍完照片 if (msg.obj == null) { return; } String filePath = msg.obj.toString(); Intent intent = new Intent(W30sCameraActivity.this, PreviewActivity.class); Bitmap bitmapByUrl = getBitmapByUrl(filePath); Log.d("======图1==", filePath + "--" + bitmapByUrl); SharedPreferencesUtils.setParam(W30sCameraActivity.this, "camera", filePath); xiangceIM.setImageBitmap(bitmapByUrl); intent.putExtra("filePath", filePath); startActivity(intent); break; case 1111: byte[] b = (byte[]) msg.obj; handleAndSaveBitmap(b); break; } } }; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.e(TAG, "-----onCreate---"); // Hide the window title. requestWindowFeature(Window.FEATURE_NO_TITLE); //隐藏状态栏 //设置当前窗体为全屏显示-----------------定义全屏参数 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); //setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//强制横屏 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//【旋转问题】首先强制竖屏,手机横过来时候 控件不变 setContentView(R.layout.w30s_camera_activity); initViews(); IntentFilter intentFilter = new IntentFilter(W37BleOperateManager.X_WATCH_TAKE_PHOTO); intentFilter.addAction(W37_CAMERA_TAKE_PHOTO); registerReceiver(myBroadcastReceiver,intentFilter); verticalDevice(); } private void initViews() { //【重力感应处理】 app内锁定横屏 或用户锁定横屏时候获得方向 mScreenSwitchInstance = ScreenSwitchUtils.init(getApplicationContext()); findViewById(R.id.image_backes).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); if (!CameraUtils.checkCameraHardware(this)) { // Toast.makeText(W30sCameraActivity.this, "设备没有摄像头", Toast.LENGTH_SHORT).show(); finish(); return; } init(); DoubleClick(); // centerWindowView = findViewById(R.id.center_window_view); Log.d("CameraSurfaceView", "CameraSurfaceView onCreate currentThread : " + Thread.currentThread()); // 得到屏幕的大小 WindowManager wManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE); Display display = wManager.getDefaultDisplay(); mScreenHeight = display.getHeight(); mScreenWidth = display.getWidth(); viewHeight = mScreenWidth / 2; //startCamera(); } private void verticalDevice() { Set<String> set = new HashSet<>(Arrays.asList(WatchUtils.TJ_FilterNamas)); if(MyCommandManager.DEVICENAME == null)return; if(WatchUtils.isVPBleDevice(MyCommandManager.DEVICENAME)){ MyApp.getInstance().getVpOperateManager().startCamera(iBleWriteResponse, new ICameraDataListener() { @Override public void OnCameraDataChange(ECameraStatus coStatus) { if (coStatus == ECameraStatus.TAKEPHOTO_CAN) { //拍照 if (isShow) { if (isShowCamera) { takePhonePic(); } } } } }); return; } if(set.contains(MyCommandManager.DEVICENAME)){ //监听 L4Command.CameraOn(new L4M.BTResultListenr() { @Override public void On_Result(String TypeInfo, String StrData, Object DataObj) { final String tTypeInfo = TypeInfo; final String TempStr = StrData; final Object TempObj = DataObj; Log.e(TAG, "inTempStr:" + TempStr); if (TypeInfo.equals(L4M.ERROR) && StrData.equals(L4M.TIMEOUT)) { return; } runOnUiThread(new Runnable() { @Override public void run() { if (tTypeInfo.equals(L4M.RemoteCapOn) && TempStr.equals(L4M.OK)) { Log.e(TAG, " RemoteCapOn"); } if (tTypeInfo.equals(L4M.RemoteCapOFF) && TempStr.equals(L4M.OK)) { Log.e(TAG, " RemoteCapOFF"); } if (tTypeInfo.equals(L4M.RemoteCapTakeCap) && TempStr.equals(L4M.OK)) { Log.e(TAG, " RemoteCapTakeCap"); L4Command.CameraCap_Respone();//响应 takePhonePic(); } } }); } }); } } private IBleWriteResponse iBleWriteResponse = new IBleWriteResponse() { @Override public void onResponse(int i) { } }; @Override protected void onStart() { super.onStart(); Log.e(TAG, "-----onStart---"); //【重力感应处理】 try { mScreenSwitchInstance.start(this); isShowCamera = true; startCamera(); String cameraStute = (String) SharedPreferencesUtils.getParam(W30sCameraActivity.this, "cameraStute", ""); if (!WatchUtils.isEmpty(cameraStute)) { p = mCamera.getParameters(); switch (cameraStute) { case Camera.Parameters.FLASH_MODE_ON:// 拍照时打开闪光灯 p.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO); mCamera.setParameters(p); //如果闪状态为 拍照时打开-----改为-----》》》系统决定 shanguangIM.setImageDrawable(getResources().getDrawable(R.mipmap.camera_flash_auto)); break; case Camera.Parameters.FLASH_MODE_OFF:// 拍照时始终关闭闪光灯 p.setFlashMode(Camera.Parameters.FLASH_MODE_ON); mCamera.setParameters(p); //如果闪关灯状态为 始终关闭-----改为-----》》》拍照时打开 shanguangIM.setImageDrawable(getResources().getDrawable(R.mipmap.camera_flash_on)); break; case Camera.Parameters.FLASH_MODE_AUTO:// 系统决定是否开启闪光灯(推荐使用) p.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); mCamera.setParameters(p); //如果闪状态为 系统决定-----改为-----》》》始终关闭 shanguangIM.setImageDrawable(getResources().getDrawable(R.mipmap.camera_flash_off)); break; } } //注册连接状态的广播 //registerReceiver(myBroadcastReceiver, makeGattUpdateIntentFilter()); //注册舟海手环拍照的广播 MyApp.getInstance().getW37BleOperateManager().registerW37CameraListener(); }catch (Exception e){ e.printStackTrace(); } } Camera.Parameters p; BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Log.e(TAG,"---------camera="+action); if(action == null) return; if (action.equals(W37DataAnalysis.W37_CAMERA_TAKE_PHOTO)) { //舟海系列拍照 if (isShow) { if (isShowCamera) { takePhonePic(); } // handler.sendEmptyMessageDelayed(FOCUS_YAOYIYAO, 6000); } } if(action.equals(W37BleOperateManager.X_WATCH_TAKE_PHOTO)){ //XWatch拍照 if (isShow) { if (isShowCamera) { takePhonePic(); } } } } }; /** * 广播过滤 * * @return */ private static IntentFilter makeGattUpdateIntentFilter() { final IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(W30SBLEServices.ACTION_CAMERA_AVAILABLE_DEVICE);//拍照 return intentFilter; } @Override protected void onResume() { super.onResume(); Log.e(TAG, "-----onResume---"); isShow = true; // startCamera(); //changeCameraTwo(isChange); } @Override protected void onPause() { super.onPause(); Log.e(TAG, "-----onPause---"); stopFocus(); isShow = false; releaseCamera(); } @Override protected void onStop() { super.onStop(); Log.e(TAG, "-----onStop---"); //【重力感应处理】 isShow = false; mScreenSwitchInstance.stop(); } @Override protected void onDestroy() { super.onDestroy(); Log.e(TAG, "-----onDestroy---"); try { Log.e(TAG,"---MyCommandManager.DEVICENAME="+MyCommandManager.DEVICENAME); //退出拍照模式 if (MyCommandManager.DEVICENAME != null) { Set<String> set = new HashSet<>(Arrays.asList(WatchUtils.TJ_FilterNamas)); if (WatchUtils.isVPBleDevice(MyCommandManager.DEVICENAME)) { MyApp.getInstance().getVpOperateManager().stopCamera(iBleWriteResponse, new ICameraDataListener() { @Override public void OnCameraDataChange(ECameraStatus coStatus) { } }); } //腾进达方案,用户信息要同步 else if (!WatchUtils.isEmpty(MyCommandManager.DEVICENAME) || set.contains(MyCommandManager.DEVICENAME)) { //拍照结束时销毁 L4Command.CameraOff(); L4M.SetResultListener(null); } else if(MyCommandManager.DEVICENAME.equals("SWatch")){ XWatchBleAnalysis.getW37DataAnalysis().openOrCloseCamera(0); } } isShow = false; releaseCamera(); unregisterReceiver(myBroadcastReceiver); MyApp.getInstance().getW37BleOperateManager().unRegisterW37CameraListener(); }catch (Exception e){ e.printStackTrace(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); Log.e(TAG, "------CameraSurfaceView imgPath : " + requestCode + "===" + resultCode); if (requestCode == FLAG_CHOOCE_PICTURE && resultCode == RESULT_OK) { isShow = true; startCamera(); } } @Override protected void onRestart() { super.onRestart(); Log.e(TAG, "---onRestart---"); } /** * 根据图片路径获取本地图片的Bitmap * * @param url * @return */ public Bitmap getBitmapByUrl(String url) { FileInputStream fis = null; Bitmap bitmap = null; try { fis = new FileInputStream(url); bitmap = BitmapFactory.decodeStream(fis); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); bitmap = null; } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } fis = null; } } return bitmap; } ImageView xiangtouzhuanIM, shanguangIM, paizhaoIM, xiangceIM; private void init() { id_rl_cp_view = (RelativeLayout) findViewById(R.id.id_rl_cp_view); mCameraPreview = (CameraPreview) findViewById(R.id.camera_preview); mCameraLine = (CameraLine) findViewById(R.id.ccmer_line); xiangtouzhuanIM = (ImageView) findViewById(R.id.xiangtouzhuan); shanguangIM = (ImageView) findViewById(R.id.shanguang); paizhaoIM = (ImageView) findViewById(R.id.paizhao); xiangceIM = (ImageView) findViewById(R.id.xiangce); xiangtouzhuanIM.setOnClickListener(this); shanguangIM.setOnClickListener(this); paizhaoIM.setOnClickListener(this); xiangceIM.setOnClickListener(this); } private void startCamera() { // Open the default i.e. the first rear facing camera. try { if (mCamera == null) { mCamera = Camera.open(tmpCamera); } } catch (Exception e) { e.printStackTrace(); // Toast.makeText(this, "启动照相机失败,请检查设备并打开权限", Toast.LENGTH_SHORT).show(); } cameraCurrentlyLocked = defaultCameraId; mCameraPreview.setCamera(mCamera); startFocus(); } /** * 开启自动对焦 */ private void startFocus() { stopFocus(); handler.sendEmptyMessageDelayed(FLAG_AUTO_FOCUS, FOCUS_DURATION); } /** * 关闭自动对焦 */ private void stopFocus() { handler.removeMessages(FLAG_AUTO_FOCUS); } /** * 释放mCamera */ private void releaseCamera() { // Because the Camera object is a shared resource, it's very // important to release it when the activity is paused. if (mCamera != null) { mCameraPreview.setCamera(null); mCamera.release(); mCamera = null; } } /** * 双击放大缩小 */ private void DoubleClick() { //双击效果 DoubleClickConfig.registerDoubleClickListener(id_rl_cp_view, new DoubleClickConfig.OnDoubleClickListener() { @Override public void OnSingleClick(View v) { // TODO Auto-generated method stub zoomDown();//单机缩小 } @Override public void OnDoubleClick(View v) { // TODO Auto-generated method stub zoomUp();//双击放大 } }); } /** * 缩小 */ public void zoomDown() { if (mCamera == null) { return; } Camera.Parameters p = mCamera.getParameters(); if (!p.isZoomSupported()) return; if (zoomValue > 0) { zoomValue--; } else { zoomValue = 0; // Toast.makeText(getApplicationContext(), "已缩小到最小级别", Toast.LENGTH_SHORT).show(); return; } int value = (int) (1F * zoomValue / ZOOM_FACTOR * p.getMaxZoom()); p.setZoom(value); mCamera.setParameters(p); } /** * 放大 */ public void zoomUp() { if (mCamera == null) { return; } Camera.Parameters p = mCamera.getParameters(); if (!p.isZoomSupported()) return; if (zoomValue < ZOOM_FACTOR) { zoomValue++; } else { zoomValue = ZOOM_FACTOR; // Toast.makeText(getApplicationContext(), "已放大到最大级别", Toast.LENGTH_SHORT).show(); return; } int value = (int) (1F * zoomValue / ZOOM_FACTOR * p.getMaxZoom()); p.setZoom(value); mCamera.setParameters(p); } /** * 拍照 * * @param shutter * @param raw * @param jpeg */ public void takePicture(Camera.ShutterCallback shutter, Camera.PictureCallback raw, Camera.PictureCallback jpeg) { if (mCamera != null) { if (safeToTakePicture) { mCamera.takePicture(shutter, raw, jpeg); safeToTakePicture = false; } } } /** * 开关闪光灯 * <p/> * 持续的亮灯FLASH_MODE_TORCH * 闪一下FLASH_MODE_ON * 关闭模式FLASH_MODE_OFF * 自动感应是否要用闪光灯FLASH_MODE_AUTO */ public void toggleFlash() { if (mCamera == null) { return; } /** * Camera.Parameters.FLASH_MODE_ON 拍照时打开闪光灯 * Camera.Parameters.FLASH_MODE_OFF 拍照时始终关闭闪光灯 * Camera.Parameters.FLASH_MODE_AUTO 系统决定是否开启闪光灯(推荐使用) * Camera.Parameters.FLASH_MODE_TORCH 手电筒模式 一直开着闪光灯。 */ if (p == null) { p = mCamera.getParameters(); } String cameraStute = (String) SharedPreferencesUtils.getParam(W30sCameraActivity.this, "cameraStute", ""); if (!WatchUtils.isEmpty(cameraStute)) { p = mCamera.getParameters(); switch (cameraStute) { case Camera.Parameters.FLASH_MODE_ON:// 拍照时打开闪光灯 p.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO); mCamera.setParameters(p); //如果闪状态为 拍照时打开-----改为-----》》》系统决定 shanguangIM.setImageDrawable(getResources().getDrawable(R.mipmap.camera_flash_auto)); break; case Camera.Parameters.FLASH_MODE_OFF:// 拍照时始终关闭闪光灯 p.setFlashMode(Camera.Parameters.FLASH_MODE_ON); mCamera.setParameters(p); //如果闪关灯状态为 始终关闭-----改为-----》》》拍照时打开 shanguangIM.setImageDrawable(getResources().getDrawable(R.mipmap.camera_flash_on)); break; case Camera.Parameters.FLASH_MODE_AUTO:// 系统决定是否开启闪光灯(推荐使用) p.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); mCamera.setParameters(p); //如果闪状态为 系统决定-----改为-----》》》始终关闭 shanguangIM.setImageDrawable(getResources().getDrawable(R.mipmap.camera_flash_off)); break; } } // if (Camera.Parameters.FLASH_MODE_OFF.equals(p.getFlashMode())) { // p.setFlashMode(Camera.Parameters.FLASH_MODE_ON); // mCamera.setParameters(p); // shanguangIM.setImageDrawable(getResources().getDrawable(R.mipmap.camera_flash_on)); // } else if (Camera.Parameters.FLASH_MODE_ON.equals(p.getFlashMode())) { // p.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO); // mCamera.setParameters(p); // shanguangIM.setImageDrawable(getResources().getDrawable(R.mipmap.camera_flash_auto)); // } else if (Camera.Parameters.FLASH_MODE_AUTO.equals(p.getFlashMode())) { // p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);//持续的亮灯 // mCamera.setParameters(p); // shanguangIM.setImageDrawable(getResources().getDrawable(R.mipmap.camera_flash_light)); // } else if (Camera.Parameters.FLASH_MODE_TORCH.equals(p.getFlashMode())) { // p.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); // mCamera.setParameters(p); // shanguangIM.setImageDrawable(getResources().getDrawable(R.mipmap.camera_flash_off)); // } else { // Toast.makeText(this, "Flash mode setting is not supported.", Toast.LENGTH_SHORT).show(); // } } /** * 切换前后相投 */ void changeCameraTwo(boolean ischange) { //切换前后摄像头 int cameraCount = 0; Camera.CameraInfo cameraInfo = new Camera.CameraInfo(); cameraCount = Camera.getNumberOfCameras();//得到摄像头的个数 if (mCamera == null) return; Log.e(TAG, "---cameraPosition=" + cameraPosition); for (int i = 0; i < cameraCount; i++) { Camera.getCameraInfo(i, cameraInfo);//得到每一个摄像头的信息 if (cameraPosition == 1) { // Toast.makeText(this, "1现在是后置,变更为前置", Toast.LENGTH_SHORT).show(); //现在是后置,变更为前置 if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {//代表摄像头的方位,CAMERA_FACING_FRONT前置 CAMERA_FACING_BACK后置 mCamera.stopPreview();//停掉原来摄像头的预览 /* mCamera.release();//释放资源 mCamera = null;//取消原来摄像头*/ releaseCamera(); mCamera = Camera.open(i);//打开当前选中的摄像头 tmpCamera = i; Log.e(TAG, "---22--tmp-=" + tmpCamera + "--i=" + i); try { mCamera.setPreviewDisplay(mCameraPreview.getLouisSurfaceHolder());//通过surfaceview显示取景画面 mCamera.setDisplayOrientation(90); // mCameraPreview.setCamera(mCamera); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } mCamera.startPreview();//开始预览 cameraPosition = 0; break; } } else { // Toast.makeText(this, "2现在是前置, 变更为后置", Toast.LENGTH_SHORT).show(); //现在是前置, 变更为后置 if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {//代表摄像头的方位,CAMERA_FACING_FRONT前置 CAMERA_FACING_BACK后置 mCamera.stopPreview();//停掉原来摄像头的预览 /* mCamera.release();//释放资源 mCamera = null;//取消原来摄像头*/ releaseCamera(); mCamera = Camera.open(i);//打开当前选中的摄像头 tmpCamera = i; Log.e(TAG, "---22--tmp-=" + tmpCamera + "--i=" + i); try { mCamera.setPreviewDisplay(mCameraPreview.getLouisSurfaceHolder());//通过surfaceview显示取景画面 mCamera.setDisplayOrientation(90); // mCameraPreview.setCamera(mCamera); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } mCamera.startPreview();//开始预览 cameraPosition = 1; break; } } } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.xiangtouzhuan: isChange = true; changeCameraTwo(isChange); break; case R.id.shanguang: toggleFlash(); break; case R.id.paizhao: if (isShowCamera) { takePhonePic(); } break; case R.id.xiangce: choosePicture(); break; } } public void takePhonePic() { try { stopFocus(); takePicture(null, null, new Camera.PictureCallback() { @Override public void onPictureTaken(byte[] data, Camera camera) { if (data == null || data.length <= 0) { safeToTakePicture = true; return; } Log.d("CameraSurfaceView", "CameraSurfaceView onPictureTaken data.length : " + data.length); isPortrait = mScreenSwitchInstance.isPortrait(); orientationState = mScreenSwitchInstance.getOrientationState(); Log.e("==========", "louis==xx==isPortrait:" + isPortrait); Log.e("=========", "louis==xx==orientationState:" + orientationState); // 保存图片 final byte[] b = data; new Thread(new Runnable() { @Override public void run() { Message message = new Message(); message.obj = b; message.what = 1111; handler.sendMessage(message); isShowCamera = false; safeToTakePicture = true; } }).start(); } }); } catch (Exception e) { e.printStackTrace(); } } /** * 查看拍摄的图片 */ private void choosePicture() { startActivity(W30sAlbumActivity.class); } /** * 处理拍照图片并保存 * * @param data */ private Bitmap rightBitmap; private synchronized void handleAndSaveBitmap(byte[] data) { // 保存图片 //### Bitmap b = BitmapFactory.decodeByteArray(data, 0, data.length); //Bitmap b = CameraUtils.Bytes2Bitmap(data); Bitmap b = CameraUtils.byteToBitmap(data); Log.e(TAG, "----handleAndSaveBitmap--cameraPosition=" + cameraPosition + "--=" + orientationState); if (cameraPosition == 1) { //后置摄像头 //rightBitmap = Utils.rotate(b, 0); rightBitmap = CameraUtils.rotate(b, 90);//摆正位置 //rightBitmap = Utils.rotate(b, 180); // rightBitmap = Utils.rotate(b, 270); //根据重力感应 更正旋转 switch (orientationState) { case ScreenSwitchUtils.ORIENTATION_HEAD_IS_UP: break; case ScreenSwitchUtils.ORIENTATION_HEAD_IS_DOWN: rightBitmap = CameraUtils.rotate(rightBitmap, 180); break; case ScreenSwitchUtils.ORIENTATION_HEAD_IS_LEFT: rightBitmap = CameraUtils.rotate(rightBitmap, 270); break; case ScreenSwitchUtils.ORIENTATION_HEAD_IS_RIGHT: rightBitmap = CameraUtils.rotate(rightBitmap, 90); break; } } else { //前置摄像头 rightBitmap = CameraUtils.rotate(b, 270);//摆正位置 //根据重力感应 更正旋转 switch (orientationState) { case ScreenSwitchUtils.ORIENTATION_HEAD_IS_UP: // if(isChange){ // rightBitmap = CameraUtils.rotate(rightBitmap, 180); // } break; case ScreenSwitchUtils.ORIENTATION_HEAD_IS_DOWN: rightBitmap = CameraUtils.rotate(rightBitmap, 180); break; case ScreenSwitchUtils.ORIENTATION_HEAD_IS_LEFT: rightBitmap = CameraUtils.rotate(rightBitmap, 90); break; case ScreenSwitchUtils.ORIENTATION_HEAD_IS_RIGHT: rightBitmap = CameraUtils.rotate(rightBitmap, 270); break; } } if (rightBitmap != null) { String filePath = saveImageToGallery(W30sCameraActivity.this, rightBitmap); // String filePath = saveImageFile(W30sCameraActivity.this, rightBitmap); Message message = handler.obtainMessage(); message.what = TAKE_PHOTO_FINISH; message.obj = filePath; message.sendToTarget(); } } // // private String saveImageFile(Context context, Bitmap bmp) { // String filePath = null; // File file = Utils.getDiskCacheDir(this, "B30"); // if (!file.exists()) { // file.mkdirs(); // } //// File f = new File(file, "picture.jpg"); // String fileName = System.currentTimeMillis() + ".jpg"; // File f = new File(file, fileName); // try { // BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f)); // bmp.compress(Bitmap.CompressFormat.JPEG, 100, bos); // bos.flush(); // bos.close(); // filePath = f.getAbsolutePath(); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } finally { // if (bmp != null && !bmp.isRecycled()) { // bmp.recycle(); // bmp = null; // } // // 其次把文件插入到系统图库 // try { // MediaStore.Images.Media.insertImage(context.getContentResolver(), // file.getAbsolutePath(), fileName, null); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } // // 最后通知图库更新 // context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + f))); // } // return filePath; // } public static String saveImageToGallery(Context context, Bitmap bmp) { String filePath = null; // 首先保存图片 File appDir = new File(Environment.getExternalStorageDirectory(), "/Pictures"); if (!appDir.exists()) { appDir.mkdir(); } String fileName = System.currentTimeMillis() + ".jpg"; File file = new File(appDir, fileName); Log.d("======图==", file + ""); try { FileOutputStream fos = new FileOutputStream(file); bmp.compress(Bitmap.CompressFormat.JPEG, 70, fos); fos.flush(); fos.close(); filePath = file.getAbsolutePath(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // // 其次把文件插入到系统图库 // try { // MediaStore.Images.Media.insertImage(context.getContentResolver(), // file.getAbsolutePath(), fileName, null); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } // 最后通知图库更新 // context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(String.valueOf(appDir)))); // context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + "w30s/pic"))); if (bmp != null && !bmp.isRecycled()) { bmp.recycle(); bmp = null; } return filePath; } /** * 获取从相册中选择的图片的据对路径 * * @param uri * @return */ private String getUrl(Uri uri) { if (uri == null) { return null; } String[] proj = {MediaStore.Images.Media.DATA}; Cursor actualimagecursor = managedQuery(uri, proj, null, null, null); int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); actualimagecursor.moveToFirst(); String img_path = actualimagecursor.getString(actual_image_column_index); return TextUtils.isEmpty(img_path) ? null : img_path; } }
package org.app.exp; import java.util.Scanner; public class RemoveWhiteSpace { public void removeWhiteSpace(String input) { String result = " "; result = input.trim(); System.out.println(result); }// method public static void main(String[] args) { // get Scanner class object Scanner sc = new Scanner(System.in); System.out.println("Enter Any String :"); String input = sc.nextLine(); // method call new RemoveWhiteSpace().removeWhiteSpace(input); // close Scanner class object sc.close(); }// main }// class
package org.knowm.xchart.internal.series; import java.awt.*; /** * A Series containing X and Y data to be plotted on a Chart with X and Y Axes. * * @author timmolter */ public abstract class AxesChartSeries extends Series { final DataType xAxisDataType; final DataType yAxisType; /** the minimum value of axis range */ protected double xMin; /** the maximum value of axis range */ protected double xMax; /** the minimum value of axis range */ protected double yMin; /** the maximum value of axis range */ protected double yMax; /** Line Style */ private BasicStroke stroke; /** Line Color */ private Color lineColor; /** Line Width */ private float lineWidth = -1.0f; /** * Constructor * * @param name * @param xAxisDataType */ protected AxesChartSeries(String name, DataType xAxisDataType) { super(name); this.xAxisDataType = xAxisDataType; yAxisType = DataType.Number; } /** * Constructor * * @param name * @param xAxisDataType * @param yAxisDataType */ protected AxesChartSeries(String name, DataType xAxisDataType, DataType yAxisDataType) { super(name); this.xAxisDataType = xAxisDataType; this.yAxisType = yAxisDataType; } protected abstract void calculateMinMax(); public double getXMin() { return xMin; } public double getXMax() { return xMax; } public double getYMin() { return yMin; } public double getYMax() { return yMax; } public BasicStroke getLineStyle() { return stroke; } /** * Set the line style of the series * * @param basicStroke */ public AxesChartSeries setLineStyle(BasicStroke basicStroke) { stroke = basicStroke; if (this.lineWidth > 0.0f) { stroke = new BasicStroke( lineWidth, this.stroke.getEndCap(), this.stroke.getLineJoin(), this.stroke.getMiterLimit(), this.stroke.getDashArray(), this.stroke.getDashPhase()); } return this; } public Color getLineColor() { return lineColor; } /** * Set the line color of the series * * @param color */ public AxesChartSeries setLineColor(java.awt.Color color) { this.lineColor = color; return this; } public float getLineWidth() { return lineWidth; } /** * Set the line width of the series * * @param lineWidth */ public AxesChartSeries setLineWidth(float lineWidth) { this.lineWidth = lineWidth; return this; } public DataType getxAxisDataType() { return xAxisDataType; } public DataType getyAxisDataType() { return yAxisType; } }
package geometry; import java.awt.geom.*; import java.util.Random; public class SegmentsIntersection { public static boolean isCrossIntersect(long x1, long y1, long x2, long y2, long x3, long y3, long x4, long y4) { long z1 = (x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1); long z2 = (x2 - x1) * (y4 - y1) - (y2 - y1) * (x4 - x1); long z3 = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3); long z4 = (x4 - x3) * (y2 - y3) - (y4 - y3) * (x2 - x3); return (z1 < 0 || z2 < 0) && (z1 > 0 || z2 > 0) && (z3 < 0 || z4 < 0) && (z3 > 0 || z4 > 0); } public static boolean isCrossOrTouchIntersect(long x1, long y1, long x2, long y2, long x3, long y3, long x4, long y4) { if (Math.max(x1, x2) < Math.min(x3, x4) || Math.max(x3, x4) < Math.min(x1, x2) || Math.max(y1, y2) < Math.min(y3, y4) || Math.max(y3, y4) < Math.min(y1, y2)) return false; long z1 = (x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1); long z2 = (x2 - x1) * (y4 - y1) - (y2 - y1) * (x4 - x1); long z3 = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3); long z4 = (x4 - x3) * (y2 - y3) - (y4 - y3) * (x2 - x3); return (z1 <= 0 || z2 <= 0) && (z1 >= 0 || z2 >= 0) && (z3 <= 0 || z4 <= 0) && (z3 >= 0 || z4 >= 0); } public static Point2D.Double getLinesIntersection(long x1, long y1, long x2, long y2, long x3, long y3, long x4, long y4) { long a1 = y2 - y1; long b1 = x1 - x2; long c1 = -(x1 * y2 - x2 * y1); long a2 = y4 - y3; long b2 = x3 - x4; long c2 = -(x3 * y4 - x4 * y3); long det = a1 * b2 - a2 * b1; if (det == 0) return null; double x = -(c1 * b2 - c2 * b1) / (double) det; double y = -(a1 * c2 - a2 * c1) / (double) det; return new Point2D.Double(x, y); } // random tests public static void main(String[] args) { Random rnd = new Random(); for (int step = 0; step < 1000_000; step++) { int r = 10; int x1 = rnd.nextInt(r) - r / 2; int y1 = rnd.nextInt(r) - r / 2; int x2 = rnd.nextInt(r) - r / 2; int y2 = rnd.nextInt(r) - r / 2; int x3 = rnd.nextInt(r) - r / 2; int y3 = rnd.nextInt(r) - r / 2; int x4 = rnd.nextInt(r) - r / 2; int y4 = rnd.nextInt(r) - r / 2; boolean crossIntersect = isCrossIntersect(x1, y1, x2, y2, x3, y3, x4, y4); boolean crossOrTouchIntersect = isCrossOrTouchIntersect(x1, y1, x2, y2, x3, y3, x4, y4); boolean crossOrTouchIntersect2 = Line2D.linesIntersect(x1, y1, x2, y2, x3, y3, x4, y4); crossOrTouchIntersect2 &= !(x1 == x2 && y1 == y2 && x3 == x4 && y3 == y4 && (x1 != x3 || y1 != y3)); // applying fix if (crossOrTouchIntersect != crossOrTouchIntersect2 || crossIntersect && !crossOrTouchIntersect) throw new RuntimeException(); } System.out.println(getLinesIntersection(0, 0, 4, 2, 2, -1, 2, 5).equals(new Point2D.Double(2, 1))); } }
/* * Copyright 2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.internal.resource.local; import org.gradle.internal.resource.ResourceNotFoundException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; public class FileLocalResource implements LocalResource { private final File file; public FileLocalResource(File file) { this.file = file; } @Override public long getContentLength() { return file.length(); } public InputStream open() { try { return new FileInputStream(file); } catch (FileNotFoundException e) { throw new ResourceNotFoundException(file.toURI(), String.format("File '%s' does not exist.", file), e); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.openstack.glance.springboot; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Generated; import org.apache.camel.CamelContext; import org.apache.camel.component.openstack.glance.GlanceComponent; import org.apache.camel.spi.ComponentCustomizer; import org.apache.camel.spi.HasId; import org.apache.camel.spring.boot.CamelAutoConfiguration; import org.apache.camel.spring.boot.ComponentConfigurationProperties; import org.apache.camel.spring.boot.util.CamelPropertiesHelper; import org.apache.camel.spring.boot.util.ConditionalOnCamelContextAndAutoConfigurationBeans; import org.apache.camel.spring.boot.util.GroupCondition; import org.apache.camel.spring.boot.util.HierarchicalPropertiesEvaluator; import org.apache.camel.support.IntrospectionSupport; import org.apache.camel.util.ObjectHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Lazy; /** * Generated by camel-package-maven-plugin - do not edit this file! */ @Generated("org.apache.camel.springboot.maven.SpringBootAutoConfigurationMojo") @Configuration @Conditional({ConditionalOnCamelContextAndAutoConfigurationBeans.class, GlanceComponentAutoConfiguration.GroupConditions.class}) @AutoConfigureAfter(CamelAutoConfiguration.class) @EnableConfigurationProperties({ComponentConfigurationProperties.class, GlanceComponentConfiguration.class}) public class GlanceComponentAutoConfiguration { private static final Logger LOGGER = LoggerFactory .getLogger(GlanceComponentAutoConfiguration.class); @Autowired private ApplicationContext applicationContext; @Autowired private CamelContext camelContext; @Autowired private GlanceComponentConfiguration configuration; @Autowired(required = false) private List<ComponentCustomizer<GlanceComponent>> customizers; static class GroupConditions extends GroupCondition { public GroupConditions() { super("camel.component", "camel.component.openstack-glance"); } } @Lazy @Bean(name = "openstack-glance-component") @ConditionalOnMissingBean(GlanceComponent.class) public GlanceComponent configureGlanceComponent() throws Exception { GlanceComponent component = new GlanceComponent(); component.setCamelContext(camelContext); Map<String, Object> parameters = new HashMap<>(); IntrospectionSupport.getProperties(configuration, parameters, null, false); for (Map.Entry<String, Object> entry : parameters.entrySet()) { Object value = entry.getValue(); Class<?> paramClass = value.getClass(); if (paramClass.getName().endsWith("NestedConfiguration")) { Class nestedClass = null; try { nestedClass = (Class) paramClass.getDeclaredField( "CAMEL_NESTED_CLASS").get(null); HashMap<String, Object> nestedParameters = new HashMap<>(); IntrospectionSupport.getProperties(value, nestedParameters, null, false); Object nestedProperty = nestedClass.newInstance(); CamelPropertiesHelper.setCamelProperties(camelContext, nestedProperty, nestedParameters, false); entry.setValue(nestedProperty); } catch (NoSuchFieldException e) { } } } CamelPropertiesHelper.setCamelProperties(camelContext, component, parameters, false); if (ObjectHelper.isNotEmpty(customizers)) { for (ComponentCustomizer<GlanceComponent> customizer : customizers) { boolean useCustomizer = (customizer instanceof HasId) ? HierarchicalPropertiesEvaluator.evaluate( applicationContext.getEnvironment(), "camel.component.customizer", "camel.component.openstack-glance.customizer", ((HasId) customizer).getId()) : HierarchicalPropertiesEvaluator.evaluate( applicationContext.getEnvironment(), "camel.component.customizer", "camel.component.openstack-glance.customizer"); if (useCustomizer) { LOGGER.debug("Configure component {}, with customizer {}", component, customizer); customizer.customize(component); } } } return component; } }
package mage.cards.r; import mage.MageInt; import mage.abilities.TriggeredAbilityImpl; import mage.abilities.condition.common.SourceTappedCondition; import mage.abilities.effects.common.UntapAllControllerEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.constants.Zone; import mage.filter.common.FilterCreaturePermanent; import mage.game.Game; import mage.game.events.GameEvent; import java.util.UUID; /** * @author TheElk801 */ public final class ReveilleSquad extends CardImpl { public ReveilleSquad(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{2}{W}{W}"); this.subtype.add(SubType.HUMAN); this.subtype.add(SubType.REBEL); this.power = new MageInt(3); this.toughness = new MageInt(3); // Whenever one or more creatures attack you, if Reveille Squad is untapped, you may untap all creatures you control. this.addAbility(new ReveilleSquadTriggeredAbility()); } private ReveilleSquad(final ReveilleSquad card) { super(card); } @Override public ReveilleSquad copy() { return new ReveilleSquad(this); } } class ReveilleSquadTriggeredAbility extends TriggeredAbilityImpl { public ReveilleSquadTriggeredAbility() { super(Zone.BATTLEFIELD, new UntapAllControllerEffect(new FilterCreaturePermanent("all creatures you control")), true); } public ReveilleSquadTriggeredAbility(final ReveilleSquadTriggeredAbility ability) { super(ability); } @Override public ReveilleSquadTriggeredAbility copy() { return new ReveilleSquadTriggeredAbility(this); } @Override public boolean checkEventType(GameEvent event, Game game) { return event.getType() == GameEvent.EventType.DECLARED_ATTACKERS; } @Override public boolean checkTrigger(GameEvent event, Game game) { for (UUID attackerId : game.getCombat().getAttackers()) { if (game.getCombat().getDefenderId(attackerId).equals(controllerId)) { return true; } } return false; } @Override public boolean checkInterveningIfClause(Game game) { return SourceTappedCondition.UNTAPPED.apply(game, this); } @Override public String getRule() { return "Whenever one or more creatures attack you, if {this} is untapped, you may untap all creatures you control."; } }
package com.phl.print.plugin.logline.code; import com.phl.print.plugin.logline.PrintExtUtil; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; public class LinelogClassAdapter extends ClassVisitor implements Opcodes { private String className; public LinelogClassAdapter(ClassVisitor classVisitor) { super(ASM5, classVisitor); } @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { super.visit(version, access, name, signature, superName, interfaces); this.className = name; } @Override public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) { MethodVisitor mv = cv.visitMethod(access, name, descriptor, signature, exceptions); if (PrintExtUtil.getInstance().ignorePackageNames(className)) { return mv; } return null == mv ? null : new LinelogMethodAdapter(mv); } }
/* * Roughly Enough Items by Danielshe. * Licensed under the MIT License. */ package me.shedaniel.rei.plugin; import com.google.common.collect.Lists; import me.shedaniel.rei.api.RecipeDisplay; import net.minecraft.block.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.recipe.Ingredient; import net.minecraft.recipe.Recipe; import net.minecraft.util.Identifier; import java.util.*; public class DefaultBrewingDisplay implements RecipeDisplay { private ItemStack input, output; private Ingredient reactant; public DefaultBrewingDisplay(ItemStack input, Ingredient reactant, ItemStack output) { this.input = input; this.reactant = reactant; this.output = output; } @Override public Optional<Recipe> getRecipe() { return Optional.empty(); } @Override public List<List<ItemStack>> getInput() { return Lists.newArrayList(Collections.singletonList(input), Arrays.asList(reactant.getStackArray())); } @Override public List<ItemStack> getOutput() { return Collections.singletonList(output); } @Override public Identifier getRecipeCategory() { return DefaultPlugin.BREWING; } public List<ItemStack> getOutput(int slot) { List<ItemStack> stack = new ArrayList<>(); for(int i = 0; i < slot * 2; i++) stack.add(new ItemStack(Blocks.AIR)); for(int i = 0; i < 6 - slot * 2; i++) stack.addAll(getOutput()); return stack; } @Override public List<List<ItemStack>> getRequiredItems() { return Collections.singletonList(Collections.singletonList(ItemStack.EMPTY)); } }
package skadistats.clarity.processor.packet; import org.xerial.snappy.Snappy; import skadistats.clarity.io.bitstream.BitStream; import skadistats.clarity.event.Provides; import skadistats.clarity.source.Source; import java.io.IOException; @Provides({ UsesPacketReader.class }) public class PacketReader { public byte[] readFromSource(Source source, int size, boolean isCompressed) throws IOException { byte[] buf = new byte[size]; source.readBytes(buf, 0, size); if (isCompressed) { return Snappy.uncompress(buf); } else { return buf; } } public byte[] readFromBitStream(BitStream bs, int size) throws IOException { byte[] buf = new byte[(size + 7) / 8]; bs.readBitsIntoByteArray(buf, size); return buf; } }
package com.geli.gmall.pms.entity; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import java.util.Date; import lombok.Data; /** * spu属性值 * @author jiangli * @since 2020-06-19 15:19:43 */ @ApiModel @Data @TableName("pms_product_attr_value") public class ProductAttrValue implements Serializable { private static final long serialVersionUID = 1L; /** * id */ @TableId @ApiModelProperty(name = "id",value = "id") private Long id; /** * 商品id */ @ApiModelProperty(name = "spuId",value = "商品id") private Long spuId; /** * 属性id */ @ApiModelProperty(name = "attrId",value = "属性id") private Long attrId; /** * 属性名 */ @ApiModelProperty(name = "attrName",value = "属性名") private String attrName; /** * 属性值 */ @ApiModelProperty(name = "attrValue",value = "属性值") private String attrValue; /** * 顺序 */ @ApiModelProperty(name = "attrSort",value = "顺序") private Integer attrSort; /** * 快速展示【是否展示在介绍上;0-否 1-是】 */ @ApiModelProperty(name = "quickShow",value = "快速展示【是否展示在介绍上;0-否 1-是】") private Integer quickShow; }
/* * 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.beam.sdk.io; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeFalse; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.nio.channels.Channels; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.List; import org.apache.beam.sdk.io.fs.CreateOptions.StandardCreateOptions; import org.apache.beam.sdk.io.fs.MatchResult; import org.apache.beam.sdk.io.fs.ResolveOptions.StandardResolveOptions; import org.apache.beam.sdk.testing.RestoreSystemProperties; import org.apache.beam.sdk.util.MimeTypes; import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.FluentIterable; import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableList; import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.Iterables; import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.Lists; import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.io.Files; import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.io.LineReader; import org.apache.commons.lang3.SystemUtils; import org.hamcrest.Matchers; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link LocalFileSystem}. */ @RunWith(JUnit4.class) @SuppressWarnings({ "nullness" // TODO(https://issues.apache.org/jira/browse/BEAM-10402) }) public class LocalFileSystemTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @Rule public RestoreSystemProperties restoreSystemProperties = new RestoreSystemProperties(); private LocalFileSystem localFileSystem = new LocalFileSystem(); @Test public void testCreateWithExistingFile() throws Exception { File existingFile = temporaryFolder.newFile(); testCreate(existingFile.toPath()); } @Test public void testCreateWithinExistingDirectory() throws Exception { testCreate(temporaryFolder.getRoot().toPath().resolve("file.txt")); } @Test public void testCreateWithNonExistentSubDirectory() throws Exception { testCreate(temporaryFolder.getRoot().toPath().resolve("non-existent-dir").resolve("file.txt")); } private void testCreate(Path path) throws Exception { String expected = "my test string"; // First with the path string createFileWithContent(path, expected); assertThat( Files.readLines(path.toFile(), StandardCharsets.UTF_8), containsInAnyOrder(expected)); // Delete the file before trying as URI assertTrue("Unable to delete file " + path, path.toFile().delete()); // Second with the path URI createFileWithContent(Paths.get(path.toUri()), expected); assertThat( Files.readLines(path.toFile(), StandardCharsets.UTF_8), containsInAnyOrder(expected)); } @Test public void testReadWithExistingFile() throws Exception { String expected = "my test string"; File existingFile = temporaryFolder.newFile(); Files.write(expected, existingFile, StandardCharsets.UTF_8); String data; try (Reader reader = Channels.newReader( localFileSystem.open( LocalResourceId.fromPath(existingFile.toPath(), false /* isDirectory */)), StandardCharsets.UTF_8.name())) { data = new LineReader(reader).readLine(); } assertEquals(expected, data); } @Test public void testReadNonExistentFile() throws Exception { thrown.expect(FileNotFoundException.class); localFileSystem .open( LocalResourceId.fromPath( temporaryFolder.getRoot().toPath().resolve("non-existent-file.txt"), false /* isDirectory */)) .close(); } private void assertContents(List<Path> destFiles, List<String> contents) throws Exception { for (int i = 0; i < destFiles.size(); ++i) { assertThat( Files.readLines(destFiles.get(i).toFile(), StandardCharsets.UTF_8), containsInAnyOrder(contents.get(i))); } } @Test public void testCopyWithExistingSrcFile() throws Exception { Path srcPath1 = temporaryFolder.newFile().toPath(); Path srcPath2 = temporaryFolder.newFile().toPath(); Path destPath1 = temporaryFolder.getRoot().toPath().resolve("nonexistentdir").resolve("dest1"); Path destPath2 = srcPath2.resolveSibling("dest2"); createFileWithContent(srcPath1, "content1"); createFileWithContent(srcPath2, "content2"); localFileSystem.copy( toLocalResourceIds(ImmutableList.of(srcPath1, srcPath2), false /* isDirectory */), toLocalResourceIds(ImmutableList.of(destPath1, destPath2), false /* isDirectory */)); assertContents( ImmutableList.of(destPath1, destPath2), ImmutableList.of("content1", "content2")); } @Test public void testMoveWithExistingSrcFile() throws Exception { Path srcPath1 = temporaryFolder.newFile().toPath(); Path srcPath2 = temporaryFolder.newFile().toPath(); Path destPath1 = temporaryFolder.getRoot().toPath().resolve("nonexistentdir").resolve("dest1"); Path destPath2 = srcPath2.resolveSibling("dest2"); createFileWithContent(srcPath1, "content1"); createFileWithContent(srcPath2, "content2"); localFileSystem.rename( toLocalResourceIds(ImmutableList.of(srcPath1, srcPath2), false /* isDirectory */), toLocalResourceIds(ImmutableList.of(destPath1, destPath2), false /* isDirectory */)); assertContents( ImmutableList.of(destPath1, destPath2), ImmutableList.of("content1", "content2")); assertFalse(srcPath1 + "exists", srcPath1.toFile().exists()); assertFalse(srcPath2 + "exists", srcPath2.toFile().exists()); } @Test public void testDelete() throws Exception { File f1 = temporaryFolder.newFile("file1"); File f2 = temporaryFolder.newFile("file2"); File f3 = temporaryFolder.newFile("other-file"); localFileSystem.delete( toLocalResourceIds(Lists.newArrayList(f1.toPath(), f2.toPath()), false /* isDirectory */)); assertFalse(f1.exists()); assertFalse(f2.exists()); assertTrue(f3.exists()); } @Test public void testMatchWithGlob() throws Exception { String globPattern = "/A/a=[0-9][0-9][0-9]/*/*"; File baseFolder = temporaryFolder.newFolder("A"); File folder1 = new File(baseFolder, "a=100"); File folder2 = new File(baseFolder, "a=233"); File dataFolder1 = new File(folder1, "data1"); File dataFolder2 = new File(folder2, "data_dir"); File expectedFile1 = new File(dataFolder1, "file1"); File expectedFile2 = new File(dataFolder2, "data_file2"); createEmptyFile(expectedFile1); createEmptyFile(expectedFile2); List<String> expected = ImmutableList.of(expectedFile1.getAbsolutePath(), expectedFile2.getAbsolutePath()); List<MatchResult> matchResults = matchGlobWithPathPrefix(temporaryFolder.getRoot().toPath(), globPattern); assertThat( toFilenames(matchResults), containsInAnyOrder(expected.toArray(new String[expected.size()]))); } @Test public void testMatchRelativeWildcardPath() throws Exception { File baseFolder = temporaryFolder.newFolder("A"); File expectedFile1 = new File(baseFolder, "file1"); expectedFile1.createNewFile(); List<String> expected = ImmutableList.of(expectedFile1.getAbsolutePath()); // This no longer works: // System.setProperty("user.dir", temporaryFolder.getRoot().toString()); // There is no way to set the working directory without forking. Instead we // call in to the helper method that gives just about as good test coverage. List<MatchResult> matchResults = localFileSystem.match(temporaryFolder.getRoot().toString(), ImmutableList.of("A/*")); assertThat( toFilenames(matchResults), containsInAnyOrder(expected.toArray(new String[expected.size()]))); } @Test public void testMatchExact() throws Exception { List<String> expected = ImmutableList.of(temporaryFolder.newFile("a").toString()); temporaryFolder.newFile("aa"); temporaryFolder.newFile("ab"); List<MatchResult> matchResults = localFileSystem.match( ImmutableList.of(temporaryFolder.getRoot().toPath().resolve("a").toString())); assertThat( toFilenames(matchResults), containsInAnyOrder(expected.toArray(new String[expected.size()]))); } @Test public void testMatchDirectory() throws Exception { final Path dir = temporaryFolder.newFolder("dir").toPath(); final MatchResult matchResult = Iterables.getOnlyElement(localFileSystem.match(Collections.singletonList(dir.toString()))); assertThat( matchResult, equalTo( MatchResult.create( MatchResult.Status.OK, ImmutableList.of( MatchResult.Metadata.builder() .setResourceId(LocalResourceId.fromPath(dir, true)) .setIsReadSeekEfficient(true) .setSizeBytes(dir.toFile().length()) .setLastModifiedMillis(dir.toFile().lastModified()) .build())))); } @Test public void testMatchPatternNone() throws Exception { temporaryFolder.newFile("a"); temporaryFolder.newFile("aa"); temporaryFolder.newFile("ab"); List<MatchResult> matchResults = matchGlobWithPathPrefix(temporaryFolder.getRoot().toPath().resolve("b"), "*"); assertEquals(1, matchResults.size()); assertEquals(MatchResult.Status.NOT_FOUND, matchResults.get(0).status()); } @Test public void testMatchForNonExistentFile() throws Exception { temporaryFolder.newFile("aa"); List<MatchResult> matchResults = localFileSystem.match( ImmutableList.of(temporaryFolder.getRoot().toPath().resolve("a").toString())); assertEquals(1, matchResults.size()); assertEquals(MatchResult.Status.NOT_FOUND, matchResults.get(0).status()); } @Test public void testMatchMultipleWithFileExtension() throws Exception { List<String> expected = ImmutableList.of( temporaryFolder.newFile("a.txt").toString(), temporaryFolder.newFile("aa.txt").toString(), temporaryFolder.newFile("ab.txt").toString()); temporaryFolder.newFile("a.avro"); temporaryFolder.newFile("ab.avro"); List<MatchResult> matchResults = matchGlobWithPathPrefix(temporaryFolder.getRoot().toPath().resolve("a"), "*.txt"); assertThat( toFilenames(matchResults), containsInAnyOrder(expected.toArray(new String[expected.size()]))); } @Test public void testMatchInDirectory() throws Exception { List<String> expected = ImmutableList.of(temporaryFolder.newFile("a").toString()); temporaryFolder.newFile("aa"); temporaryFolder.newFile("ab"); String expectedFile = expected.get(0); int slashIndex = expectedFile.lastIndexOf('/'); if (SystemUtils.IS_OS_WINDOWS) { slashIndex = expectedFile.lastIndexOf('\\'); } String directory = expectedFile.substring(0, slashIndex); String relative = expectedFile.substring(slashIndex + 1); // This no longer works: // System.setProperty("user.dir", directory); // There is no way to set the working directory without forking. Instead we // call in to the helper method that gives just about as good test coverage. List<MatchResult> results = localFileSystem.match(directory, ImmutableList.of(relative)); assertThat( toFilenames(results), containsInAnyOrder(expected.toArray(new String[expected.size()]))); } @Test public void testMatchWithFileSlashPrefix() throws Exception { List<String> expected = ImmutableList.of(temporaryFolder.newFile("a").toString()); temporaryFolder.newFile("aa"); temporaryFolder.newFile("ab"); String file = "file:/" + temporaryFolder.getRoot().toPath().resolve("a").toString(); List<MatchResult> results = localFileSystem.match(ImmutableList.of(file)); assertThat( toFilenames(results), containsInAnyOrder(expected.toArray(new String[expected.size()]))); } @Test public void testMatchWithFileThreeSlashesPrefix() throws Exception { List<String> expected = ImmutableList.of(temporaryFolder.newFile("a").toString()); temporaryFolder.newFile("aa"); temporaryFolder.newFile("ab"); String file = "file:///" + temporaryFolder.getRoot().toPath().resolve("a").toString(); List<MatchResult> results = localFileSystem.match(ImmutableList.of(file)); assertThat( toFilenames(results), containsInAnyOrder(expected.toArray(new String[expected.size()]))); } @Test public void testMatchMultipleWithoutSubdirectoryExpansion() throws Exception { File unmatchedSubDir = temporaryFolder.newFolder("aaa"); File unmatchedSubDirFile = File.createTempFile("sub-dir-file", "", unmatchedSubDir); unmatchedSubDirFile.deleteOnExit(); List<String> expected = ImmutableList.of( temporaryFolder.newFile("a").toString(), temporaryFolder.newFile("aa").toString(), temporaryFolder.newFile("ab").toString()); temporaryFolder.newFile("ba"); temporaryFolder.newFile("bb"); List<MatchResult> matchResults = matchGlobWithPathPrefix(temporaryFolder.getRoot().toPath().resolve("a"), "*"); assertThat( toFilenames(matchResults), containsInAnyOrder(expected.toArray(new String[expected.size()]))); } @Test public void testMatchMultipleWithSubdirectoryExpansion() throws Exception { File matchedSubDir = temporaryFolder.newFolder("a"); File matchedSubDirFile = File.createTempFile("sub-dir-file", "", matchedSubDir); matchedSubDirFile.deleteOnExit(); File unmatchedSubDir = temporaryFolder.newFolder("b"); File unmatchedSubDirFile = File.createTempFile("sub-dir-file", "", unmatchedSubDir); unmatchedSubDirFile.deleteOnExit(); List<String> expected = ImmutableList.of( matchedSubDirFile.toString(), temporaryFolder.newFile("aa").toString(), temporaryFolder.newFile("ab").toString()); temporaryFolder.newFile("ba"); temporaryFolder.newFile("bb"); List<MatchResult> matchResults = matchGlobWithPathPrefix(temporaryFolder.getRoot().toPath().resolve("a"), "**"); assertThat( toFilenames(matchResults), Matchers.hasItems(expected.toArray(new String[expected.size()]))); } @Test public void testMatchWithDirectoryFiltersOutDirectory() throws Exception { List<String> expected = ImmutableList.of(temporaryFolder.newFile("a").toString()); temporaryFolder.newFolder("a_dir_that_should_not_be_matched"); List<MatchResult> matchResults = matchGlobWithPathPrefix(temporaryFolder.getRoot().toPath().resolve("a"), "*"); assertThat( toFilenames(matchResults), containsInAnyOrder(expected.toArray(new String[expected.size()]))); } @Test public void testMatchWithoutParentDirectory() throws Exception { // TODO: Java core test failing on windows, https://issues.apache.org/jira/browse/BEAM-10741 assumeFalse(SystemUtils.IS_OS_WINDOWS); Path pattern = LocalResourceId.fromPath(temporaryFolder.getRoot().toPath(), true /* isDirectory */) .resolve("non_existing_dir", StandardResolveOptions.RESOLVE_DIRECTORY) .resolve("*", StandardResolveOptions.RESOLVE_FILE) .getPath(); assertTrue(toFilenames(localFileSystem.match(ImmutableList.of(pattern.toString()))).isEmpty()); } @Test public void testMatchNewResource() { // TODO: Java core test failing on windows, https://issues.apache.org/jira/browse/BEAM-10742 assumeFalse(SystemUtils.IS_OS_WINDOWS); LocalResourceId fileResource = localFileSystem.matchNewResource("/some/test/resource/path", false /* isDirectory */); LocalResourceId dirResource = localFileSystem.matchNewResource("/some/test/resource/path", true /* isDirectory */); assertNotEquals(fileResource, dirResource); assertThat( fileResource .getCurrentDirectory() .resolve("path", StandardResolveOptions.RESOLVE_DIRECTORY), equalTo(dirResource.getCurrentDirectory())); assertThat( fileResource .getCurrentDirectory() .resolve("path", StandardResolveOptions.RESOLVE_DIRECTORY), equalTo(dirResource.getCurrentDirectory())); assertThat(dirResource.toString(), equalTo("/some/test/resource/path/")); IllegalArgumentException exception = assertThrows( IllegalArgumentException.class, () -> localFileSystem.matchNewResource("/some/test/resource/path/", false)); assertTrue(exception.getMessage().startsWith("Expected file path but received directory path")); } private void createFileWithContent(Path path, String content) throws Exception { try (Writer writer = Channels.newWriter( localFileSystem.create( LocalResourceId.fromPath(path, false /* isDirectory */), StandardCreateOptions.builder().setMimeType(MimeTypes.TEXT).build()), StandardCharsets.UTF_8.name())) { writer.write(content); } } private List<MatchResult> matchGlobWithPathPrefix(Path pathPrefix, String glob) throws IOException { // Windows doesn't like resolving paths with * in glob, so the glob is concatenated as String. return localFileSystem.match(ImmutableList.of(pathPrefix + glob)); } private List<LocalResourceId> toLocalResourceIds(List<Path> paths, final boolean isDirectory) { return FluentIterable.from(paths) .transform(path -> LocalResourceId.fromPath(path, isDirectory)) .toList(); } private List<String> toFilenames(List<MatchResult> matchResults) { return FluentIterable.from(matchResults) .transformAndConcat( matchResult -> { try { return matchResult.metadata(); } catch (IOException e) { throw new RuntimeException(e); } }) .transform(metadata -> ((LocalResourceId) metadata.resourceId()).getPath().toString()) .toList(); } private static void createEmptyFile(File file) throws IOException { if (!file.getParentFile().mkdirs() || !file.createNewFile()) { throw new IOException("Failed creating empty file " + file.getAbsolutePath()); } } }
/* * Copyright 2015 Adobe Systems Incorporated * * 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 aemmocksample.archetype.core.filters; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.engine.EngineConstants; import org.osgi.framework.Constants; import org.osgi.service.component.annotations.Component; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Simple servlet filter component that logs incoming requests. */ @Component(service = Filter.class, property = { Constants.SERVICE_DESCRIPTION + "=Demo to filter incoming requests", EngineConstants.SLING_FILTER_SCOPE + "=" + EngineConstants.FILTER_SCOPE_REQUEST, Constants.SERVICE_RANKING + ":Integer=-700" }) public class LoggingFilter implements Filter { private final Logger logger = LoggerFactory.getLogger(getClass()); @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain filterChain) throws IOException, ServletException { final SlingHttpServletRequest slingRequest = (SlingHttpServletRequest) request; logger.debug("request for {}, with selector {}", slingRequest .getRequestPathInfo().getResourcePath(), slingRequest .getRequestPathInfo().getSelectorString()); filterChain.doFilter(request, response); } @Override public void init(FilterConfig filterConfig) { } @Override public void destroy() { } }
/* * Copyright 2014 OpenMarket Ltd * Copyright 2017 Vector Creations Ltd * Copyright 2018 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.matrix.androidsdk.rest.model; import android.text.TextUtils; import com.google.gson.annotations.SerializedName; import org.matrix.androidsdk.interfaces.DatedObject; import org.matrix.androidsdk.util.ContentManager; import org.matrix.androidsdk.util.Log; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Comparator; /** * Class representing a room member: a user with membership information. */ public class RoomMember implements Externalizable, DatedObject { private static final String LOG_TAG = RoomMember.class.getSimpleName(); public static final String MEMBERSHIP_JOIN = "join"; public static final String MEMBERSHIP_INVITE = "invite"; public static final String MEMBERSHIP_LEAVE = "leave"; public static final String MEMBERSHIP_BAN = "ban"; // not supported by the server sync response by computed from the room state events public static final String MEMBERSHIP_KICK = "kick"; @SerializedName("displayname") public String displayname; @SerializedName("avatar_url") public String avatarUrl; public String membership; public Invite thirdPartyInvite; // tells that the inviter starts a direct chat room @SerializedName("is_direct") public Boolean isDirect; private String userId = null; // timestamp of the event which has created this member private long mOriginServerTs = -1; // the event used to build the room member private String mOriginalEventId = null; // kick / ban reason public String reason; // user which banned or kicked this member public String mSender; @Override public long getDate() { return mOriginServerTs; } @Override public void readExternal(ObjectInput input) throws IOException, ClassNotFoundException { if (input.readBoolean()) { displayname = input.readUTF(); } if (input.readBoolean()) { avatarUrl = input.readUTF(); } if (input.readBoolean()) { membership = input.readUTF(); } if (input.readBoolean()) { thirdPartyInvite = (Invite) input.readObject(); } if (input.readBoolean()) { isDirect = input.readBoolean(); } if (input.readBoolean()) { userId = input.readUTF(); } mOriginServerTs = input.readLong(); if (input.readBoolean()) { mOriginalEventId = input.readUTF(); } if (input.readBoolean()) { reason = input.readUTF(); } if (input.readBoolean()) { mSender = input.readUTF(); } } @Override public void writeExternal(ObjectOutput output) throws IOException { output.writeBoolean(null != displayname); if (null != displayname) { output.writeUTF(displayname); } output.writeBoolean(null != avatarUrl); if (null != avatarUrl) { output.writeUTF(avatarUrl); } output.writeBoolean(null != membership); if (null != membership) { output.writeUTF(membership); } output.writeBoolean(null != thirdPartyInvite); if (null != thirdPartyInvite) { output.writeObject(thirdPartyInvite); } output.writeBoolean(null != isDirect); if (null != isDirect) { output.writeBoolean(isDirect); } output.writeBoolean(null != userId); if (null != userId) { output.writeUTF(userId); } output.writeLong(mOriginServerTs); output.writeBoolean(null != mOriginalEventId); if (null != mOriginalEventId) { output.writeUTF(mOriginalEventId); } output.writeBoolean(null != reason); if (null != reason) { output.writeUTF(reason); } output.writeBoolean(null != mSender); if (null != mSender) { output.writeUTF(mSender); } } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public void setOriginServerTs(long aTs) { mOriginServerTs = aTs; } public long getOriginServerTs() { return mOriginServerTs; } public void setOriginalEventId(String eventId) { mOriginalEventId = eventId; } public String getOriginalEventId() { return mOriginalEventId; } public String getAvatarUrl() { // allow only url which starts with mxc:// if ((null != avatarUrl) && !avatarUrl.toLowerCase().startsWith(ContentManager.MATRIX_CONTENT_URI_SCHEME)) { Log.e(LOG_TAG, "## getAvatarUrl() : the member " + userId + " has an invalid avatar url " + avatarUrl); return null; } return avatarUrl; } public void setAvatarUrl(String anAvatarUrl) { avatarUrl = anAvatarUrl; } public String getThirdPartyInviteToken() { if ((null != thirdPartyInvite) && (null != thirdPartyInvite.signed)) { return thirdPartyInvite.signed.token; } return null; } // Comparator to order members alphabetically public static Comparator<RoomMember> alphaComparator = new Comparator<RoomMember>() { @Override public int compare(RoomMember member1, RoomMember member2) { String lhs = member1.getName(); String rhs = member2.getName(); if (lhs == null) { return -1; } else if (rhs == null) { return 1; } if (lhs.startsWith("@")) { lhs = lhs.substring(1); } if (rhs.startsWith("@")) { rhs = rhs.substring(1); } return String.CASE_INSENSITIVE_ORDER.compare(lhs, rhs); } }; /** * Test if a room member fields matches with a pattern. * The check is done with the displayname and the userId. * * @param aPattern the pattern to search. * @return true if it matches. */ public boolean matchWithPattern(String aPattern) { if (TextUtils.isEmpty(aPattern) || TextUtils.isEmpty(aPattern.trim())) { return false; } boolean res = false; if (!TextUtils.isEmpty(displayname)) { res = (displayname.toLowerCase().indexOf(aPattern) >= 0); } if (!res && !TextUtils.isEmpty(userId)) { res = (userId.toLowerCase().indexOf(aPattern) >= 0); } return res; } /** * Test if a room member matches with a reg ex. * The check is done with the displayname and the userId. * * @param aRegEx the reg ex * @return true if it matches. */ public boolean matchWithRegEx(String aRegEx) { if (TextUtils.isEmpty(aRegEx)) { return false; } boolean res = false; if (!TextUtils.isEmpty(displayname)) { res = displayname.matches(aRegEx); } if (!res && !TextUtils.isEmpty(userId)) { res = userId.matches(aRegEx); } return res; } /** * Compare two members. * The members are equals if each field have the same value. * * @param otherMember the member to compare. * @return true if they define the same member. */ public boolean equals(RoomMember otherMember) { // compare to null if (null == otherMember) { return false; } // compare display name boolean isEqual = TextUtils.equals(displayname, otherMember.displayname); if (isEqual) { isEqual = TextUtils.equals(avatarUrl, otherMember.avatarUrl); } if (isEqual) { isEqual = TextUtils.equals(membership, otherMember.membership); } if (isEqual) { isEqual = TextUtils.equals(userId, otherMember.userId); } return isEqual; } public String getName() { if (displayname != null) { return displayname; } if (userId != null) { return userId; } return null; } /** * Prune the room member data as we would have done with its original state event. */ public void prune() { // Redact redactable data displayname = null; avatarUrl = null; reason = null; // Note: if we had access to the original event content, we should store // the `redacted_because` of the redaction event in it. } public RoomMember deepCopy() { RoomMember copy = new RoomMember(); copy.displayname = displayname; copy.avatarUrl = avatarUrl; copy.membership = membership; copy.userId = userId; copy.mOriginalEventId = mOriginalEventId; copy.mSender = mSender; copy.reason = reason; return copy; } /** * @return true if the user has been banned or kicked */ public boolean kickedOrBanned() { return TextUtils.equals(membership, MEMBERSHIP_KICK) || TextUtils.equals(membership, MEMBERSHIP_BAN); } }
/* * Copyright 2016 Patrick Favre-Bulle * * 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 at.favre.app.hood.demo; import android.content.Context; import android.content.Intent; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Toast; import at.favre.app.hood.demo.databinding.ActivityMoreBinding; import at.favre.lib.hood.Hood; import at.favre.lib.hood.interfaces.actions.ManagerControl; public class MoreActivity extends AppCompatActivity { private ManagerControl shakeControl; public static void start(Context context) { Intent starter = new Intent(context, MoreActivity.class); context.startActivity(starter); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); final ActivityMoreBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_more); shakeControl = Hood.ext().registerShakeToOpenDebugActivity(this, DebugDarkMultiPageActivity.createIntent(this, DebugDarkMultiPageActivity.class)); binding.btnStopShake.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { binding.tvTryShake.setVisibility(View.INVISIBLE); v.setEnabled(false); shakeControl.stop(); } }); binding.tvDoubletap.setOnTouchListener(Hood.ext().createArbitraryTapListener(2, new View.OnClickListener() { @Override public void onClick(View v) { DebugDarkActivity.start(MoreActivity.this, DebugDarkActivity.class); } })); binding.tvTripletap.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { Toast.makeText(MoreActivity.this, "LONG CLICK", Toast.LENGTH_SHORT).show(); return true; } }); binding.tvTripletap.setOnTouchListener(Hood.ext().createArbitraryTapListener(3, new View.OnClickListener() { @Override public void onClick(View v) { DebugLightActivity.start(MoreActivity.this, DebugLightActivity.class); } })); } @Override protected void onResume() { super.onResume(); shakeControl.start(); } @Override protected void onPause() { super.onPause(); shakeControl.stop(); } }
/* * 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 io.netty.buffer; /** * A MutableWrappedByteBuf that also maintains a metric of the number of huge buffer bytes and * counts. */ public class LargeBuffer extends MutableWrappedByteBuf { public LargeBuffer(ByteBuf buffer) { super(buffer); } @Override public ByteBuf copy(int index, int length) { return new LargeBuffer(buffer.copy(index, length)); } }
/* * Copyright 2019 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 androidx.camera.core; import androidx.annotation.GuardedBy; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import androidx.camera.core.impl.ImageReaderProxy; import androidx.camera.core.impl.utils.executor.CameraXExecutors; import androidx.camera.core.impl.utils.futures.FutureCallback; import androidx.camera.core.impl.utils.futures.Futures; import java.lang.ref.WeakReference; import java.util.concurrent.Executor; /** * OnImageAvailableListener with non-blocking behavior. Analyzes images in a non-blocking way by * dropping images when analyzer is busy. * * <p> Used with {@link ImageAnalysis}. */ final class ImageAnalysisNonBlockingAnalyzer extends ImageAnalysisAbstractAnalyzer { // The executor for managing cached image. @SuppressWarnings("WeakerAccess") /* synthetic access */ final Executor mBackgroundExecutor; private final Object mLock = new Object(); // The cached image when analyzer is busy. Image removed from cache must be closed by 1) closing // it directly or 2) re-posting it to close it eventually. @GuardedBy("mLock") @Nullable @VisibleForTesting ImageProxy mCachedImage; // The latest unclosed image sent to the app. @GuardedBy("mLock") @Nullable private CacheAnalyzingImageProxy mPostedImage; ImageAnalysisNonBlockingAnalyzer(Executor executor) { mBackgroundExecutor = executor; } @Nullable @Override ImageProxy acquireImage(@NonNull ImageReaderProxy imageReaderProxy) { // Use acquireLatestImage() so older images should be released. return imageReaderProxy.acquireLatestImage(); } /** * This method guarantees closing the image by either 1) closing the image in the current * thread, 2) caching it for later or 3) posting it to user Thread to close it. * * @param imageProxy the incoming image frame. */ @Override void onValidImageAvailable(@NonNull ImageProxy imageProxy) { synchronized (mLock) { if (!mIsAttached) { imageProxy.close(); return; } if (mPostedImage != null) { // There is unclosed image held by the app. The incoming image has to wait. if (imageProxy.getImageInfo().getTimestamp() <= mPostedImage.getImageInfo().getTimestamp()) { // Discard the incoming image that is in the wrong order. Cached image can be // in this state. imageProxy.close(); } else { // Otherwise cache the incoming image and repost it later. if (mCachedImage != null) { mCachedImage.close(); } mCachedImage = imageProxy; } return; } // Post the incoming image to app. final CacheAnalyzingImageProxy newPostedImage = new CacheAnalyzingImageProxy(imageProxy, this); mPostedImage = newPostedImage; Futures.addCallback(analyzeImage(newPostedImage), new FutureCallback<Void>() { @Override public void onSuccess(Void result) { // No-op. If the post is successful, app should close it. } @Override public void onFailure(Throwable t) { // Close the image if we didn't post it to user. newPostedImage.close(); } }, CameraXExecutors.directExecutor()); } } @Override void clearCache() { synchronized (mLock) { if (mCachedImage != null) { mCachedImage.close(); mCachedImage = null; } } } /** * Removes cached image from cache and analyze it. */ void analyzeCachedImage() { synchronized (mLock) { mPostedImage = null; if (mCachedImage != null) { ImageProxy cachedImage = mCachedImage; mCachedImage = null; onValidImageAvailable(cachedImage); } } } /** * An {@link ImageProxy} that analyze cached image on close. */ static class CacheAnalyzingImageProxy extends ForwardingImageProxy { // WeakReference so that if the app holds onto the ImageProxy instance the analyzer can // still be GCed. final WeakReference<ImageAnalysisNonBlockingAnalyzer> mNonBlockingAnalyzerWeakReference; /** * Creates a new instance which wraps the given image. * * @param image to wrap * @param nonBlockingAnalyzer instance of the nonblocking analyzer */ CacheAnalyzingImageProxy(ImageProxy image, ImageAnalysisNonBlockingAnalyzer nonBlockingAnalyzer) { super(image); mNonBlockingAnalyzerWeakReference = new WeakReference<>(nonBlockingAnalyzer); addOnImageCloseListener((imageProxy) -> { ImageAnalysisNonBlockingAnalyzer analyzer = mNonBlockingAnalyzerWeakReference.get(); if (analyzer != null) { analyzer.mBackgroundExecutor.execute(analyzer::analyzeCachedImage); } }); } } }
package in.edu.ssn.ssnapp.onboarding; import android.net.Uri; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.AccelerateDecelerateInterpolator; import android.widget.ImageView; import androidx.fragment.app.Fragment; import com.bumptech.glide.Glide; import in.edu.ssn.ssnapp.R; public class ThreeFragment extends Fragment { static ImageView hand1IV, hand2IV; static ImageView tempIV; static boolean firstRun = false; public ThreeFragment() { // Required empty public constructor } public static void startAnimation() { firstRun = true; hand1IV.animate() .translationY(tempIV.getBaseline()) .scaleX(1) .scaleY(1) .alpha(1) .setDuration(600) .setInterpolator(new AccelerateDecelerateInterpolator()); hand2IV.animate() .translationY(tempIV.getBaseline()) .scaleX(1) .scaleY(1) .alpha(1) .setDuration(800) .setStartDelay(150) .setInterpolator(new AccelerateDecelerateInterpolator()); } public static void clearAnimation() { hand1IV.animate().translationY(100).alpha(0).scaleX(0).scaleY(0).setDuration(1); hand2IV.animate().translationY(250).alpha(0).scaleX(0).scaleY(0).setDuration(1); OnboardingActivity.firstRun3 = false; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_three, container, false); initUI(view); return view; } private void initUI(View view) { hand1IV = view.findViewById(R.id.hand1IV); hand2IV = view.findViewById(R.id.hand2IV); tempIV = view.findViewById(R.id.tempIV); Glide.with(this).load(Uri.parse("file:///android_asset/onboarding/trees2.png")).into(hand1IV); Glide.with(this).load(Uri.parse("file:///android_asset/onboarding/bench.png")).into(hand2IV); } @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if (isVisibleToUser) { /*if(firstRun){ startAnimation(); }*/ } else { if (firstRun) clearAnimation(); } } }
/** * Copyright 2009-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ibatis.scripting.xmltags; import org.apache.ibatis.builder.SqlSourceBuilder; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.SqlSource; import org.apache.ibatis.session.Configuration; import java.util.Map; /** * @author Clinton Begin * * 用于描述 Mapper XML 文件中配置的SQL资源信息。这些SQL 通常包含动态SQL 配置或者 ${} 信息占位符。需要在 Mapper 调用时才能确定具体SQL 语句。 */ public class DynamicSqlSource implements SqlSource { private final Configuration configuration; private final SqlNode rootSqlNode; public DynamicSqlSource(Configuration configuration, SqlNode rootSqlNode) { this.configuration = configuration; this.rootSqlNode = rootSqlNode; } @Override public BoundSql getBoundSql(Object parameterObject) { // 通过参数对象创建动态 SQL 上下文。 DynamicContext context = new DynamicContext(configuration, parameterObject); /** * 对动态SQL 进行解析(只处理 “${}”)。(组合模式) */ rootSqlNode.apply(context); // 通过SqlSourceBuilder解析"#{}"占位符中的属性,并将SQL语句中的"#{}"占位符替换成"?"占位符 SqlSourceBuilder sqlSourceParser = new SqlSourceBuilder(configuration); Class<?> parameterType = parameterObject == null ? Object.class : parameterObject.getClass(); /** * 对 SQL 内容进一步处理,生成 StaticSqlSource 对象 {@link SqlSourceBuilder#parse(String, Class, Map)} * * 1、获取动态 SQL (将 “#{}” 替换为 “?”)解析后的结果 {@link DynamicContext#getSql()} */ SqlSource sqlSource = sqlSourceParser.parse(context.getSql(), parameterType, context.getBindings()); /** * 获得 boundSql 实例 {@link org.apache.ibatis.builder.StaticSqlSource#getBoundSql(Object)} */ BoundSql boundSql = sqlSource.getBoundSql(parameterObject); /** * 将 <bind> 标签绑定的参数添加到 BoundSql 对象中 {@link BoundSql#setAdditionalParameter(String, Object)} */ context.getBindings().forEach(boundSql::setAdditionalParameter); return boundSql; } }
package com.inova8.odata2sparql.RdfModelToMetadata; import java.util.Map; import java.util.TreeMap; import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind; import com.inova8.odata2sparql.Constants.RdfConstants; public class RdfEdmType { private static final Map<String, EdmPrimitiveTypeKind> SIMPLE_TYPE_MAPPING = new TreeMap<String, EdmPrimitiveTypeKind>(); static { SIMPLE_TYPE_MAPPING.put(RdfConstants.RDF_PLAIN_LITERAL, EdmPrimitiveTypeKind.String); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2000/01/rdf-schema#Literal", EdmPrimitiveTypeKind.String); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#decimal", EdmPrimitiveTypeKind.Decimal); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#Literal", EdmPrimitiveTypeKind.String); SIMPLE_TYPE_MAPPING.put(RdfConstants.XSD_STRING, EdmPrimitiveTypeKind.String); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#boolean", EdmPrimitiveTypeKind.Boolean); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#float", EdmPrimitiveTypeKind.Double); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#double", EdmPrimitiveTypeKind.Double); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#duration", EdmPrimitiveTypeKind.Int16); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#dateTime", EdmPrimitiveTypeKind.DateTimeOffset); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#time", EdmPrimitiveTypeKind.DateTimeOffset); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#date", EdmPrimitiveTypeKind.Date); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#gYearMonth", EdmPrimitiveTypeKind.Date); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#gYear", EdmPrimitiveTypeKind.Date); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#gMonthDay", EdmPrimitiveTypeKind.Date); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#gDay", EdmPrimitiveTypeKind.Date); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#gMonth", EdmPrimitiveTypeKind.Date); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#hexBinary", EdmPrimitiveTypeKind.Binary); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#base64Binary", EdmPrimitiveTypeKind.Binary); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#anyURI", EdmPrimitiveTypeKind.String); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#QName", EdmPrimitiveTypeKind.String); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#NOTATION", EdmPrimitiveTypeKind.String); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#normalizedString", EdmPrimitiveTypeKind.String); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#token", EdmPrimitiveTypeKind.String); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#language", EdmPrimitiveTypeKind.String); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#IDREFS", EdmPrimitiveTypeKind.String); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#ENTITIES", EdmPrimitiveTypeKind.String); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#NMTOKEN", EdmPrimitiveTypeKind.String); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#Name", EdmPrimitiveTypeKind.String); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#NCName", EdmPrimitiveTypeKind.String); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#ID", EdmPrimitiveTypeKind.String); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#IDREF", EdmPrimitiveTypeKind.String); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#ENTITY", EdmPrimitiveTypeKind.String); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#integer", EdmPrimitiveTypeKind.Int32); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#nonPositiveInteger", EdmPrimitiveTypeKind.Int32); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#negativeInteger", EdmPrimitiveTypeKind.Int32); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#long", EdmPrimitiveTypeKind.Int64); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#int", EdmPrimitiveTypeKind.Int32); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#short", EdmPrimitiveTypeKind.Int16); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#byte", EdmPrimitiveTypeKind.Byte); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#nonNegativeInteger", EdmPrimitiveTypeKind.Int32); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#unsignedLong", EdmPrimitiveTypeKind.Int64); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#unsignedInt", EdmPrimitiveTypeKind.Int32); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#unsignedShort", EdmPrimitiveTypeKind.Int16); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#unsignedByte", EdmPrimitiveTypeKind.Byte); SIMPLE_TYPE_MAPPING.put("http://www.w3.org/2001/XMLSchema#positiveInteger", EdmPrimitiveTypeKind.Int32); }; public static EdmPrimitiveTypeKind getEdmType(String propertyTypeName) { if (propertyTypeName== null || !SIMPLE_TYPE_MAPPING.containsKey(propertyTypeName)) return EdmPrimitiveTypeKind.String; return SIMPLE_TYPE_MAPPING.get(propertyTypeName); } public static boolean isAnyUri(String propertyTypeName) { if (propertyTypeName== null || !SIMPLE_TYPE_MAPPING.containsKey(propertyTypeName)) return false; return propertyTypeName.equals("http://www.w3.org/2001/XMLSchema#anyURI"); }; public static String anyUri() { return "Edm.anyURI"; }; }
/* * Copyright 2002-2014 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.xd.dirt.stream; import static org.springframework.xd.dirt.stream.ParsingContext.job; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.springframework.beans.factory.DisposableBean; import org.springframework.integration.channel.DirectChannel; import org.springframework.integration.support.MessageBuilder; import org.springframework.messaging.MessageChannel; import org.springframework.util.Assert; import org.springframework.xd.dirt.integration.bus.MessageBus; import org.springframework.xd.dirt.zookeeper.Paths; import org.springframework.xd.dirt.zookeeper.ZooKeeperConnection; import org.springframework.xd.module.ModuleDescriptor; /** * @author Glenn Renfro * @author Luke Taylor * @author Ilayaperumal Gopinathan * @author Gunnar Hillert */ public class JobDeployer extends AbstractInstancePersistingDeployer<JobDefinition, Job> implements DisposableBean { private final String JOB_CHANNEL_PREFIX = "job:"; private final MessageBus messageBus; private final ConcurrentMap<String, MessageChannel> jobChannels = new ConcurrentHashMap<String, MessageChannel>(); public JobDeployer(ZooKeeperConnection zkConnection, JobDefinitionRepository definitionRepository, JobRepository instanceRepository, XDParser parser, MessageBus messageBus) { super(zkConnection, definitionRepository, instanceRepository, parser, job); Assert.notNull(messageBus, "MessageBus must not be null"); this.messageBus = messageBus; } @Override protected Job makeInstance(JobDefinition definition) { return new Job(definition); } public void launch(String name, String jobParameters) { MessageChannel channel = jobChannels.get(name); if (channel == null) { jobChannels.putIfAbsent(name, new DirectChannel()); channel = jobChannels.get(name); messageBus.bindProducer(JOB_CHANNEL_PREFIX + name, channel, null); } // Double check so that user gets an informative error message JobDefinition job = getDefinitionRepository().findOne(name); if (job == null) { throwNoSuchDefinitionException(name); } if (instanceRepository.findOne(name) == null) { throwNotDeployedException(name); } // todo: is this Assert necessary? if not we can remove the parser dependency and parse method Assert.isTrue(parse(name, job.getDefinition()).size() == 1, "Expecting only a single module"); channel.send(MessageBuilder.withPayload(jobParameters != null ? jobParameters : "").build()); } @Override protected JobDefinition createDefinition(String name, String definition) { return new JobDefinition(name, definition); } @Override protected String getDeploymentPath(JobDefinition definition) { return Paths.build(Paths.JOB_DEPLOYMENTS, definition.getName()); } private List<ModuleDescriptor> parse(String name, String definition) { return parser.parse(name, definition, definitionKind); } @Override public void destroy() throws Exception { for (Map.Entry<String, MessageChannel> entry : jobChannels.entrySet()) { messageBus.unbindProducer(JOB_CHANNEL_PREFIX + entry.getKey(), entry.getValue()); } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.requests.extensions; import com.microsoft.graph.core.IBaseClient; import com.microsoft.graph.options.Option; import com.microsoft.graph.requests.generated.BaseWorkbookFunctionsMultiNomialRequest; // This file is available for extending, afterwards please submit a pull request. /** * The class for the Workbook Functions Multi Nomial Request. */ public class WorkbookFunctionsMultiNomialRequest extends BaseWorkbookFunctionsMultiNomialRequest implements IWorkbookFunctionsMultiNomialRequest { /** * The request for this WorkbookFunctionsMultiNomial * * @param requestUrl the request URL * @param client the service client * @param requestOptions the options for this request */ public WorkbookFunctionsMultiNomialRequest(final String requestUrl, final IBaseClient client, final java.util.List<? extends Option> requestOptions) { super(requestUrl, client, requestOptions); } }
package net.arvin.selector.uis.widgets; import android.content.Context; import android.graphics.Color; import android.graphics.PorterDuff; import android.util.AttributeSet; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import net.arvin.selector.R; import net.arvin.selector.SelectorHelper; import net.arvin.selector.data.Media; import net.arvin.selector.data.MediaType; import net.arvin.selector.utils.PSUtil; /** * Created by arvinljw on 2020/7/17 15:14 * Function: * Desc: */ public class MediaView extends RelativeLayout implements View.OnClickListener { private ImageView imgMedia; private TextView tvSelect; private ImageView imgTagGif; private View layoutTagVideo; private TextView tvVideoDuration; private Media media; private int pos; private OnMediaViewClickListener onMediaViewClickListener; public MediaView(Context context) { this(context, null); } public MediaView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public MediaView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { inflate(getContext(), R.layout.ps_layout_media, this); imgMedia = findViewById(R.id.ps_media_image); tvSelect = findViewById(R.id.ps_tv_select); imgTagGif = findViewById(R.id.ps_img_gif_tag); layoutTagVideo = findViewById(R.id.ps_layout_video_tag); tvVideoDuration = findViewById(R.id.ps_tv_video_duration); findViewById(R.id.ps_layout_select).setOnClickListener(this); imgMedia.setOnClickListener(this); } public void setData(Media media, int pos, int chooseSize) { this.media = media; this.pos = pos; SelectorHelper.imageEngine.loadImage(imgMedia, media.getUri()); boolean isSingle = chooseSize == 1; tvSelect.setVisibility(isSingle ? View.GONE : View.VISIBLE); if (!isSingle) { if (media.getChoseNum() == 0) { imgMedia.setColorFilter(null); tvSelect.setSelected(false); tvSelect.setText(""); } else { imgMedia.setColorFilter(Color.parseColor("#66000000"), PorterDuff.Mode.DARKEN); tvSelect.setSelected(true); tvSelect.setText(String.valueOf(media.getChoseNum())); } } if (MediaType.isGif(media.getMimeType())) { layoutTagVideo.setVisibility(View.GONE); imgTagGif.setVisibility(View.VISIBLE); } else if (MediaType.isVideo(media.getMimeType())) { imgTagGif.setVisibility(View.GONE); layoutTagVideo.setVisibility(View.VISIBLE); tvVideoDuration.setText(PSUtil.getDuration(media.getDuration())); } else { imgTagGif.setVisibility(View.GONE); layoutTagVideo.setVisibility(View.GONE); } } public void setOnMediaViewClickListener(OnMediaViewClickListener onMediaViewClickListener) { this.onMediaViewClickListener = onMediaViewClickListener; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, widthMeasureSpec); } @Override public void onClick(View v) { if (v == imgMedia) { if (onMediaViewClickListener != null) { onMediaViewClickListener.onMediaViewClicked(v, OnMediaViewClickListener.TYPE_IMAGE, media, pos); } } else if (v.getId() == R.id.ps_layout_select) { if (onMediaViewClickListener != null) { onMediaViewClickListener.onMediaViewClicked(v, OnMediaViewClickListener.TYPE_SELECT, media, pos); } } } public interface OnMediaViewClickListener { int TYPE_IMAGE = 1; int TYPE_SELECT = 2; void onMediaViewClicked(View v, int type, Media item, int pos); } }
package org.baeldung.web; import static org.junit.Assert.assertEquals; import org.junit.Test; import com.jayway.restassured.RestAssured; import com.jayway.restassured.response.Response; public class SwaggerLiveTest { private static final String URL_PREFIX = "http://localhost:8080/spring-security-rest/api"; @Test public void whenVerifySpringFoxIsWorking_thenOK() { final Response response = RestAssured.get(URL_PREFIX + "/v2/api-docs"); assertEquals(200, response.statusCode()); System.out.println(response.asString()); } }
package com.udacity.jdnd.course3.critter.model.dto; import java.time.DayOfWeek; import java.util.HashSet; import java.util.Objects; import java.util.Set; import com.udacity.jdnd.course3.critter.model.EmployeeSkillType; import lombok.Getter; import lombok.Setter; /** * Represents the form that employee request and response data takes. Does not map * to the database directly. */ @Getter @Setter public class EmployeeDTO extends UserDTO { private Set<EmployeeSkillType> skills = new HashSet<EmployeeSkillType>(); private Set<DayOfWeek> daysAvailable =new HashSet<DayOfWeek>(); @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + Objects.hash(daysAvailable, skills); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; EmployeeDTO other = (EmployeeDTO) obj; return Objects.equals(daysAvailable, other.daysAvailable) && Objects.equals(skills, other.skills); } @Override public String toString() { return "EmployeeDTO [skills=" + skills + ", daysAvailable=" + daysAvailable + ", toString()=" + super.toString() + "]"; } }