text
stringlengths
7
1.01M
/* * 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.streampipes.connect.container.worker.rest; import com.google.common.base.Charsets; import com.google.common.io.Resources; import org.apache.streampipes.connect.container.worker.management.AdapterWorkerManagement; import org.apache.streampipes.connect.rest.AbstractContainerResource; import org.apache.streampipes.container.assets.AssetZipGenerator; import org.apache.streampipes.container.util.AssetsUtil; import java.io.IOException; import java.net.URL; import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @Path("/api/v1/{username}/worker/adapters") public class AdapterResource extends AbstractContainerResource { private AdapterWorkerManagement adapterWorkerManagement; public AdapterResource() { this.adapterWorkerManagement = new AdapterWorkerManagement(); } @GET @Path("/{id}/assets") @Produces("application/zip") public Response getAssets(@PathParam("id") String id) { List<String> includedAssets = this.adapterWorkerManagement.getAdapter(id).declareModel().getIncludedAssets(); try { return ok(new AssetZipGenerator(id, includedAssets).makeZip()); } catch (IOException e) { e.printStackTrace(); return fail(); } } @GET @Path("/{id}/assets/icon") @Produces("image/png") public Response getIconAsset(@PathParam("id") String elementId) throws IOException { URL iconUrl = Resources.getResource(AssetsUtil.makeIconPath(elementId)); return ok(Resources.toByteArray(iconUrl)); } @GET @Path("/{id}/assets/documentation") @Produces(MediaType.TEXT_PLAIN) public String getDocumentationAsset(@PathParam("id") String elementId) throws IOException { URL documentationUrl = Resources.getResource(AssetsUtil.makeDocumentationPath(elementId)); return Resources.toString(documentationUrl, Charsets.UTF_8); } }
/******************************************************************************* * Copyright (c) 1998, 2015 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.internal.sessions; import java.util.ArrayList; import java.util.List; import org.eclipse.persistence.descriptors.ClassDescriptor; import org.eclipse.persistence.mappings.AggregateCollectionMapping; /** * This change record records the changes for AggregateCollectionMapping. */ public class AggregateCollectionChangeRecord extends CollectionChangeRecord implements org.eclipse.persistence.sessions.changesets.AggregateCollectionChangeRecord { protected List<ObjectChangeSet> changedValues; /** * This default constructor. */ public AggregateCollectionChangeRecord() { super(); } /** * This constructor returns an ChangeRecord representing an AggregateMapping. * @param owner org.eclipse.persistence.internal.sessions.ObjectChangeSet represents the Object Change Set that uses this record */ public AggregateCollectionChangeRecord(ObjectChangeSet owner) { super(); this.owner = owner; } /** * ADVANCED: * Return the values representing the changed AggregateCollection. */ public List<ObjectChangeSet> getChangedValues() { if (changedValues == null) { changedValues = new ArrayList(2); } return changedValues; } /** * Returns descriptor corresponding to the object. */ ClassDescriptor getReferenceDescriptor(Object object, AbstractSession session) { return ((AggregateCollectionMapping)this.mapping).getReferenceDescriptor(object.getClass(), session); } /** * INTERNAL: * This method will be used to merge one record into another */ public void mergeRecord(ChangeRecord mergeFromRecord, UnitOfWorkChangeSet mergeToChangeSet, UnitOfWorkChangeSet mergeFromChangeSet) { this.setChangedValues(((AggregateCollectionChangeRecord)mergeFromRecord).getChangedValues()); //an aggregate collection changerecord contains a copy of the entire collection, not just the changes //so there in no need to merge it, just replace it. for (ObjectChangeSet change : getChangedValues()) { change.updateReferences(mergeToChangeSet, mergeFromChangeSet); } } /** * INTERNAL: * Set the changed values. */ public void setChangedValues(List<ObjectChangeSet> newValues) { this.changedValues = newValues; } /** * INTERNAL: * This method will be used to update the objectsChangeSets references * If this is an aggregate change set then there is no need to update the * reference as the ChangeSet has no identity outside of this record * Check to see if it exists here already to prevent us from creating a little * extra garbage. */ public void updateReferences(UnitOfWorkChangeSet mergeToChangeSet, UnitOfWorkChangeSet mergeFromChangeSet) { for (ObjectChangeSet mergedChangeSet : getChangedValues()) { Object localObject = mergeToChangeSet.getUOWCloneForObjectChangeSet(mergedChangeSet); if (localObject == null) { mergeToChangeSet.addObjectChangeSetForIdentity(mergedChangeSet, mergeFromChangeSet.getUOWCloneForObjectChangeSet(mergedChangeSet)); } } } }
package May2021GoogLeetcode; public class _0787CheapestFlightsWithinKStops { public static void main(String[] args) { System.out.println(findCheapestPrice(3, new int[][] { new int[] { 0, 1, 100 }, new int[] { 1, 2, 100 }, new int[] { 0, 2, 500 } }, 0, 2, 1)); System.out.println(findCheapestPrice(3, new int[][] { new int[] { 0, 1, 200 }, new int[] { 1, 2, 100 }, new int[] { 0, 2, 500 } }, 0, 2, 0)); } public static int findCheapestPrice(int n, int[][] flights, int src, int dst, int K) { } }
/* * 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 bean; import javax.enterprise.context.RequestScoped; import javax.inject.Named; import org.primefaces.model.chart.PieChartModel; import dao.UsuarioDao; import model.Usuario; import dao.ResultadoDao; import java.util.Hashtable; import java.util.List; import javax.annotation.PostConstruct; import model.Resultado; import org.primefaces.model.chart.BarChartModel; /** * * @author bibim */ @Named(value="dashboardBean") @RequestScoped public class DashboardBean { private PieChartModel pieModel; private BarChartModel barModel; private List<Resultado> resultados; public DashboardBean() { resultados = new ResultadoDao().buscarTodas(); } @PostConstruct public void init() { } public PieChartModel getPieModel() { return pieModel; } public void setPieModel(PieChartModel pieModel){ this.pieModel = pieModel; } public BarChartModel getBarModel(){ return barModel; } public void setBarModel(BarChartModel barModel){ this.barModel = barModel; } public void listarResultado(){ ResultadoDao resultadoDao; List<Resultado> listaResultado; try{ resultadoDao = new ResultadoDao(); listaResultado = resultadoDao.buscarTodas(); graficar(listaResultado); }catch(Exception e){ } } private void graficar(List<Resultado> listaResultado){ pieModel = new PieChartModel(); for(Resultado resultado :listaResultado){ pieModel.set(resultado.getIdUsuario().getNomeUsuario(), resultado.getValorObtido()); } pieModel.setTitle("Alunos"); pieModel.setLegendPosition("e"); pieModel.setFill(false); pieModel.setShowDataLabels(true); pieModel.setDiameter(150); } public List<Resultado> getResultados() { return resultados; } public void setResultados(List<Resultado> resultados) { this.resultados = resultados; } }
package com.alibaba.datax.plugin.reader.otsstreamreader.internal.core; import com.alibaba.datax.common.util.Configuration; import com.alibaba.datax.plugin.reader.otsstreamreader.internal.common.ConfigurationHelper; import com.alibaba.datax.plugin.reader.otsstreamreader.internal.common.TestHelper; import com.alibaba.datax.plugin.reader.otsstreamreader.internal.config.OTSStreamReaderConfig; import com.alibaba.datax.plugin.reader.otsstreamreader.internal.config.StatusTableConstants; import com.alibaba.datax.plugin.reader.otsstreamreader.internal.model.ShardCheckpoint; import com.alibaba.datax.plugin.reader.otsstreamreader.internal.model.StreamJob; import com.alibaba.datax.plugin.reader.otsstreamreader.internal.utils.OTSHelper; import com.alicloud.openservices.tablestore.model.*; import com.alicloud.openservices.tablestore.*; import org.junit.*; import java.util.*; import static org.junit.Assert.*; public class TestCheckpointTimeTracker { public final String streamId = "StreamIdForTest"; private static SyncClientInterface client; private static String dataTable = "DataTable_CheckpointTimeTrackerTest"; private static String statusTable = "StatusTable_CheckpointTimeTrackerTest"; private static OTSStreamReaderConfig config; private static OTSStreamReaderChecker otsStreamReaderChecker; @BeforeClass public static void beforeClass() { Configuration configuration = ConfigurationHelper.loadConf(dataTable, statusTable, 1, 2); config = OTSStreamReaderConfig.load(configuration); client = OTSHelper.getOTSInstance(config); otsStreamReaderChecker = new OTSStreamReaderChecker(client, config); } @Before public void deleteAndRecreateTable() { TestHelper.deleteTable(statusTable); otsStreamReaderChecker.checkAndCreateStatusTableIfNotExist(); } private void writeShardCount(CheckpointTimeTracker ctt, long timestamp, int shardCount) { PrimaryKey primaryKey = ctt.getPrimaryKeyForShardCount(timestamp); RowPutChange rowPutChange = new RowPutChange(statusTable, primaryKey); rowPutChange.addColumn(StatusTableConstants.SHARDCOUNT_COLUMN_NAME, ColumnValue.fromLong(shardCount)); PutRowRequest putRowRequest = new PutRowRequest(rowPutChange); client.putRow(putRowRequest); } @Test public void testGetShardCountForCheck() { CheckpointTimeTracker ctt = new CheckpointTimeTracker(client, statusTable, streamId); int shardCount = 666; long timestamp = System.currentTimeMillis(); writeShardCount(ctt, timestamp, shardCount); long shardCountGot = ctt.getShardCountForCheck(timestamp); assertEquals(shardCount, shardCountGot); shardCountGot = ctt.getShardCountForCheck(1); assertEquals(shardCountGot, -1); } @Test public void testReadWriteCheckpoint() { CheckpointTimeTracker ctt = new CheckpointTimeTracker(client, statusTable, streamId); ShardCheckpoint scp = new ShardCheckpoint("shardId1", "version", "checkpoint", 1); long now = System.currentTimeMillis(); ctt.writeCheckpoint(now, scp); ShardCheckpoint scpGot = ctt.readCheckpoint(scp.getShardId(), now); assertEquals(scp, scpGot); } @Test public void testGetAllCheckpoints() throws Exception { CheckpointTimeTracker ctt = new CheckpointTimeTracker(client, statusTable, streamId); Thread.sleep(1000); long now = System.currentTimeMillis(); List<ShardCheckpoint> allScps = new ArrayList<ShardCheckpoint>(); String version = "new_version"; for (int i = 0; i < 10000; i++) { ShardCheckpoint scp = new ShardCheckpoint("shardId" + i, version, "checkpoint_" + i, i); ctt.writeCheckpoint(now, scp); allScps.add(scp); } Map<String, ShardCheckpoint> allScpsGot = ctt.getAllCheckpoints(now); assertEquals(allScps.size(), allScpsGot.size()); for (ShardCheckpoint scp : allScps) { ShardCheckpoint scpGot = allScpsGot.get(scp.getShardId()); assertNotNull(scpGot); assertEquals(scp, scpGot); } allScpsGot = ctt.getAllCheckpoints(now + 1); assertTrue(allScpsGot.isEmpty()); } @Test public void clearAllCheckpoints() throws Exception { CheckpointTimeTracker ctt = new CheckpointTimeTracker(client, statusTable, streamId); Thread.sleep(1000); long now = System.currentTimeMillis(); List<ShardCheckpoint> allScps = new ArrayList<ShardCheckpoint>(); String version = "new_version"; for (int i = 0; i < 100; i++) { ShardCheckpoint scp = new ShardCheckpoint("shardId" + i, version, "checkpoint_" + i, i); ctt.writeCheckpoint(now, scp); allScps.add(scp); } Map<String, ShardCheckpoint> allScpsGot = ctt.getAllCheckpoints(now); assertEquals(allScps.size(), allScpsGot.size()); for (ShardCheckpoint scp : allScps) { ShardCheckpoint scpGot = allScpsGot.get(scp.getShardId()); assertNotNull(scpGot); assertEquals(scp, scpGot); } ctt.clearAllCheckpoints(now); allScpsGot = ctt.getAllCheckpoints(now); assertTrue(allScpsGot.isEmpty()); } private void writeOldCheckpoint(long timestamp, String shardId, String checkpointValue) { String statusValue = String.format("%16d", timestamp) + "\t" + shardId; List<PrimaryKeyColumn> pkCols = new ArrayList<PrimaryKeyColumn>(); pkCols.add(new PrimaryKeyColumn("StreamId", PrimaryKeyValue.fromString(streamId))); pkCols.add(new PrimaryKeyColumn("StatusType", PrimaryKeyValue.fromString("CheckpointForDataxReader"))); pkCols.add(new PrimaryKeyColumn("StatusValue", PrimaryKeyValue.fromString(statusValue))); PrimaryKey primaryKey = new PrimaryKey(pkCols); RowPutChange rowPutChange = new RowPutChange(statusTable, primaryKey); rowPutChange.addColumn("Checkpoint", ColumnValue.fromString(checkpointValue)); PutRowRequest putRowRequest = new PutRowRequest(rowPutChange); client.putRow(putRowRequest); } @Test public void testCompatibleWithOldCheckpoint() { CheckpointTimeTracker ctt = new CheckpointTimeTracker(client, statusTable, streamId); ShardCheckpoint scp = new ShardCheckpoint("shardId_compatible", "", "checkpoint_compatible", 0); long now = System.currentTimeMillis(); writeOldCheckpoint(now, scp.getShardId(), scp.getCheckpoint()); ShardCheckpoint scpGot = ctt.readCheckpoint(scp.getShardId(), now); assertEquals(scp, scpGot); scpGot = ctt.readCheckpoint(scp.getShardId(), now + 1); assertNull(scpGot); } @Test public void testGetAllOldCheckpoints() throws Exception { CheckpointTimeTracker ctt = new CheckpointTimeTracker(client, statusTable, streamId); Thread.sleep(1000); long now = System.currentTimeMillis(); List<ShardCheckpoint> allScps = new ArrayList<ShardCheckpoint>(); for (int i = 0; i < 10000; i++) { ShardCheckpoint scp = new ShardCheckpoint("shardId" + i, "", "checkpoint_" + i, 0); writeOldCheckpoint(now, scp.getShardId(), scp.getCheckpoint()); allScps.add(scp); } Map<String, ShardCheckpoint> allScpsGot = ctt.getAllCheckpoints(now); assertEquals(allScps.size(), allScpsGot.size()); for (ShardCheckpoint scp : allScps) { ShardCheckpoint scpGot = allScpsGot.get(scp.getShardId()); assertNotNull(scpGot); assertEquals(scp, scpGot); } allScpsGot = ctt.getAllCheckpoints(now + 1); assertTrue(allScpsGot.isEmpty()); } @Test public void testReadWriteShardTimeCheckpoint() { CheckpointTimeTracker ctt = new CheckpointTimeTracker(client, statusTable, streamId); long now = System.currentTimeMillis(); int count = 20; for (int i = 0; i < count; i++) { ctt.setShardTimeCheckpoint("stShardId_" + i, now, "checkpoint_0"); ctt.setShardTimeCheckpoint("stShardId_" + i, now - 1, "checkpoint_1"); ctt.setShardTimeCheckpoint("stShardId_" + i, now - 2, "checkpoint_2"); ctt.setShardTimeCheckpoint("stShardId_" + i, now - 3, "checkpoint_3"); ctt.setShardTimeCheckpoint("stShardId_" + i, now - 4, "checkpoint_4"); ctt.setShardTimeCheckpoint("stShardId_" + i, now - 5, "checkpoint_5"); } for (int i = 0; i < count; i++) { String checkpoint = ctt.getShardLargestCheckpointInTimeRange("stShardId_" + i, now - 1, now + 100); assertNotNull(checkpoint); assertEquals(checkpoint, "checkpoint_0"); } String checkpoint = ctt.getShardLargestCheckpointInTimeRange("shardId_0", now + 1, now + 100); assertNull(checkpoint); checkpoint = ctt.getShardLargestCheckpointInTimeRange("shardId_999", now - 1, now + 100); assertNull(checkpoint); } @Test public void testReadWriteStreamJob() throws Exception { CheckpointTimeTracker ctt = new CheckpointTimeTracker(client, statusTable, streamId); long endTime = System.currentTimeMillis(); long startTime = endTime - 3600; Set<String> shardIds = new HashSet<String>(); for (int i = 0; i < 100000; i++) { shardIds.add("00ec4f3d-20f3-40d5-bb47-c6608720d4d8_1476847567848063_" + i); } StreamJob streamJob = new StreamJob(dataTable, streamId, "version_0", shardIds, startTime, endTime); ctt.writeStreamJob(streamJob); StreamJob streamJobGot = ctt.readStreamJob(endTime); assertEquals(streamJob.getShardIds(), streamJobGot.getShardIds()); assertEquals(streamJob.getStartTimeInMillis(), streamJobGot.getStartTimeInMillis()); assertEquals(streamJob.getEndTimeInMillis(), streamJobGot.getEndTimeInMillis()); assertEquals(streamJob.getStreamId(), streamJobGot.getStreamId()); assertEquals(streamJob.getTableName(), streamJobGot.getTableName()); assertEquals(streamJob.getVersion(), streamJobGot.getVersion()); } @Test public void testGetAndCheckAllCheckpoints() throws Exception { CheckpointTimeTracker ctt = new CheckpointTimeTracker(client, statusTable, streamId); long now = System.currentTimeMillis(); // stream job match with checkpoints { long startTime = now; long endTime = now + 1; List<String> shardIds = new ArrayList<String>(); for (int i = 0; i < 100; i++) { shardIds.add("shardId_" + i); } StreamJob streamJob = new StreamJob(dataTable, streamId, "version_0", new HashSet<String>(shardIds), startTime, endTime); ctt.writeStreamJob(streamJob); List<ShardCheckpoint> checkpoints = new ArrayList<ShardCheckpoint>(); for (int id = 0; id < shardIds.size(); id++) { String shardId = shardIds.get(id); ShardCheckpoint checkpoint = new ShardCheckpoint(shardId, streamJob.getVersion(), "shard_iterator_" + id, id); checkpoints.add(checkpoint); ctt.writeCheckpoint(endTime, checkpoint); } Map<String,ShardCheckpoint> checkpointsGot = new HashMap<String, ShardCheckpoint>(); boolean findCheckpoint = ctt.getAndCheckAllCheckpoints(endTime, streamId, checkpointsGot); assertTrue(findCheckpoint); assertEquals(checkpointsGot.size(), checkpoints.size()); for (ShardCheckpoint checkpoint : checkpoints) { ShardCheckpoint checkpointGot = checkpointsGot.get(checkpoint.getShardId()); assertNotNull(checkpointGot); assertEquals(checkpoint, checkpointGot); } } // checkpoints is less than that in job { long startTime = now + 1; long endTime = now + 2; List<String> shardIds = new ArrayList<String>(); for (int i = 0; i < 100; i++) { shardIds.add("shardId_" + i); } StreamJob streamJob = new StreamJob(dataTable, streamId, "version_0", new HashSet<String>(shardIds), startTime, endTime); ctt.writeStreamJob(streamJob); List<ShardCheckpoint> checkpoints = new ArrayList<ShardCheckpoint>(); for (int id = 0; id < shardIds.size() - 2; id++) { String shardId = shardIds.get(id); ShardCheckpoint checkpoint = new ShardCheckpoint(shardId, streamJob.getVersion(), "shard_iterator_" + id, id); checkpoints.add(checkpoint); ctt.writeCheckpoint(endTime, checkpoint); } Map<String,ShardCheckpoint> checkpointsGot = new HashMap<String, ShardCheckpoint>(); boolean findCheckpoint = ctt.getAndCheckAllCheckpoints(endTime, streamId, checkpointsGot); assertTrue(!findCheckpoint); assertTrue(checkpointsGot.isEmpty()); } // checkpoint is more than that in job { long startTime = now + 2; long endTime = now + 3; List<String> shardIds = new ArrayList<String>(); for (int i = 0; i < 100; i++) { shardIds.add("shardId_" + i); } StreamJob streamJob = new StreamJob(dataTable, streamId, "version_0", new HashSet<String>(shardIds), startTime, endTime); ctt.writeStreamJob(streamJob); List<ShardCheckpoint> checkpoints = new ArrayList<ShardCheckpoint>(); for (int id = 0; id < shardIds.size() - 3; id++) { String shardId = shardIds.get(id); ShardCheckpoint checkpoint = new ShardCheckpoint(shardId, streamJob.getVersion(), "shard_iterator_" + id, id); checkpoints.add(checkpoint); ctt.writeCheckpoint(endTime, checkpoint); } ctt.writeCheckpoint(endTime, new ShardCheckpoint("shardId_a", streamJob.getVersion(), "shard_iterator", 0)); ctt.writeCheckpoint(endTime, new ShardCheckpoint("shardId_b", streamJob.getVersion(), "shard_iterator", 0)); ctt.writeCheckpoint(endTime, new ShardCheckpoint("shardId_c", streamJob.getVersion(), "shard_iterator", 0)); Map<String,ShardCheckpoint> checkpointsGot = new HashMap<String, ShardCheckpoint>(); boolean findCheckpoint = ctt.getAndCheckAllCheckpoints(endTime, streamId, checkpointsGot); assertTrue(!findCheckpoint); assertTrue(checkpointsGot.isEmpty()); } // all checkpoints with the same version, but with different version with job { long startTime = now + 3; long endTime = now + 4; List<String> shardIds = new ArrayList<String>(); for (int i = 0; i < 100; i++) { shardIds.add("shardId_" + i); } StreamJob streamJob = new StreamJob(dataTable, streamId, "version_0", new HashSet<String>(shardIds), startTime, endTime); ctt.writeStreamJob(streamJob); List<ShardCheckpoint> checkpoints = new ArrayList<ShardCheckpoint>(); for (int id = 0; id < shardIds.size(); id++) { String shardId = shardIds.get(id); ShardCheckpoint checkpoint = new ShardCheckpoint(shardId, streamJob.getVersion() + "!", "shard_iterator_" + id, id); checkpoints.add(checkpoint); ctt.writeCheckpoint(endTime, checkpoint); } Map<String,ShardCheckpoint> checkpointsGot = new HashMap<String, ShardCheckpoint>(); boolean findCheckpoint = ctt.getAndCheckAllCheckpoints(endTime, streamId, checkpointsGot); assertTrue(!findCheckpoint); assertTrue(checkpointsGot.isEmpty()); } // check point is mix with different versions { long startTime = now + 4; long endTime = now + 5; List<String> shardIds = new ArrayList<String>(); for (int i = 0; i < 100; i++) { shardIds.add("shardId_" + i); } StreamJob streamJob = new StreamJob(dataTable, streamId, "version_0", new HashSet<String>(shardIds), startTime, endTime); ctt.writeStreamJob(streamJob); List<ShardCheckpoint> checkpoints = new ArrayList<ShardCheckpoint>(); for (int id = 0; id < shardIds.size(); id++) { String shardId = shardIds.get(id); ShardCheckpoint checkpoint = new ShardCheckpoint( shardId, id > 2 && id < 10 ? streamJob.getVersion() + "!" : streamJob.getVersion(), "shard_iterator_" + id, id); checkpoints.add(checkpoint); ctt.writeCheckpoint(endTime, checkpoint); } Map<String,ShardCheckpoint> checkpointsGot = new HashMap<String, ShardCheckpoint>(); boolean findCheckpoint = ctt.getAndCheckAllCheckpoints(endTime, streamId, checkpointsGot); assertTrue(!findCheckpoint); assertTrue(checkpointsGot.isEmpty()); } // stream id is different { long startTime = now; long endTime = now + 1; List<String> shardIds = new ArrayList<String>(); for (int i = 0; i < 100; i++) { shardIds.add("shardId_" + i); } StreamJob streamJob = new StreamJob(dataTable, streamId, "version_0", new HashSet<String>(shardIds), startTime, endTime); ctt.writeStreamJob(streamJob); List<ShardCheckpoint> checkpoints = new ArrayList<ShardCheckpoint>(); for (int id = 0; id < shardIds.size(); id++) { String shardId = shardIds.get(id); ShardCheckpoint checkpoint = new ShardCheckpoint(shardId, streamJob.getVersion(), "shard_iterator_" + id, id); checkpoints.add(checkpoint); ctt.writeCheckpoint(endTime, checkpoint); } Map<String,ShardCheckpoint> checkpointsGot = new HashMap<String, ShardCheckpoint>(); boolean findCheckpoint = ctt.getAndCheckAllCheckpoints(endTime, streamId + "!", checkpointsGot); assertTrue(!findCheckpoint); assertTrue(checkpointsGot.isEmpty()); } } @Test public void testGetAndCheckAllOldCheckpoints() { CheckpointTimeTracker ctt = new CheckpointTimeTracker(client, statusTable, streamId); long now = System.currentTimeMillis(); int shardCount = 100; List<ShardCheckpoint> checkpoints = new ArrayList<ShardCheckpoint>(); for (int i = 0; i < shardCount; i++) { ShardCheckpoint checkpoint = new ShardCheckpoint("shardId_" + i, "", "shard_iterator_" + i, 0); writeOldCheckpoint(now, checkpoint.getShardId(), checkpoint.getCheckpoint()); checkpoints.add(checkpoint); } // shard count not exist Map<String,ShardCheckpoint> checkpointsGot = new HashMap<String, ShardCheckpoint>(); boolean findCheckpoint = ctt.getAndCheckAllCheckpoints(now, streamId, checkpointsGot); assertTrue(!findCheckpoint); assertTrue(checkpointsGot.isEmpty()); // count not match writeShardCount(ctt, now, shardCount - 1); findCheckpoint = ctt.getAndCheckAllCheckpoints(now, streamId, checkpointsGot); assertTrue(!findCheckpoint); // with correct shard count writeShardCount(ctt, now, shardCount); findCheckpoint = ctt.getAndCheckAllCheckpoints(now, streamId, checkpointsGot); assertTrue(findCheckpoint); assertEquals(checkpointsGot.size(), shardCount); for (ShardCheckpoint checkpoint : checkpoints) { ShardCheckpoint checkpointGot = checkpointsGot.get(checkpoint.getShardId()); assertNotNull(checkpointGot); assertEquals(checkpoint, checkpointGot); } } }
// Copyright 2000-2019 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.spellchecker.generator; import com.intellij.lang.Language; import com.intellij.lang.LanguageNamesValidation; import com.intellij.lang.refactoring.NamesValidator; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressIndicatorProvider; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileVisitor; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.spellchecker.SpellCheckerManager; import com.intellij.spellchecker.inspections.SpellCheckingInspection; import com.intellij.spellchecker.inspections.Splitter; import com.intellij.spellchecker.tokenizer.TokenConsumer; import com.intellij.spellchecker.util.SpellCheckerBundle; import com.intellij.util.containers.MultiMap; import org.jetbrains.annotations.NotNull; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.*; public abstract class SpellCheckerDictionaryGenerator { private static final Logger LOG = Logger.getInstance(SpellCheckerDictionaryGenerator.class); private final Set<String> globalSeenNames = new HashSet<>(); protected final Project myProject; private final String myDefaultDictName; protected final String myDictOutputFolder; protected final MultiMap<String, VirtualFile> myDict2FolderMap; protected final Set<VirtualFile> myExcludedFolders = new HashSet<>(); protected SpellCheckerManager mySpellCheckerManager; public SpellCheckerDictionaryGenerator(final Project project, final String dictOutputFolder, final String defaultDictName) { myDict2FolderMap = new MultiMap<>(); myProject = project; myDefaultDictName = defaultDictName; mySpellCheckerManager = SpellCheckerManager.getInstance(myProject); myDictOutputFolder = dictOutputFolder; } public void addFolder(String dictName, VirtualFile path) { myDict2FolderMap.putValue(dictName, path); } public void excludeFolder(VirtualFile folder) { myExcludedFolders.add(folder); } public void generate() { ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> { ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator(); progressIndicator.setIndeterminate(false); // let's do result a bit more predictable final List<String> dictionaries = new ArrayList<>(myDict2FolderMap.keySet()); // ruby dictionary generate(myDefaultDictName, progressIndicator); progressIndicator.setFraction(1. / (dictionaries.size() + 1)); // other gem-related dictionaries in alphabet order Collections.sort(dictionaries); for (int i = 0; i < dictionaries.size(); i++) { String dict = dictionaries.get(i); if (myDefaultDictName.equals(dict)) { continue; } generate(dict, progressIndicator); progressIndicator.setFraction(i / (dictionaries.size() + 1.)); } }, SpellCheckerBundle.message("dictionary.generator.progress.title"), true, myProject); } private void generate(@NotNull String dict, ProgressIndicator progressIndicator) { progressIndicator.setText(SpellCheckerBundle.message("dictionary.generator.processing.title", dict)); generateDictionary(myProject, myDict2FolderMap.get(dict), myDictOutputFolder + "/" + dict + ".dic", progressIndicator); } private void generateDictionary(final Project project, final Collection<VirtualFile> folderPaths, final String outFile, final ProgressIndicator progressIndicator) { final HashSet<String> seenNames = new HashSet<>(); // Collect stuff ApplicationManager.getApplication().runReadAction(() -> { for (VirtualFile folder : folderPaths) { progressIndicator.setText2(SpellCheckerBundle.message("dictionary.generator.scanning.folder.title", folder.getPath())); final PsiManager manager = PsiManager.getInstance(project); processFolder(seenNames, manager, folder); } }); if (seenNames.isEmpty()) { LOG.info(" No new words was found."); return; } final StringBuilder builder = new StringBuilder(); // Sort names final ArrayList<String> names = new ArrayList<>(seenNames); Collections.sort(names); for (String name : names) { if (builder.length() > 0) { builder.append("\n"); } builder.append(name); } final File dictionaryFile = new File(outFile); FileUtil.createIfDoesntExist(dictionaryFile); try (FileWriter writer = new FileWriter(dictionaryFile.getPath())) { writer.write(builder.toString()); } catch (IOException e) { LOG.error(e); } } protected void processFolder(final HashSet<String> seenNames, final PsiManager manager, final VirtualFile folder) { VfsUtilCore.visitChildrenRecursively(folder, new VirtualFileVisitor<Void>() { @Override public boolean visitFile(@NotNull VirtualFile file) { ProgressIndicatorProvider.checkCanceled(); if (myExcludedFolders.contains(file)) { return false; } if (!file.isDirectory()) { final PsiFile psiFile = manager.findFile(file); if (psiFile != null) { processFile(psiFile, seenNames); } } return true; } }); } protected abstract void processFile(PsiFile file, HashSet<String> seenNames); protected void process(@NotNull final PsiElement element, @NotNull final HashSet<String> seenNames) { final int endOffset = element.getTextRange().getEndOffset(); // collect leafs (spell checker inspection works with leafs) final List<PsiElement> leafs = new ArrayList<>(); if (element.getChildren().length == 0) { // if no children - it is a leaf! leafs.add(element); } else { // else collect leafs under given element PsiElement currentLeaf = PsiTreeUtil.firstChild(element); while (currentLeaf != null && currentLeaf.getTextRange().getEndOffset() <= endOffset) { leafs.add(currentLeaf); currentLeaf = PsiTreeUtil.nextLeaf(currentLeaf); } } for (PsiElement leaf : leafs) { processLeafsNames(leaf, seenNames); } } protected void processLeafsNames(@NotNull final PsiElement leafElement, @NotNull final HashSet<String> seenNames) { final Language language = leafElement.getLanguage(); SpellCheckingInspection.tokenize(leafElement, language, new TokenConsumer() { @Override public void consumeToken(PsiElement element, final String text, boolean useRename, int offset, TextRange rangeToCheck, Splitter splitter) { splitter.split(text, rangeToCheck, textRange -> { final String word = textRange.substring(text); addSeenWord(seenNames, word, language); }); } }); } protected void addSeenWord(HashSet<String> seenNames, String word, Language language) { final String lowerWord = StringUtil.toLowerCase(word); if (globalSeenNames.contains(lowerWord)) { return; } final NamesValidator namesValidator = LanguageNamesValidation.INSTANCE.forLanguage(language); if (namesValidator.isKeyword(word, myProject)) { return; } globalSeenNames.add(lowerWord); if (mySpellCheckerManager.hasProblem(lowerWord)) { seenNames.add(lowerWord); } } }
package com.pepper.framework.interceptor.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 自定义注解防止表单重复提交 * * @author pepper * */ @Inherited @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface RepeatSubmit { }
package uk.gov.hmcts.reform.bailcaseapi.domain.handlers.presubmit; import static java.util.Collections.emptyList; import static java.util.Objects.requireNonNull; import static uk.gov.hmcts.reform.bailcaseapi.domain.entities.BailCaseFieldDefinition.DIRECTIONS; import java.util.List; import java.util.Optional; import org.springframework.stereotype.Component; import uk.gov.hmcts.reform.bailcaseapi.domain.entities.BailCase; import uk.gov.hmcts.reform.bailcaseapi.domain.entities.BailCaseFieldDefinition; import uk.gov.hmcts.reform.bailcaseapi.domain.entities.Direction; import uk.gov.hmcts.reform.bailcaseapi.domain.entities.DynamicList; import uk.gov.hmcts.reform.bailcaseapi.domain.entities.Value; import uk.gov.hmcts.reform.bailcaseapi.domain.entities.ccd.Event; import uk.gov.hmcts.reform.bailcaseapi.domain.entities.ccd.callback.Callback; import uk.gov.hmcts.reform.bailcaseapi.domain.entities.ccd.callback.PreSubmitCallbackResponse; import uk.gov.hmcts.reform.bailcaseapi.domain.entities.ccd.callback.PreSubmitCallbackStage; import uk.gov.hmcts.reform.bailcaseapi.domain.entities.ccd.field.IdValue; import uk.gov.hmcts.reform.bailcaseapi.domain.handlers.PreSubmitCallbackHandler; @Component public class ChangeDirectionDueMidEvent implements PreSubmitCallbackHandler<BailCase> { private static final String DIRECTION = "Direction "; public boolean canHandle( PreSubmitCallbackStage callbackStage, Callback<BailCase> callback ) { requireNonNull(callbackStage, "callbackStage must not be null"); requireNonNull(callback, "callback must not be null"); return callbackStage == PreSubmitCallbackStage.MID_EVENT && callback.getEvent() == Event.CHANGE_BAIL_DIRECTION_DUE_DATE; } public PreSubmitCallbackResponse<BailCase> handle( PreSubmitCallbackStage callbackStage, Callback<BailCase> callback ) { if (!canHandle(callbackStage, callback)) { throw new IllegalStateException("Cannot handle callback"); } BailCase bailCase = callback .getCaseDetails() .getCaseData(); Optional<List<IdValue<Direction>>> maybeDirections = bailCase.read(DIRECTIONS); DynamicList bailDirectionList = bailCase.read(BailCaseFieldDefinition.BAIL_DIRECTION_LIST, DynamicList.class) .orElseThrow(() -> new IllegalStateException("bailDirectionList is missing")); // find selected direction's id Value selectedDirection = bailDirectionList.getValue(); int selectedDirectionId = Integer.parseInt(selectedDirection.getCode().substring(DIRECTION.length())); List<IdValue<Direction>> directions = maybeDirections.orElse(emptyList()); if (!directions.isEmpty()) { // find direction to be changed // e.g. what is Direction 4 on UI has index 3 in the collection IdValue<Direction> directionToChange = directions.get(selectedDirectionId - 1); // write fields of the direction that's being changed into the bailcase object if present bailCase.write(BailCaseFieldDefinition.BAIL_DIRECTION_EDIT_EXPLANATION, directionToChange.getValue().getSendDirectionDescription()); bailCase.write(BailCaseFieldDefinition.BAIL_DIRECTION_EDIT_PARTIES, directionToChange.getValue().getSendDirectionList()); bailCase.write(BailCaseFieldDefinition.BAIL_DIRECTION_EDIT_DATE_DUE, directionToChange.getValue().getDateOfCompliance()); bailCase.write(BailCaseFieldDefinition.BAIL_DIRECTION_EDIT_DATE_SENT, directionToChange.getValue().getDateSent()); } else { bailCase.write(BailCaseFieldDefinition.BAIL_DIRECTION_EDIT_EXPLANATION, ""); bailCase.write(BailCaseFieldDefinition.BAIL_DIRECTION_EDIT_PARTIES, ""); bailCase.write(BailCaseFieldDefinition.BAIL_DIRECTION_EDIT_DATE_DUE, ""); bailCase.write(BailCaseFieldDefinition.BAIL_DIRECTION_EDIT_DATE_SENT, ""); } return new PreSubmitCallbackResponse<>(bailCase); } }
/* * Copyright 2017-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.gcp.pubsub.core; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutionException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.api.core.ApiService; import com.google.api.core.SettableApiFuture; import com.google.cloud.pubsub.v1.MessageReceiver; import com.google.cloud.pubsub.v1.Publisher; import com.google.cloud.pubsub.v1.Subscriber; import com.google.protobuf.ByteString; import com.google.pubsub.v1.PubsubMessage; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.cloud.gcp.pubsub.core.publisher.PubSubPublisherTemplate; import org.springframework.cloud.gcp.pubsub.core.test.allowed.AllowedPayload; import org.springframework.cloud.gcp.pubsub.support.PublisherFactory; import org.springframework.cloud.gcp.pubsub.support.SubscriberFactory; import org.springframework.cloud.gcp.pubsub.support.converter.JacksonPubSubMessageConverter; import org.springframework.util.concurrent.ListenableFuture; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * @author João André Martins * @author Chengyuan Zhao * @author Doug Hoard * @author Mike Eltsufin */ @RunWith(MockitoJUnitRunner.class) public class PubSubTemplateTests { @Rule public ExpectedException expectedException = ExpectedException.none(); @Mock private PublisherFactory mockPublisherFactory; @Mock private SubscriberFactory mockSubscriberFactory; @Mock private Publisher mockPublisher; @Mock private Subscriber mockSubscriber; private PubSubTemplate pubSubTemplate; private PubsubMessage pubsubMessage; private SettableApiFuture<String> settableApiFuture; private PubSubTemplate createTemplate() { PubSubTemplate pubSubTemplate = new PubSubTemplate(this.mockPublisherFactory, this.mockSubscriberFactory); return pubSubTemplate; } private PubSubPublisherTemplate createPublisherTemplate() { PubSubPublisherTemplate pubSubPublisherTemplate = new PubSubPublisherTemplate(this.mockPublisherFactory); pubSubPublisherTemplate.setMessageConverter(new JacksonPubSubMessageConverter(new ObjectMapper())); return pubSubPublisherTemplate; } @Before public void setUp() { this.pubSubTemplate = createTemplate(); when(this.mockPublisherFactory.createPublisher("testTopic")) .thenReturn(this.mockPublisher); this.settableApiFuture = SettableApiFuture.create(); when(this.mockPublisher.publish(isA(PubsubMessage.class))) .thenReturn(this.settableApiFuture); when(this.mockSubscriberFactory.createSubscriber( eq("testSubscription"), isA(MessageReceiver.class))) .thenReturn(this.mockSubscriber); when(this.mockSubscriber.startAsync()).thenReturn(mock(ApiService.class)); this.pubsubMessage = PubsubMessage.newBuilder().setData( ByteString.copyFrom("permanating".getBytes())).build(); } @Test public void testPublish() throws ExecutionException, InterruptedException { this.settableApiFuture.set("result"); ListenableFuture<String> future = this.pubSubTemplate.publish("testTopic", this.pubsubMessage); assertThat(future.get()).isEqualTo("result"); } @Test public void testPublish_String() { this.pubSubTemplate.publish("testTopic", "testPayload"); verify(this.mockPublisher, times(1)) .publish(isA(PubsubMessage.class)); } @Test public void testPublish_Bytes() { this.pubSubTemplate.publish("testTopic", "testPayload".getBytes()); verify(this.mockPublisher, times(1)) .publish(isA(PubsubMessage.class)); } @Test public void testPublish_Object() throws IOException { AllowedPayload allowedPayload = new AllowedPayload(); allowedPayload.name = "allowed"; allowedPayload.value = 12345; PubSubPublisherTemplate pubSubPublisherTemplate = spy(createPublisherTemplate()); doAnswer((invocation) -> { PubsubMessage message = invocation.getArgument(1); assertThat(message.getData().toStringUtf8()) .isEqualTo("{\"@class\":" + "\"org.springframework.cloud.gcp.pubsub.core.test.allowed.AllowedPayload\"" + ",\"name\":\"allowed\",\"value\":12345}"); return null; }).when(pubSubPublisherTemplate).publish(eq("test"), any()); pubSubPublisherTemplate.publish("test", allowedPayload); verify(pubSubPublisherTemplate, times(1)).publish(eq("test"), isA(PubsubMessage.class)); } @Test public void testPublish_withHeaders() { Map<String, String> headers = new HashMap<>(); headers.put("emperor of sand", "sultan's curse"); headers.put("remission", "elephant man"); this.pubSubTemplate.publish("testTopic", "jaguar god", headers); verify(this.mockPublisher).publish(argThat((message) -> message.getAttributesMap().get("emperor of sand").equals("sultan's curse") && message.getAttributesMap().get("remission").equals("elephant man"))); } @Test public void testSend_noPublisher() { this.expectedException.expect(PubSubException.class); this.expectedException.expectMessage("couldn't create the publisher."); when(this.mockPublisherFactory.createPublisher("testTopic")) .thenThrow(new PubSubException("couldn't create the publisher.")); this.pubSubTemplate.publish("testTopic", this.pubsubMessage); } @Test public void testSend_onFailure() { ListenableFuture<String> future = this.pubSubTemplate.publish("testTopic", this.pubsubMessage); this.settableApiFuture.setException(new Exception("future failed.")); assertThatThrownBy(() -> future.get()) .isInstanceOf(ExecutionException.class) .hasMessageContaining("future failed."); } @Test public void testSubscribe() { Subscriber subscriber = this.pubSubTemplate.subscribe("testSubscription", (message) -> { }); assertThat(subscriber).isEqualTo(this.mockSubscriber); verify(this.mockSubscriber, times(1)).startAsync(); } }
package com.sample.springboot.orika.converter; import com.sample.springboot.orika.enums.SampleEnum; import ma.glasnost.orika.converter.BidirectionalConverter; import ma.glasnost.orika.metadata.Type; public class EnumsConverters { public static class SampleEnumToIntegerConverter extends BidirectionalConverter<SampleEnum, Integer> { /** * 后台返回页面 * sampleEnum=null返回null 新增页面选择框不会被默认选中 */ @Override public Integer convertTo(SampleEnum source, Type<Integer> type) { if (null == source) { return null; } return source.value(); } /** * 页面传值给后台 * value=null设置为ENUM_UNKNOWN 保证数据库中`sample_enum`没有空值 */ @Override public SampleEnum convertFrom(Integer source, Type<SampleEnum> type) { if (null == source) { return SampleEnum.ENUM_UNKNOWN; } return SampleEnum.valueOf(source); } } }
import java.util.Scanner; /** * Recitation created by Gareth Halladay, 08/17. <br> * Content was gathered from two sources: * <ul> * <li> http://www.cs.wustl.edu/~kjg/cse131/modules/recursion/lab.html * <li> http://codingbat.com/prob/p273235?parent=/home/bono@usc.edu/recursionLab * </ul> * */ public class Recursion { /** * Every number after the first two is the sum of the two preceding ones. <br> * index: 0, 1, 2, 3, 4, 5, 6... <br> * output: 0, 1, 1, 2, 3, 5, 8... * @param n which fibonacci number to compute. * @return the fibonacci number. */ public static int fib(int n){ if(n == 0){return 0;} if(n == 1){return 1;} return fib(n -1) + fib(n - 2); } /** * Write a multiplication method recursively using repeated addition. <br> * Do not use the multiplication operator or a loop. * * @param j a positive or negative integer. * @param k a positive or negative integer. * @return the product of the k and j. */ public static int mult(int j, int k){ if(k > 0){ if(k == 1){return j;} return j + mult(j, k - 1); } else{ if(k == -1){return -1 * j;} return (-1 * j) + mult(j, k + 1); } } /** * Write a method that computes j^k. <br> * Do not use Math.pow() or a loop. <br> * @param j a non-negative number * @param k a non-negative number * @return j^k */ public static int expt(int j, int k){ if (k == 1){return j;} return j * expt(j, k - 1); } /** * Check to see if a word is a palindrome. Should be case-independent. * @param word a String without whitespace * @return true if the word is a palindrome */ public static boolean isPalindrome(String word){ if(word.length() == 1){return true;} if(word.length() == 0){return true;} if(Character.toLowerCase(word.charAt(0)) == Character.toLowerCase(word.charAt(word.length() - 1))){ word = word.substring(1, word.length() - 1); return isPalindrome(word); } return false; } /** * Returns length of the longest word in the given String using recursion (no loops). * Hint: a Scanner may be helpful for finding word boundaries. After delimiting by space, * use the following method on your String to remove punctuation {@code .replaceAll("[^a-zA-Z]", "")} * If you use a Scanner, you will need a helper method to do the recursion on the Scanner object. * * @return The length of the longest word in the String. * @see Scanner#Scanner(String) * @see Scanner#next() * @see String#split(String) * @see String#replaceAll(String, String) * @see Math#max(int, int) */ public static int longestWordHelper(Scanner scanner, int longest){ if(!scanner.hasNext()){return longest;} String cur = scanner.next().replaceAll("[^a-zA-Z]", ""); if(cur.length() > longest){ longest = cur.length(); } return longestWordHelper(scanner, longest); } public static int longestWordLength(String words){ Scanner scnr = new Scanner(words); return longestWordHelper(scnr, 0); } /** * Remove consecutive duplicate characters from a String. <br> * Case should not matter, if two or more consecutive duplicate <br> * characters have different cases, then the first letter should be kept. * @param word A word with possible consecutive duplicate characters. * @return A word without any consecutive duplicate characters. */ public static String dedupeChars(String word){ if(word.length() == 1){return word;} // if(word.length() == 2){return word.substring(0, 1);} if(word.length() >= 2 && Character.toLowerCase(word.charAt(0)) == Character.toLowerCase(word.charAt(1))){ return dedupeChars( word.substring(0, 1) + word.substring(2)); } return word.substring(0, 1) + dedupeChars(word.substring(1)); } public static void main(String [] args){ // Test your methods here! // Uncomment each block as you are ready to test it. //Note: in zyBooks the main in Main.java will run instead, and it is all of the below statements. System.out.println("Testing the fibonacci method"); System.out.printf("fib(0) should be 0 -> %d\n", fib(0)); System.out.printf("fib(1) should be 1 -> %d\n", fib(1)); System.out.printf("fib(2) should be 1 -> %d\n", fib(2)); System.out.printf("fib(5) should be 5 -> %d\n", fib(5)); System.out.printf("fib(10) should be 55 -> %d\n", fib(10)); System.out.printf("fib(13) should be 233 -> %d\n", fib(13)); System.out.println(); System.out.println("Testing out the multiplication method"); System.out.printf("mult(8, 2) should be 16 -> %d\n", mult(8, 2)); System.out.printf("mult(2, 8) should be 16 -> %d\n", mult(2, 8)); System.out.printf("mult(4, -3) should be -12 -> %d\n", mult(4, -3)); System.out.printf("mult(-3, 4) should be -12 -> %d\n", mult(-3, 4)); System.out.println(); System.out.println("Testing out the exponent method"); System.out.printf("expt(2, 5) should be 32 -> %d\n", expt(2, 5)); System.out.printf("expt(5, 2) should be 25 -> %d\n", expt(5, 2)); System.out.println(); System.out.println("Testing out the palindrome method"); System.out.printf("isPalindrome(\"a\") should be true -> %b\n", isPalindrome("a")); System.out.printf("isPalindrome(\"Aibohphobia\") should be true -> %b\n", isPalindrome("Aibohphobia")); System.out.printf("isPalindrome(\"noon\") should be true -> %b\n", isPalindrome("noon")); System.out.printf("isPalindrome(\"Recursion\") should be false -> %b\n", isPalindrome("Recursion")); System.out.println(); System.out.println("Testing out the longestWordLength method\n"); String quoteOne = "Grit, one of the keys to success. The person who perseveres is the one who\n" + "will surely win. Success does not come from giving up, it comes from believing\n" + "in yourself and continuously working towards the realization of a worthy ideal.\n" + "Do not ever give up on what you want most. You know what you truly want.\n" + "Believe in your dreams and goals and take daily consistent action in order to\n" + "make your dreams a reality."; System.out.printf("The longest word in the following quote:\n%s\nshould be 12 -> %d\n\n", quoteOne, longestWordLength(quoteOne)); String quoteTwo = "Try to be like the turtle – at ease in your own shell."; System.out.printf("The longest word in the following quote:\n%s\nshould be 6 -> %d\n\n", quoteTwo, longestWordLength(quoteTwo)); System.out.println(); System.out.println("Testing the dedupeChars method"); System.out.printf("dedupeChars(\"a\") should be a -> %s\n", dedupeChars("a")); System.out.printf("dedupeChars(\"aa\") should be a -> %s\n", dedupeChars("aa")); System.out.printf("dedupeChars(\"Ppi\") should be Pi -> %s\n", dedupeChars("Ppi")); System.out.printf("dedupeChars(\"MiSsisSiPpi\") should be MiSisiPi -> %s\n", dedupeChars("MiSsisSiPpi")); System.out.printf("dedupeChars(\"swimMmMming\") should be swiming -> %s\n", dedupeChars("swimMmMming")); /* */ } }
package com.example.ckraft.myapplication; import android.os.AsyncTask; import android.widget.Toast; import com.example.ckraft.myapplication.R; import com.google.gson.Gson; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; /** * Created by ckraft on 8/25/2016. */ public class GetRequestTask extends AsyncTask<String, String, String> { public interface TaskListener { public void onStarted(); public void onFinished(String response); } // This is the reference to the associated listener private final TaskListener taskListener; public GetRequestTask(TaskListener listener) { // The listener reference is passed in through the constructor this.taskListener = listener; } @Override protected void onPreExecute(){ super.onPreExecute(); // In onPreExecute we check if the listener is valid if(this.taskListener != null) { // And if it is we call the callback function on it. this.taskListener.onStarted(); } } @Override protected String doInBackground(String... params){ String response = new String(); HttpURLConnection connection = null; BufferedReader reader = null; try { URL url = new URL(params[0]); connection = (HttpURLConnection) url.openConnection(); AppContext.applyCookie(connection); connection.connect(); InputStream stream = connection.getInputStream(); reader = new BufferedReader(new InputStreamReader(stream)); StringBuffer buffer = new StringBuffer(); String line =""; while ((line = reader.readLine()) != null){ buffer.append(line); } String finalJson = buffer.toString(); stream.close(); connection.disconnect(); response = finalJson; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { if(connection != null) { connection.disconnect(); } try { if(reader != null) { reader.close(); } } catch (IOException e) { e.printStackTrace(); } } return response; } @Override protected void onPostExecute(final String response) { super.onPostExecute(response); // In onPostExecute we check if the listener is valid if(this.taskListener != null) { // And if it is we call the callback function on it. this.taskListener.onFinished(response); } } }
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.action.admin.indices.segments; import org.elasticsearch.action.ShardOperationFailedException; import org.elasticsearch.action.support.ActionFilters; import org.elasticsearch.action.support.broadcast.node.TransportBroadcastByNodeAction; import org.elasticsearch.cluster.ClusterService; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.block.ClusterBlockException; import org.elasticsearch.cluster.block.ClusterBlockLevel; import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver; import org.elasticsearch.cluster.routing.ShardRouting; import org.elasticsearch.cluster.routing.ShardsIterator; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.index.IndexService; import org.elasticsearch.index.shard.IndexShard; import org.elasticsearch.indices.IndicesService; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.TransportService; import java.io.IOException; import java.util.List; /** * */ public class TransportIndicesSegmentsAction extends TransportBroadcastByNodeAction<IndicesSegmentsRequest, IndicesSegmentResponse, ShardSegments> { private final IndicesService indicesService; @Inject public TransportIndicesSegmentsAction(Settings settings, ThreadPool threadPool, ClusterService clusterService, TransportService transportService, IndicesService indicesService, ActionFilters actionFilters, IndexNameExpressionResolver indexNameExpressionResolver) { super(settings, IndicesSegmentsAction.NAME, threadPool, clusterService, transportService, actionFilters, indexNameExpressionResolver, IndicesSegmentsRequest::new, ThreadPool.Names.MANAGEMENT); this.indicesService = indicesService; } /** * Segments goes across *all* active shards. */ @Override protected ShardsIterator shards(ClusterState clusterState, IndicesSegmentsRequest request, String[] concreteIndices) { return clusterState.routingTable().allShards(concreteIndices); } @Override protected ClusterBlockException checkGlobalBlock(ClusterState state, IndicesSegmentsRequest request) { return state.blocks().globalBlockedException(ClusterBlockLevel.METADATA_READ); } @Override protected ClusterBlockException checkRequestBlock(ClusterState state, IndicesSegmentsRequest countRequest, String[] concreteIndices) { return state.blocks().indicesBlockedException(ClusterBlockLevel.METADATA_READ, concreteIndices); } @Override protected ShardSegments readShardResult(StreamInput in) throws IOException { return ShardSegments.readShardSegments(in); } @Override protected IndicesSegmentResponse newResponse(IndicesSegmentsRequest request, int totalShards, int successfulShards, int failedShards, List<ShardSegments> results, List<ShardOperationFailedException> shardFailures, ClusterState clusterState) { return new IndicesSegmentResponse(results.toArray(new ShardSegments[results.size()]), totalShards, successfulShards, failedShards, shardFailures); } @Override protected IndicesSegmentsRequest readRequestFrom(StreamInput in) throws IOException { final IndicesSegmentsRequest request = new IndicesSegmentsRequest(); request.readFrom(in); return request; } @Override protected ShardSegments shardOperation(IndicesSegmentsRequest request, ShardRouting shardRouting) { IndexService indexService = indicesService.indexServiceSafe(shardRouting.index()); IndexShard indexShard = indexService.getShard(shardRouting.id()); return new ShardSegments(indexShard.routingEntry(), indexShard.segments(request.verbose())); } }
/* * Copyright 2016-2017 Hippo B.V. (http://www.onehippo.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.onehippo.cms.channelmanager.content.document; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; import javax.jcr.Node; import javax.jcr.RepositoryException; import javax.jcr.Session; import org.hippoecm.repository.api.WorkflowException; import org.hippoecm.repository.standardworkflow.EditableWorkflow; import org.hippoecm.repository.util.DocumentUtils; import org.hippoecm.repository.util.JcrUtils; import org.hippoecm.repository.util.WorkflowUtils; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.onehippo.cms.channelmanager.content.document.model.Document; import org.onehippo.cms.channelmanager.content.document.model.FieldValue; import org.onehippo.cms.channelmanager.content.document.util.EditingUtils; import org.onehippo.cms.channelmanager.content.document.util.FieldPath; import org.onehippo.cms.channelmanager.content.documenttype.DocumentTypesService; import org.onehippo.cms.channelmanager.content.documenttype.field.FieldTypeUtils; import org.onehippo.cms.channelmanager.content.documenttype.field.type.FieldType; import org.onehippo.cms.channelmanager.content.documenttype.model.DocumentType; import org.onehippo.cms.channelmanager.content.error.BadRequestException; import org.onehippo.cms.channelmanager.content.error.ErrorInfo; import org.onehippo.cms.channelmanager.content.error.ForbiddenException; import org.onehippo.cms.channelmanager.content.error.InternalServerErrorException; import org.onehippo.cms.channelmanager.content.error.MethodNotAllowed; import org.onehippo.cms.channelmanager.content.error.NotFoundException; import org.powermock.api.easymock.PowerMock; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.eq; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.expectLastCall; import static org.easymock.EasyMock.getCurrentArguments; import static org.easymock.EasyMock.isA; import static org.easymock.EasyMock.replay; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @RunWith(PowerMockRunner.class) @PowerMockIgnore("javax.management.*") @PrepareForTest({WorkflowUtils.class, DocumentUtils.class, DocumentTypesService.class, JcrUtils.class, EditingUtils.class, FieldTypeUtils.class}) public class DocumentsServiceImplTest { private Session session; private Locale locale; private DocumentsServiceImpl documentsService = (DocumentsServiceImpl) DocumentsService.get(); @Before public void setup() throws RepositoryException { session = createMock(Session.class); locale = new Locale("en"); PowerMock.mockStatic(DocumentTypesService.class); PowerMock.mockStatic(DocumentUtils.class); PowerMock.mockStatic(EditingUtils.class); PowerMock.mockStatic(FieldTypeUtils.class); PowerMock.mockStatic(JcrUtils.class); PowerMock.mockStatic(WorkflowUtils.class); } @Test public void createDraftNotAHandle() throws Exception { final String uuid = "uuid"; expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.empty()); PowerMock.replayAll(); try { documentsService.createDraft(uuid, session, locale); fail("No Exception"); } catch (NotFoundException e) { assertNull(e.getPayload()); } PowerMock.verifyAll(); } @Test public void createDraftNoNodeType() throws Exception { final String uuid = "uuid"; final Node handle = createMock(Node.class); expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.of(handle)); expect(DocumentUtils.getVariantNodeType(handle)).andReturn(Optional.empty()); PowerMock.replayAll(); try { documentsService.createDraft(uuid, session, locale); fail("No Exception"); } catch (NotFoundException e) { assertNull(e.getPayload()); } PowerMock.verifyAll(); } @Test public void createDraftDeleted() throws Exception { final String uuid = "uuid"; final Node handle = createMock(Node.class); expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.of(handle)); expect(DocumentUtils.getVariantNodeType(handle)).andReturn(Optional.of("hippo:deleted")); PowerMock.replayAll(); try { documentsService.createDraft(uuid, session, locale); fail("No Exception"); } catch (NotFoundException e) { assertNull(e.getPayload()); } PowerMock.verifyAll(); } @Test public void createDraftNoWorkflow() throws Exception { final String uuid = "uuid"; final Node handle = createMock(Node.class); expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.of(handle)); expect(DocumentUtils.getVariantNodeType(handle)).andReturn(Optional.of("some:nodetype")); expect(DocumentUtils.getDisplayName(handle)).andReturn(Optional.of("Display Name")); expect(WorkflowUtils.getWorkflow(handle, "editing", EditableWorkflow.class)).andReturn(Optional.empty()); PowerMock.replayAll(); try { documentsService.createDraft(uuid, session, locale); fail("No Exception"); } catch (MethodNotAllowed e) { assertTrue(e.getPayload() instanceof ErrorInfo); ErrorInfo errorInfo = (ErrorInfo) e.getPayload(); assertThat(errorInfo.getReason(), equalTo(ErrorInfo.Reason.NOT_A_DOCUMENT)); assertThat(errorInfo.getParams().get("displayName"), equalTo("Display Name")); } PowerMock.verifyAll(); } @Test public void createDraftNotEditable() throws Exception { final String uuid = "uuid"; final Node handle = createMock(Node.class); final EditableWorkflow workflow = createMock(EditableWorkflow.class); expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.of(handle)); expect(DocumentUtils.getVariantNodeType(handle)).andReturn(Optional.of("some:nodetype")); expect(WorkflowUtils.getWorkflow(handle, "editing", EditableWorkflow.class)).andReturn(Optional.of(workflow)); expect(EditingUtils.canCreateDraft(workflow)).andReturn(false); expect(EditingUtils.determineEditingFailure(workflow, session)).andReturn(Optional.empty()); PowerMock.replayAll(); try { documentsService.createDraft(uuid, session, locale); fail("No Exception"); } catch (ForbiddenException e) { assertNull(e.getPayload()); } PowerMock.verifyAll(); } @Test public void createDraftOtherHolder() throws Exception { final String uuid = "uuid"; final Node handle = createMock(Node.class); final EditableWorkflow workflow = createMock(EditableWorkflow.class); final ErrorInfo errorInfo = new ErrorInfo(ErrorInfo.Reason.OTHER_HOLDER); expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.of(handle)); expect(DocumentUtils.getVariantNodeType(handle)).andReturn(Optional.of("some:nodetype")); expect(DocumentUtils.getDisplayName(handle)).andReturn(Optional.empty()); expect(WorkflowUtils.getWorkflow(handle, "editing", EditableWorkflow.class)).andReturn(Optional.of(workflow)); expect(EditingUtils.canCreateDraft(workflow)).andReturn(false); expect(EditingUtils.determineEditingFailure(workflow, session)).andReturn(Optional.of(errorInfo)); PowerMock.replayAll(); try { documentsService.createDraft(uuid, session, locale); fail("No Exception"); } catch (ForbiddenException e) { assertThat(e.getPayload(), equalTo(errorInfo)); } PowerMock.verifyAll(); } @Test public void createDraftNoDocumentNodeType() throws Exception { final String uuid = "uuid"; final Node handle = createMock(Node.class); final EditableWorkflow workflow = createMock(EditableWorkflow.class); expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.of(handle)); expect(DocumentUtils.getVariantNodeType(handle)).andReturn(Optional.of("some:nodetype")); expect(DocumentUtils.getVariantNodeType(handle)).andReturn(Optional.empty()); expect(WorkflowUtils.getWorkflow(handle, "editing", EditableWorkflow.class)).andReturn(Optional.of(workflow)); expect(EditingUtils.canCreateDraft(workflow)).andReturn(true); PowerMock.replayAll(); try { documentsService.createDraft(uuid, session, locale); fail("No Exception"); } catch (InternalServerErrorException e) { assertNull(e.getPayload()); } PowerMock.verifyAll(); } @Test public void createDraftNoSession() throws Exception { final String uuid = "uuid"; final String variantType = "variant:type"; final Node handle = createMock(Node.class); final EditableWorkflow workflow = createMock(EditableWorkflow.class); final DocumentTypesService documentTypesService = createMock(DocumentTypesService.class); expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.of(handle)); expect(DocumentUtils.getVariantNodeType(handle)).andReturn(Optional.of(variantType)).anyTimes(); expect(WorkflowUtils.getWorkflow(handle, "editing", EditableWorkflow.class)).andReturn(Optional.of(workflow)); expect(EditingUtils.canCreateDraft(workflow)).andReturn(true); expect(DocumentTypesService.get()).andReturn(documentTypesService); expect(JcrUtils.getNodePathQuietly(handle)).andReturn("/bla"); expect(handle.getSession()).andThrow(new RepositoryException()); PowerMock.replayAll(handle); try { documentsService.createDraft(uuid, session, locale); fail("No Exception"); } catch (InternalServerErrorException e) { assertNull(e.getPayload()); } PowerMock.verifyAll(); } @Test public void createDraftNoDocumentType() throws Exception { final String uuid = "uuid"; final String variantType = "variant:type"; final Node handle = createMock(Node.class); final EditableWorkflow workflow = createMock(EditableWorkflow.class); final DocumentTypesService documentTypesService = createMock(DocumentTypesService.class); expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.of(handle)); expect(DocumentUtils.getVariantNodeType(handle)).andReturn(Optional.of(variantType)).anyTimes(); expect(WorkflowUtils.getWorkflow(handle, "editing", EditableWorkflow.class)).andReturn(Optional.of(workflow)); expect(EditingUtils.canCreateDraft(workflow)).andReturn(true); expect(DocumentTypesService.get()).andReturn(documentTypesService); expect(JcrUtils.getNodePathQuietly(handle)).andReturn("/bla"); expect(handle.getSession()).andReturn(session); expect(documentTypesService.getDocumentType(variantType, session, locale)).andThrow(new NotFoundException()); PowerMock.replayAll(handle, documentTypesService); try { documentsService.createDraft(uuid, session, locale); fail("No Exception"); } catch (InternalServerErrorException e) { assertNull(e.getPayload()); } PowerMock.verifyAll(); } @Test public void createDraftUnknownValidator() throws Exception { final String uuid = "uuid"; final Node handle = createMock(Node.class); final EditableWorkflow workflow = createMock(EditableWorkflow.class); final DocumentType docType = provideDocumentType(handle); expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.of(handle)); expect(DocumentUtils.getDisplayName(handle)).andReturn(Optional.of("Display Name")); expect(WorkflowUtils.getWorkflow(handle, "editing", EditableWorkflow.class)).andReturn(Optional.of(workflow)); expect(EditingUtils.canCreateDraft(workflow)).andReturn(true); expect(docType.isReadOnlyDueToUnknownValidator()).andReturn(true); PowerMock.replayAll(docType); try { documentsService.createDraft(uuid, session, locale); fail("No Exception"); } catch (ForbiddenException e) { assertTrue(e.getPayload() instanceof ErrorInfo); final ErrorInfo errorInfo = (ErrorInfo) e.getPayload(); assertThat(errorInfo.getReason(), equalTo(ErrorInfo.Reason.UNKNOWN_VALIDATOR)); assertThat(errorInfo.getParams().get("displayName"), equalTo("Display Name")); } PowerMock.verifyAll(); } @Test public void createDraftFailed() throws Exception { final String uuid = "uuid"; final Node handle = createMock(Node.class); final EditableWorkflow workflow = createMock(EditableWorkflow.class); final DocumentType docType = provideDocumentType(handle); expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.of(handle)); expect(WorkflowUtils.getWorkflow(handle, "editing", EditableWorkflow.class)).andReturn(Optional.of(workflow)); expect(EditingUtils.canCreateDraft(workflow)).andReturn(true); expect(EditingUtils.createDraft(workflow, session)).andReturn(Optional.empty()); expect(docType.isReadOnlyDueToUnknownValidator()).andReturn(false); PowerMock.replayAll(docType); try { documentsService.createDraft(uuid, session, locale); fail("No Exception"); } catch (ForbiddenException e) { assertNull(e.getPayload()); } PowerMock.verifyAll(); } @Test public void createDraftSuccess() throws Exception { final String uuid = "uuid"; final Node handle = createMock(Node.class); final Node draft = createMock(Node.class); final Node unpublished = createMock(Node.class); final EditableWorkflow workflow = createMock(EditableWorkflow.class); final DocumentType docType = provideDocumentType(handle); final List<FieldType> fields = Collections.emptyList(); expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.of(handle)); expect(DocumentUtils.getDisplayName(handle)).andReturn(Optional.of("Display Name")); expect(WorkflowUtils.getWorkflow(handle, "editing", EditableWorkflow.class)).andReturn(Optional.of(workflow)); expect(EditingUtils.canCreateDraft(workflow)).andReturn(true); expect(EditingUtils.createDraft(workflow, session)).andReturn(Optional.of(draft)); FieldTypeUtils.readFieldValues(eq(draft), eq(fields), isA(Map.class)); expectLastCall(); expect(docType.getId()).andReturn("document:type"); expect(docType.isReadOnlyDueToUnknownValidator()).andReturn(false); expect(docType.getFields()).andReturn(fields).anyTimes(); expect(WorkflowUtils.getDocumentVariantNode(eq(handle), eq(WorkflowUtils.Variant.UNPUBLISHED))).andReturn(Optional.of(unpublished)); FieldTypeUtils.readFieldValues(eq(unpublished), eq(fields), isA(Map.class)); expectLastCall(); PowerMock.replayAll(docType); Document document = documentsService.createDraft(uuid, session, locale); assertThat(document.getId(), equalTo("uuid")); assertThat(document.getDisplayName(), equalTo("Display Name")); assertThat(document.getInfo().getType().getId(), equalTo("document:type")); assertThat(document.getInfo().isDirty(), equalTo(false)); PowerMock.verifyAll(); } @Test public void createDirtyDraft() throws Exception { final String uuid = "uuid"; final Node handle = createMock(Node.class); final Node draft = createMock(Node.class); final Node unpublished = createMock(Node.class); final EditableWorkflow workflow = createMock(EditableWorkflow.class); final DocumentType docType = provideDocumentType(handle); final List<FieldType> fields = Collections.emptyList(); expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.of(handle)); expect(DocumentUtils.getDisplayName(handle)).andReturn(Optional.of("Display Name")); expect(WorkflowUtils.getWorkflow(handle, "editing", EditableWorkflow.class)).andReturn(Optional.of(workflow)); expect(EditingUtils.canCreateDraft(workflow)).andReturn(true); expect(EditingUtils.createDraft(workflow, session)).andReturn(Optional.of(draft)); FieldTypeUtils.readFieldValues(eq(draft), eq(fields), isA(Map.class)); expectLastCall(); expect(docType.getId()).andReturn("document:type"); expect(docType.isReadOnlyDueToUnknownValidator()).andReturn(false); expect(docType.getFields()).andReturn(fields); expect(WorkflowUtils.getDocumentVariantNode(eq(handle), eq(WorkflowUtils.Variant.UNPUBLISHED))).andReturn(Optional.of(unpublished)); expect(docType.getFields()).andReturn(fields); FieldTypeUtils.readFieldValues(eq(unpublished), eq(fields), isA(Map.class)); expectLastCall().andAnswer(() -> ((Map)getCurrentArguments()[2]).put("extraField", new FieldValue("value"))); PowerMock.replayAll(docType); Document document = documentsService.createDraft(uuid, session, locale); assertThat(document.getId(), equalTo("uuid")); assertThat(document.getDisplayName(), equalTo("Display Name")); assertThat(document.getInfo().getType().getId(), equalTo("document:type")); assertThat(document.getInfo().isDirty(), equalTo(true)); PowerMock.verifyAll(); } @Test public void updateDraftNotAHandle() throws Exception { final Document document = new Document(); final String uuid = "uuid"; expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.empty()); PowerMock.replayAll(); try { documentsService.updateDraft(uuid, document, session, locale); fail("No Exception"); } catch (NotFoundException e) { assertNull(e.getPayload()); } PowerMock.verifyAll(); } @Test public void updateDraftNoWorkflow() throws Exception { final Document document = new Document(); final String uuid = "uuid"; final Node handle = createMock(Node.class); expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.of(handle)); expect(DocumentUtils.getVariantNodeType(handle)).andReturn(Optional.of("some:documenttype")); expect(DocumentUtils.getDisplayName(handle)).andReturn(Optional.empty()); expect(WorkflowUtils.getWorkflow(handle, "editing", EditableWorkflow.class)).andReturn(Optional.empty()); PowerMock.replayAll(); try { documentsService.updateDraft(uuid, document, session, locale); fail("No Exception"); } catch (MethodNotAllowed e) { assertTrue(e.getPayload() instanceof ErrorInfo); ErrorInfo errorInfo = (ErrorInfo) e.getPayload(); assertThat(errorInfo.getReason(), equalTo(ErrorInfo.Reason.NOT_A_DOCUMENT)); } PowerMock.verifyAll(); } @Test public void updateDraftVariantNotFound() throws Exception { final Document document = new Document(); final String uuid = "uuid"; final Node handle = createMock(Node.class); final EditableWorkflow workflow = createMock(EditableWorkflow.class); expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.of(handle)); expect(DocumentUtils.getVariantNodeType(handle)).andReturn(Optional.of("some:documenttype")); expect(WorkflowUtils.getWorkflow(handle, "editing", EditableWorkflow.class)).andReturn(Optional.of(workflow)); expect(WorkflowUtils.getDocumentVariantNode(handle, WorkflowUtils.Variant.DRAFT)).andReturn(Optional.empty()); PowerMock.replayAll(); try { documentsService.updateDraft(uuid, document, session, locale); fail("No Exception"); } catch (NotFoundException e) { assertNull(e.getPayload()); } PowerMock.verifyAll(); } @Test public void updateDraftNotEditing() throws Exception { final Document document = new Document(); final String uuid = "uuid"; final Node handle = createMock(Node.class); final Node draft = createMock(Node.class); final EditableWorkflow workflow = createMock(EditableWorkflow.class); expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.of(handle)); expect(DocumentUtils.getVariantNodeType(handle)).andReturn(Optional.of("some:documenttype")); expect(WorkflowUtils.getDocumentVariantNode(handle, WorkflowUtils.Variant.DRAFT)).andReturn(Optional.of(draft)); expect(WorkflowUtils.getWorkflow(handle, "editing", EditableWorkflow.class)).andReturn(Optional.of(workflow)); expect(EditingUtils.canUpdateDraft(workflow)).andReturn(false); expect(EditingUtils.determineEditingFailure(workflow, session)).andReturn(Optional.empty()); PowerMock.replayAll(); try { documentsService.updateDraft(uuid, document, session, locale); fail("No Exception"); } catch (ForbiddenException e) { assertTrue(e.getPayload() instanceof ErrorInfo); ErrorInfo errorInfo = (ErrorInfo) e.getPayload(); assertThat(errorInfo.getReason(), equalTo(ErrorInfo.Reason.NO_HOLDER)); assertNull(errorInfo.getParams()); } PowerMock.verifyAll(); } @Test public void updateDraftOtherHolder() throws Exception { final Document document = new Document(); final String uuid = "uuid"; final Node handle = createMock(Node.class); final Node draft = createMock(Node.class); final EditableWorkflow workflow = createMock(EditableWorkflow.class); final ErrorInfo errorInfo = new ErrorInfo(ErrorInfo.Reason.OTHER_HOLDER); expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.of(handle)); expect(DocumentUtils.getVariantNodeType(handle)).andReturn(Optional.of("some:documenttype")); expect(WorkflowUtils.getDocumentVariantNode(handle, WorkflowUtils.Variant.DRAFT)).andReturn(Optional.of(draft)); expect(WorkflowUtils.getWorkflow(handle, "editing", EditableWorkflow.class)).andReturn(Optional.of(workflow)); expect(EditingUtils.canUpdateDraft(workflow)).andReturn(false); expect(EditingUtils.determineEditingFailure(workflow, session)).andReturn(Optional.of(errorInfo)); PowerMock.replayAll(); try { documentsService.updateDraft(uuid, document, session, locale); fail("No Exception"); } catch (ForbiddenException e) { assertThat(e.getPayload(), equalTo(errorInfo)); } PowerMock.verifyAll(); } @Test public void updateDraftNoDocumentType() throws Exception { final Document document = new Document(); final String uuid = "uuid"; final Node handle = createMock(Node.class); final Node draft = createMock(Node.class); final EditableWorkflow workflow = createMock(EditableWorkflow.class); expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.of(handle)); expect(DocumentUtils.getVariantNodeType(handle)).andReturn(Optional.of("some:documenttype")); expect(DocumentUtils.getVariantNodeType(handle)).andReturn(Optional.empty()); expect(WorkflowUtils.getDocumentVariantNode(handle, WorkflowUtils.Variant.DRAFT)).andReturn(Optional.of(draft)); expect(WorkflowUtils.getWorkflow(handle, "editing", EditableWorkflow.class)).andReturn(Optional.of(workflow)); expect(EditingUtils.canUpdateDraft(workflow)).andReturn(true); PowerMock.replayAll(); try { documentsService.updateDraft(uuid, document, session, locale); fail("No Exception"); } catch (InternalServerErrorException e) { assertNull(e.getPayload()); } PowerMock.verifyAll(); } @Test public void updateDraftUnknownValidator() throws Exception { final Document document = new Document(); final String uuid = "uuid"; final Node handle = createMock(Node.class); final Node draft = createMock(Node.class); final EditableWorkflow workflow = createMock(EditableWorkflow.class); final DocumentType docType = provideDocumentType(handle); expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.of(handle)); expect(WorkflowUtils.getDocumentVariantNode(handle, WorkflowUtils.Variant.DRAFT)).andReturn(Optional.of(draft)); expect(WorkflowUtils.getWorkflow(handle, "editing", EditableWorkflow.class)).andReturn(Optional.of(workflow)); expect(EditingUtils.canUpdateDraft(workflow)).andReturn(true); expect(docType.isReadOnlyDueToUnknownValidator()).andReturn(true); PowerMock.replayAll(docType); try { documentsService.updateDraft(uuid, document, session, locale); fail("No Exception"); } catch (ForbiddenException e) { assertNull(e.getPayload()); } PowerMock.verifyAll(); } @Test public void updateDraftWriteFailure() throws Exception { final Document document = new Document(); final String uuid = "uuid"; final Node handle = createMock(Node.class); final Node draft = createMock(Node.class); final EditableWorkflow workflow = createMock(EditableWorkflow.class); final DocumentType docType = provideDocumentType(handle); final BadRequestException badRequest = new BadRequestException(); expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.of(handle)); expect(WorkflowUtils.getDocumentVariantNode(handle, WorkflowUtils.Variant.DRAFT)).andReturn(Optional.of(draft)); expect(WorkflowUtils.getWorkflow(handle, "editing", EditableWorkflow.class)).andReturn(Optional.of(workflow)); expect(EditingUtils.canUpdateDraft(workflow)).andReturn(true); FieldTypeUtils.writeFieldValues(document.getFields(), Collections.emptyList(), draft); expectLastCall().andThrow(badRequest); expect(docType.isReadOnlyDueToUnknownValidator()).andReturn(false); expect(docType.getFields()).andReturn(Collections.emptyList()); PowerMock.replayAll(docType); try { documentsService.updateDraft(uuid, document, session, locale); fail("No Exception"); } catch (BadRequestException e) { assertThat(e, equalTo(badRequest)); } PowerMock.verifyAll(); } @Test public void updateDraftSaveFailure() throws Exception { final Document document = new Document(); final String uuid = "uuid"; final Node handle = createMock(Node.class); final Node draft = createMock(Node.class); final EditableWorkflow workflow = createMock(EditableWorkflow.class); final DocumentType docType = provideDocumentType(handle); expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.of(handle)); expect(WorkflowUtils.getDocumentVariantNode(handle, WorkflowUtils.Variant.DRAFT)).andReturn(Optional.of(draft)); expect(WorkflowUtils.getWorkflow(handle, "editing", EditableWorkflow.class)).andReturn(Optional.of(workflow)); expect(EditingUtils.canUpdateDraft(workflow)).andReturn(true); FieldTypeUtils.writeFieldValues(document.getFields(), Collections.emptyList(), draft); expectLastCall(); expect(docType.isReadOnlyDueToUnknownValidator()).andReturn(false); expect(docType.getFields()).andReturn(Collections.emptyList()); session.save(); expectLastCall().andThrow(new RepositoryException()); PowerMock.replayAll(docType, session); try { documentsService.updateDraft(uuid, document, session, locale); fail("No Exception"); } catch (InternalServerErrorException e) { assertNull(e.getPayload()); } PowerMock.verifyAll(); } @Test public void updateDraftValidationFailure() throws Exception { final Document document = new Document(); final String uuid = "uuid"; final Node handle = createMock(Node.class); final Node draft = createMock(Node.class); final EditableWorkflow workflow = createMock(EditableWorkflow.class); final DocumentType docType = provideDocumentType(handle); expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.of(handle)); expect(WorkflowUtils.getDocumentVariantNode(handle, WorkflowUtils.Variant.DRAFT)).andReturn(Optional.of(draft)); expect(WorkflowUtils.getWorkflow(handle, "editing", EditableWorkflow.class)).andReturn(Optional.of(workflow)); expect(EditingUtils.canUpdateDraft(workflow)).andReturn(true); FieldTypeUtils.writeFieldValues(document.getFields(), Collections.emptyList(), draft); expectLastCall(); expect(FieldTypeUtils.validateFieldValues(document.getFields(), Collections.emptyList())).andReturn(false); expect(docType.isReadOnlyDueToUnknownValidator()).andReturn(false); expect(docType.getFields()).andReturn(Collections.emptyList()).anyTimes(); session.save(); expectLastCall(); PowerMock.replayAll(docType, session); try { documentsService.updateDraft(uuid, document, session, locale); fail("No Exception"); } catch (BadRequestException e) { assertThat(e.getPayload(), equalTo(document)); } PowerMock.verifyAll(); } @Test public void updateDraftCopyToPreviewFailure() throws Exception { final Document document = new Document(); final String uuid = "uuid"; final Node handle = createMock(Node.class); final Node draft = createMock(Node.class); final EditableWorkflow workflow = createMock(EditableWorkflow.class); final DocumentType docType = provideDocumentType(handle); expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.of(handle)); expect(WorkflowUtils.getDocumentVariantNode(handle, WorkflowUtils.Variant.DRAFT)).andReturn(Optional.of(draft)); expect(WorkflowUtils.getWorkflow(handle, "editing", EditableWorkflow.class)).andReturn(Optional.of(workflow)); expect(EditingUtils.canUpdateDraft(workflow)).andReturn(true); expect(EditingUtils.copyToPreviewAndKeepEditing(workflow, session)).andReturn(Optional.empty()); expect(EditingUtils.determineEditingFailure(workflow, session)).andReturn(Optional.empty()); FieldTypeUtils.writeFieldValues(document.getFields(), Collections.emptyList(), draft); expectLastCall(); expect(FieldTypeUtils.validateFieldValues(document.getFields(), Collections.emptyList())).andReturn(true); expect(docType.isReadOnlyDueToUnknownValidator()).andReturn(false); expect(docType.getFields()).andReturn(Collections.emptyList()).anyTimes(); session.save(); expectLastCall(); PowerMock.replayAll(docType, session); try { documentsService.updateDraft(uuid, document, session, locale); fail("No Exception"); } catch (InternalServerErrorException e) { assertTrue(e.getPayload() instanceof ErrorInfo); ErrorInfo errorInfo = (ErrorInfo) e.getPayload(); assertThat(errorInfo.getReason(), equalTo(ErrorInfo.Reason.NO_HOLDER)); assertNull(errorInfo.getParams()); } PowerMock.verifyAll(); } @Test public void updateDraftSuccess() throws Exception { final Document document = new Document(); final String uuid = "uuid"; final Node handle = createMock(Node.class); final Node draft = createMock(Node.class); final EditableWorkflow workflow = createMock(EditableWorkflow.class); final DocumentType docType = provideDocumentType(handle); expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.of(handle)); expect(WorkflowUtils.getDocumentVariantNode(handle, WorkflowUtils.Variant.DRAFT)).andReturn(Optional.of(draft)); expect(WorkflowUtils.getWorkflow(handle, "editing", EditableWorkflow.class)).andReturn(Optional.of(workflow)); expect(EditingUtils.canUpdateDraft(workflow)).andReturn(true); expect(EditingUtils.copyToPreviewAndKeepEditing(workflow, session)).andReturn(Optional.of(draft)); FieldTypeUtils.writeFieldValues(document.getFields(), Collections.emptyList(), draft); expectLastCall(); expect(FieldTypeUtils.validateFieldValues(document.getFields(), Collections.emptyList())).andReturn(true); expect(docType.getFields()).andReturn(Collections.emptyList()); FieldTypeUtils.readFieldValues(draft, Collections.emptyList(), document.getFields()); expectLastCall(); expect(docType.isReadOnlyDueToUnknownValidator()).andReturn(false); expect(docType.getFields()).andReturn(Collections.emptyList()).anyTimes(); session.save(); expectLastCall(); PowerMock.replayAll(docType, session); Document persistedDocument = documentsService.updateDraft(uuid, document, session, locale); assertThat(persistedDocument, equalTo(document)); PowerMock.verifyAll(); } @Test public void updateDirtyDraftSuccess() throws Exception { final Document document = new Document(); document.getInfo().setDirty(true); final String uuid = "uuid"; final Node handle = createMock(Node.class); final Node draft = createMock(Node.class); final EditableWorkflow workflow = createMock(EditableWorkflow.class); final DocumentType docType = provideDocumentType(handle); expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.of(handle)); expect(WorkflowUtils.getDocumentVariantNode(handle, WorkflowUtils.Variant.DRAFT)).andReturn(Optional.of(draft)); expect(WorkflowUtils.getWorkflow(handle, "editing", EditableWorkflow.class)).andReturn(Optional.of(workflow)); expect(EditingUtils.canUpdateDraft(workflow)).andReturn(true); expect(EditingUtils.copyToPreviewAndKeepEditing(workflow, session)).andReturn(Optional.of(draft)); FieldTypeUtils.writeFieldValues(document.getFields(), Collections.emptyList(), draft); expectLastCall(); expect(FieldTypeUtils.validateFieldValues(document.getFields(), Collections.emptyList())).andReturn(true); expect(docType.getFields()).andReturn(Collections.emptyList()); FieldTypeUtils.readFieldValues(draft, Collections.emptyList(), document.getFields()); expectLastCall(); expect(docType.isReadOnlyDueToUnknownValidator()).andReturn(false); expect(docType.getFields()).andReturn(Collections.emptyList()).anyTimes(); session.save(); expectLastCall(); PowerMock.replayAll(docType, session); Document persistedDocument = documentsService.updateDraft(uuid, document, session, locale); assertThat(persistedDocument.getId(), equalTo(document.getId())); assertThat(persistedDocument.getDisplayName(), equalTo(document.getDisplayName())); assertThat(persistedDocument.getFields(), equalTo(document.getFields())); assertThat(persistedDocument.getInfo().isDirty(), equalTo(false)); PowerMock.verifyAll(); } @Test public void updateDraftFieldNotAHandle() throws Exception { final String uuid = "uuid"; final FieldPath fieldPath = new FieldPath("ns:field"); final List<FieldValue> fieldValues = Collections.singletonList(new FieldValue("drafted value")); expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.empty()); PowerMock.replayAll(); try { documentsService.updateDraftField(uuid, fieldPath, fieldValues, session, locale); fail("No Exception"); } catch (NotFoundException e) { assertNull(e.getPayload()); } PowerMock.verifyAll(); } @Test public void updateDraftFieldNoWorkflow() throws Exception { final String uuid = "uuid"; final Node handle = createMock(Node.class); final FieldPath fieldPath = new FieldPath("ns:field"); final List<FieldValue> fieldValues = Collections.singletonList(new FieldValue("drafted value")); expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.of(handle)); expect(DocumentUtils.getVariantNodeType(handle)).andReturn(Optional.of("some:documenttype")); expect(DocumentUtils.getDisplayName(handle)).andReturn(Optional.empty()); expect(WorkflowUtils.getWorkflow(handle, "editing", EditableWorkflow.class)).andReturn(Optional.empty()); PowerMock.replayAll(); try { documentsService.updateDraftField(uuid, fieldPath, fieldValues, session, locale); fail("No Exception"); } catch (MethodNotAllowed e) { assertTrue(e.getPayload() instanceof ErrorInfo); ErrorInfo errorInfo = (ErrorInfo) e.getPayload(); assertThat(errorInfo.getReason(), equalTo(ErrorInfo.Reason.NOT_A_DOCUMENT)); } PowerMock.verifyAll(); } @Test public void updateDraftFieldVariantNotFound() throws Exception { final String uuid = "uuid"; final Node handle = createMock(Node.class); final EditableWorkflow workflow = createMock(EditableWorkflow.class); final FieldPath fieldPath = new FieldPath("ns:field"); final List<FieldValue> fieldValues = Collections.singletonList(new FieldValue("drafted value")); expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.of(handle)); expect(DocumentUtils.getVariantNodeType(handle)).andReturn(Optional.of("some:documenttype")); expect(WorkflowUtils.getWorkflow(handle, "editing", EditableWorkflow.class)).andReturn(Optional.of(workflow)); expect(WorkflowUtils.getDocumentVariantNode(handle, WorkflowUtils.Variant.DRAFT)).andReturn(Optional.empty()); PowerMock.replayAll(); try { documentsService.updateDraftField(uuid, fieldPath, fieldValues, session, locale); fail("No Exception"); } catch (NotFoundException e) { assertNull(e.getPayload()); } PowerMock.verifyAll(); } @Test public void updateDraftFieldNotEditing() throws Exception { final String uuid = "uuid"; final Node handle = createMock(Node.class); final Node draft = createMock(Node.class); final EditableWorkflow workflow = createMock(EditableWorkflow.class); final FieldPath fieldPath = new FieldPath("ns:field"); final List<FieldValue> fieldValues = Collections.singletonList(new FieldValue("drafted value")); expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.of(handle)); expect(DocumentUtils.getVariantNodeType(handle)).andReturn(Optional.of("some:documenttype")); expect(WorkflowUtils.getDocumentVariantNode(handle, WorkflowUtils.Variant.DRAFT)).andReturn(Optional.of(draft)); expect(WorkflowUtils.getWorkflow(handle, "editing", EditableWorkflow.class)).andReturn(Optional.of(workflow)); expect(EditingUtils.canUpdateDraft(workflow)).andReturn(false); expect(EditingUtils.determineEditingFailure(workflow, session)).andReturn(Optional.empty()); PowerMock.replayAll(); try { documentsService.updateDraftField(uuid, fieldPath, fieldValues, session, locale); fail("No Exception"); } catch (ForbiddenException e) { assertTrue(e.getPayload() instanceof ErrorInfo); ErrorInfo errorInfo = (ErrorInfo) e.getPayload(); assertThat(errorInfo.getReason(), equalTo(ErrorInfo.Reason.NO_HOLDER)); assertNull(errorInfo.getParams()); } PowerMock.verifyAll(); } @Test public void updateDraftFieldOtherHolder() throws Exception { final String uuid = "uuid"; final Node handle = createMock(Node.class); final Node draft = createMock(Node.class); final EditableWorkflow workflow = createMock(EditableWorkflow.class); final ErrorInfo errorInfo = new ErrorInfo(ErrorInfo.Reason.OTHER_HOLDER); final FieldPath fieldPath = new FieldPath("ns:field"); final List<FieldValue> fieldValues = Collections.singletonList(new FieldValue("drafted value")); expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.of(handle)); expect(DocumentUtils.getVariantNodeType(handle)).andReturn(Optional.of("some:documenttype")); expect(WorkflowUtils.getDocumentVariantNode(handle, WorkflowUtils.Variant.DRAFT)).andReturn(Optional.of(draft)); expect(WorkflowUtils.getWorkflow(handle, "editing", EditableWorkflow.class)).andReturn(Optional.of(workflow)); expect(EditingUtils.canUpdateDraft(workflow)).andReturn(false); expect(EditingUtils.determineEditingFailure(workflow, session)).andReturn(Optional.of(errorInfo)); PowerMock.replayAll(); try { documentsService.updateDraftField(uuid, fieldPath, fieldValues, session, locale); fail("No Exception"); } catch (ForbiddenException e) { assertThat(e.getPayload(), equalTo(errorInfo)); } PowerMock.verifyAll(); } @Test public void updateDraftFieldNoDocumentType() throws Exception { final String uuid = "uuid"; final Node handle = createMock(Node.class); final Node draft = createMock(Node.class); final EditableWorkflow workflow = createMock(EditableWorkflow.class); final FieldPath fieldPath = new FieldPath("ns:field"); final List<FieldValue> fieldValues = Collections.singletonList(new FieldValue("drafted value")); expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.of(handle)); expect(DocumentUtils.getVariantNodeType(handle)).andReturn(Optional.of("some:documenttype")); expect(DocumentUtils.getVariantNodeType(handle)).andReturn(Optional.empty()); expect(WorkflowUtils.getDocumentVariantNode(handle, WorkflowUtils.Variant.DRAFT)).andReturn(Optional.of(draft)); expect(WorkflowUtils.getWorkflow(handle, "editing", EditableWorkflow.class)).andReturn(Optional.of(workflow)); expect(EditingUtils.canUpdateDraft(workflow)).andReturn(true); PowerMock.replayAll(); try { documentsService.updateDraftField(uuid, fieldPath, fieldValues, session, locale); fail("No Exception"); } catch (InternalServerErrorException e) { assertNull(e.getPayload()); } PowerMock.verifyAll(); } @Test public void updateDraftFieldUnknownValidator() throws Exception { final String uuid = "uuid"; final Node handle = createMock(Node.class); final Node draft = createMock(Node.class); final EditableWorkflow workflow = createMock(EditableWorkflow.class); final DocumentType docType = provideDocumentType(handle); final FieldPath fieldPath = new FieldPath("ns:field"); final List<FieldValue> fieldValues = Collections.singletonList(new FieldValue("drafted value")); expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.of(handle)); expect(WorkflowUtils.getDocumentVariantNode(handle, WorkflowUtils.Variant.DRAFT)).andReturn(Optional.of(draft)); expect(WorkflowUtils.getWorkflow(handle, "editing", EditableWorkflow.class)).andReturn(Optional.of(workflow)); expect(EditingUtils.canUpdateDraft(workflow)).andReturn(true); expect(docType.isReadOnlyDueToUnknownValidator()).andReturn(true); PowerMock.replayAll(docType); try { documentsService.updateDraftField(uuid, fieldPath, fieldValues, session, locale); fail("No Exception"); } catch (ForbiddenException e) { assertNull(e.getPayload()); } PowerMock.verifyAll(); } @Test public void updateDraftFieldWriteFailure() throws Exception { final String uuid = "uuid"; final Node handle = createMock(Node.class); final Node draft = createMock(Node.class); final EditableWorkflow workflow = createMock(EditableWorkflow.class); final DocumentType docType = provideDocumentType(handle); final FieldPath fieldPath = new FieldPath("ns:field"); final List<FieldType> fields = Collections.emptyList(); final List<FieldValue> fieldValues = Collections.singletonList(new FieldValue("drafted value")); final BadRequestException badRequest = new BadRequestException(); expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.of(handle)); expect(WorkflowUtils.getDocumentVariantNode(handle, WorkflowUtils.Variant.DRAFT)).andReturn(Optional.of(draft)); expect(WorkflowUtils.getWorkflow(handle, "editing", EditableWorkflow.class)).andReturn(Optional.of(workflow)); expect(EditingUtils.canUpdateDraft(workflow)).andReturn(true); expect(docType.isReadOnlyDueToUnknownValidator()).andReturn(false); expect(docType.getFields()).andReturn(Collections.emptyList()); expect(FieldTypeUtils.writeFieldValue(fieldPath, fieldValues, fields, draft)).andThrow(badRequest); PowerMock.replayAll(docType); try { documentsService.updateDraftField(uuid, fieldPath, fieldValues, session, locale); fail("No Exception"); } catch (BadRequestException e) { assertThat(e, equalTo(badRequest)); } PowerMock.verifyAll(); } @Test public void updateDraftFieldNotSavedWhenUnknown() throws Exception { final String uuid = "uuid"; final Node handle = createMock(Node.class); final Node draft = createMock(Node.class); final EditableWorkflow workflow = createMock(EditableWorkflow.class); final DocumentType docType = provideDocumentType(handle); final FieldPath fieldPath = new FieldPath("ns:field"); final List<FieldValue> fieldValues = Collections.singletonList(new FieldValue("drafted value")); final List<FieldType> fields = Collections.emptyList(); expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.of(handle)); expect(WorkflowUtils.getDocumentVariantNode(handle, WorkflowUtils.Variant.DRAFT)).andReturn(Optional.of(draft)); expect(WorkflowUtils.getWorkflow(handle, "editing", EditableWorkflow.class)).andReturn(Optional.of(workflow)); expect(EditingUtils.canUpdateDraft(workflow)).andReturn(true); expect(docType.isReadOnlyDueToUnknownValidator()).andReturn(false); expect(docType.getFields()).andReturn(fields); expect(FieldTypeUtils.writeFieldValue(fieldPath, fieldValues, fields, draft)).andReturn(false); PowerMock.replayAll(docType, session); documentsService.updateDraftField(uuid, fieldPath, fieldValues, session, locale); PowerMock.verifyAll(); } @Test public void updateDraftFieldSuccess() throws Exception { final String uuid = "uuid"; final Node handle = createMock(Node.class); final Node draft = createMock(Node.class); final EditableWorkflow workflow = createMock(EditableWorkflow.class); final DocumentType docType = provideDocumentType(handle); final FieldPath fieldPath = new FieldPath("ns:field"); final List<FieldValue> fieldValues = Collections.singletonList(new FieldValue("drafted value")); final List<FieldType> fields = Collections.emptyList(); expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.of(handle)); expect(WorkflowUtils.getDocumentVariantNode(handle, WorkflowUtils.Variant.DRAFT)).andReturn(Optional.of(draft)); expect(WorkflowUtils.getWorkflow(handle, "editing", EditableWorkflow.class)).andReturn(Optional.of(workflow)); expect(EditingUtils.canUpdateDraft(workflow)).andReturn(true); expect(docType.isReadOnlyDueToUnknownValidator()).andReturn(false); expect(docType.getFields()).andReturn(fields); expect(FieldTypeUtils.writeFieldValue(fieldPath, fieldValues, fields, draft)).andReturn(true); session.save(); expectLastCall(); PowerMock.replayAll(docType, session); documentsService.updateDraftField(uuid, fieldPath, fieldValues, session, locale); PowerMock.verifyAll(); } @Test public void updateDraftFieldSaveFailure() throws Exception { final String uuid = "uuid"; final Node handle = createMock(Node.class); final Node draft = createMock(Node.class); final EditableWorkflow workflow = createMock(EditableWorkflow.class); final DocumentType docType = provideDocumentType(handle); final FieldPath fieldPath = new FieldPath("ns:field"); final List<FieldValue> fieldValues = Collections.singletonList(new FieldValue("drafted value")); final List<FieldType> fields = Collections.emptyList(); expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.of(handle)); expect(WorkflowUtils.getDocumentVariantNode(handle, WorkflowUtils.Variant.DRAFT)).andReturn(Optional.of(draft)); expect(WorkflowUtils.getWorkflow(handle, "editing", EditableWorkflow.class)).andReturn(Optional.of(workflow)); expect(EditingUtils.canUpdateDraft(workflow)).andReturn(true); expect(docType.isReadOnlyDueToUnknownValidator()).andReturn(false); expect(docType.getFields()).andReturn(Collections.emptyList()); expect(FieldTypeUtils.writeFieldValue(fieldPath, fieldValues, fields, draft)).andReturn(true); session.save(); expectLastCall().andThrow(new RepositoryException()); PowerMock.replayAll(docType, session); try { documentsService.updateDraftField(uuid, fieldPath, fieldValues, session, locale); fail("No Exception"); } catch (InternalServerErrorException e) { assertNull(e.getPayload()); } PowerMock.verifyAll(); } @Test public void deleteDraftNotAHandle() throws Exception { final String uuid = "uuid"; expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.empty()); PowerMock.replayAll(); try { documentsService.deleteDraft(uuid, session, locale); fail("No Exception"); } catch (NotFoundException e) { assertNull(e.getPayload()); } PowerMock.verifyAll(); } @Test public void deleteDraftNoWorkflow() throws Exception { final String uuid = "uuid"; final Node handle = createMock(Node.class); expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.of(handle)); expect(DocumentUtils.getVariantNodeType(handle)).andReturn(Optional.of("some:documenttype")); expect(DocumentUtils.getDisplayName(handle)).andReturn(Optional.empty()); expect(WorkflowUtils.getWorkflow(handle, "editing", EditableWorkflow.class)).andReturn(Optional.empty()); PowerMock.replayAll(); try { documentsService.deleteDraft(uuid, session, locale); fail("No Exception"); } catch (MethodNotAllowed e) { assertTrue(e.getPayload() instanceof ErrorInfo); ErrorInfo errorInfo = (ErrorInfo) e.getPayload(); assertThat(errorInfo.getReason(), equalTo(ErrorInfo.Reason.NOT_A_DOCUMENT)); } PowerMock.verifyAll(); } @Test public void deleteDraftNotDeletable() throws Exception { final String uuid = "uuid"; final Node handle = createMock(Node.class); final EditableWorkflow workflow = createMock(EditableWorkflow.class); expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.of(handle)); expect(DocumentUtils.getVariantNodeType(handle)).andReturn(Optional.of("some:documenttype")); expect(WorkflowUtils.getWorkflow(handle, "editing", EditableWorkflow.class)).andReturn(Optional.of(workflow)); expect(EditingUtils.canDeleteDraft(workflow)).andReturn(false); PowerMock.replayAll(); try { documentsService.deleteDraft(uuid, session, locale); fail("No Exception"); } catch (ForbiddenException e) { assertTrue(e.getPayload() instanceof ErrorInfo); ErrorInfo errorInfo = (ErrorInfo) e.getPayload(); assertThat(errorInfo.getReason(), equalTo(ErrorInfo.Reason.ALREADY_DELETED)); } PowerMock.verifyAll(); } @Test public void deleteDraftDisposeFailure() throws Exception { final String uuid = "uuid"; final Node handle = createMock(Node.class); final EditableWorkflow workflow = createMock(EditableWorkflow.class); expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.of(handle)); expect(DocumentUtils.getVariantNodeType(handle)).andReturn(Optional.of("some:documenttype")); expect(WorkflowUtils.getWorkflow(handle, "editing", EditableWorkflow.class)).andReturn(Optional.of(workflow)); expect(EditingUtils.canDeleteDraft(workflow)).andReturn(true); expect(workflow.disposeEditableInstance()).andThrow(new WorkflowException("bla")); PowerMock.replayAll(workflow); try { documentsService.deleteDraft(uuid, session, locale); fail("No Exception"); } catch (InternalServerErrorException e) { assertNull(e.getPayload()); } PowerMock.verifyAll(); } @Test public void deleteDraftSuccess() throws Exception { final String uuid = "uuid"; final Node handle = createMock(Node.class); final EditableWorkflow workflow = createMock(EditableWorkflow.class); expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.of(handle)); expect(DocumentUtils.getVariantNodeType(handle)).andReturn(Optional.of("some:documenttype")); expect(WorkflowUtils.getWorkflow(handle, "editing", EditableWorkflow.class)).andReturn(Optional.of(workflow)); expect(EditingUtils.canDeleteDraft(workflow)).andReturn(true); expect(workflow.disposeEditableInstance()).andReturn(null); PowerMock.replayAll(workflow); documentsService.deleteDraft(uuid, session, locale); PowerMock.verifyAll(); } @Test public void getPublished() throws Exception { final String uuid = "uuid"; final Node handle = createMock(Node.class); final Node published = createMock(Node.class); final DocumentType docType = provideDocumentType(handle); expect(DocumentUtils.getHandle(uuid, session)).andReturn(Optional.of(handle)); expect(DocumentUtils.getDisplayName(handle)).andReturn(Optional.of("Document Display Name")); expect(WorkflowUtils.getDocumentVariantNode(handle, WorkflowUtils.Variant.PUBLISHED)).andReturn(Optional.of(published)); FieldTypeUtils.readFieldValues(eq(published), eq(Collections.emptyList()), isA(Map.class)); expectLastCall(); expect(docType.getId()).andReturn("document:type"); expect(docType.getFields()).andReturn(Collections.emptyList()); PowerMock.replayAll(docType); Document document = documentsService.getPublished(uuid, session, locale); assertThat(document.getDisplayName(), equalTo("Document Display Name")); PowerMock.verifyAll(); } private DocumentType provideDocumentType(final Node handle) throws Exception { final String variantType = "variant:type"; final DocumentType docType = createMock(DocumentType.class); final DocumentTypesService documentTypesService = createMock(DocumentTypesService.class); expect(DocumentUtils.getVariantNodeType(handle)).andReturn(Optional.of(variantType)).anyTimes(); expect(DocumentTypesService.get()).andReturn(documentTypesService); expect(documentTypesService.getDocumentType(variantType, session, locale)).andReturn(docType); expect(handle.getSession()).andReturn(session); replay(documentTypesService, handle); return docType; } }
/* * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.aop.framework; import java.io.Serializable; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.List; import org.aopalliance.intercept.MethodInvocation; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.aop.AopInvocationException; import org.springframework.aop.RawTargetAccess; import org.springframework.aop.TargetSource; import org.springframework.aop.support.AopUtils; import org.springframework.core.DecoratingProxy; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; /** * JDK-based {@link AopProxy} implementation for the Spring AOP framework, * based on JDK {@link java.lang.reflect.Proxy dynamic proxies}. * * <p>Creates a dynamic proxy, implementing the interfaces exposed by * the AopProxy. Dynamic proxies <i>cannot</i> be used to proxy methods * defined in classes, rather than interfaces. * * <p>Objects of this type should be obtained through proxy factories, * configured by an {@link AdvisedSupport} class. This class is internal * to Spring's AOP framework and need not be used directly by client code. * * <p>Proxies created using this class will be thread-safe if the * underlying (target) class is thread-safe. * * <p>Proxies are serializable so long as all Advisors (including Advices * and Pointcuts) and the TargetSource are serializable. * * @author Rod Johnson * @author Juergen Hoeller * @author Rob Harrop * @author Dave Syer * @see java.lang.reflect.Proxy * @see AdvisedSupport * @see ProxyFactory */ final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializable { /** use serialVersionUID from Spring 1.2 for interoperability. */ private static final long serialVersionUID = 5531744639992436476L; /* * NOTE: We could avoid the code duplication between this class and the CGLIB * proxies by refactoring "invoke" into a template method. However, this approach * adds at least 10% performance overhead versus a copy-paste solution, so we sacrifice * elegance for performance. (We have a good test suite to ensure that the different * proxies behave the same :-) * This way, we can also more easily take advantage of minor optimizations in each class. */ /** We use a static Log to avoid serialization issues. */ private static final Log logger = LogFactory.getLog(JdkDynamicAopProxy.class); /** Config used to configure this proxy. */ private final AdvisedSupport advised; /** * Is the {@link #equals} method defined on the proxied interfaces? */ private boolean equalsDefined; /** * Is the {@link #hashCode} method defined on the proxied interfaces? */ private boolean hashCodeDefined; /** * Construct a new JdkDynamicAopProxy for the given AOP configuration. * @param config the AOP configuration as AdvisedSupport object * @throws AopConfigException if the com.Li.config is invalid. We try to throw an informative * exception in this case, rather than let a mysterious failure happen later. */ public JdkDynamicAopProxy(AdvisedSupport config) throws AopConfigException { Assert.notNull(config, "AdvisedSupport must not be null"); if (config.getAdvisors().length == 0 && config.getTargetSource() == AdvisedSupport.EMPTY_TARGET_SOURCE) { throw new AopConfigException("No advisors and no TargetSource specified"); } this.advised = config; } @Override public Object getProxy() { return getProxy(ClassUtils.getDefaultClassLoader()); } @Override public Object getProxy(@Nullable ClassLoader classLoader) { if (logger.isTraceEnabled()) { logger.trace("Creating JDK dynamic proxy: " + this.advised.getTargetSource()); } Class<?>[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised, true); findDefinedEqualsAndHashCodeMethods(proxiedInterfaces); return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this); } /** * Finds any {@link #equals} or {@link #hashCode} method that may be defined * on the supplied set of interfaces. * @param proxiedInterfaces the interfaces to introspect */ private void findDefinedEqualsAndHashCodeMethods(Class<?>[] proxiedInterfaces) { for (Class<?> proxiedInterface : proxiedInterfaces) { Method[] methods = proxiedInterface.getDeclaredMethods(); for (Method method : methods) { if (AopUtils.isEqualsMethod(method)) { this.equalsDefined = true; } if (AopUtils.isHashCodeMethod(method)) { this.hashCodeDefined = true; } if (this.equalsDefined && this.hashCodeDefined) { return; } } } } /** * Implementation of {@code InvocationHandler.invoke}. * <p>Callers will see exactly the exception thrown by the target, * unless a hook method throws an exception. */ @Override @Nullable public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object oldProxy = null; boolean setProxyContext = false; TargetSource targetSource = this.advised.targetSource; Object target = null; try { if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) { // The target does not implement the equals(Object) method itself. return equals(args[0]); } else if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) { // The target does not implement the hashCode() method itself. return hashCode(); } else if (method.getDeclaringClass() == DecoratingProxy.class) { // There is only getDecoratedClass() declared -> dispatch to proxy com.Li.config. return AopProxyUtils.ultimateTargetClass(this.advised); } else if (!this.advised.opaque && method.getDeclaringClass().isInterface() && method.getDeclaringClass().isAssignableFrom(Advised.class)) { // Service invocations on ProxyConfig with the proxy com.Li.config... return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args); } Object retVal; if (this.advised.exposeProxy) { // Make invocation available if necessary. oldProxy = AopContext.setCurrentProxy(proxy); setProxyContext = true; } // Get as late as possible to minimize the time we "own" the target, // in case it comes from a pool. target = targetSource.getTarget(); Class<?> targetClass = (target != null ? target.getClass() : null); // Get the interception chain for this method. List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass); // Check whether we have any advice. If we don't, we can fallback on direct // reflective invocation of the target, and avoid creating a MethodInvocation. if (chain.isEmpty()) { // We can skip creating a MethodInvocation: just invoke the target directly // Note that the final invoker must be an InvokerInterceptor so we know it does // nothing but a reflective operation on the target, and no hot swapping or fancy proxying. Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args); retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse); } else { // We need to create a method invocation... MethodInvocation invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain); // Proceed to the joinpoint through the interceptor chain. retVal = invocation.proceed(); } // Massage return value if necessary. Class<?> returnType = method.getReturnType(); if (retVal != null && retVal == target && returnType != Object.class && returnType.isInstance(proxy) && !RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) { // Special case: it returned "this" and the return type of the method // is type-compatible. Note that we can't help if the target sets // a reference to itself in another returned object. retVal = proxy; } else if (retVal == null && returnType != Void.TYPE && returnType.isPrimitive()) { throw new AopInvocationException( "Null return value from advice does not match primitive return type for: " + method); } return retVal; } finally { if (target != null && !targetSource.isStatic()) { // Must have come from TargetSource. targetSource.releaseTarget(target); } if (setProxyContext) { // Restore old proxy. AopContext.setCurrentProxy(oldProxy); } } } /** * Equality means interfaces, advisors and TargetSource are equal. * <p>The compared object may be a JdkDynamicAopProxy instance itself * or a dynamic proxy wrapping a JdkDynamicAopProxy instance. */ @Override public boolean equals(@Nullable Object other) { if (other == this) { return true; } if (other == null) { return false; } JdkDynamicAopProxy otherProxy; if (other instanceof JdkDynamicAopProxy) { otherProxy = (JdkDynamicAopProxy) other; } else if (Proxy.isProxyClass(other.getClass())) { InvocationHandler ih = Proxy.getInvocationHandler(other); if (!(ih instanceof JdkDynamicAopProxy)) { return false; } otherProxy = (JdkDynamicAopProxy) ih; } else { // Not a valid comparison... return false; } // If we get here, otherProxy is the other AopProxy. return AopProxyUtils.equalsInProxy(this.advised, otherProxy.advised); } /** * Proxy uses the hash code of the TargetSource. */ @Override public int hashCode() { return JdkDynamicAopProxy.class.hashCode() * 13 + this.advised.getTargetSource().hashCode(); } }
/** * Copyright (c) 2019,2020 honintech * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package cn.weforward.devops.weforward.view; import java.util.List; import cn.weforward.common.util.TransList; import cn.weforward.devops.project.Bind; import cn.weforward.devops.project.Env; import cn.weforward.devops.project.Machine; import cn.weforward.devops.project.MachineInfo; import cn.weforward.devops.project.Prop; import cn.weforward.devops.user.GroupRight; import cn.weforward.protocol.doc.annotation.DocAttribute; import cn.weforward.protocol.doc.annotation.DocObject; /** * 机器视图 * * @author daibo * */ @DocObject(description = "机器视图") public class MachineView { /** 机器 */ protected Machine m_Machine; /** * 构造 * * @param machine */ public MachineView(Machine machine) { m_Machine = machine; } /** * 构造视图 * * @param machine * @return */ public static MachineView valueOf(Machine machine) { return null == machine ? null : new MachineView(machine); } /** * id * * @return */ @DocAttribute(type = String.class, description = "机器id", index = 1) public String getId() { return m_Machine.getPersistenceId().getId(); } /** * 名称 * * @return */ @DocAttribute(type = String.class, description = "机器名称", index = 2) public String getName() { return m_Machine.getName(); } /** * 所属者 * * @return */ @DocAttribute(type = UserView.class, description = "所属者", index = 3) public UserView getOwner() { return UserView.valueOf(m_Machine.getOwner()); } /** * 环境变量 * * @return */ @DocAttribute(type = List.class, description = "环境变量", index = 4) public List<Env> getEnvs() { return m_Machine.getEnvs(); } /** * 属性 * * @return */ @DocAttribute(type = List.class, description = "属性", index = 5) public List<Prop> getProps() { return m_Machine.getProps(); } /** * 绑定 * * @return */ @DocAttribute(type = List.class, description = "绑定", index = 6) public List<Bind> getBinds() { return m_Machine.getBinds(); } /** * 是否可编辑 * * @return */ @DocAttribute(type = boolean.class, description = "是否可编辑") public boolean isCanEdit() { return m_Machine.isRight(Machine.RIGHT_UPDATE); } /** * 是否可删除 * * @return */ @DocAttribute(type = boolean.class, description = "是否可删除") public boolean isCanDelete() { return m_Machine.isRight(Machine.RIGHT_UPDATE); } /** * 所属群组 * * @return */ @DocAttribute(description = "所属群组") public List<GroupView> getGroups() { return new TransList<GroupView, GroupRight>(m_Machine.getGroups()) { @Override public GroupView trans(GroupRight v) { return GroupView.valueOf(v); } }; } @DocAttribute(type = MachineInfoView.class, description = "机器信息") public MachineInfoView getInfo() { MachineInfo info = m_Machine.getInfo(); return null == info ? null : new MachineInfoView(info); } }
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights * Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.cloudsearchv2.model.transform; import java.util.Map; import java.util.HashMap; import java.util.ArrayList; import java.util.Map.Entry; import javax.xml.stream.events.XMLEvent; import com.amazonaws.services.cloudsearchv2.model.*; import com.amazonaws.transform.Unmarshaller; import com.amazonaws.transform.MapEntry; import com.amazonaws.transform.StaxUnmarshallerContext; import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*; /** * IndexFieldStatus StAX Unmarshaller */ public class IndexFieldStatusStaxUnmarshaller implements Unmarshaller<IndexFieldStatus, StaxUnmarshallerContext> { public IndexFieldStatus unmarshall(StaxUnmarshallerContext context) throws Exception { IndexFieldStatus indexFieldStatus = new IndexFieldStatus(); int originalDepth = context.getCurrentDepth(); int targetDepth = originalDepth + 1; if (context.isStartOfDocument()) targetDepth += 1; while (true) { XMLEvent xmlEvent = context.nextEvent(); if (xmlEvent.isEndDocument()) return indexFieldStatus; if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) { if (context.testExpression("Options", targetDepth)) { indexFieldStatus.setOptions(IndexFieldStaxUnmarshaller .getInstance().unmarshall(context)); continue; } if (context.testExpression("Status", targetDepth)) { indexFieldStatus.setStatus(OptionStatusStaxUnmarshaller .getInstance().unmarshall(context)); continue; } } else if (xmlEvent.isEndElement()) { if (context.getCurrentDepth() < originalDepth) { return indexFieldStatus; } } } } private static IndexFieldStatusStaxUnmarshaller instance; public static IndexFieldStatusStaxUnmarshaller getInstance() { if (instance == null) instance = new IndexFieldStatusStaxUnmarshaller(); return instance; } }
/* * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * The Apereo Foundation licenses this file to you under the 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.unitime.timetable.gwt.client.aria; import com.google.gwt.aria.client.CheckedValue; import com.google.gwt.aria.client.Roles; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Element; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.ui.Focusable; import com.google.gwt.user.client.ui.HasValue; import com.google.gwt.user.client.ui.Image; /** * @author Tomas Muller */ public class AriaToggleButton extends Image implements HasAriaLabel, HasValue<Boolean>, Focusable { private ImageResource iCheckedFace, iUncheckedFace; private boolean iValue = false; public AriaToggleButton(ImageResource checked, ImageResource unchecked) { iCheckedFace = checked; iUncheckedFace = unchecked; setResource(iUncheckedFace); Roles.getCheckboxRole().set(getElement()); Roles.getCheckboxRole().setAriaCheckedState(getElement(), CheckedValue.FALSE); setTabIndex(0); sinkEvents(Event.ONKEYUP | Event.ONCLICK); } @Override public String getAriaLabel() { return getAltText(); } @Override public void setAriaLabel(String text) { setAltText(text); } @Override public void setAltText(String altText) { super.setAltText(altText); if (getTitle() == null || getTitle().isEmpty()) setTitle(altText); } @Override public void setValue(Boolean value) { setValue(value, true); } @Override public HandlerRegistration addValueChangeHandler(ValueChangeHandler<Boolean> handler) { return addHandler(handler, ValueChangeEvent.getType()); } @Override public int getTabIndex() { return getElement().getTabIndex(); } @Override public void setAccessKey(char key) { setAccessKey(getElement(), key); } private native void setAccessKey(Element elem, char key) /*-{ elem.accessKey = String.fromCharCode(key); }-*/; @Override public void setFocus(boolean focused) { if (focused) getElement().focus(); else getElement().blur(); } @Override public void setTabIndex(int index) { getElement().setTabIndex(index); } @Override public Boolean getValue() { return iValue; } @Override public void setValue(Boolean value, boolean fireEvents) { if (value == null) value = false; iValue = value; setResource(iValue ? iCheckedFace : iUncheckedFace); Roles.getCheckboxRole().setAriaCheckedState(getElement(), iValue ? CheckedValue.TRUE : CheckedValue.FALSE); if (fireEvents) ValueChangeEvent.fire(this, getValue()); } protected void onClick() { getElement().dispatchEvent(Document.get().createClickEvent(1, 0, 0, 0, 0, false, false, false, false)); } @Override public void onBrowserEvent(Event event) { if (event.getTypeInt() == Event.ONKEYUP && event.getKeyCode() == KeyCodes.KEY_SPACE) { onClick(); } if (event.getTypeInt() == Event.ONCLICK) { setValue(!getValue()); } super.onBrowserEvent(event); } }
/* * Copyright 2017 John Grosh & Kaidan Gustave * * 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 party.balloonboat.commands; import com.jagrosh.jdautilities.commandclient.CommandEvent; import com.jagrosh.jdautilities.menu.pagination.PaginatorBuilder; import com.jagrosh.jdautilities.utils.FinderUtil; import com.jagrosh.jdautilities.waiter.EventWaiter; import net.dv8tion.jda.core.Permission; import net.dv8tion.jda.core.entities.Member; import net.dv8tion.jda.core.entities.User; import party.balloonboat.data.Database; import party.balloonboat.utils.FormatUtils; import java.util.List; /** * @author Kaidan Gustave */ public class FromCommand extends DatabaseCommand { private final PaginatorBuilder pBuilder; public FromCommand(Database database, EventWaiter waiter) { super(database); this.name = "From"; this.arguments = "<User>"; this.help = "Gets a list of ratings from a user."; this.cooldown = 10; this.cooldownScope = CooldownScope.USER; this.botPermissions = new Permission[]{ Permission.MESSAGE_ADD_REACTION, Permission.MESSAGE_MANAGE, Permission.MESSAGE_EMBED_LINKS }; this.pBuilder = new PaginatorBuilder() .waitOnSinglePage(false) .setFinalAction(m -> m.clearReactions().queue(v -> {}, v -> {})) .setItemsPerPage(10) .setEventWaiter(waiter); } @Override protected void execute(CommandEvent event) { final Member member; if(event.getArgs().isEmpty()) member = event.getMember(); else { List<Member> members = FinderUtil.findMembers(event.getArgs(), event.getGuild()); if(members.size() > 1) { event.replyError(FormatUtils.tooManyMembers(event.getArgs(),members)); return; } if(members.size() < 1) { event.replyError("Could not find a user matching \""+event.getArgs()+"\"!"); return; } member = members.get(0); } event.replyWarning("Getting Ratings...", message -> { pBuilder.clearItems(); pBuilder.setText((page, total) -> String.format("Ratings made by **%s**#%s | Page %d/%d", member.getUser().getName(), member.getUser().getDiscriminator(), page, total)); database.getRatingsFrom(member.getUser()).forEach((userId, rating) -> { final User user; if(event.getJDA().getShardInfo() != null) user = event.getJDA().asBot().getShardManager().getUserById(userId); else user = event.getJDA().getUserById(userId); if(user != null) pBuilder.addItems(String.format("**%s**#%s %d", user.getName(), user.getDiscriminator(), rating)); else pBuilder.addItems(String.format("**Unknown** (ID: %d) %d", userId, rating)); }); if(member.getColor() != null) pBuilder.setColor(member.getColor()); pBuilder.build().display(message); }); } }
/* * Copyright 2015 JBoss, by Red Hat, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.uberfire.client.screens.welcome; import javax.annotation.PostConstruct; import javax.enterprise.context.Dependent; import org.uberfire.client.annotations.WorkbenchContextId; import org.uberfire.client.annotations.WorkbenchPartTitle; import org.uberfire.client.annotations.WorkbenchScreen; import com.google.gwt.core.client.GWT; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Widget; @Dependent @WorkbenchScreen(identifier = "welcome") public class WelcomeScreen extends Composite { interface ViewBinder extends UiBinder<Widget, WelcomeScreen> { } private static ViewBinder uiBinder = GWT.create( ViewBinder.class ); @PostConstruct public void init() { initWidget( uiBinder.createAndBindUi( this ) ); } @WorkbenchPartTitle public String getTitle() { return "Welcome"; } @WorkbenchContextId public String getMyContextRef() { return "welcomeContext"; } }
/* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.bigtable.hbase.adapters; import org.apache.hadoop.hbase.client.Row; /** * An interface for adapters that will convert an HBase Operation into Google Cloud Java Bigtable * Models type. * * @param <T> The HBase operation type * @param <U> The Google Cloud Java Bigtable Model type. * @author sduskis * @version $Id: $Id */ public interface OperationAdapter<T extends Row, U> { /** * Adapt a single HBase Operation to a single Bigtable generated message. * * @param operation The HBase operation to convert. * @param u Type to which HBase operation will be mapped to. Typically it will be Google Cloud * Java Bigtable Models. */ public void adapt(T operation, U u); }
package com.jerusalem.goods.dao; import com.jerusalem.goods.entity.SpuImagesEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Repository; /**** * 持久层 * spu图片 * @author jerusalem * @email 3276586184@qq.com * @date 2020-04-09 14:48:19 */ @Mapper @Repository public interface SpuImagesDao extends BaseMapper<SpuImagesEntity> { }
// // Author: Yves Lafon <ylafon@w3.org> // // (c) COPYRIGHT MIT, ERCIM, Keio, Beihang University, 2017. // Please first read the full copyright statement in file COPYRIGHT.html package org.w3c.css.properties.css3; import org.w3c.css.util.ApplContext; import org.w3c.css.util.InvalidParamException; import org.w3c.css.values.CssExpression; import org.w3c.css.values.CssIdent; import org.w3c.css.values.CssTypes; import org.w3c.css.values.CssValue; /** * @spec https://www.w3.org/TR/2020/WD-css-lists-3-20201117/#propdef-list-style-position */ public class CssListStylePosition extends org.w3c.css.properties.css.CssListStylePosition { public static final CssIdent[] allowed_values; static { String[] _allowed_values = {"inside", "outside"}; int i = 0; allowed_values = new CssIdent[_allowed_values.length]; for (String s : _allowed_values) { allowed_values[i++] = CssIdent.getIdent(s); } } public static final CssIdent getAllowedIdent(CssIdent ident) { for (CssIdent id : allowed_values) { if (id.equals(ident)) { return id; } } return null; } /** * Create a new CssListStylePosition */ public CssListStylePosition() { value = initial; } /** * Set the value of the property<br/> * Does not check the number of values * * @param expression The expression for this property * @throws org.w3c.css.util.InvalidParamException The expression is incorrect */ public CssListStylePosition(ApplContext ac, CssExpression expression) throws InvalidParamException { this(ac, expression, false); } /** * Set the value of the property * * @param expression The expression for this property * @param check set it to true to check the number of values * @throws org.w3c.css.util.InvalidParamException The expression is incorrect */ public CssListStylePosition(ApplContext ac, CssExpression expression, boolean check) throws InvalidParamException { if (check && expression.getCount() > 1) { throw new InvalidParamException("unrecognize", ac); } setByUser(); CssValue val; val = expression.getValue(); if (val.getType() != CssTypes.CSS_IDENT) { throw new InvalidParamException("value", val, getPropertyName(), ac); } CssIdent id = val.getIdent(); if (!CssIdent.isCssWide(id) && getAllowedIdent(id) == null) { throw new InvalidParamException("value", val.toString(), getPropertyName(), ac); } value = val; expression.next(); } }
package net.sf.antcontrib.net; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import org.apache.ivy.ant.IvyConfigure; import org.apache.ivy.ant.IvyCacheFileset; import org.apache.tools.ant.BuildException; public class Ivy20Adapter implements IvyAdapter { public void configure(URLImportTask task) { IvyConfigure configure = new IvyConfigure(); configure.setProject(task.getProject()); configure.setLocation(task.getLocation()); configure.setOwningTarget(task.getOwningTarget()); configure.setTaskName(task.getTaskName()); configure.setOverride("true"); configure.setSettingsId("urlimporttask"); configure.init(); URL ivyConfUrl = task.getIvyConfUrl(); File ivyConfFile = task.getIvyConfFile(); String repositoryUrl = task.getRepositoryUrl(); File repositoryDir = task.getRepositoryDir(); String ivyPattern = task.getIvyPattern(); String artifactPattern = task.getArtifactPattern(); if (ivyConfUrl != null) { if (ivyConfUrl.getProtocol().equalsIgnoreCase("file")) { String path = ivyConfUrl.getPath(); File f = new File(path); if (!f.isAbsolute()) { f = new File(task.getProject().getBaseDir(), path); } configure.setFile(f); } else { try { configure.setUrl(ivyConfUrl.toExternalForm()); } catch (MalformedURLException e) { throw new BuildException(e); } } } else if (ivyConfFile != null) { configure.setFile(ivyConfFile); } else if (repositoryDir != null || repositoryUrl != null) { File temp = null; FileWriter fw = null; try { temp = File.createTempFile("ivyconf", ".xml"); temp.deleteOnExit(); fw = new FileWriter(temp); fw.write("<ivysettings>"); fw.write("<settings defaultResolver=\"default\" />"); fw.write("<resolvers>"); if (repositoryDir != null) { fw.write("<filesystem name=\"default\">"); fw.write("<ivy pattern=\"" + repositoryDir + "/" + ivyPattern + "\" />"); fw.write("<artifact pattern=\"" + repositoryDir + "/" + artifactPattern + "\" />"); fw.write("</filesystem>"); } else { fw.write("<url name=\"default\">"); fw.write("<ivy pattern=\"" + repositoryUrl + "/" + ivyPattern + "\" />"); fw.write("<artifact pattern=\"" + repositoryUrl + "/" + artifactPattern + "\" />"); fw.write("</url>"); } fw.write("</resolvers>"); fw.write("<latest-strategies>"); fw.write("<latest-revision name=\"latest\"/>"); fw.write("</latest-strategies>"); fw.write("</ivysettings>"); fw.close(); fw = null; configure.setFile(temp); } catch (IOException e) { throw new BuildException(e); } finally { try { if (fw != null) { fw.close(); fw = null; } } catch (IOException e) { ; } } } // task.getProject().addReference("urlimporttask", configure); configure.execute(); } public void fileset(URLImportTask task, String setId) { String org = task.getOrg(); String module = task.getModule(); String rev = task.getRev(); String conf = task.getConf(); IvyCacheFileset cacheFileSet = new IvyCacheFileset(); cacheFileSet.setProject(task.getProject()); cacheFileSet.setLocation(task.getLocation()); cacheFileSet.setOwningTarget(task.getOwningTarget()); cacheFileSet.setTaskName(task.getTaskName()); cacheFileSet.setInline(true); cacheFileSet.setOrganisation(org); cacheFileSet.setModule(module); cacheFileSet.setRevision(rev); cacheFileSet.setConf(conf); cacheFileSet.init(); cacheFileSet.setSetid(setId); cacheFileSet.setSettingsRef(new org.apache.tools.ant.types.Reference(task.getProject(), "urlimporttask")); cacheFileSet.execute(); } }
import javax.swing.*; import java.io.BufferedReader; import java.io.FileReader; import java.awt.Color; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.JOptionPane; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class ConvertImageFolder{ JProgressBar progressBar; JFrame frame; int itemPercentage; // Porcentagem de cada item int imageWidth; int imageHeight; JTextField widthField; JTextField heightField; String imageFolder; public static void main( String args[]){ // ConvertImageFolder convertImage = new ConvertImageFolder(); // Init the gui new ConvertImageFolder().gui(); // convertImage.gui(); } public void startConvertion(){ // Loop though all the files in that folder imageWidth = Integer.parseInt(widthField.getText()); imageHeight = Integer.parseInt(heightField.getText()); ConvertImageFolder convertImage = new ConvertImageFolder(); if(imageWidth == 0 || imageHeight == 0){ JOptionPane.showMessageDialog(null, "Digite os valores de altura e largura antes de continuar!", "Erro", JOptionPane.INFORMATION_MESSAGE); return; } File[] files = new File(imageFolder).listFiles(); System.out.println("number of items "+files.length); convertImage.setItemPercentage(files.length); for (File file : files) { if (file.isDirectory()){ JOptionPane.showMessageDialog(null, "Existem outras subpastas, fotos nessas subpastas nao serao convertidas ", "Informacao", JOptionPane.INFORMATION_MESSAGE); }else{ convertImage.convertImage(imageFolder, file.getName()); convertImage.changeProgress(); } } convertImage.finish(); } public void setItemPercentage(int filesCount){ itemPercentage = 100/filesCount; System.out.println("result of the division "+itemPercentage); } public void gui(){ // Get image folder imageFolder = new ConvertImageFolder().getImageFolder(); JOptionPane.showMessageDialog(null, "Pasta de imagem "+imageFolder, "Informacao", JOptionPane.INFORMATION_MESSAGE); frame = new JFrame("Convertendo Imagens"); JPanel mainPanel = new JPanel(); JLabel widthLabel = new JLabel("Largura"); JLabel heightLabel = new JLabel("Altura"); widthField = new JTextField(); heightField = new JTextField(); int marginLeft = 40; JButton startConvertionButton = new JButton("Converter imagens"); progressBar = new JProgressBar(0, 100); progressBar.setValue(0); progressBar.setStringPainted(true); mainPanel.setBounds(0, 0, 280, 180); widthLabel.setBounds(10+marginLeft, 20, 100, 20); heightLabel.setBounds(10+marginLeft, 45, 100, 20); widthField.setBounds(115+marginLeft, 20, 50, 20); heightField.setBounds(115+marginLeft, 45, 50, 20); startConvertionButton.setBounds(10+marginLeft, 70, 150, 30); startConvertionButton.addActionListener(new ConvertImageFolder.startConvertionButton()); progressBar.setBounds(10, 105, 250, 30); mainPanel.setLayout(null); mainPanel.add(widthLabel); mainPanel.add(heightLabel); mainPanel.add(widthField); mainPanel.add(heightField); mainPanel.add(startConvertionButton); mainPanel.add(progressBar); frame.add(mainPanel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(280, 180); frame.setVisible(true); } public void finish(){ frame.dispose(); } public class startConvertionButton implements ActionListener { public void actionPerformed(ActionEvent e) { new ConvertImageFolder().startConvertion(); } } public void changeProgress(){ progressBar.setValue(progressBar.getValue()+itemPercentage); } public void convertImage(String imageFolder, String fileName){ BufferedImage bufferedImage; BufferedImage newBufferedImage; Image image; try { //read image file String imagePath = imageFolder+"/"+fileName; bufferedImage = ImageIO.read(new File(imagePath)); //Resize the image image = bufferedImage.getScaledInstance(imageWidth, imageHeight, Image.SCALE_DEFAULT); // create a blank, RGB, same width and height, and a white background newBufferedImage = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB); newBufferedImage.createGraphics().drawImage(image, 0, 0, Color.WHITE, null); // write to jpeg file ImageIO.write(newBufferedImage, "jpg", new File(imageFolder+"/a_"+fileName)); // JOptionPane.showMessageDialog(null, "A imagem foi convertida e inserida! ", "Informacao", // JOptionPane.INFORMATION_MESSAGE); } catch (IOException e) { JOptionPane.showMessageDialog(null, e.toString(), "Erro", JOptionPane.ERROR_MESSAGE); } } public String getImageFolder(){ String returnValue = null; String line; try{ BufferedReader reader = new BufferedReader(new FileReader("temp/folder_convert_info.txt")); while ((line = reader.readLine()) != null){ returnValue = line; } reader.close(); }catch(Exception e){ JOptionPane.showMessageDialog(null, e.toString(), "Erro", JOptionPane.ERROR_MESSAGE); } return returnValue; } }
package fr.insee.rmes.api.operations; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import fr.insee.rmes.api.AbstractMetadataApi; import fr.insee.rmes.modeles.operations.CsvFamily; import fr.insee.rmes.modeles.operations.CsvIndicateur; import fr.insee.rmes.modeles.operations.CsvSerie; import fr.insee.rmes.modeles.operations.Famille; import fr.insee.rmes.modeles.operations.Familles; import fr.insee.rmes.modeles.operations.Indicateur; import fr.insee.rmes.modeles.operations.Serie; import fr.insee.rmes.modeles.operations.documentations.DocumentationSims; import fr.insee.rmes.queries.operations.OperationsQueries; 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; @Path("/operations") @Tag(name = "operations", description = "Operations API") public class OperationsAPI extends AbstractMetadataApi { private static Logger logger = LogManager.getLogger(OperationsAPI.class); private OperationsApiService operationsApiService = new OperationsApiService(); @Path("/arborescence") @GET @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @Operation( operationId = "getSeries", summary = "Liste des opérations disponibles dans leur arborescence", responses = { @ApiResponse(content = @Content(schema = @Schema(implementation = Familles.class)), description="Familles") }) public Response getOperationsTree( @Parameter( description = "Le diffuseur des données (permet de filtrer les opérations retournées)", schema = @Schema(nullable = true, allowableValues = { "insee.fr" }, type = "string")) @QueryParam("diffuseur") String diffuseur, @Parameter(hidden = true) @HeaderParam(HttpHeaders.ACCEPT) String header) { logger.debug("Received GET request operations tree"); String csvResult = sparqlUtils.executeSparqlQuery(OperationsQueries.getFamilies()); List<CsvFamily> familyList = csvUtils.populateMultiPOJO(csvResult, CsvFamily.class); if (familyList.isEmpty()) { return Response.status(Status.NOT_FOUND).entity("").build(); } else { Map<String,List<String>> exclusions = new HashMap<>(); if (StringUtils.equals(diffuseur, "insee.fr")) { exclusions = operationsApiService.readExclusions(); } Map<String, Famille> familyMap = operationsApiService.getListeFamilyToOperation(familyList,exclusions); if (header.equals(MediaType.APPLICATION_XML)) { Familles familles = new Familles(new ArrayList<>(familyMap.values())); return Response.ok(responseUtils.produceResponse(familles, header)).build(); } else { return Response.ok(responseUtils.produceResponse(familyMap.values(), header)).build(); } } } @Path("/rapportQualite/{id: [0-9]{4}}") @GET @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @Operation( operationId = "getDocumentation", summary = "Documentation d'une opération, d'un indicateur ou d'une série", responses = { @ApiResponse(content = @Content(schema = @Schema(implementation = DocumentationSims.class)), description="Documentation SIMS") }) public Response getDocumentation( @Parameter( description = "Identifiant de la documentation (format : [0-9]{4})", required = true, schema = @Schema(pattern = "[0-9]{4}", type = "string"), example = "1979") @PathParam("id") String id, @Parameter(hidden = true) @HeaderParam(HttpHeaders.ACCEPT) String header) { logger.debug("Received GET request documentation"); String csvResult = sparqlUtils.executeSparqlQuery(OperationsQueries.getDocumentationTitle(id)); DocumentationSims sims = new DocumentationSims(); sims = (DocumentationSims) csvUtils.populatePOJO(csvResult, sims); if (sims.getUri() == null) { return Response.status(Status.NOT_FOUND).entity("").build(); } else { sims.setRubriques(operationsApiService.getListRubriques(id)); return Response.ok(responseUtils.produceResponse(sims, header)).build(); } } @Path("/serie/{idSeries}") @GET @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @Operation(operationId = "getSeries", summary = "Informations sur une série statistique de l'Insee", responses = { @ApiResponse(content = @Content(schema = @Schema(implementation = Serie.class)), description="Séries") }) public Response getSeries( @Parameter( description = "Identifiant de la série(format : s[0-9]{4})", required = true, schema = @Schema(pattern = "s[0-9]{4}", type = "string"), example = "s1223") @PathParam("idSeries") String idSeries, @Parameter(hidden = true) @HeaderParam(HttpHeaders.ACCEPT) String header) { logger.debug("Received GET request series"); String csvResult = sparqlUtils.executeSparqlQuery(OperationsQueries.getSeries(idSeries)); CsvSerie csvSerie = new CsvSerie(); csvSerie = (CsvSerie) csvUtils.populatePOJO(csvResult, csvSerie); if (csvSerie.getSeriesId() == null) { return Response.status(Status.NOT_FOUND).entity("").build(); } else { return Response .ok(responseUtils.produceResponse(operationsApiService.getSerie(csvSerie, idSeries), header)) .build(); } } @Path("/indicateur/{idIndicateur}") @GET @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @Operation(operationId = "getIndicateur", summary = "Informations sur un indicateur de l'Insee", responses = { @ApiResponse(content = @Content(schema = @Schema(implementation = Indicateur.class)), description="Indicateur") }) public Response getIndicateur( @Parameter( description = "Identifiant de l'indicateur (format : p[0-9]{4})", required = true, schema = @Schema(pattern = "p[0-9]{4}", type = "string"), example ="p1670") @PathParam("idIndicateur") String idIndicateur, @Parameter(hidden = true) @HeaderParam(HttpHeaders.ACCEPT) String header) { logger.debug("Received GET request indicator"); String csvResult = sparqlUtils.executeSparqlQuery(OperationsQueries.getIndicator(idIndicateur)); CsvIndicateur csvIndic = new CsvIndicateur(); csvIndic = (CsvIndicateur) csvUtils.populatePOJO(csvResult, csvIndic); if (csvIndic.getId() == null) { return Response.status(Status.NOT_FOUND).entity("").build(); } else { return Response .ok(responseUtils.produceResponse(operationsApiService.getIndicateur(csvIndic, idIndicateur), header)) .build(); } } }
package ttc2018; import com.google.common.collect.Iterators; import org.neo4j.configuration.GraphDatabaseSettings; import org.neo4j.dbms.api.DatabaseManagementService; import org.neo4j.dbms.api.DatabaseManagementServiceBuilder; import org.neo4j.exceptions.KernelException; import org.neo4j.graphdb.*; import org.neo4j.io.fs.FileUtils; import org.neo4j.kernel.api.procedure.GlobalProcedures; import org.neo4j.kernel.internal.GraphDatabaseAPI; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; import java.util.stream.Stream; import static ttc2018.Labels.*; import static ttc2018.Query.ID_COLUMN_NAME; import static ttc2018.Query.SCORE_COLUMN_NAME; import static ttc2018.RelationshipTypes.*; public abstract class Solution implements AutoCloseable { DatabaseManagementService managementService; GraphDatabaseService graphDb; public abstract String Initial(); /** * Update reading changes from CSV file */ public abstract String Update(File changes); private final static String NEO4J_HOME = System.getenv("NEO4J_HOME"); private final static Path DB_DIR = new File(NEO4J_HOME + "/data").toPath(); private final static String LOAD_SCRIPT = "load-scripts/load.sh"; private String DataPath; Solution(String DataPath) throws IOException, InterruptedException { this.DataPath = new File(DataPath).getCanonicalPath(); } public GraphDatabaseService getDbConnection() { if (graphDb == null) { try { initializeDb(); } catch (KernelException e) { throw new RuntimeException(e); } } return graphDb; } protected void initializeDb() throws KernelException { managementService = new DatabaseManagementServiceBuilder(new File(NEO4J_HOME).toPath()) .setConfig(GraphDatabaseSettings.procedure_unrestricted, List.of("apoc.*", "gds.*")) .build(); graphDb = managementService.database(GraphDatabaseSettings.DEFAULT_DATABASE_NAME); Runtime.getRuntime().addShutdownHook(new Thread(this::close)); } @Override public void close() { if (managementService != null) { managementService.shutdown(); managementService = null; } } // https://github.com/neo4j-contrib/neo4j-apoc-procedures/blob/3.5/src/test/java/apoc/util/TestUtil.java#L95 public static void registerProcedure(GraphDatabaseService db, Class<?>... procedures) throws KernelException, KernelException { GlobalProcedures proceduresService = ((GraphDatabaseAPI) db).getDependencyResolver().resolveDependency(GlobalProcedures.class); for (Class<?> procedure : procedures) { proceduresService.registerProcedure(procedure, true); proceduresService.registerFunction(procedure, true); proceduresService.registerAggregationFunction(procedure, true); } } String runReadQuery(Query q) { return runReadQuery(q, Collections.emptyMap()); } String runReadQuery(Query q, Map<String, Object> parameters) { try (Transaction tx = graphDb.beginTx()) { return runReadQuery(tx, q, parameters); } } protected static final int resultLimit = 3; String runReadQuery(Transaction tx, Query q, Map<String, Object> parameters) { try (Result rs = q.execute(tx, parameters)) { List<String> result = new ArrayList<>(); int rowCount = 0; while (rs.hasNext()) { Map<String, Object> row = rs.next(); String id = row.get(ID_COLUMN_NAME).toString(); if (LiveContestDriver.ShowScoresForValidation) { result.add(String.format("%1$s,%2$s", id, row.get(SCORE_COLUMN_NAME))); } else { result.add(id); } ++rowCount; if (rowCount >= resultLimit) break; } return String.join("|", result); } } void runAndCommitVoidQuery(Query q) { runAndCommitVoidQuery(q, Collections.emptyMap()); } void runAndCommitVoidQuery(Query q, Map<String, Object> parameters) { try (Transaction tx = graphDb.beginTx()) { runVoidQuery(tx, q, parameters); tx.commit(); } } void runVoidQuery(Transaction tx, Query q, Map<String, Object> parameters) { try (Result rs = q.execute(tx, parameters)) { rs.accept(row -> true); } } void loadData() throws IOException, InterruptedException { if (System.getenv("NEO4J_HOME") == null) throw new RuntimeException("$NEO4J_HOME is not defined."); // delete previous DB FileUtils.deleteDirectory(DB_DIR); ProcessBuilder pb = new ProcessBuilder(LOAD_SCRIPT); Map<String, String> env = pb.environment(); env.put("NEO4J_DATA_DIR", DataPath); File log = new File("log.txt"); pb.redirectErrorStream(true); pb.redirectOutput(ProcessBuilder.Redirect.appendTo(log)); Process p = pb.start(); p.waitFor(); // DB initialization GraphDatabaseService dbConnection = getDbConnection(); // add uniqueness constraints and indices try (Transaction tx = dbConnection.beginTx()) { addConstraintsAndIndicesInTx(tx); tx.commit(); } try (Transaction tx = dbConnection.beginTx()) { tx.schema().awaitIndexesOnline(Long.MAX_VALUE, TimeUnit.NANOSECONDS); // TODO: meaningful timeout tx.commit(); } } protected void addConstraintsAndIndicesInTx(Transaction tx) { for (Labels label : Labels.values()) { tx.schema() .constraintFor(label) .assertPropertyIsUnique(NODE_ID_PROPERTY) .create(); } } void beforeUpdate(File changes) { try (Transaction tx = getDbConnection().beginTx()) { processChangeSet(tx, changes); tx.commit(); } } public static final String SEPARATOR = "|"; public static final String COMMENTS_CHANGE_TYPE = "Comments"; public static final String NODE_ID_PROPERTY = "id"; public static final String USER_NAME_PROPERTY = "name"; public static final String SUBMISSION_TIMESTAMP_PROPERTY = "timestamp"; public static final String SUBMISSION_CONTENT_PROPERTY = "content"; public static final String SUBMISSION_SCORE_PROPERTY = "score"; public static final long SUBMISSION_SCORE_DEFAULT = 0L; public static final String FRIEND_OVERLAY_EDGE_COMMENT_ID_PROPERTY = "commentId"; private void processChangeSet(Transaction tx, File changeSet) { try (Stream<String> stream = Files.lines(changeSet.toPath())) { stream.forEachOrdered(s -> { String[] line = s.split(Pattern.quote(SEPARATOR)); switch (line[0]) { case "Posts": case COMMENTS_CHANGE_TYPE: { long id = Long.parseLong(line[1]); addSubmissionVertex(tx, line); break; } case "Friends": { // add edges only once if (Long.parseLong(line[1]) <= Long.parseLong(line[2])) { addFriendEdge(tx, line); } break; } case "Likes": { addLikesEdge(tx, line); break; } case "Users": { addUserVertex(tx, line); break; } default: throw new RuntimeException("Invalid record type received from CSV input: " + line[0]); } }); } catch (IOException e) { throw new RuntimeException(e); } } protected Node addSubmissionVertex(Transaction tx, String[] line) { long id = Long.parseLong(line[1]); String timestamp = line[2]; String content = line[3]; long submitterId = Long.parseLong(line[4]); Node submitter = findSingleNodeByIdProperty(tx, User, submitterId); Label[] labels = line[0].equals(COMMENTS_CHANGE_TYPE) ? CommentLabelSet : PostLabelSet; Node submission = tx.createNode(labels); submission.setProperty(NODE_ID_PROPERTY, id); submission.setProperty(SUBMISSION_TIMESTAMP_PROPERTY, timestamp); submission.setProperty(SUBMISSION_CONTENT_PROPERTY, content); submission.createRelationshipTo(submitter, SUBMITTER); if (line[0].equals(COMMENTS_CHANGE_TYPE)) { long previousSubmissionId = Long.parseLong(line[5]); Node previousSubmission = findSingleNodeByIdProperty(tx, Submission, previousSubmissionId); submission.createRelationshipTo(previousSubmission, COMMENT_TO); afterNewComment(tx, submission, submitter, previousSubmission); } else { afterNewPost(tx, submission, submitter); } return submission; } protected void afterNewComment(Transaction tx, Node comment, Node submitter, Node previousSubmission) { } protected void afterNewPost(Transaction tx, Node post, Node submitter) { } protected Relationship addFriendEdge(Transaction tx, String[] line) { return insertEdge(tx, line, FRIEND, User, User); } protected Relationship addLikesEdge(Transaction tx, String[] line) { return insertEdge(tx, line, LIKES, User, Comment); } protected Node addUserVertex(Transaction tx, String[] line) { long id = Long.parseLong(line[1]); String name = line[2]; Node user = tx.createNode(User); user.setProperty(NODE_ID_PROPERTY, id); user.setProperty(USER_NAME_PROPERTY, name); return user; } private Node findSingleNodeByIdProperty(Transaction tx, Labels label, long id) { try (ResourceIterator<Node> nodes = tx.findNodes(label, NODE_ID_PROPERTY, id)) { return Iterators.getOnlyElement(nodes); } } private Relationship insertEdge(Transaction tx, String[] line, RelationshipTypes relationshipType, Labels sourceLabel, Labels targetLabel) { long sourceId = Long.parseLong(line[1]); long targetId = Long.parseLong(line[2]); Node source = findSingleNodeByIdProperty(tx, sourceLabel, sourceId); Node target = findSingleNodeByIdProperty(tx, targetLabel, targetId); return source.createRelationshipTo(target, relationshipType); } }
/** * Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U <br> * This file is part of FI-WARE project. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. * </p> * <p> * You may obtain a copy of the License at:<br> * <br> * http://www.apache.org/licenses/LICENSE-2.0 * </p> * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * </p> * <p> * See the License for the specific language governing permissions and limitations under the License. * </p> * <p> * For those usages not covered by the Apache version 2.0 License please contact with opensource@tid.es * </p> */ package com.telefonica.euro_iaas.paasmanager.installator.rec.services; import com.telefonica.euro_iaas.paasmanager.exception.ProductInstallatorException; import com.telefonica.euro_iaas.paasmanager.exception.ProductReconfigurationException; /** * @author jesus.movilla */ public interface RECPICService { // void createPICs(VM vm, String appId) throws ProductInstallatorException; void createPIC(String vapp, String appId, String picId, String vmName) throws ProductInstallatorException; void configurePIC(String vapp, String appId, String picId, String vmName) throws ProductReconfigurationException, ProductInstallatorException; }
/* * Copyright (c) 2019 Mastercard 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. * * Loyalty Wifi API * The Loyalty Boingo Wifi API offers cardholders, via their issuers, the ability to search and connect to Mastercard Global Wifi hotspots around the world through this digital channel. These APIs can be used to build a rich, interactive wifi experience within the issuer's existing mobile or web application. * * OpenAPI spec version: 1.0.0 * Contact: loyalty-benefits-support@mastercard.flowdock.com * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package com.mastercard.developer.loyalty_wifi_client; import com.squareup.okhttp.*; import okio.Buffer; import okio.BufferedSink; import okio.GzipSink; import okio.Okio; import java.io.IOException; /** * Encodes request bodies using gzip. * * Taken from https://github.com/square/okhttp/issues/350 */ class GzipRequestInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { Request originalRequest = chain.request(); if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) { return chain.proceed(originalRequest); } Request compressedRequest = originalRequest.newBuilder() .header("Content-Encoding", "gzip") .method(originalRequest.method(), forceContentLength(gzip(originalRequest.body()))) .build(); return chain.proceed(compressedRequest); } private RequestBody forceContentLength(final RequestBody requestBody) throws IOException { final Buffer buffer = new Buffer(); requestBody.writeTo(buffer); return new RequestBody() { @Override public MediaType contentType() { return requestBody.contentType(); } @Override public long contentLength() { return buffer.size(); } @Override public void writeTo(BufferedSink sink) throws IOException { sink.write(buffer.snapshot()); } }; } private RequestBody gzip(final RequestBody body) { return new RequestBody() { @Override public MediaType contentType() { return body.contentType(); } @Override public long contentLength() { return -1; // We don't know the compressed length in advance! } @Override public void writeTo(BufferedSink sink) throws IOException { BufferedSink gzipSink = Okio.buffer(new GzipSink(sink)); body.writeTo(gzipSink); gzipSink.close(); } }; } }
/* * This module, both source code and documentation, * is in the Public Domain, and comes with NO WARRANTY. */ package com.github.blagerweij.sessionlock; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import liquibase.database.Database; import liquibase.database.core.PostgresDatabase; import liquibase.exception.DatabaseException; import liquibase.exception.LockException; import liquibase.lockservice.DatabaseChangeLogLock; /** * Employs PostgreSQL <i>advisory locks</i>. * * <blockquote> * * <p>While a flag stored in a table could be used for the same purpose, advisory locks are faster, * avoid table bloat, and are automatically cleaned up by the server at the end of the session. * * <p>There are two ways to acquire an advisory lock in PostgreSQL: at session level or at * transaction level. Once acquired at session level, an advisory lock is held until explicitly * released or the session ends. Unlike standard lock requests, session-level advisory lock requests * do not honor transaction semantics: a lock acquired during a transaction that is later rolled * back will still be held following the rollback, and likewise an unlock is effective even if the * calling transaction fails later. * * </blockquote> * * @see "<a href='https://www.postgresql.org/docs/9.6/explicit-locking.html#ADVISORY-LOCKS'>Advisory * Locks</a> (PostgreSQL Documentation)" */ public class PGLockService extends SessionLockService { static final String SQL_TRY_LOCK = "SELECT pg_try_advisory_lock(?,?)"; static final String SQL_UNLOCK = "SELECT pg_advisory_unlock(?,?)"; static final String SQL_LOCK_INFO = "SELECT l.pid," + " a.client_hostname," + " a.backend_start," + " a.state" + " FROM pg_locks l" + " LEFT JOIN pg_stat_activity a" + " ON a.pid = l.pid" + " WHERE l.locktype = 'advisory'" + " AND l.classid = ?" + " AND l.objid = ?" + " AND l.objsubid = 2" + " AND l.granted"; @Override public boolean supports(Database database) { return (database instanceof PostgresDatabase) && isAtLeastPostgres91(database); } private static boolean isAtLeastPostgres91(Database database) { try { return (database.getDatabaseMajorVersion() > 9) || (database.getDatabaseMajorVersion() == 9 && database.getDatabaseMinorVersion() >= 1); } catch (DatabaseException e) { getLog(PGLockService.class).warning("Problem querying database version", e); return false; } } private int[] getChangeLogLockId() { // Unlike the general Object.hashCode() contract, // String.hashCode() should be stable across VM instances and Java versions. return new int[] { database.getDatabaseChangeLogLockTableName().hashCode(), database.getDefaultSchemaName().hashCode() }; } private static Boolean getBooleanResult(PreparedStatement stmt) throws SQLException { try (ResultSet rs = stmt.executeQuery()) { rs.next(); return (Boolean) rs.getObject(1); } } /** * @see "<a * href='https://www.postgresql.org/docs/9.6/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS'> * <code>pg_try_advisory_lock</code></a> (Advisory Lock Functions)" */ @Override protected boolean acquireLock(Connection con) throws SQLException, LockException { try (PreparedStatement stmt = con.prepareStatement(SQL_TRY_LOCK)) { int[] lockId = getChangeLogLockId(); stmt.setInt(1, lockId[0]); stmt.setInt(2, lockId[1]); return Boolean.TRUE.equals(getBooleanResult(stmt)); } } /** * @see "<a * href='https://www.postgresql.org/docs/9.6/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS'> * <code>pg_advisory_unlock</code></a> (Advisory Lock Functions)" */ @Override protected void releaseLock(Connection con) throws SQLException, LockException { try (PreparedStatement stmt = con.prepareStatement(SQL_UNLOCK)) { int[] lockId = getChangeLogLockId(); stmt.setInt(1, lockId[0]); stmt.setInt(2, lockId[1]); Boolean unlocked = getBooleanResult(stmt); if (!Boolean.TRUE.equals(unlocked)) { throw new LockException("pg_advisory_unlock() returned " + unlocked); } } } /** * Obtains information about the database changelog lock. * * <blockquote> * * Like all locks in PostgreSQL, a complete list of advisory locks currently held by any session * can be found in the <code>pg_locks</code> system view. * * </blockquote> * * @see "<a href='https://www.postgresql.org/docs/9.6/view-pg-locks.html'><code>pg_locks</code> * </a> (PostgreSQL Documentation)" * @see "<a * href='https://www.postgresql.org/docs/9.6/monitoring-stats.html#PG-STAT-ACTIVITY-VIEW'> * <code>pg_stat_activity</code> View</a> (PostgreSQL Documentation)" */ @Override protected DatabaseChangeLogLock usedLock(Connection con) throws SQLException, LockException { try (PreparedStatement stmt = con.prepareStatement(SQL_LOCK_INFO)) { int[] lockId = getChangeLogLockId(); stmt.setInt(1, lockId[0]); stmt.setInt(2, lockId[1]); try (ResultSet rs = stmt.executeQuery()) { if (!rs.next()) { return null; } // This is not really the time the lock has been obtained... Timestamp lockGranted = rs.getTimestamp("backend_start"); return new DatabaseChangeLogLock(1, lockGranted, lockedBy(rs)); } } } private static String lockedBy(ResultSet rs) throws SQLException { String host = rs.getString("client_hostname"); if (host == null) { return "pid#" + rs.getInt("pid"); } return host + " (" + rs.getString("state") + ")"; } }
/* * MIT License * * Copyright (c) 2021 MASES s.r.l. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /************************************************************************************** * <auto-generated> * This code was generated from a template using JCOReflector * * Manual changes to this file may cause unexpected behavior in your application. * Manual changes to this file will be overwritten if the code is regenerated. * </auto-generated> *************************************************************************************/ package system.linq; import org.mases.jcobridge.*; import org.mases.jcobridge.netreflection.*; import java.util.ArrayList; // Import section import system.Single; import system.Decimal; import system.linq.IQueryable; import system.linq.IQueryableImplementation; /** * The base .NET class managing System.Linq.Queryable, System.Linq.Queryable, Version=4.0.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a. * <p> * * See: <a href="https://docs.microsoft.com/en-us/dotnet/api/System.Linq.Queryable" target="_top">https://docs.microsoft.com/en-us/dotnet/api/System.Linq.Queryable</a> */ public class Queryable extends NetObject { /** * Fully assembly qualified name: System.Linq.Queryable, Version=4.0.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a */ public static final String assemblyFullName = "System.Linq.Queryable, Version=4.0.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; /** * Assembly name: System.Linq.Queryable */ public static final String assemblyShortName = "System.Linq.Queryable"; /** * Qualified class name: System.Linq.Queryable */ public static final String className = "System.Linq.Queryable"; static JCOBridge bridge = JCOBridgeInstance.getInstance(assemblyFullName); /** * The type managed from JCOBridge. See {@link JCType} */ public static JCType classType = createType(); static JCEnum enumInstance = null; JCObject classInstance = null; static JCType createType() { try { String classToCreate = className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); if (JCOReflector.getDebug()) JCOReflector.writeLog("Creating %s", classToCreate); JCType typeCreated = bridge.GetType(classToCreate); if (JCOReflector.getDebug()) JCOReflector.writeLog("Created: %s", (typeCreated != null) ? typeCreated.toString() : "Returned null value"); return typeCreated; } catch (JCException e) { JCOReflector.writeLog(e); return null; } } void addReference(String ref) throws Throwable { try { bridge.AddReference(ref); } catch (JCNativeException jcne) { throw translateException(jcne); } } /** * Internal constructor. Use with caution */ public Queryable(java.lang.Object instance) throws Throwable { super(instance); if (instance instanceof JCObject) { classInstance = (JCObject) instance; } else throw new Exception("Cannot manage object, it is not a JCObject"); } public String getJCOAssemblyName() { return assemblyFullName; } public String getJCOClassName() { return className; } public String getJCOObjectName() { return className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); } public java.lang.Object getJCOInstance() { return classInstance; } public void setJCOInstance(JCObject instance) { classInstance = instance; super.setJCOInstance(classInstance); } public JCType getJCOType() { return classType; } /** * Try to cast the {@link IJCOBridgeReflected} instance into {@link Queryable}, a cast assert is made to check if types are compatible. * @param from {@link IJCOBridgeReflected} instance to be casted * @return {@link Queryable} instance * @throws java.lang.Throwable in case of error during cast operation */ public static Queryable cast(IJCOBridgeReflected from) throws Throwable { NetType.AssertCast(classType, from); return new Queryable(from.getJCOInstance()); } // Constructors section public Queryable() throws Throwable { } // Methods section public static IQueryable AsQueryable(IEnumerable source) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.IndexOutOfRangeException, system.NotSupportedException, system.ArgumentNullException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.globalization.CultureNotFoundException, system.PlatformNotSupportedException, system.MissingMethodException, system.reflection.TargetInvocationException { if (classType == null) throw new UnsupportedOperationException("classType is null."); try { JCObject objAsQueryable = (JCObject)classType.Invoke("AsQueryable", source == null ? null : source.getJCOInstance()); return new IQueryableImplementation(objAsQueryable); } catch (JCNativeException jcne) { throw translateException(jcne); } } // Properties section // Instance Events section }
package com.sme.multithreading.service; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinTask; import java.util.concurrent.Future; import java.util.concurrent.RecursiveTask; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.apache.commons.lang3.time.StopWatch; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sme.multithreading.model.Message; /** * Integration tests to work with {@link SlowService}. */ public class SlowServiceIntegrationTest { private static final Logger LOGGER = LoggerFactory.getLogger(SlowServiceIntegrationTest.class); private final SlowService slowService = new SlowService(); private final StopWatch stopWatch = new StopWatch(); @BeforeEach void setUp() { stopWatch.reset(); } /** * <pre> * Fetch messages step by step from slow services. * The result takes 53 seconds on my machine. * </pre> */ @Test void testGetMessagesInSequentialComputation() throws Exception { final int count = 100; List<Message> list = new ArrayList<>(); stopWatch.start(); IntStream.range(0, count).forEach(id -> { list.add(slowService.getMessage(id)); }); stopWatch.stop(); LOGGER.debug("Time in seconds: " + stopWatch.getTime(TimeUnit.SECONDS)); assertEquals(count, list.size()); } /** * <pre> * Fetch messages in the different pools: * - Executors#newCachedThreadPool pool creates new threads as needed, but reuses previously constructed threads when they are available. The result takes 996 milliseconds on my machine; * - Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()) takes 4853 milliseconds; * - Executors.newWorkStealingPool() takes 4506 milliseconds. * </pre> */ @Test void testGetMessagesInThreadPool() throws Exception { final int count = 100; runInThreadPool(count, 1_500, Executors.newCachedThreadPool()); stopWatch.reset(); runInThreadPool(count, 10_000, Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors())); stopWatch.reset(); runInThreadPool(count, 10_000, Executors.newWorkStealingPool()); } private void runInThreadPool(final int count, final int timeout, ExecutorService executorService) throws InterruptedException { List<Callable<Message>> tasks = new ArrayList<>(); stopWatch.start(); IntStream.range(0, count).forEach(id -> { tasks.add(() -> slowService.getMessage(id)); }); List<Future<Message>> futureResult = executorService.invokeAll(tasks, timeout, TimeUnit.MILLISECONDS); executorService.shutdown(); List<Message> result = futureResult.stream() // we do ot use parallel stream here, because we do not expect a lot of rows .map(t -> { try { return t.get(); } catch (InterruptedException | ExecutionException e) { LOGGER.error("Cannot fetch a value", e); throw new RuntimeException(e); } }) .sorted(Comparator.comparing(Message::getDelay)) // extra operation to check the slowest request .collect(Collectors.toList()); stopWatch.stop(); LOGGER.debug("Time in seconds: " + stopWatch.getTime(TimeUnit.MILLISECONDS)); assertEquals(count, result.size()); Message slowestMessage = result.get(count - 1); LOGGER.debug("Get the slowest {} message", slowestMessage); assertTrue(stopWatch.getTime(TimeUnit.MILLISECONDS) > slowestMessage.getDelay()); } /** * <pre> * Parallel stream based on Fork-Join framework. * * The result takes 4562 milliseconds on my machine. * </pre> */ @Test void testGetMessagesInParallelStream() throws Exception { final int count = 100; stopWatch.start(); List<Message> result = IntStream.range(0, count) .parallel() .mapToObj(id -> slowService.getMessage(id)) .sorted(Comparator.comparing(Message::getDelay)) // extra operation to check the slowest request .collect(Collectors.toList()); stopWatch.stop(); LOGGER.debug("Time in seconds: " + stopWatch.getTime(TimeUnit.MILLISECONDS)); assertEquals(count, result.size()); Message slowestMessage = result.get(count - 1); LOGGER.debug("Get the slowest {} message", slowestMessage); assertTrue(stopWatch.getTime(TimeUnit.MILLISECONDS) > slowestMessage.getDelay()); } /** * <pre> * Test call on Fork-Join framework: * - ForkJoinPool.commonPool() takes 6015 ms to perform logic; * - new ForkJoinPool(100 / 2) takes 1755 ms to perform logic; * </pre> */ @Test void testGetMessagesInForkJoin() throws Exception { final int count = 100; runInForkJoinPool(count, ForkJoinPool.commonPool()); stopWatch.reset(); runInForkJoinPool(count, new ForkJoinPool(count / 2)); } private void runInForkJoinPool(final int count, ForkJoinPool forkJoinPool) { stopWatch.start(); MessageRecursiveTask recursiveTask = new MessageRecursiveTask(IntStream.range(0, count).toArray()); List<Message> result = forkJoinPool.invoke(recursiveTask); // fork and join stopWatch.stop(); LOGGER.debug("Time in seconds: " + stopWatch.getTime(TimeUnit.MILLISECONDS)); assertEquals(count, result.size()); Message slowestMessage = result.get(count - 1); LOGGER.debug("Get the slowest {} message", slowestMessage); assertTrue(stopWatch.getTime(TimeUnit.MILLISECONDS) > slowestMessage.getDelay()); } /** * {@link RecursiveTask} implementation to run in Fork-Join pool recursively. */ private class MessageRecursiveTask extends RecursiveTask<List<Message>> { private final int[] ids; MessageRecursiveTask(int[] ids) { this.ids = ids; } @Override protected List<Message> compute() { List<Message> list = new ArrayList<>(); if (ids.length > 1) { Collection<MessageRecursiveTask> collection = ForkJoinTask.invokeAll(createSubtasks()); // schedule all for asynchronous execution list.addAll(collection.stream() .map(ForkJoinTask::join) .flatMap(List::stream) .collect(Collectors.toList())); } else { list.add(process(ids[0])); } return list; } private Message process(int id) { return slowService.getMessage(id); } private List<MessageRecursiveTask> createSubtasks() { List<MessageRecursiveTask> subTasks = new ArrayList<>(); int length = ids.length; int[] left = Arrays.copyOfRange(ids, 0, (length + 1) / 2); int[] right = Arrays.copyOfRange(ids, (length + 1) / 2, length); subTasks.add(new MessageRecursiveTask(left)); subTasks.add(new MessageRecursiveTask(right)); return subTasks; } } }
package com.netflix.niws.loadbalancer; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.netflix.discovery.CacheRefreshedEvent; import com.netflix.discovery.EurekaClient; import com.netflix.discovery.EurekaEventListener; import com.netflix.loadbalancer.ServerListUpdater; import org.easymock.Capture; import org.easymock.EasyMock; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import javax.inject.Provider; import java.util.Queue; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; /** * @author David Liu */ public class EurekaNotificationServerListUpdaterTest { private EurekaClient eurekaClientMock; private EurekaClient eurekaClientMock2; private ThreadPoolExecutor testExecutor; @Before public void setUp() { eurekaClientMock = setUpEurekaClientMock(); eurekaClientMock2 = setUpEurekaClientMock(); // use a test executor so that the tests do not share executors testExecutor = new ThreadPoolExecutor( 2, 2 * 5, 0, TimeUnit.NANOSECONDS, new ArrayBlockingQueue<Runnable>(1000), new ThreadFactoryBuilder() .setNameFormat("EurekaNotificationServerListUpdater-%d") .setDaemon(true) .build() ); } @Test public void testUpdating() throws Exception { EurekaNotificationServerListUpdater serverListUpdater = new EurekaNotificationServerListUpdater( new Provider<EurekaClient>() { @Override public EurekaClient get() { return eurekaClientMock; } }, testExecutor ); try { Capture<EurekaEventListener> eventListenerCapture = new Capture<EurekaEventListener>(); eurekaClientMock.registerEventListener(EasyMock.capture(eventListenerCapture)); EasyMock.replay(eurekaClientMock); final AtomicBoolean firstTime = new AtomicBoolean(false); final CountDownLatch firstLatch = new CountDownLatch(1); final CountDownLatch secondLatch = new CountDownLatch(1); serverListUpdater.start(new ServerListUpdater.UpdateAction() { @Override public void doUpdate() { if (firstTime.compareAndSet(false, true)) { firstLatch.countDown(); } else { secondLatch.countDown(); } } }); eventListenerCapture.getValue().onEvent(new CacheRefreshedEvent()); Assert.assertTrue(firstLatch.await(2, TimeUnit.SECONDS)); // wait a bit for the updateQueued flag to be reset for (int i = 1; i < 10; i++) { if (serverListUpdater.updateQueued.get()) { Thread.sleep(i * 100); } else { break; } } eventListenerCapture.getValue().onEvent(new CacheRefreshedEvent()); Assert.assertTrue(secondLatch.await(2, TimeUnit.SECONDS)); } finally { serverListUpdater.stop(); EasyMock.verify(eurekaClientMock); } } @Test public void testStopWithCommonExecutor() throws Exception { EurekaNotificationServerListUpdater serverListUpdater1 = new EurekaNotificationServerListUpdater( new Provider<EurekaClient>() { @Override public EurekaClient get() { return eurekaClientMock; } }, testExecutor ); EurekaNotificationServerListUpdater serverListUpdater2 = new EurekaNotificationServerListUpdater( new Provider<EurekaClient>() { @Override public EurekaClient get() { return eurekaClientMock2; } }, testExecutor ); Capture<EurekaEventListener> eventListenerCapture = new Capture<EurekaEventListener>(); eurekaClientMock.registerEventListener(EasyMock.capture(eventListenerCapture)); Capture<EurekaEventListener> eventListenerCapture2 = new Capture<EurekaEventListener>(); eurekaClientMock2.registerEventListener(EasyMock.capture(eventListenerCapture2)); EasyMock.replay(eurekaClientMock); EasyMock.replay(eurekaClientMock2); final CountDownLatch updateCountLatch = new CountDownLatch(2); serverListUpdater1.start(new ServerListUpdater.UpdateAction() { @Override public void doUpdate() { updateCountLatch.countDown(); } }); serverListUpdater2.start(new ServerListUpdater.UpdateAction() { @Override public void doUpdate() { updateCountLatch.countDown(); } }); eventListenerCapture.getValue().onEvent(new CacheRefreshedEvent()); eventListenerCapture2.getValue().onEvent(new CacheRefreshedEvent()); Assert.assertTrue(updateCountLatch.await(2, TimeUnit.SECONDS)); // latch is for both serverListUpdater1.stop(); serverListUpdater2.stop(); EasyMock.verify(eurekaClientMock); EasyMock.verify(eurekaClientMock2); } @Test public void testTaskAlreadyQueued() throws Exception { EurekaNotificationServerListUpdater serverListUpdater = new EurekaNotificationServerListUpdater( new Provider<EurekaClient>() { @Override public EurekaClient get() { return eurekaClientMock; } }, testExecutor ); try { Capture<EurekaEventListener> eventListenerCapture = new Capture<EurekaEventListener>(); eurekaClientMock.registerEventListener(EasyMock.capture(eventListenerCapture)); EasyMock.replay(eurekaClientMock); final CountDownLatch countDownLatch = new CountDownLatch(1); serverListUpdater.start(new ServerListUpdater.UpdateAction() { @Override public void doUpdate() { if (countDownLatch.getCount() == 0) { Assert.fail("should only countdown once"); } countDownLatch.countDown(); } }); eventListenerCapture.getValue().onEvent(new CacheRefreshedEvent()); eventListenerCapture.getValue().onEvent(new CacheRefreshedEvent()); Assert.assertTrue(countDownLatch.await(2, TimeUnit.SECONDS)); Thread.sleep(100); // sleep a bit more Assert.assertFalse(serverListUpdater.updateQueued.get()); } finally { serverListUpdater.stop(); EasyMock.verify(eurekaClientMock); } } @Test public void testSubmitExceptionClearQueued() { ThreadPoolExecutor executorMock = EasyMock.createMock(ThreadPoolExecutor.class); EasyMock.expect(executorMock.submit(EasyMock.isA(Runnable.class))) .andThrow(new RejectedExecutionException("test exception")); EasyMock.expect(executorMock.isShutdown()).andReturn(Boolean.FALSE); EurekaNotificationServerListUpdater serverListUpdater = new EurekaNotificationServerListUpdater( new Provider<EurekaClient>() { @Override public EurekaClient get() { return eurekaClientMock; } }, executorMock ); try { Capture<EurekaEventListener> eventListenerCapture = new Capture<EurekaEventListener>(); eurekaClientMock.registerEventListener(EasyMock.capture(eventListenerCapture)); EasyMock.replay(eurekaClientMock); EasyMock.replay(executorMock); serverListUpdater.start(new ServerListUpdater.UpdateAction() { @Override public void doUpdate() { Assert.fail("should not reach here"); } }); eventListenerCapture.getValue().onEvent(new CacheRefreshedEvent()); Assert.assertFalse(serverListUpdater.updateQueued.get()); } finally { serverListUpdater.stop(); EasyMock.verify(executorMock); EasyMock.verify(eurekaClientMock); } } @Test public void testEurekaClientUnregister() { ThreadPoolExecutor executorMock = EasyMock.createMock(ThreadPoolExecutor.class); EasyMock.expect(executorMock.isShutdown()).andReturn(Boolean.TRUE); EurekaNotificationServerListUpdater serverListUpdater = new EurekaNotificationServerListUpdater( new Provider<EurekaClient>() { @Override public EurekaClient get() { return eurekaClientMock; } }, executorMock ); try { Capture<EurekaEventListener> registeredListener = new Capture<EurekaEventListener>(); eurekaClientMock.registerEventListener(EasyMock.capture(registeredListener)); EasyMock.replay(eurekaClientMock); EasyMock.replay(executorMock); serverListUpdater.start(new ServerListUpdater.UpdateAction() { @Override public void doUpdate() { Assert.fail("should not reach here"); } }); registeredListener.getValue().onEvent(new CacheRefreshedEvent()); } finally { EasyMock.verify(executorMock); EasyMock.verify(eurekaClientMock); } } @Test(expected = IllegalStateException.class) public void testFailIfDiscoveryIsNotAvailable() { EurekaNotificationServerListUpdater serverListUpdater = new EurekaNotificationServerListUpdater( new Provider<EurekaClient>() { @Override public EurekaClient get() { return null; } }, testExecutor ); serverListUpdater.start(new ServerListUpdater.UpdateAction() { @Override public void doUpdate() { Assert.fail("Should not reach here"); } }); } private EurekaClient setUpEurekaClientMock() { final EurekaClient eurekaClientMock = EasyMock.createMock(EurekaClient.class); EasyMock .expect(eurekaClientMock.unregisterEventListener(EasyMock.isA(EurekaEventListener.class))) .andReturn(true).times(1); return eurekaClientMock; } }
// Autor y desarrollador parcial o total: Santiago Hernández Plazas (santiago.h.plazas@gmail.com). package co.gov.ideamredd.web.usuario.dao; import org.jasypt.encryption.pbe.StandardPBEStringEncryptor; public class Security { public static String encriptar(String cadena) { StandardPBEStringEncryptor s = new StandardPBEStringEncryptor(); s.setPassword("uniquekey"); return s.encrypt(cadena); } public static String desencriptar(String cadena) { StandardPBEStringEncryptor s = new StandardPBEStringEncryptor(); s.setPassword("uniquekey"); String contenido = ""; for (int i = 0; i < cadena.length(); i++) { contenido += (cadena.charAt(i) == ' ') ? "+" : cadena.charAt(i); }// fin del for // cadena.replace("/\s/g","_");F String devuelve = ""; try { devuelve = s.decrypt(contenido); } catch (Exception e) { } return devuelve; } }
/* * Copyright © 2019 Cask Data, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package io.cdap.plugin.http.source.common.pagination.page; import io.cdap.cdap.api.data.format.StructuredRecord; import io.cdap.cdap.api.data.schema.Schema; import io.cdap.cdap.etl.api.InvalidEntry; /** * Creates invalid entries. */ public class InvalidEntryCreator { private static final String ERROR_SCHEMA_BODY_PROPERTY = "body"; private static final Schema STRING_ERROR_SCHEMA = Schema.recordOf("stringError", Schema.Field.of(ERROR_SCHEMA_BODY_PROPERTY, Schema.of(Schema.Type.STRING))); private static final Schema BYTES_ERROR_SCHEMA = Schema.recordOf("bytesError", Schema.Field.of(ERROR_SCHEMA_BODY_PROPERTY, Schema.of(Schema.Type.BYTES))); public static InvalidEntry<StructuredRecord> buildBytesError(byte[] bytes, Throwable ex) { String errorText = String.format("Cannot convert bytes to a record. Reason: '%s: %s'", ex.getClass().getName(), ex.getMessage()); StructuredRecord.Builder builder = StructuredRecord.builder(BYTES_ERROR_SCHEMA); builder.set(ERROR_SCHEMA_BODY_PROPERTY, bytes); return new InvalidEntry<>(0, errorText, builder.build()); } public static InvalidEntry<StructuredRecord> buildStringError(String recordBody, Throwable e) { String errorText = String.format("Cannot convert line '%s' to a record. Reason: '%s: %s'", recordBody, e.getClass().getName(), e.getMessage()); return buildStringError(0, recordBody, errorText); } public static InvalidEntry<StructuredRecord> buildStringError(int code, String recordBody, String errorText) { StructuredRecord.Builder builder = StructuredRecord.builder(STRING_ERROR_SCHEMA); builder.set(ERROR_SCHEMA_BODY_PROPERTY, recordBody); return new InvalidEntry<>(code, errorText, builder.build()); } }
package me.zhengjie.modules.system.rest; import me.zhengjie.aop.log.Log; import me.zhengjie.modules.system.dojo.ModelA; import me.zhengjie.modules.system.dojo.Order; import me.zhengjie.modules.system.service.ActModelService; import me.zhengjie.modules.system.service.dto.ModelDto; import org.activiti.engine.RepositoryService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import java.io.UnsupportedEncodingException; @RestController @RequestMapping("api") public class ActModelController { @Autowired private ActModelService actModelService; @Log("查询流程") @GetMapping("/act") @PreAuthorize("hasAnyRole('ADMIN','ACT_ALL','ACT_SELECT')") public ResponseEntity getOrder(ModelDto criteria, Pageable pageable){ return new ResponseEntity(actModelService.queryAll(criteria,pageable), HttpStatus.OK); } @Log("新增流程") @PostMapping("/act") @PreAuthorize("hasAnyRole('ADMIN','ACT_ALL','ACT_CREATE')") public ResponseEntity create(@Validated @RequestBody ModelA resources) throws UnsupportedEncodingException { System.out.println(111); return new ResponseEntity(actModelService.create(resources),HttpStatus.CREATED); } }
package com.example.android.quakereport; public class Earthquake { // Name of the Android version (e.g. Gingerbread, Honeycomb, Ice Cream Sandwich) private Double mMagnitude; // Android version number (e.g. 2.3-2.7, 3.0-3.2.6, 4.0-4.0.4) private String mLocation; // Drawable resource ID // private String mDate; private long mTimeInMilliseconds; /** Website URL of the earthquake */ private String mUrl; /* * Create a new AndroidFlavor object. * * @param vName is the name of the Android version (e.g. Gingerbread) * @param vNumber is the corresponding Android version number (e.g. 2.3-2.7) * @param image is drawable reference ID that corresponds to the Android version * */ // public Earthquake(String vName, String vNumber, String imageResourceId) // { // mMagnitude = vName; // mLocation = vNumber; // mDate = imageResourceId; // } // /** // * Constructs a new {@link Earthquake} object. // * // * @param magnitude is the magnitude (size) of the earthquake // * @param location is the city location of the earthquake // * @param timeInMilliseconds is the time in milliseconds (from the Epoch) when the // * earthquake happened // */ // public Earthquake(Double magnitude, String location, long timeInMilliseconds) { // mMagnitude = magnitude; // mLocation = location; // mTimeInMilliseconds = timeInMilliseconds; // } /** * Constructs a new {@link Earthquake} object. * * @param magnitude is the magnitude (size) of the earthquake * @param location is the location where the earthquake happened * @param timeInMilliseconds is the time in milliseconds (from the Epoch) when the * earthquake happened * @param url is the website URL to find more details about the earthquake */ public Earthquake(double magnitude, String location, long timeInMilliseconds, String url) { mMagnitude = magnitude; mLocation = location; mTimeInMilliseconds = timeInMilliseconds; mUrl = url; } // public Earthquake(String magnitude, String location, String dateToDisplay) { // } /** * Get the name of the Android version */ // public String getMagnitude() { // return mMagnitude; // } public double getMagnitude() { return mMagnitude; } /** * Get the Android version number */ public String getLocation() { return mLocation; } /** * Get the image resource ID */ // public String getDate() { // return mDate; // } /** * Returns the time of the earthquake. */ public long getTimeInMilliseconds() { return mTimeInMilliseconds; } public String getUrl() { return mUrl; } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v2/errors/not_empty_error.proto package com.google.ads.googleads.v2.errors; public interface NotEmptyErrorEnumOrBuilder extends // @@protoc_insertion_point(interface_extends:google.ads.googleads.v2.errors.NotEmptyErrorEnum) com.google.protobuf.MessageOrBuilder { }
/** * This program and the accompanying materials * are made available under the terms of the License * which accompanies this distribution in the file LICENSE.txt */ package com.archimatetool.model; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Application Service</b></em>'. * <!-- end-user-doc --> * * * @see com.archimatetool.model.IArchimatePackage#getApplicationService() * @model * @generated */ public interface IApplicationService extends IApplicationElement, IBehaviorElement { } // IApplicationService
// Copyright 2021 Goldman Sachs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.finos.legend.engine.plan.execution.stores.relational.connection.ds.specifications.keys; import org.finos.legend.engine.plan.execution.stores.relational.connection.ds.DataSourceSpecificationKey; import java.io.File; import java.util.Objects; public class EmbeddedH2DataSourceSpecificationKey implements DataSourceSpecificationKey { private final String databaseName; private final File directory; private final boolean autoServerMode; public EmbeddedH2DataSourceSpecificationKey(String databaseName, File directory) { this(databaseName, directory, false); } public EmbeddedH2DataSourceSpecificationKey(String databaseName, File directory, boolean autoServerMode) { this.databaseName = databaseName; this.directory = directory; this.autoServerMode = autoServerMode; } public String getDatabaseName() { return this.databaseName; } public File getDirectory() { return this.directory; } public boolean isAutoServerMode() { return this.autoServerMode; } @Override public String shortId() { return "EmbeddedH2_" + "db:" + this.databaseName + "dir:" + (null != this.directory ? this.directory.getPath() : "") + "auto:" + this.autoServerMode; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } EmbeddedH2DataSourceSpecificationKey that = (EmbeddedH2DataSourceSpecificationKey) o; return this.autoServerMode == that.autoServerMode && Objects.equals(this.databaseName, that.databaseName) && Objects.equals(this.directory, that.directory); } @Override public int hashCode() { return Objects.hash(this.databaseName, this.directory, this.autoServerMode); } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ package org.apache.poi.xssf.usermodel; import org.apache.poi.ss.usermodel.BorderFormatting; import org.apache.poi.ss.usermodel.BorderStyle; import org.apache.poi.ss.usermodel.Color; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBorder; import org.openxmlformats.schemas.spreadsheetml.x2006.main.STBorderStyle; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBorderPr; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTColor; /** * XSSF high level representation for Border Formatting component * of Conditional Formatting settings */ public class XSSFBorderFormatting implements BorderFormatting { CTBorder _border; /*package*/ XSSFBorderFormatting(CTBorder border) { _border = border; } /** * @deprecated POI 3.15. Use {@link #getBorderBottomEnum()}. * This method will return an BorderStyle enum in the future. */ @Override public short getBorderBottom() { return getBorderBottomEnum().getCode(); } /** * @since POI 3.15 */ @Override public BorderStyle getBorderBottomEnum() { STBorderStyle.Enum ptrn = _border.isSetBottom() ? _border.getBottom().getStyle() : null; return ptrn == null ? BorderStyle.NONE : BorderStyle.valueOf((short)(ptrn.intValue() - 1)); } /** * @deprecated POI 3.15. Use {@link #getBorderDiagonalEnum()}. * This method will return an BorderStyle enum in the future. */ @Override public short getBorderDiagonal() { return getBorderDiagonalEnum().getCode(); } /** * @since POI 3.15 */ @Override public BorderStyle getBorderDiagonalEnum() { STBorderStyle.Enum ptrn = _border.isSetDiagonal() ? _border.getDiagonal().getStyle() : null; return ptrn == null ? BorderStyle.NONE : BorderStyle.valueOf((short)(ptrn.intValue() - 1)); } /** * @deprecated POI 3.15. Use {@link #getBorderLeftEnum()}. * This method will return an BorderStyle enum in the future. */ @Override public short getBorderLeft() { return getBorderLeftEnum().getCode(); } /** * @since POI 3.15 */ @Override public BorderStyle getBorderLeftEnum() { STBorderStyle.Enum ptrn = _border.isSetLeft() ? _border.getLeft().getStyle() : null; return ptrn == null ? BorderStyle.NONE : BorderStyle.valueOf((short)(ptrn.intValue() - 1)); } /** * @deprecated POI 3.15. Use {@link #getBorderRightEnum()}. * This method will return an BorderStyle enum in the future. */ @Override public short getBorderRight() { return getBorderRightEnum().getCode(); } /** * @since POI 3.15 */ @Override public BorderStyle getBorderRightEnum() { STBorderStyle.Enum ptrn = _border.isSetRight() ? _border.getRight().getStyle() : null; return ptrn == null ? BorderStyle.NONE : BorderStyle.valueOf((short)(ptrn.intValue() - 1)); } /** * @deprecated POI 3.15. Use {@link #getBorderTopEnum()}. * This method will return an BorderStyle enum in the future. */ @Override public short getBorderTop() { return getBorderTopEnum().getCode(); } /** * @since POI 3.15 */ @Override public BorderStyle getBorderTopEnum() { STBorderStyle.Enum ptrn = _border.isSetTop() ? _border.getTop().getStyle() : null; return ptrn == null ? BorderStyle.NONE : BorderStyle.valueOf((short)(ptrn.intValue() - 1)); } @Override public XSSFColor getBottomBorderColorColor() { if(!_border.isSetBottom()) return null; CTBorderPr pr = _border.getBottom(); return new XSSFColor(pr.getColor()); } @Override public short getBottomBorderColor() { XSSFColor color = getBottomBorderColorColor(); if (color == null) return 0; return color.getIndexed(); } @Override public XSSFColor getDiagonalBorderColorColor() { if(!_border.isSetDiagonal()) return null; CTBorderPr pr = _border.getDiagonal(); return new XSSFColor(pr.getColor()); } @Override public short getDiagonalBorderColor() { XSSFColor color = getDiagonalBorderColorColor(); if (color == null) return 0; return color.getIndexed(); } @Override public XSSFColor getLeftBorderColorColor() { if(!_border.isSetLeft()) return null; CTBorderPr pr = _border.getLeft(); return new XSSFColor(pr.getColor()); } @Override public short getLeftBorderColor() { XSSFColor color = getLeftBorderColorColor(); if (color == null) return 0; return color.getIndexed(); } @Override public XSSFColor getRightBorderColorColor() { if(!_border.isSetRight()) return null; CTBorderPr pr = _border.getRight(); return new XSSFColor(pr.getColor()); } @Override public short getRightBorderColor() { XSSFColor color = getRightBorderColorColor(); if (color == null) return 0; return color.getIndexed(); } @Override public XSSFColor getTopBorderColorColor() { if(!_border.isSetTop()) return null; CTBorderPr pr = _border.getTop(); return new XSSFColor(pr.getColor()); } @Override public short getTopBorderColor() { XSSFColor color = getRightBorderColorColor(); if (color == null) return 0; return color.getIndexed(); } /** * @deprecated 3.15 beta 2. Use {@link #setBorderBottom(BorderStyle)} */ @Override public void setBorderBottom(short border) { setBorderBottom(BorderStyle.valueOf(border)); } @Override public void setBorderBottom(BorderStyle border) { CTBorderPr pr = _border.isSetBottom() ? _border.getBottom() : _border.addNewBottom(); if(border == BorderStyle.NONE) _border.unsetBottom(); else pr.setStyle(STBorderStyle.Enum.forInt(border.getCode() + 1)); } /** * @deprecated 3.15 beta 2. Use {@link #setBorderDiagonal(BorderStyle)} */ @Override public void setBorderDiagonal(short border) { setBorderDiagonal(BorderStyle.valueOf(border)); } @Override public void setBorderDiagonal(BorderStyle border) { CTBorderPr pr = _border.isSetDiagonal() ? _border.getDiagonal() : _border.addNewDiagonal(); if(border == BorderStyle.NONE) _border.unsetDiagonal(); else pr.setStyle(STBorderStyle.Enum.forInt(border.getCode() + 1)); } /** * @deprecated 3.15 beta 2. Use {@link #setBorderLeft(BorderStyle)} */ @Override public void setBorderLeft(short border) { setBorderLeft(BorderStyle.valueOf(border)); } @Override public void setBorderLeft(BorderStyle border) { CTBorderPr pr = _border.isSetLeft() ? _border.getLeft() : _border.addNewLeft(); if(border == BorderStyle.NONE) _border.unsetLeft(); else pr.setStyle(STBorderStyle.Enum.forInt(border.getCode() + 1)); } /** * @deprecated 3.15 beta 2. Use {@link #setBorderRight(BorderStyle)} */ @Override public void setBorderRight(short border) { setBorderRight(BorderStyle.valueOf(border)); } @Override public void setBorderRight(BorderStyle border) { CTBorderPr pr = _border.isSetRight() ? _border.getRight() : _border.addNewRight(); if(border == BorderStyle.NONE) _border.unsetRight(); else pr.setStyle(STBorderStyle.Enum.forInt(border.getCode() + 1)); } /** * @deprecated 3.15 beta 2. Use {@link #setBorderTop(BorderStyle)} */ @Override public void setBorderTop(short border) { setBorderTop(BorderStyle.valueOf(border)); } @Override public void setBorderTop(BorderStyle border) { CTBorderPr pr = _border.isSetTop() ? _border.getTop() : _border.addNewTop(); if(border == BorderStyle.NONE) _border.unsetTop(); else pr.setStyle(STBorderStyle.Enum.forInt(border.getCode() + 1)); } @Override public void setBottomBorderColor(Color color) { XSSFColor xcolor = XSSFColor.toXSSFColor(color); if (xcolor == null) setBottomBorderColor((CTColor)null); else setBottomBorderColor(xcolor.getCTColor()); } @Override public void setBottomBorderColor(short color) { CTColor ctColor = CTColor.Factory.newInstance(); ctColor.setIndexed(color); setBottomBorderColor(ctColor); } public void setBottomBorderColor(CTColor color) { CTBorderPr pr = _border.isSetBottom() ? _border.getBottom() : _border.addNewBottom(); if (color == null) { pr.unsetColor(); } else { pr.setColor(color); } } @Override public void setDiagonalBorderColor(Color color) { XSSFColor xcolor = XSSFColor.toXSSFColor(color); if (xcolor == null) setDiagonalBorderColor((CTColor)null); else setDiagonalBorderColor(xcolor.getCTColor()); } @Override public void setDiagonalBorderColor(short color) { CTColor ctColor = CTColor.Factory.newInstance(); ctColor.setIndexed(color); setDiagonalBorderColor(ctColor); } public void setDiagonalBorderColor(CTColor color) { CTBorderPr pr = _border.isSetDiagonal() ? _border.getDiagonal() : _border.addNewDiagonal(); if (color == null) { pr.unsetColor(); } else { pr.setColor(color); } } @Override public void setLeftBorderColor(Color color) { XSSFColor xcolor = XSSFColor.toXSSFColor(color); if (xcolor == null) setLeftBorderColor((CTColor)null); else setLeftBorderColor(xcolor.getCTColor()); } @Override public void setLeftBorderColor(short color) { CTColor ctColor = CTColor.Factory.newInstance(); ctColor.setIndexed(color); setLeftBorderColor(ctColor); } public void setLeftBorderColor(CTColor color) { CTBorderPr pr = _border.isSetLeft() ? _border.getLeft() : _border.addNewLeft(); if (color == null) { pr.unsetColor(); } else { pr.setColor(color); } } @Override public void setRightBorderColor(Color color) { XSSFColor xcolor = XSSFColor.toXSSFColor(color); if (xcolor == null) setRightBorderColor((CTColor)null); else setRightBorderColor(xcolor.getCTColor()); } @Override public void setRightBorderColor(short color) { CTColor ctColor = CTColor.Factory.newInstance(); ctColor.setIndexed(color); setRightBorderColor(ctColor); } public void setRightBorderColor(CTColor color) { CTBorderPr pr = _border.isSetRight() ? _border.getRight() : _border.addNewRight(); if (color == null) { pr.unsetColor(); } else { pr.setColor(color); } } @Override public void setTopBorderColor(Color color) { XSSFColor xcolor = XSSFColor.toXSSFColor(color); if (xcolor == null) setTopBorderColor((CTColor)null); else setTopBorderColor(xcolor.getCTColor()); } @Override public void setTopBorderColor(short color) { CTColor ctColor = CTColor.Factory.newInstance(); ctColor.setIndexed(color); setTopBorderColor(ctColor); } public void setTopBorderColor(CTColor color) { CTBorderPr pr = _border.isSetTop() ? _border.getTop() : _border.addNewTop(); if (color == null) { pr.unsetColor(); } else { pr.setColor(color); } } }
/* * Copyright 2015-2020 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.identitymanagement.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UploadSSHPublicKey" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class UploadSSHPublicKeyRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The name of the IAM user to associate the SSH public key with. * </p> * <p> * This parameter allows (through its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string of * characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also include any of * the following characters: _+=,.@- * </p> */ private String userName; /** * <p> * The SSH public key. The public key must be encoded in ssh-rsa format or PEM format. The minimum bit-length of the * public key is 2048 bits. For example, you can generate a 2048-bit key, and the resulting PEM file is 1679 bytes * long. * </p> * <p> * The <a href="http://wikipedia.org/wiki/regex">regex pattern</a> used to validate this parameter is a string of * characters consisting of the following: * </p> * <ul> * <li> * <p> * Any printable ASCII character ranging from the space character (<code>\u0020</code>) through the end of the ASCII * character range * </p> * </li> * <li> * <p> * The printable characters in the Basic Latin and Latin-1 Supplement character set (through <code>\u00FF</code>) * </p> * </li> * <li> * <p> * The special characters tab (<code>\u0009</code>), line feed (<code>\u000A</code>), and carriage return (<code>\u000D</code> * ) * </p> * </li> * </ul> */ private String sSHPublicKeyBody; /** * <p> * The name of the IAM user to associate the SSH public key with. * </p> * <p> * This parameter allows (through its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string of * characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also include any of * the following characters: _+=,.@- * </p> * * @param userName * The name of the IAM user to associate the SSH public key with.</p> * <p> * This parameter allows (through its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string * of characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also * include any of the following characters: _+=,.@- */ public void setUserName(String userName) { this.userName = userName; } /** * <p> * The name of the IAM user to associate the SSH public key with. * </p> * <p> * This parameter allows (through its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string of * characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also include any of * the following characters: _+=,.@- * </p> * * @return The name of the IAM user to associate the SSH public key with.</p> * <p> * This parameter allows (through its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string * of characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also * include any of the following characters: _+=,.@- */ public String getUserName() { return this.userName; } /** * <p> * The name of the IAM user to associate the SSH public key with. * </p> * <p> * This parameter allows (through its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string of * characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also include any of * the following characters: _+=,.@- * </p> * * @param userName * The name of the IAM user to associate the SSH public key with.</p> * <p> * This parameter allows (through its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string * of characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also * include any of the following characters: _+=,.@- * @return Returns a reference to this object so that method calls can be chained together. */ public UploadSSHPublicKeyRequest withUserName(String userName) { setUserName(userName); return this; } /** * <p> * The SSH public key. The public key must be encoded in ssh-rsa format or PEM format. The minimum bit-length of the * public key is 2048 bits. For example, you can generate a 2048-bit key, and the resulting PEM file is 1679 bytes * long. * </p> * <p> * The <a href="http://wikipedia.org/wiki/regex">regex pattern</a> used to validate this parameter is a string of * characters consisting of the following: * </p> * <ul> * <li> * <p> * Any printable ASCII character ranging from the space character (<code>\u0020</code>) through the end of the ASCII * character range * </p> * </li> * <li> * <p> * The printable characters in the Basic Latin and Latin-1 Supplement character set (through <code>\u00FF</code>) * </p> * </li> * <li> * <p> * The special characters tab (<code>\u0009</code>), line feed (<code>\u000A</code>), and carriage return (<code>\u000D</code> * ) * </p> * </li> * </ul> * * @param sSHPublicKeyBody * The SSH public key. The public key must be encoded in ssh-rsa format or PEM format. The minimum bit-length * of the public key is 2048 bits. For example, you can generate a 2048-bit key, and the resulting PEM file * is 1679 bytes long.</p> * <p> * The <a href="http://wikipedia.org/wiki/regex">regex pattern</a> used to validate this parameter is a * string of characters consisting of the following: * </p> * <ul> * <li> * <p> * Any printable ASCII character ranging from the space character (<code>\u0020</code>) through the end of * the ASCII character range * </p> * </li> * <li> * <p> * The printable characters in the Basic Latin and Latin-1 Supplement character set (through * <code>\u00FF</code>) * </p> * </li> * <li> * <p> * The special characters tab (<code>\u0009</code>), line feed (<code>\u000A</code>), and carriage return ( * <code>\u000D</code>) * </p> * </li> */ public void setSSHPublicKeyBody(String sSHPublicKeyBody) { this.sSHPublicKeyBody = sSHPublicKeyBody; } /** * <p> * The SSH public key. The public key must be encoded in ssh-rsa format or PEM format. The minimum bit-length of the * public key is 2048 bits. For example, you can generate a 2048-bit key, and the resulting PEM file is 1679 bytes * long. * </p> * <p> * The <a href="http://wikipedia.org/wiki/regex">regex pattern</a> used to validate this parameter is a string of * characters consisting of the following: * </p> * <ul> * <li> * <p> * Any printable ASCII character ranging from the space character (<code>\u0020</code>) through the end of the ASCII * character range * </p> * </li> * <li> * <p> * The printable characters in the Basic Latin and Latin-1 Supplement character set (through <code>\u00FF</code>) * </p> * </li> * <li> * <p> * The special characters tab (<code>\u0009</code>), line feed (<code>\u000A</code>), and carriage return (<code>\u000D</code> * ) * </p> * </li> * </ul> * * @return The SSH public key. The public key must be encoded in ssh-rsa format or PEM format. The minimum * bit-length of the public key is 2048 bits. For example, you can generate a 2048-bit key, and the * resulting PEM file is 1679 bytes long.</p> * <p> * The <a href="http://wikipedia.org/wiki/regex">regex pattern</a> used to validate this parameter is a * string of characters consisting of the following: * </p> * <ul> * <li> * <p> * Any printable ASCII character ranging from the space character (<code>\u0020</code>) through the end of * the ASCII character range * </p> * </li> * <li> * <p> * The printable characters in the Basic Latin and Latin-1 Supplement character set (through * <code>\u00FF</code>) * </p> * </li> * <li> * <p> * The special characters tab (<code>\u0009</code>), line feed (<code>\u000A</code>), and carriage return ( * <code>\u000D</code>) * </p> * </li> */ public String getSSHPublicKeyBody() { return this.sSHPublicKeyBody; } /** * <p> * The SSH public key. The public key must be encoded in ssh-rsa format or PEM format. The minimum bit-length of the * public key is 2048 bits. For example, you can generate a 2048-bit key, and the resulting PEM file is 1679 bytes * long. * </p> * <p> * The <a href="http://wikipedia.org/wiki/regex">regex pattern</a> used to validate this parameter is a string of * characters consisting of the following: * </p> * <ul> * <li> * <p> * Any printable ASCII character ranging from the space character (<code>\u0020</code>) through the end of the ASCII * character range * </p> * </li> * <li> * <p> * The printable characters in the Basic Latin and Latin-1 Supplement character set (through <code>\u00FF</code>) * </p> * </li> * <li> * <p> * The special characters tab (<code>\u0009</code>), line feed (<code>\u000A</code>), and carriage return (<code>\u000D</code> * ) * </p> * </li> * </ul> * * @param sSHPublicKeyBody * The SSH public key. The public key must be encoded in ssh-rsa format or PEM format. The minimum bit-length * of the public key is 2048 bits. For example, you can generate a 2048-bit key, and the resulting PEM file * is 1679 bytes long.</p> * <p> * The <a href="http://wikipedia.org/wiki/regex">regex pattern</a> used to validate this parameter is a * string of characters consisting of the following: * </p> * <ul> * <li> * <p> * Any printable ASCII character ranging from the space character (<code>\u0020</code>) through the end of * the ASCII character range * </p> * </li> * <li> * <p> * The printable characters in the Basic Latin and Latin-1 Supplement character set (through * <code>\u00FF</code>) * </p> * </li> * <li> * <p> * The special characters tab (<code>\u0009</code>), line feed (<code>\u000A</code>), and carriage return ( * <code>\u000D</code>) * </p> * </li> * @return Returns a reference to this object so that method calls can be chained together. */ public UploadSSHPublicKeyRequest withSSHPublicKeyBody(String sSHPublicKeyBody) { setSSHPublicKeyBody(sSHPublicKeyBody); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getUserName() != null) sb.append("UserName: ").append(getUserName()).append(","); if (getSSHPublicKeyBody() != null) sb.append("SSHPublicKeyBody: ").append(getSSHPublicKeyBody()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof UploadSSHPublicKeyRequest == false) return false; UploadSSHPublicKeyRequest other = (UploadSSHPublicKeyRequest) obj; if (other.getUserName() == null ^ this.getUserName() == null) return false; if (other.getUserName() != null && other.getUserName().equals(this.getUserName()) == false) return false; if (other.getSSHPublicKeyBody() == null ^ this.getSSHPublicKeyBody() == null) return false; if (other.getSSHPublicKeyBody() != null && other.getSSHPublicKeyBody().equals(this.getSSHPublicKeyBody()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getUserName() == null) ? 0 : getUserName().hashCode()); hashCode = prime * hashCode + ((getSSHPublicKeyBody() == null) ? 0 : getSSHPublicKeyBody().hashCode()); return hashCode; } @Override public UploadSSHPublicKeyRequest clone() { return (UploadSSHPublicKeyRequest) super.clone(); } }
package p3d4amb.sat.lib; /** * Builds the image as a series of points */ public interface PointsProvider { Points getPoints(int width, int height); }
/* * 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.isis.persistence.jdo.datanucleus5.metamodel.facets.prop.column; import java.util.stream.Stream; import javax.jdo.annotations.Column; import javax.jdo.annotations.IdentityType; import org.apache.isis.metamodel.facetapi.FacetUtil; import org.apache.isis.metamodel.facetapi.FeatureType; import org.apache.isis.metamodel.facetapi.MetaModelRefiner; import org.apache.isis.metamodel.facets.FacetFactoryAbstract; import org.apache.isis.metamodel.facets.FacetedMethod; import org.apache.isis.metamodel.facets.objectvalue.maxlen.MaxLengthFacet; import org.apache.isis.metamodel.facets.properties.property.maxlength.MaxLengthFacetForPropertyAnnotation; import org.apache.isis.metamodel.progmodel.ProgrammingModel; import org.apache.isis.metamodel.spec.ObjectSpecification; import org.apache.isis.metamodel.spec.feature.Contributed; import org.apache.isis.metamodel.spec.feature.ObjectAssociation; import org.apache.isis.metamodel.specloader.validator.MetaModelValidator; import org.apache.isis.metamodel.specloader.validator.MetaModelValidatorVisiting; import org.apache.isis.metamodel.specloader.validator.MetaModelValidatorVisiting.Visitor; import org.apache.isis.persistence.jdo.datanucleus5.metamodel.JdoMetamodelUtil; import org.apache.isis.persistence.jdo.datanucleus5.metamodel.facets.object.persistencecapable.JdoPersistenceCapableFacet; import org.apache.isis.persistence.jdo.datanucleus5.metamodel.facets.prop.notpersistent.JdoNotPersistentFacet; import lombok.val; public class MaxLengthDerivedFromJdoColumnAnnotationFacetFactory extends FacetFactoryAbstract implements MetaModelRefiner { public MaxLengthDerivedFromJdoColumnAnnotationFacetFactory() { super(FeatureType.PROPERTIES_ONLY); } @Override public void process(final ProcessMethodContext processMethodContext) { // only applies to JDO entities; ignore any view models final Class<?> cls = processMethodContext.getCls(); if(!JdoMetamodelUtil.isPersistenceEnhanced(cls)) { return; } if(String.class != processMethodContext.getMethod().getReturnType()) { return; } val jdoColumnAnnotation = processMethodContext.synthesizeOnMethod(Column.class) .orElse(null); if (jdoColumnAnnotation==null) { return; } if(jdoColumnAnnotation.length() == -1) { return; } final FacetedMethod holder = processMethodContext.getFacetHolder(); MaxLengthFacet existingFacet = holder.getFacet(MaxLengthFacet.class); final MaxLengthFacet facet = new MaxLengthFacetDerivedFromJdoColumn(jdoColumnAnnotation.length(), holder); if(!existingFacet.isFallback()) { // will raise violation later facet.setUnderlyingFacet(existingFacet); } FacetUtil.addFacet(facet); } @Override public void refineProgrammingModel(ProgrammingModel programmingModel) { programmingModel.addValidator(newValidatorVisitor()); } private Visitor newValidatorVisitor() { return new MetaModelValidatorVisiting.Visitor() { @Override public boolean visit(ObjectSpecification objectSpec, MetaModelValidator validator) { validate(objectSpec, validator); return true; } private void validate(ObjectSpecification objectSpec, MetaModelValidator validator) { final JdoPersistenceCapableFacet pcFacet = objectSpec.getFacet(JdoPersistenceCapableFacet.class); if(pcFacet==null || pcFacet.getIdentityType() == IdentityType.NONDURABLE) { return; } final Stream<ObjectAssociation> associations = objectSpec .streamAssociations(Contributed.EXCLUDED) .filter(ObjectAssociation.Predicates.PROPERTIES); associations.forEach(association->{ // skip checks if annotated with JDO @NotPersistent if(association.containsNonFallbackFacet(JdoNotPersistentFacet.class)) { return; } final MaxLengthFacet facet = association.getFacet(MaxLengthFacet.class); final MaxLengthFacet underlying = (MaxLengthFacet) facet.getUnderlyingFacet(); if(underlying == null) { return; } // if(facet instanceof MaxLengthFacetDerivedFromJdoColumn && underlying instanceof MaxLengthFacetForMaxLengthAnnotationOnProperty) { // if(facet.value() != underlying.value()) { // validator.onFailure( // association, // association.getIdentifier(), // "%s: inconsistent lengths specified in Isis' @MaxLength(...) and @javax.jdo.annotations.Column(length=...); use just @javax.jdo.annotations.Column(length=...)", // association.getIdentifier().toClassAndNameIdentityString()); // } // } if(facet instanceof MaxLengthFacetDerivedFromJdoColumn && underlying instanceof MaxLengthFacetForPropertyAnnotation) { if(facet.value() != underlying.value()) { validator.onFailure( association, association.getIdentifier(), "%s: inconsistent lengths specified in Isis' @Property(maxLength=...) and @javax.jdo.annotations.Column(length=...); use just @javax.jdo.annotations.Column(length=...)", association.getIdentifier().toClassAndNameIdentityString()); } } }); } }; } }
/* * Copyright (C) 2014 The Dagger 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 dagger.internal.codegen.binding; import static dagger.internal.codegen.extension.DaggerStreams.toImmutableSet; import static dagger.spi.model.BindingKind.COMPONENT_PROVISION; import static dagger.spi.model.BindingKind.PROVISION; import dagger.internal.codegen.binding.MembersInjectionBinding.InjectionSite; import dagger.internal.codegen.collect.ImmutableSet; import dagger.internal.codegen.collect.ImmutableSortedSet; import dagger.internal.codegen.compileroption.CompilerOptions; import dagger.spi.model.BindingKind; import dagger.spi.model.DependencyRequest; import dagger.spi.model.Scope; import io.jbock.auto.value.AutoValue; import io.jbock.auto.value.extension.memoized.Memoized; import java.util.Optional; /** A value object representing the mechanism by which a {@code Key} can be provided. */ @AutoValue public abstract class ProvisionBinding extends ContributionBinding { @Override @Memoized public ImmutableSet<DependencyRequest> explicitDependencies() { return ImmutableSet.<DependencyRequest>builder() .addAll(provisionDependencies()) .addAll(membersInjectionDependencies()) .build(); } /** * Dependencies necessary to invoke an {@code @Inject} constructor or {@code @Provides} method. */ public abstract ImmutableSet<DependencyRequest> provisionDependencies(); @Memoized ImmutableSet<DependencyRequest> membersInjectionDependencies() { return injectionSites() .stream() .flatMap(i -> i.dependencies().stream()) .collect(toImmutableSet()); } /** * {@code InjectionSite}s for all {@code @Inject} members if {@code #kind()} is {@code * BindingKind#INJECTION}, otherwise empty. */ public abstract ImmutableSortedSet<InjectionSite> injectionSites(); @Override public BindingType bindingType() { return BindingType.PROVISION; } @Override public abstract Optional<ProvisionBinding> unresolved(); // TODO(ronshapiro): we should be able to remove this, but AutoValue barks on the Builder's scope // method, saying that the method doesn't correspond to a property of ProvisionBinding @Override public abstract Optional<Scope> scope(); public static Builder builder() { return new AutoValue_ProvisionBinding.Builder() .provisionDependencies(ImmutableSet.of()) .injectionSites(ImmutableSortedSet.of()); } @Override public abstract Builder toBuilder(); private static final ImmutableSet<BindingKind> KINDS_TO_CHECK_FOR_NULL = ImmutableSet.of(PROVISION, COMPONENT_PROVISION); public boolean shouldCheckForNull(CompilerOptions compilerOptions) { return KINDS_TO_CHECK_FOR_NULL.contains(kind()) && !contributedPrimitiveType().isPresent() && !nullableType().isPresent() && compilerOptions.doCheckForNulls(); } // Profiling determined that this method is called enough times that memoizing it had a measurable // performance improvement for large components. @Memoized @Override public boolean requiresModuleInstance() { return super.requiresModuleInstance(); } @Memoized @Override public abstract int hashCode(); // TODO(ronshapiro,dpb): simplify the equality semantics @Override public abstract boolean equals(Object obj); /** A {@code ProvisionBinding} builder. */ @AutoValue.Builder public abstract static class Builder extends ContributionBinding.Builder<ProvisionBinding, Builder> { @Override public Builder dependencies(Iterable<DependencyRequest> dependencies) { return provisionDependencies(dependencies); } abstract Builder provisionDependencies(Iterable<DependencyRequest> provisionDependencies); public abstract Builder injectionSites(ImmutableSortedSet<InjectionSite> injectionSites); @Override public abstract Builder unresolved(ProvisionBinding unresolved); public abstract Builder scope(Optional<Scope> scope); } }
package com.github.tcurrie.rest.factory.it.apis; import java.util.Set; public interface TestApi { void runnable(); void consumer(Pojo m); Pojo producer(); Pojo reverse(Pojo c); Pojo concatenate(Pojo a, Pojo b); Set<Pojo> dedup(Pojo... values); Pojo min(Set<Pojo> values); int add(int a, int b); int sum(int... values); int throwsException() throws Exception; int throwsRuntimeException(); String join(String[] values); String join(String[] values, String separator); }
package com.praylist.socialcomponents.main.SplashAnimation; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import com.google.firebase.auth.FirebaseAuth; import com.praylist.socialcomponents.main.main.MainActivity; import com.praylist.socialcomponents.main.onBoarding.onBoardingActivity; public class SplashActivity extends AppCompatActivity { Handler handler = new Handler(); String myid; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); try{ myid = FirebaseAuth.getInstance().getCurrentUser().getUid(); } catch (Exception e){ myid=null; } handler.postDelayed(new Runnable() { @Override public void run() { if(myid!=null){ Intent intent = new Intent(getApplicationContext(), MainActivity.class); startActivity(intent); finish(); }else{ Intent intent = new Intent(getApplicationContext(), onBoardingActivity.class); startActivity(intent); finish(); } } },1500); } }
package com.sunrise.web.controller.system; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import com.sunrise.common.config.Global; import com.sunrise.common.core.controller.BaseController; import com.sunrise.framework.util.ShiroUtils; import com.sunrise.system.domain.SysMenu; import com.sunrise.system.domain.SysUser; import com.sunrise.system.service.ISysMenuService; /** * 首页 业务处理 * * @author sunrise */ @Controller public class SysIndexController extends BaseController { @Autowired private ISysMenuService menuService; // 系统首页 @GetMapping("/index") public String index(ModelMap mmap) { // 取身份信息 SysUser user = ShiroUtils.getSysUser(); // 根据用户id取出菜单 List<SysMenu> menus = menuService.selectMenusByUser(user); mmap.put("menus", menus); mmap.put("user", user); mmap.put("copyrightYear", Global.getCopyrightYear()); return "index"; } // 系统介绍 @GetMapping("/system/main") public String main(ModelMap mmap) { mmap.put("version", Global.getVersion()); return "main"; } }
package io.aftersound.weave.batch.jobspec.ft.file; import io.aftersound.weave.common.NamedType; import io.aftersound.weave.filehandler.FileHandlingControl; public class SourceFileHandlingControl implements FileHandlingControl { public static final NamedType<FileHandlingControl> TYPE = NamedType.of( "SOURCE_TYPE", SourceFileHandlingControl.class ); @Override public String getType() { return TYPE.name(); } }
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.buck.cli; import com.facebook.buck.artifact_cache.config.ArtifactCacheBuckConfig; import com.facebook.buck.artifact_cache.config.DirCacheEntry; import com.facebook.buck.core.cell.Cell; import com.facebook.buck.core.util.log.Logger; import com.facebook.buck.event.listener.JavaUtilsLoggingBuildListener; import com.facebook.buck.io.filesystem.ProjectFilesystem; import com.facebook.buck.util.ExitCode; import com.google.common.collect.ImmutableList; import java.io.IOException; import java.nio.file.AccessDeniedException; import java.nio.file.Path; import java.util.HashSet; import java.util.Set; import org.kohsuke.args4j.Option; public class CleanCommand extends AbstractCommand { private static final Logger LOG = Logger.get(CleanCommand.class); private static final String KEEP_CACHE_ARG = "--keep-cache"; private static final String DRY_RUN_ARG = "--dry-run"; @Option(name = KEEP_CACHE_ARG, usage = "Keeps the local cache.") private boolean keepCache = false; @Option( name = DRY_RUN_ARG, usage = "Performs a dry-run and prints the paths that would be removed.") private boolean dryRun = false; private void cleanCell(CommandRunnerParams params, Cell cell) { // Ideally, we would like the implementation of this method to be as simple as: // // getProjectFilesystem().deleteRecursivelyIfExists(BuckConstant.BUCK_OUTPUT_DIRECTORY); // // However, we want to avoid blowing away directories that IntelliJ indexes, because that tends // to make it angry. Currently, those directories are: // // Project.ANDROID_GEN_DIR // BuckConstant.ANNOTATION_DIR // // However, Buck itself also uses BuckConstant.ANNOTATION_DIR. We need to fix things so that // IntelliJ does its default thing to generate code from annotations, and manages/indexes those // directories itself so we can blow away BuckConstant.ANNOTATION_DIR as part of `buck clean`. // This will also reduce how long `buck project` takes. // ProjectFilesystem projectFilesystem = cell.getFilesystem(); // On Windows, you have to close all files that will be deleted. // Because buck clean will delete build.log, you must close it first. JavaUtilsLoggingBuildListener.closeLogFile(); Set<Path> pathsToDelete = new HashSet<>(); pathsToDelete.add(projectFilesystem.getBuckPaths().getScratchDir()); pathsToDelete.add(projectFilesystem.getBuckPaths().getGenDir()); pathsToDelete.add(projectFilesystem.getBuckPaths().getTrashDir()); pathsToDelete.add(projectFilesystem.getBuckPaths().getJournalDir()); CleanCommandBuckConfig buckConfig = cell.getBuckConfig().getView(CleanCommandBuckConfig.class); // Remove dir cache. if (!keepCache) { ImmutableList<String> excludedCaches = buckConfig.getCleanExcludedCaches(); pathsToDelete.add(projectFilesystem.getBuckPaths().getCacheDir()); for (DirCacheEntry dirCacheEntry : ArtifactCacheBuckConfig.of(cell.getBuckConfig()).getCacheEntries().getDirCacheEntries()) { if (dirCacheEntry.getName().isPresent() && !excludedCaches.contains(dirCacheEntry.getName().get())) { pathsToDelete.add(dirCacheEntry.getCacheDir()); } } } // Clean out any additional directories specified via config setting. for (String subPath : buckConfig.getCleanAdditionalPaths()) { pathsToDelete.add(projectFilesystem.getPath(subPath)); } if (dryRun) { params .getConsole() .getStdOut() .println("The following directories and files would be removed:"); for (Path path : pathsToDelete) { if (projectFilesystem.exists(path)) { params.getConsole().getStdOut().println(path.toAbsolutePath()); } } } else { // Remove all the paths. for (Path path : pathsToDelete) { try { projectFilesystem.deleteRecursivelyIfExists(path); LOG.debug("Removed path: %s", path); } catch (AccessDeniedException e) { params .getConsole() .printErrorText( "Failed to remove path %s due to AccessDeniedException.%n" + "Make sure that you (not root) own all the contents inside buck-out", path); LOG.warn(e, "Failed to remove path %s due to permissions issue", path); } catch (IOException e) { LOG.warn(e, "Failed to remove path %s", path); } } } } @Override public ExitCode runWithoutHelp(CommandRunnerParams params) { for (Cell cell : params.getCells().getRootCell().getLoadedCells().values()) { cleanCell(params, cell); } return ExitCode.SUCCESS; } @Override public boolean isReadOnly() { return false; } @Override public String getShortDescription() { return "deletes any generated files and caches"; } }
package seedu.address.logic.parser; import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import java.util.Arrays; import seedu.address.logic.commands.FindAddressCommand; import seedu.address.logic.parser.exceptions.ParseException; import seedu.address.model.person.NameContainsKeywordsPredicate; /** * Parses input arguments and creates a new FindCommand object */ public class FindAddressCommandParser implements Parser<FindAddressCommand> { /** * Parses the given {@code String} of arguments in the context of the FindCommand * and returns an FindCommand object for execution. * @throws ParseException if the user input does not conform the expected format */ public FindAddressCommand parse(String args) throws ParseException { String trimmedArgs = args.trim(); if (trimmedArgs.isEmpty()) { throw new ParseException( String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindAddressCommand.MESSAGE_USAGE)); } String[] nameKeywords = trimmedArgs.split("\\s+"); return new FindAddressCommand(new NameContainsKeywordsPredicate<>(Arrays.asList(nameKeywords), "address")); } }
package io.xpire.logic.commands; import static java.util.Objects.requireNonNull; import java.util.Arrays; import java.util.Objects; //@@author JermyTan /** * Represents the result of a command execution. */ public class CommandResult { /** Feedback message to be shown to the user. */ private final String feedbackToUser; /** Help information should be shown to the user. */ private final boolean showHelp; /** The application should exit. */ private final boolean exit; /** QR code of the current list should be shown to the user. */ private final boolean showQr; /** QR code data */ private final byte[] pngData; /** * Constructs a {@code CommandResult} with the specified fields. */ private CommandResult(String feedbackToUser, boolean showHelp, boolean exit, boolean showQr, byte[] pngData) { this.feedbackToUser = requireNonNull(feedbackToUser); this.showHelp = showHelp; this.exit = exit; this.showQr = showQr; this.pngData = pngData; } /** * Constructs a {@code CommandResult} with the specified fields, * and other fields set to their default value. */ public CommandResult(String feedbackToUser, boolean showHelp, boolean exit) { this(feedbackToUser, showHelp, exit, false, new byte[0]); } /** * Constructs a {@code CommandResult} with the specified {@code feedbackToUser}, * and other fields set to their default value. */ public CommandResult(String feedbackToUser) { this(feedbackToUser, false, false, false, new byte[0]); } /** * Constructs a {@code CommandResult} with the specified fields, * and other fields set to their default value. */ public CommandResult(String feedbackToUser, boolean showQr, byte[] pngData) { this(feedbackToUser, false, false, showQr, pngData); } public String getFeedbackToUser() { return this.feedbackToUser; } public boolean isShowHelp() { return this.showHelp; } public boolean isExit() { return this.exit; } public boolean isShowQr() { return this.showQr; } public byte[] getPngData() { return this.pngData; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } else if (!(obj instanceof CommandResult)) { return false; } else { CommandResult other = (CommandResult) obj; return this.feedbackToUser.equals(other.feedbackToUser) && this.showHelp == other.showHelp && this.exit == other.exit && this.showQr == other.showQr && Arrays.equals(this.pngData, other.pngData); } } @Override public int hashCode() { return Objects.hash(this.feedbackToUser, this.showHelp, this.exit, this.showQr, Arrays.hashCode(this.pngData)); } }
package oasis.names.specification.ubl.schema.xsd.commonbasiccomponents_2; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import oasis.names.specification.ubl.schema.xsd.unqualifieddatatypes_2.TextType; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.cxf.xjc.runtime.JAXBToStringStyle; /** * <p>Java class for NegotiationDescriptionType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="NegotiationDescriptionType"&gt; * &lt;simpleContent&gt; * &lt;extension base="&lt;urn:oasis:names:specification:ubl:schema:xsd:UnqualifiedDataTypes-2&gt;TextType"&gt; * &lt;/extension&gt; * &lt;/simpleContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "NegotiationDescriptionType") public class NegotiationDescriptionType extends TextType { /** * Generates a String representation of the contents of this type. * This is an extension method, produced by the 'ts' xjc plugin * */ @Override public String toString() { return ToStringBuilder.reflectionToString(this, JAXBToStringStyle.DEFAULT_STYLE); } }
/* * Copyright 2015 Palantir Technologies, Inc. All rights reserved. * * Licensed under the BSD-3 License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://opensource.org/licenses/BSD-3-Clause * * 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.palantir.atlasdb.table.generation; import com.palantir.atlasdb.table.api.ColumnValue; public interface NamedColumnValue<T> extends ColumnValue<T> { String getColumnName(); String getShortColumnName(); @Override T getValue(); }
package eu.frenchxcore.api; import com.google.common.util.concurrent.ListenableFuture; import com.google.protobuf.Any; import com.google.protobuf.ByteString; import com.google.protobuf.Timestamp; import cosmos.base.query.v1beta1.Pagination; import cosmos.gov.v1beta2.Gov; import cosmos.staking.v1beta1.Staking; import cosmos.vesting.v1beta1.Vesting; import eu.frenchxcore.tools.LocalExecutor; import eu.frenchxcore.tools.XLogger; import fx.gravity.v1.Types; import ibc.core.client.v1.Client; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.grpc.Metadata; import io.grpc.stub.MetadataUtils; import org.jetbrains.annotations.NotNull; import tendermint.abci.ABCIApplicationGrpc; import tendermint.types.Types.Header; import javax.validation.constraints.NotBlank; import java.math.BigInteger; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; public class TendermintGrpcApi { private final ManagedChannel tendermintChannel; private final ABCIApplicationGrpc.ABCIApplicationFutureStub abciStub; private final static Map<String, TendermintGrpcApi> instances = new HashMap<>(); public static TendermintGrpcApi getInstance(String ip, int tendermintPort) { return getInstance(ip, tendermintPort, null); } public static TendermintGrpcApi getInstance(String ip, int tendermintPort, Executor executor) { XLogger.getMainLogger().trace("Creating new TendermintGrpcApi instance on " + ip + ":" + tendermintPort); TendermintGrpcApi ret = null; try { InetAddress ia = InetAddress.getByName(ip); String key = ia.getHostAddress() + ":" + tendermintPort + ":" + tendermintPort; if ((ret = (instances.get(key))) == null) { ret = new TendermintGrpcApi(ip, tendermintPort, executor); instances.put(key, ret); } } catch (UnknownHostException ex) { XLogger.getMainLogger().error(ex.getMessage()); } return ret; } /** * https://docs.cosmos.network/master/core/grpc_rest.html * https://functionx.gitbook.io/home/developers/json-rcp-abci-query * @param ip * @param tendermintPort * @param _executor */ private TendermintGrpcApi(String ip, int tendermintPort, Executor _executor) { Executor executor = (_executor == null ? LocalExecutor.getInstance().get() : _executor); this.tendermintChannel = ManagedChannelBuilder .forAddress(ip, tendermintPort) .executor(executor) .enableRetry() .maxRetryAttempts(10) .keepAliveWithoutCalls(true) .usePlaintext() .build(); abciStub = ABCIApplicationGrpc.newFutureStub(tendermintChannel).withExecutor(executor); } public void close() { if (this.tendermintChannel != null) { try { this.tendermintChannel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); } catch (InterruptedException ex) { XLogger.getMainLogger().error(ex); } } } /******************************************************** ***** TENDERMINT Module 'abci' *******************************************************/ /** * Echo a string to test an abci client/server implementation * * @param message A string to echo back */ public ListenableFuture<tendermint.abci.Types.ResponseEcho> abciEcho(String message) { return abciStub.echo(tendermint.abci.Types.RequestEcho.newBuilder().setMessage(message).build()); } /** * Signals that messages queued on the client should be flushed to the server. * It is called periodically by the client implementation to ensure asynchronous requests are actually sent, * and is called immediately to make a synchronous request, which returns when the Flush response comes back. */ public ListenableFuture<tendermint.abci.Types.ResponseFlush> abciFlush() { return abciStub.flush(tendermint.abci.Types.RequestFlush.newBuilder().build()); } /** * Return information about the application state. * Used to sync Tendermint with the application during a handshake that happens on startup. * The returned app_version will be included in the Header of every block. * Tendermint expects last_block_app_hash and last_block_height to be updated during Commit, ensuring that Commit is never called twice for the same block height. * Note: Semantic version is a reference to semantic versioning (opens new window). Semantic versions in info will be displayed as X.X.x. * * @param version The Tendermint software semantic version * @param blockVersion The Tendermint Block Protocol version * @param p2pVersion The Tendermint P2P Protocol version */ public ListenableFuture<tendermint.abci.Types.ResponseInfo> abciInfo(String version, long blockVersion, long p2pVersion) { return abciStub.info(tendermint.abci.Types.RequestInfo.newBuilder().setVersion(version).setBlockVersion(blockVersion).setP2PVersion(p2pVersion).build()); } /** * Called once upon genesis. * If ResponseInitChain.Validators is empty, the initial validator set will be the RequestInitChain.Validators * If ResponseInitChain.Validators is not empty, it will be the initial validator set (regardless of what is in RequestInitChain.Validators). * This allows the app to decide if it wants to accept the initial validator set proposed by tendermint (i.e. in the genesis file), or if it * wants to use a different one (perhaps computed based on some application specific information in the genesis file). * Both ResponseInitChain.Validators and ResponseInitChain.Validators are ValidatorUpdate structs. So, technically, they both are updating * the set of validators from the empty set. * * @param time Genesis time * @param chainId ID of the blockchain. * @param consensusParams Initial consensus-critical parameters. * @param validators Initial genesis validators, sorted by voting power. * @param appStateBytes Serialized initial application state. JSON bytes. * @param initialHeight Height of the initial block (typically 1). */ public ListenableFuture<tendermint.abci.Types.ResponseInitChain> abciInitChain(Timestamp time, String chainId, tendermint.abci.Types.ConsensusParams consensusParams, Iterable<tendermint.abci.Types.ValidatorUpdate> validators, ByteString appStateBytes, long initialHeight) { return abciStub.initChain(tendermint.abci.Types.RequestInitChain.newBuilder() .setTime(time) .setChainId(chainId) .setConsensusParams(consensusParams) .addAllValidators(validators) .setAppStateBytes(appStateBytes) .setInitialHeight(initialHeight) .build()); } /** * Query for data from the application at current or past height. * Optionally return Merkle proof. * Merkle proof includes self-describing type field to support many types of Merkle trees and encoding formats. * * @param path Path field of the request URI. Can be used with or in lieu of data. Apps MUST interpret /store as a query by key on the underlying store. * The key SHOULD be specified in the data field. Apps SHOULD allow queries over specific types like /accounts/... or /votes/... * @param data Raw query bytes. Can be used with or in lieu of Path. * @param prove Return Merkle proof with response if possible * @param height The block height for which you want the query (default=0 returns data for the latest committed block). * Note that this is the height of the block containing the application's Merkle root hash, which represents the state as * it was after committing the block at Height-1 */ public ListenableFuture<tendermint.abci.Types.ResponseQuery> abciQuery(String path, ByteString data, Boolean prove, Long height) { tendermint.abci.Types.RequestQuery.Builder rq = tendermint.abci.Types.RequestQuery.newBuilder(); if (path != null) { rq.setPath(path); } if (data != null && !data.isEmpty()) { rq.setData(data); } rq.setHeight(height != null ? height : 0L); rq.setProve(prove != null ? prove : true); return abciStub.query(rq.build()); } /** * Technically optional - not involved in processing blocks. * Guardian of the mempool: every node runs CheckTx before letting a transaction into its local mempool. * The transaction may come from an external user or another node * CheckTx validates the transaction against the current state of the application, for example, checking signatures and account balances, but does not apply any of the state changes described in the transaction. not running code in a virtual machine. * Transactions where ResponseCheckTx.Code != 0 will be rejected - they will not be broadcast to other nodes or included in a proposal block. * Tendermint attributes no other value to the response code * * @param tx The request transaction bytes * @param type One of CheckTx_New or CheckTx_Recheck. * CheckTx_New is the default and means that a full check of the transaction is required. * CheckTx_Recheck types are used when the mempool is initiating a normal recheck of a transaction. */ public ListenableFuture<tendermint.abci.Types.ResponseCheckTx> abciCheckTx(ByteString tx, tendermint.abci.Types.CheckTxType type) { tendermint.abci.Types.RequestCheckTx.Builder rq = tendermint.abci.Types.RequestCheckTx.newBuilder(); if (tx != null && !tx.isEmpty()) { rq.setTx(tx); } rq.setType(type); return abciStub.checkTx(rq.build()); } /** * Empty request asking the application for a list of snapshots. * Used during state sync to discover available snapshots on peers. * See Snapshot data type for details. */ public ListenableFuture<tendermint.abci.Types.ResponseListSnapshots> abciListSnapshots() { return abciStub.listSnapshots(tendermint.abci.Types.RequestListSnapshots.newBuilder().build()); } /** * Used during state sync to retrieve snapshot chunks from peers. * * @param height The height of the snapshot the chunk belongs to. * @param format The application-specific format of the snapshot the chunk belongs to. * @param chunk The chunk index, starting from 0 for the initial chunk. */ public ListenableFuture<tendermint.abci.Types.ResponseLoadSnapshotChunk> abciLoadSnapshotChunk(Long height, Integer format, Integer chunk) { return abciStub.loadSnapshotChunk( tendermint.abci.Types.RequestLoadSnapshotChunk.newBuilder() .setHeight(height) .setFormat(format) .setChunk(chunk) .build()); } /** * OfferSnapshot is called when bootstrapping a node using state sync. The application may accept or reject snapshots as appropriate. * Upon accepting, Tendermint will retrieve and apply snapshot chunks via ApplySnapshotChunk. The application may also choose to reject * a snapshot in the chunk response, in which case it should be prepared to accept further OfferSnapshot calls. * Only AppHash can be trusted, as it has been verified by the light client. Any other data can be spoofed by adversaries, so applications * should employ additional verification schemes to avoid denial-of-service attacks. The verified AppHash is automatically checked against * the restored application at the end of snapshot restoration. * For more information, see the Snapshot data type or the state sync section. * * @param snapshot The snapshot offered for restoration. * @param appHash The light client-verified app hash for this height, from the blockchain. */ public ListenableFuture<tendermint.abci.Types.ResponseOfferSnapshot> abciOfferSnapshot(tendermint.abci.Types.Snapshot snapshot, ByteString appHash) { return abciStub.offerSnapshot( tendermint.abci.Types.RequestOfferSnapshot.newBuilder() .setSnapshot(snapshot) .setAppHash(appHash) .build()); } /** * The application can choose to refetch chunks and/or ban P2P peers as appropriate. Tendermint will not do this unless instructed by the application. * The application may want to verify each chunk, e.g. by attaching chunk hashes in Snapshot.Metadata and/or incrementally verifying contents against AppHash. * When all chunks have been accepted, Tendermint will make an ABCI Info call to verify that LastBlockAppHash and LastBlockHeight matches the expected values, * and record the AppVersion in the node state. It then switches to fast sync or consensus and joins the network. * If Tendermint is unable to retrieve the next chunk after some time (e.g. because no suitable peers are available), it will reject the snapshot and try * a different one via OfferSnapshot. The application should be prepared to reset and accept it or abort as appropriate. * * @param index The chunk index, starting from 0. Tendermint applies chunks sequentially. * @param chunk The binary chunk contents, as returned by LoadSnapshotChunk. * @param sender The P2P ID of the node who sent this chunk. */ public ListenableFuture<tendermint.abci.Types.ResponseApplySnapshotChunk> abciApplySnapshotChunk(Integer index, ByteString chunk, String sender) { return abciStub.applySnapshotChunk( tendermint.abci.Types.RequestApplySnapshotChunk.newBuilder() .setIndex(index) .setChunk(chunk) .setSender(sender) .build()); } /** * Signals the beginning of a new block. * Called prior to any DeliverTx method calls. * The header contains the height, timestamp, and more - it exactly matches the Tendermint block header. We may seek to generalize this in the future. * The LastCommitInfo and ByzantineValidators can be used to determine rewards and punishments for the validators. * * @param hash The block's hash. This can be derived from the block header. * @param header The block header. * @param lastCommitInfo Info about the last commit, including the round, and the list of validators and which ones signed the last block. * @param byzantineValidators List of evidence of validators that acted maliciously. */ public ListenableFuture<tendermint.abci.Types.ResponseBeginBlock> abciBeginBlock(ByteString hash, Header header, tendermint.abci.Types.LastCommitInfo lastCommitInfo, Collection<tendermint.abci.Types.Evidence> byzantineValidators) { return abciStub.beginBlock( tendermint.abci.Types.RequestBeginBlock.newBuilder() .setHash(hash) .setHeader(header) .setLastCommitInfo(lastCommitInfo) .addAllByzantineValidators(byzantineValidators) .build()); } /** * The core method of the application. * When DeliverTx is called, the application must execute the transaction in full before returning control to Tendermint. * ResponseDeliverTx.Code == 0 only if the transaction is fully valid. * * @param tx The request transaction bytes. */ public ListenableFuture<tendermint.abci.Types.ResponseDeliverTx> abciDeliverTx(ByteString tx) { return abciStub.deliverTx( tendermint.abci.Types.RequestDeliverTx.newBuilder() .setTx(tx) .build()); } /** * Signals the end of a block. * Called after all the transactions for the current block have been delivered, prior to the block's Commit message. * Optional validator_updates triggered by block H. These updates affect validation for blocks H+1, H+2, and H+3. * Heights following a validator update are affected in the following way: * H+1: NextValidatorsHash includes the new validator_updates value. * H+2: The validator set change takes effect and ValidatorsHash is updated. * H+3: LastCommitInfo is changed to include the altered validator set. * consensus_param_updates returned for block H apply to the consensus params for block H+1. For more information on the consensus parameters, see the application spec entry on consensus parameters. * * @param height Height of the block just executed. */ public ListenableFuture<tendermint.abci.Types.ResponseEndBlock> abciEndBlock(long height) { return abciStub.endBlock( tendermint.abci.Types.RequestEndBlock.newBuilder() .setHeight(height) .build()); } /** * Commit signals the application to persist application state. It takes no parameters. * Signal the application to persist the application state. * Return an (optional) Merkle root hash of the application state * ResponseCommit.Data is included as the Header.AppHash in the next block * it may be empty * Later calls to Query can return proofs about the application state anchored in this Merkle root hash * Note developers can return whatever they want here (could be nothing, or a constant string, etc.), so long as it is deterministic - it must not be a function of anything that did not come from the BeginBlock/DeliverTx/EndBlock methods. * Use RetainHeight with caution! If all nodes in the network remove historical blocks then this data is permanently lost, and no new nodes will be able to join the network and bootstrap. Historical blocks may also be required for other purposes, e.g. auditing, replay of non-persisted heights, light client verification, and so on. */ public ListenableFuture<tendermint.abci.Types.ResponseCommit> abciCommit() { return abciStub.commit(tendermint.abci.Types.RequestCommit.newBuilder().build()); } }
package org.jeecgframework.web.system.service.impl; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.jeecgframework.core.common.dao.ICommonDao; import org.jeecgframework.core.util.BrowserUtils; import org.jeecgframework.core.util.ContextHolderUtils; import org.jeecgframework.core.util.ResourceUtil; import org.jeecgframework.core.util.StringUtil; import org.jeecgframework.core.util.oConvertUtils; import org.jeecgframework.web.system.pojo.base.MutiLangEntity; import org.jeecgframework.web.system.service.MutiLangServiceI; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service("mutiLangService") public class MutiLangServiceImpl implements MutiLangServiceI { @Autowired public ICommonDao commonDao; /**初始化语言信息,TOMCAT启动时直接加入到内存中**/ @Transactional(readOnly = true) public void initAllMutiLang() { List<MutiLangEntity> mutiLang = this.commonDao.loadAll(MutiLangEntity.class); for (MutiLangEntity mutiLangEntity : mutiLang) { ResourceUtil.mutiLangMap.put(mutiLangEntity.getLangKey() + "_" + mutiLangEntity.getLangCode(), mutiLangEntity.getLangContext()); } } /** * 更新缓存,插入缓存 */ public void putMutiLang(String langKey,String langCode,String langContext) { ResourceUtil.mutiLangMap.put(langKey + "_" + langCode, langContext); } /** * 更新缓存,插入缓存 */ public void putMutiLang(MutiLangEntity mutiLangEntity) { ResourceUtil.mutiLangMap.put(mutiLangEntity.getLangKey() + "_" + mutiLangEntity.getLangCode(), mutiLangEntity.getLangContext()); } /**取 o_muti_lang.lang_key 的值返回当前语言的值**/ public String getLang(String langKey) { //如果为空,返回空串,防止返回null if(langKey==null){ return ""; } HttpServletRequest request = ContextHolderUtils.getRequest(); String language = oConvertUtils.getString(request.getSession().getAttribute("lang")); if(oConvertUtils.isEmpty(language)){ language = BrowserUtils.getBrowserLanguage(request); } String langContext = ResourceUtil.mutiLangMap.get(langKey + "_" + language); if(StringUtil.isEmpty(langContext)) { langContext = ResourceUtil.mutiLangMap.get("common.notfind.langkey" + "_" + language); if("null".equals(langContext)||langContext==null ||langKey.startsWith("?")){ langContext = ""; } langContext = langContext + langKey; } return langContext; } public String getLang(String lanKey, String langArg) { String langContext = ""; if(StringUtil.isEmpty(langArg)) { langContext = getLang(lanKey); } else { String[] argArray = langArg.split(","); langContext = getLang(lanKey); for(int i=0; i< argArray.length; i++) { String langKeyArg = argArray[i].trim(); String langKeyContext = getLang(langKeyArg); langContext = StringUtil.replace(langContext, "{" + i + "}", langKeyContext); } } return langContext; } /** 刷新多语言cach **/ public void refleshMutiLangCach() { ResourceUtil.mutiLangMap.clear(); initAllMutiLang(); } }
package com.gtc.opportunity.trader.service.xoopportunity.replenishment.precision.optaplan; import lombok.Data; import java.math.BigDecimal; /** * Created by Valentyn Berezin on 26.03.18. */ @Data public class XoReplenishPrice { private final BigDecimal lossFrom; private final BigDecimal lossTo; private final BigDecimal targetBuyPrice; private final BigDecimal targetSellPrice; }
import java.text.DateFormat; import java.util.Date; import java.util.logging.Level; @aa( a = {ac.class} ) public class a4 implements ac { private static boolean a; private static y<ad> b; private static final String[] c; public static void main(String[] var0) throws Exception { t.a.setLevel(Level.FINE); t.a(); a = true; while(true) { Thread.sleep(10000L); System.out.println(c[1] + ((ad)b.a()).a()); } } public void a() throws Exception { try { if (a) { System.out.println(c[0] + DateFormat.getTimeInstance().format(new Date())); } } catch (Exception var1) { throw var1; } } static { String[] var10000; int var1; int var2; char[] var10003; char[] var10004; char[] var4; int var10005; int var10006; char var10007; byte var10008; label51: { var10000 = new String[2]; var10003 = "f\u0019\u0016n-[\u001c\u0016n0AKS".toCharArray(); var10005 = var10003.length; var1 = 0; var10004 = var10003; var2 = var10005; if (var10005 <= 1) { var4 = var10003; var10006 = var1; } else { var10004 = var10003; var2 = var10005; if (var10005 <= var1) { break label51; } var4 = var10003; var10006 = var1; } while(true) { var10007 = var4[var10006]; switch (var1 % 5) { case 0: var10008 = 50; break; case 1: var10008 = 113; break; case 2: var10008 = 115; break; case 3: var10008 = 78; break; default: var10008 = 89; } var4[var10006] = (char)(var10007 ^ var10008); ++var1; if (var2 == 0) { var10006 = var2; var4 = var10004; } else { if (var2 <= var1) { break; } var4 = var10004; var10006 = var1; } } } var10000[0] = (new String(var10004)).intern(); var10003 = "~\u0010\u0000:y[\u001f\u0005!:S\u0005\u001a!7\bQ".toCharArray(); var10005 = var10003.length; var1 = 0; var10004 = var10003; var2 = var10005; if (var10005 <= 1) { var4 = var10003; var10006 = var1; } else { var10004 = var10003; var2 = var10005; if (var10005 <= var1) { var10000[1] = (new String(var10003)).intern(); c = var10000; a = false; b = y.a(ad.class); return; } var4 = var10003; var10006 = var1; } while(true) { var10007 = var4[var10006]; switch (var1 % 5) { case 0: var10008 = 50; break; case 1: var10008 = 113; break; case 2: var10008 = 115; break; case 3: var10008 = 78; break; default: var10008 = 89; } var4[var10006] = (char)(var10007 ^ var10008); ++var1; if (var2 == 0) { var10006 = var2; var4 = var10004; } else { if (var2 <= var1) { var10000[1] = (new String(var10004)).intern(); c = var10000; a = false; b = y.a(ad.class); return; } var4 = var10004; var10006 = var1; } } } }
package redis.clients.jedis.commands.unified; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static redis.clients.jedis.util.AssertUtil.assertByteArrayListEquals; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import redis.clients.jedis.args.ListPosition; import redis.clients.jedis.args.ListDirection; import redis.clients.jedis.exceptions.JedisDataException; import redis.clients.jedis.params.LPosParams; import redis.clients.jedis.resps.KeyedListElement; public abstract class ListCommandsTestBase extends UnifiedJedisCommandsTestBase { private final Logger logger = LoggerFactory.getLogger(getClass()); protected final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; protected final byte[] bfoo1 = { 0x01, 0x02, 0x03, 0x04, 0x05 }; protected final byte[] bbar = { 0x05, 0x06, 0x07, 0x08 }; protected final byte[] bcar = { 0x09, 0x0A, 0x0B, 0x0C }; protected final byte[] bA = { 0x0A }; protected final byte[] bB = { 0x0B }; protected final byte[] bC = { 0x0C }; protected final byte[] b1 = { 0x01 }; protected final byte[] b2 = { 0x02 }; protected final byte[] b3 = { 0x03 }; protected final byte[] bhello = { 0x04, 0x02 }; protected final byte[] bx = { 0x02, 0x04 }; protected final byte[] bdst = { 0x11, 0x12, 0x13, 0x14 }; @Test public void rpush() { assertEquals(1, jedis.rpush("foo", "bar")); assertEquals(2, jedis.rpush("foo", "foo")); assertEquals(4, jedis.rpush("foo", "bar", "foo")); // Binary assertEquals(1, jedis.rpush(bfoo, bbar)); assertEquals(2, jedis.rpush(bfoo, bfoo)); assertEquals(4, jedis.rpush(bfoo, bbar, bfoo)); } @Test public void lpush() { assertEquals(1, jedis.lpush("foo", "bar")); assertEquals(2, jedis.lpush("foo", "foo")); assertEquals(4, jedis.lpush("foo", "bar", "foo")); // Binary assertEquals(1, jedis.lpush(bfoo, bbar)); assertEquals(2, jedis.lpush(bfoo, bfoo)); assertEquals(4, jedis.lpush(bfoo, bbar, bfoo)); } @Test public void llen() { assertEquals(0, jedis.llen("foo")); jedis.lpush("foo", "bar"); jedis.lpush("foo", "car"); assertEquals(2, jedis.llen("foo")); // Binary assertEquals(0, jedis.llen(bfoo)); jedis.lpush(bfoo, bbar); jedis.lpush(bfoo, bcar); assertEquals(2, jedis.llen(bfoo)); } @Test public void llenNotOnList() { try { jedis.set("foo", "bar"); jedis.llen("foo"); fail("JedisDataException expected"); } catch (final JedisDataException e) { } // Binary try { jedis.set(bfoo, bbar); jedis.llen(bfoo); fail("JedisDataException expected"); } catch (final JedisDataException e) { } } @Test public void lrange() { jedis.rpush("foo", "a"); jedis.rpush("foo", "b"); jedis.rpush("foo", "c"); List<String> expected = new ArrayList<String>(); expected.add("a"); expected.add("b"); expected.add("c"); List<String> range = jedis.lrange("foo", 0, 2); assertEquals(expected, range); range = jedis.lrange("foo", 0, 20); assertEquals(expected, range); expected = new ArrayList<String>(); expected.add("b"); expected.add("c"); range = jedis.lrange("foo", 1, 2); assertEquals(expected, range); range = jedis.lrange("foo", 2, 1); assertEquals(Collections.<String> emptyList(), range); // Binary jedis.rpush(bfoo, bA); jedis.rpush(bfoo, bB); jedis.rpush(bfoo, bC); List<byte[]> bexpected = new ArrayList<byte[]>(); bexpected.add(bA); bexpected.add(bB); bexpected.add(bC); List<byte[]> brange = jedis.lrange(bfoo, 0, 2); assertByteArrayListEquals(bexpected, brange); brange = jedis.lrange(bfoo, 0, 20); assertByteArrayListEquals(bexpected, brange); bexpected = new ArrayList<byte[]>(); bexpected.add(bB); bexpected.add(bC); brange = jedis.lrange(bfoo, 1, 2); assertByteArrayListEquals(bexpected, brange); brange = jedis.lrange(bfoo, 2, 1); assertByteArrayListEquals(Collections.<byte[]> emptyList(), brange); } @Test public void ltrim() { jedis.lpush("foo", "1"); jedis.lpush("foo", "2"); jedis.lpush("foo", "3"); String status = jedis.ltrim("foo", 0, 1); List<String> expected = new ArrayList<String>(); expected.add("3"); expected.add("2"); assertEquals("OK", status); assertEquals(2, jedis.llen("foo")); assertEquals(expected, jedis.lrange("foo", 0, 100)); // Binary jedis.lpush(bfoo, b1); jedis.lpush(bfoo, b2); jedis.lpush(bfoo, b3); String bstatus = jedis.ltrim(bfoo, 0, 1); List<byte[]> bexpected = new ArrayList<byte[]>(); bexpected.add(b3); bexpected.add(b2); assertEquals("OK", bstatus); assertEquals(2, jedis.llen(bfoo)); assertByteArrayListEquals(bexpected, jedis.lrange(bfoo, 0, 100)); } @Test public void lset() { jedis.lpush("foo", "1"); jedis.lpush("foo", "2"); jedis.lpush("foo", "3"); List<String> expected = new ArrayList<String>(); expected.add("3"); expected.add("bar"); expected.add("1"); String status = jedis.lset("foo", 1, "bar"); assertEquals("OK", status); assertEquals(expected, jedis.lrange("foo", 0, 100)); // Binary jedis.lpush(bfoo, b1); jedis.lpush(bfoo, b2); jedis.lpush(bfoo, b3); List<byte[]> bexpected = new ArrayList<byte[]>(); bexpected.add(b3); bexpected.add(bbar); bexpected.add(b1); String bstatus = jedis.lset(bfoo, 1, bbar); assertEquals("OK", bstatus); assertByteArrayListEquals(bexpected, jedis.lrange(bfoo, 0, 100)); } @Test public void lindex() { jedis.lpush("foo", "1"); jedis.lpush("foo", "2"); jedis.lpush("foo", "3"); assertEquals("3", jedis.lindex("foo", 0)); assertNull(jedis.lindex("foo", 100)); // Binary jedis.lpush(bfoo, b1); jedis.lpush(bfoo, b2); jedis.lpush(bfoo, b3); assertArrayEquals(b3, jedis.lindex(bfoo, 0)); assertNull(jedis.lindex(bfoo, 100)); } @Test public void lrem() { jedis.lpush("foo", "hello"); jedis.lpush("foo", "hello"); jedis.lpush("foo", "x"); jedis.lpush("foo", "hello"); jedis.lpush("foo", "c"); jedis.lpush("foo", "b"); jedis.lpush("foo", "a"); List<String> expected = new ArrayList<String>(); expected.add("a"); expected.add("b"); expected.add("c"); expected.add("hello"); expected.add("x"); assertEquals(2, jedis.lrem("foo", -2, "hello")); assertEquals(expected, jedis.lrange("foo", 0, 1000)); assertEquals(0, jedis.lrem("bar", 100, "foo")); // Binary jedis.lpush(bfoo, bhello); jedis.lpush(bfoo, bhello); jedis.lpush(bfoo, bx); jedis.lpush(bfoo, bhello); jedis.lpush(bfoo, bC); jedis.lpush(bfoo, bB); jedis.lpush(bfoo, bA); List<byte[]> bexpected = new ArrayList<byte[]>(); bexpected.add(bA); bexpected.add(bB); bexpected.add(bC); bexpected.add(bhello); bexpected.add(bx); assertEquals(2, jedis.lrem(bfoo, -2, bhello)); assertByteArrayListEquals(bexpected, jedis.lrange(bfoo, 0, 1000)); assertEquals(0, jedis.lrem(bbar, 100, bfoo)); } @Test public void lpop() { assertNull(jedis.lpop("foo")); assertNull(jedis.lpop("foo", 0)); jedis.rpush("foo", "a"); jedis.rpush("foo", "b"); jedis.rpush("foo", "c"); assertEquals("a", jedis.lpop("foo")); assertEquals(Arrays.asList("b", "c"), jedis.lpop("foo", 10)); assertNull(jedis.lpop("foo")); assertNull(jedis.lpop("foo", 1)); // Binary assertNull(jedis.lpop(bfoo)); assertNull(jedis.lpop(bfoo, 0)); jedis.rpush(bfoo, bA); jedis.rpush(bfoo, bB); jedis.rpush(bfoo, bC); assertArrayEquals(bA, jedis.lpop(bfoo)); assertByteArrayListEquals(Arrays.asList(bB, bC), jedis.lpop(bfoo, 10)); assertNull(jedis.lpop(bfoo)); assertNull(jedis.lpop(bfoo, 1)); } @Test public void rpop() { assertNull(jedis.rpop("foo")); assertNull(jedis.rpop("foo", 0)); jedis.rpush("foo", "a"); jedis.rpush("foo", "b"); jedis.rpush("foo", "c"); assertEquals("c", jedis.rpop("foo")); assertEquals(Arrays.asList("b", "a"), jedis.rpop("foo", 10)); assertNull(jedis.rpop("foo")); assertNull(jedis.rpop("foo", 1)); // Binary assertNull(jedis.rpop(bfoo)); assertNull(jedis.rpop(bfoo, 0)); jedis.rpush(bfoo, bA); jedis.rpush(bfoo, bB); jedis.rpush(bfoo, bC); assertArrayEquals(bC, jedis.rpop(bfoo)); assertByteArrayListEquals(Arrays.asList(bB, bA), jedis.rpop(bfoo, 10)); assertNull(jedis.rpop(bfoo)); assertNull(jedis.rpop(bfoo, 1)); } @Test public void rpoplpush() { jedis.rpush("foo", "a"); jedis.rpush("foo", "b"); jedis.rpush("foo", "c"); jedis.rpush("dst", "foo"); jedis.rpush("dst", "bar"); String element = jedis.rpoplpush("foo", "dst"); assertEquals("c", element); List<String> srcExpected = new ArrayList<String>(); srcExpected.add("a"); srcExpected.add("b"); List<String> dstExpected = new ArrayList<String>(); dstExpected.add("c"); dstExpected.add("foo"); dstExpected.add("bar"); assertEquals(srcExpected, jedis.lrange("foo", 0, 1000)); assertEquals(dstExpected, jedis.lrange("dst", 0, 1000)); // Binary jedis.rpush(bfoo, bA); jedis.rpush(bfoo, bB); jedis.rpush(bfoo, bC); jedis.rpush(bdst, bfoo); jedis.rpush(bdst, bbar); byte[] belement = jedis.rpoplpush(bfoo, bdst); assertArrayEquals(bC, belement); List<byte[]> bsrcExpected = new ArrayList<byte[]>(); bsrcExpected.add(bA); bsrcExpected.add(bB); List<byte[]> bdstExpected = new ArrayList<byte[]>(); bdstExpected.add(bC); bdstExpected.add(bfoo); bdstExpected.add(bbar); assertByteArrayListEquals(bsrcExpected, jedis.lrange(bfoo, 0, 1000)); assertByteArrayListEquals(bdstExpected, jedis.lrange(bdst, 0, 1000)); } @Test public void blpop() throws InterruptedException { List<String> result = jedis.blpop(1, "foo"); assertNull(result); jedis.lpush("foo", "bar"); result = jedis.blpop(1, "foo"); assertNotNull(result); assertEquals(2, result.size()); assertEquals("foo", result.get(0)); assertEquals("bar", result.get(1)); // Multi keys result = jedis.blpop(1, "foo", "foo1"); assertNull(result); jedis.lpush("foo", "bar"); jedis.lpush("foo1", "bar1"); result = jedis.blpop(1, "foo1", "foo"); assertNotNull(result); assertEquals(2, result.size()); assertEquals("foo1", result.get(0)); assertEquals("bar1", result.get(1)); // Binary jedis.lpush(bfoo, bbar); List<byte[]> bresult = jedis.blpop(1, bfoo); assertNotNull(bresult); assertEquals(2, bresult.size()); assertArrayEquals(bfoo, bresult.get(0)); assertArrayEquals(bbar, bresult.get(1)); // Binary Multi keys bresult = jedis.blpop(1, bfoo, bfoo1); assertNull(bresult); jedis.lpush(bfoo, bbar); jedis.lpush(bfoo1, bcar); bresult = jedis.blpop(1, bfoo, bfoo1); assertNotNull(bresult); assertEquals(2, bresult.size()); assertArrayEquals(bfoo, bresult.get(0)); assertArrayEquals(bbar, bresult.get(1)); } @Test public void blpopDouble() throws InterruptedException { KeyedListElement result = jedis.blpop(0.1, "foo"); assertNull(result); jedis.lpush("foo", "bar"); result = jedis.blpop(3.2, "foo"); assertNotNull(result); assertEquals("foo", result.getKey()); assertEquals("bar", result.getElement()); // Multi keys result = jedis.blpop(0.18, "foo", "foo1"); assertNull(result); jedis.lpush("foo", "bar"); jedis.lpush("foo1", "bar1"); result = jedis.blpop(1d, "foo1", "foo"); assertNotNull(result); assertEquals("foo1", result.getKey()); assertEquals("bar1", result.getElement()); // Binary jedis.lpush(bfoo, bbar); List<byte[]> bresult = jedis.blpop(3.12, bfoo); assertNotNull(bresult); assertEquals(2, bresult.size()); assertArrayEquals(bfoo, bresult.get(0)); assertArrayEquals(bbar, bresult.get(1)); // Binary Multi keys bresult = jedis.blpop(0.11, bfoo, bfoo1); assertNull(bresult); jedis.lpush(bfoo, bbar); jedis.lpush(bfoo1, bcar); bresult = jedis.blpop(1d, bfoo, bfoo1); assertNotNull(bresult); assertEquals(2, bresult.size()); assertArrayEquals(bfoo, bresult.get(0)); assertArrayEquals(bbar, bresult.get(1)); } @Test public void blpopDoubleWithSleep() { long startMillis, totalMillis; startMillis = System.currentTimeMillis(); KeyedListElement result = jedis.blpop(0.04, "foo"); totalMillis = System.currentTimeMillis() - startMillis; assertTrue("TotalMillis=" + totalMillis, totalMillis < 200); assertNull(result); startMillis = System.currentTimeMillis(); new Thread(() -> { try { Thread.sleep(30); } catch(InterruptedException e) { logger.error("", e); } jedis.lpush("foo", "bar"); }).start(); result = jedis.blpop(1.2, "foo"); totalMillis = System.currentTimeMillis() - startMillis; assertTrue("TotalMillis=" + totalMillis, totalMillis < 200); assertNotNull(result); assertEquals("foo", result.getKey()); assertEquals("bar", result.getElement()); } @Test public void brpop() throws InterruptedException { List<String> result = jedis.brpop(1, "foo"); assertNull(result); jedis.lpush("foo", "bar"); result = jedis.brpop(1, "foo"); assertNotNull(result); assertEquals(2, result.size()); assertEquals("foo", result.get(0)); assertEquals("bar", result.get(1)); // Multi keys result = jedis.brpop(1, "foo", "foo1"); assertNull(result); jedis.lpush("foo", "bar"); jedis.lpush("foo1", "bar1"); result = jedis.brpop(1, "foo1", "foo"); assertNotNull(result); assertEquals(2, result.size()); assertEquals("foo1", result.get(0)); assertEquals("bar1", result.get(1)); // Binary jedis.lpush(bfoo, bbar); List<byte[]> bresult = jedis.brpop(1, bfoo); assertNotNull(bresult); assertEquals(2, bresult.size()); assertArrayEquals(bfoo, bresult.get(0)); assertArrayEquals(bbar, bresult.get(1)); // Binary Multi keys bresult = jedis.brpop(1, bfoo, bfoo1); assertNull(bresult); jedis.lpush(bfoo, bbar); jedis.lpush(bfoo1, bcar); bresult = jedis.brpop(1, bfoo, bfoo1); assertNotNull(bresult); assertEquals(2, bresult.size()); assertArrayEquals(bfoo, bresult.get(0)); assertArrayEquals(bbar, bresult.get(1)); } @Test public void brpopDouble() throws InterruptedException { KeyedListElement result = jedis.brpop(0.1, "foo"); assertNull(result); jedis.lpush("foo", "bar"); result = jedis.brpop(3.2, "foo"); assertNotNull(result); assertEquals("foo", result.getKey()); assertEquals("bar", result.getElement()); // Multi keys result = jedis.brpop(0.18, "foo", "foo1"); assertNull(result); jedis.lpush("foo", "bar"); jedis.lpush("foo1", "bar1"); result = jedis.brpop(1d, "foo1", "foo"); assertNotNull(result); assertEquals("foo1", result.getKey()); assertEquals("bar1", result.getElement()); // Binary jedis.lpush(bfoo, bbar); List<byte[]> bresult = jedis.brpop(3.12, bfoo); assertNotNull(bresult); assertEquals(2, bresult.size()); assertArrayEquals(bfoo, bresult.get(0)); assertArrayEquals(bbar, bresult.get(1)); // Binary Multi keys bresult = jedis.brpop(0.11, bfoo, bfoo1); assertNull(bresult); jedis.lpush(bfoo, bbar); jedis.lpush(bfoo1, bcar); bresult = jedis.brpop(1d, bfoo, bfoo1); assertNotNull(bresult); assertEquals(2, bresult.size()); assertArrayEquals(bfoo, bresult.get(0)); assertArrayEquals(bbar, bresult.get(1)); } @Test public void brpopDoubleWithSleep() { long startMillis, totalMillis; startMillis = System.currentTimeMillis(); KeyedListElement result = jedis.brpop(0.04, "foo"); totalMillis = System.currentTimeMillis() - startMillis; assertTrue("TotalMillis=" + totalMillis, totalMillis < 200); assertNull(result); startMillis = System.currentTimeMillis(); new Thread(() -> { try { Thread.sleep(30); } catch(InterruptedException e) { logger.error("", e); } jedis.lpush("foo", "bar"); }).start(); result = jedis.brpop(1.2, "foo"); totalMillis = System.currentTimeMillis() - startMillis; assertTrue("TotalMillis=" + totalMillis, totalMillis < 200); assertNotNull(result); assertEquals("foo", result.getKey()); assertEquals("bar", result.getElement()); } @Test public void lpushx() { assertEquals(0, jedis.lpushx("foo", "bar")); jedis.lpush("foo", "a"); assertEquals(2, jedis.lpushx("foo", "b")); // Binary assertEquals(0, jedis.lpushx(bfoo, bbar)); jedis.lpush(bfoo, bA); assertEquals(2, jedis.lpushx(bfoo, bB)); } @Test public void rpushx() { assertEquals(0, jedis.rpushx("foo", "bar")); jedis.lpush("foo", "a"); assertEquals(2, jedis.rpushx("foo", "b")); // Binary assertEquals(0, jedis.rpushx(bfoo, bbar)); jedis.lpush(bfoo, bA); assertEquals(2, jedis.rpushx(bfoo, bB)); } @Test public void linsert() { assertEquals(0, jedis.linsert("foo", ListPosition.BEFORE, "bar", "car")); jedis.lpush("foo", "a"); assertEquals(2, jedis.linsert("foo", ListPosition.AFTER, "a", "b")); List<String> expected = new ArrayList<String>(); expected.add("a"); expected.add("b"); assertEquals(expected, jedis.lrange("foo", 0, 100)); assertEquals(-1, jedis.linsert("foo", ListPosition.BEFORE, "bar", "car")); // Binary assertEquals(0, jedis.linsert(bfoo, ListPosition.BEFORE, bbar, bcar)); jedis.lpush(bfoo, bA); assertEquals(2, jedis.linsert(bfoo, ListPosition.AFTER, bA, bB)); List<byte[]> bexpected = new ArrayList<byte[]>(); bexpected.add(bA); bexpected.add(bB); assertByteArrayListEquals(bexpected, jedis.lrange(bfoo, 0, 100)); assertEquals(-1, jedis.linsert(bfoo, ListPosition.BEFORE, bbar, bcar)); } @Test public void brpoplpush() { new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(100); } catch (InterruptedException e) { logger.error("", e); } jedis.lpush("foo", "a"); } }).start(); String element = jedis.brpoplpush("foo", "bar", 0); assertEquals("a", element); assertEquals(1, jedis.llen("bar")); assertEquals("a", jedis.lrange("bar", 0, -1).get(0)); // Binary new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(100); } catch (InterruptedException e) { logger.error("", e); } jedis.lpush(bfoo, bA); } }).start(); byte[] belement = jedis.brpoplpush(bfoo, bbar, 0); assertArrayEquals(bA, belement); assertEquals(1, jedis.llen("bar")); assertArrayEquals(bA, jedis.lrange(bbar, 0, -1).get(0)); } @Test public void lpos() { jedis.rpush("foo", "a"); jedis.rpush("foo", "b"); jedis.rpush("foo", "c"); Long pos = jedis.lpos("foo", "b"); assertEquals(1, pos.intValue()); pos = jedis.lpos("foo", "d"); assertNull(pos); jedis.rpush("foo", "a"); jedis.rpush("foo", "b"); jedis.rpush("foo", "b"); pos = jedis.lpos("foo", "b", LPosParams.lPosParams()); assertEquals(1, pos.intValue()); pos = jedis.lpos("foo", "b", LPosParams.lPosParams().rank(3)); assertEquals(5, pos.intValue()); pos = jedis.lpos("foo", "b", LPosParams.lPosParams().rank(-2)); assertEquals(4, pos.intValue()); pos = jedis.lpos("foo", "b", LPosParams.lPosParams().rank(-5)); assertNull(pos); pos = jedis.lpos("foo", "b", LPosParams.lPosParams().rank(1).maxlen(2)); assertEquals(1, pos.intValue()); pos = jedis.lpos("foo", "b", LPosParams.lPosParams().rank(2).maxlen(2)); assertNull(pos); pos = jedis.lpos("foo", "b", LPosParams.lPosParams().rank(-2).maxlen(2)); assertEquals(4, pos.intValue()); List<Long> expected = new ArrayList<Long>(); expected.add(1L); expected.add(4L); expected.add(5L); List<Long> posList = jedis.lpos("foo", "b", LPosParams.lPosParams(), 2); assertEquals(expected.subList(0, 2), posList); posList = jedis.lpos("foo", "b", LPosParams.lPosParams(), 0); assertEquals(expected, posList); posList = jedis.lpos("foo", "b", LPosParams.lPosParams().rank(2), 0); assertEquals(expected.subList(1, 3), posList); posList = jedis.lpos("foo", "b", LPosParams.lPosParams().rank(2).maxlen(5), 0); assertEquals(expected.subList(1, 2), posList); Collections.reverse(expected); posList = jedis.lpos("foo", "b", LPosParams.lPosParams().rank(-2), 0); assertEquals(expected.subList(1, 3), posList); posList = jedis.lpos("foo", "b", LPosParams.lPosParams().rank(-1).maxlen(5), 2); assertEquals(expected.subList(0, 2), posList); // Binary jedis.rpush(bfoo, bA); jedis.rpush(bfoo, bB); jedis.rpush(bfoo, bC); pos = jedis.lpos(bfoo, bB); assertEquals(1, pos.intValue()); pos = jedis.lpos(bfoo, b3); assertNull(pos); jedis.rpush(bfoo, bA); jedis.rpush(bfoo, bB); jedis.rpush(bfoo, bA); pos = jedis.lpos(bfoo, bB, LPosParams.lPosParams().rank(2)); assertEquals(4, pos.intValue()); pos = jedis.lpos(bfoo, bB, LPosParams.lPosParams().rank(-2).maxlen(5)); assertEquals(1, pos.intValue()); expected.clear(); expected.add(0L); expected.add(3L); expected.add(5L); posList = jedis.lpos(bfoo, bA, LPosParams.lPosParams().maxlen(6), 0); assertEquals(expected, posList); posList = jedis.lpos(bfoo, bA, LPosParams.lPosParams().maxlen(6).rank(2), 1); assertEquals(expected.subList(1, 2), posList); } @Test public void lmove() { jedis.rpush("foo", "bar1", "bar2", "bar3"); assertEquals("bar3", jedis.lmove("foo", "bar", ListDirection.RIGHT, ListDirection.LEFT)); assertEquals(Collections.singletonList("bar3"), jedis.lrange("bar", 0, -1)); assertEquals(Arrays.asList("bar1", "bar2"), jedis.lrange("foo", 0, -1)); // Binary jedis.rpush(bfoo, b1, b2, b3); assertArrayEquals(b3, jedis.lmove(bfoo, bbar, ListDirection.RIGHT, ListDirection.LEFT)); assertByteArrayListEquals(Collections.singletonList(b3), jedis.lrange(bbar, 0, -1)); assertByteArrayListEquals(Arrays.asList(b1, b2), jedis.lrange(bfoo, 0, -1)); } @Test public void blmove() { new Thread(() -> { try { Thread.sleep(100); } catch (InterruptedException e) { logger.error("", e); } jedis.rpush("foo", "bar1", "bar2", "bar3"); }).start(); assertEquals("bar3", jedis.blmove("foo", "bar", ListDirection.RIGHT, ListDirection.LEFT, 0)); assertEquals(Collections.singletonList("bar3"), jedis.lrange("bar", 0, -1)); assertEquals(Arrays.asList("bar1", "bar2"), jedis.lrange("foo", 0, -1)); // Binary new Thread(() -> { try { Thread.sleep(100); } catch (InterruptedException e) { logger.error("", e); } jedis.rpush(bfoo, b1, b2, b3); }).start(); assertArrayEquals(b3, jedis.blmove(bfoo, bbar, ListDirection.RIGHT, ListDirection.LEFT, 0)); assertByteArrayListEquals(Collections.singletonList(b3), jedis.lrange(bbar, 0, -1)); assertByteArrayListEquals(Arrays.asList(b1, b2), jedis.lrange(bfoo, 0, -1)); } }
// Copyright (c) 2003-2012, Jodd Team (jodd.org). All Rights Reserved. package jodd.madvoc.result; import jodd.madvoc.ActionRequest; /** * None result processing, for direct outputs. */ public class NoneResult extends ActionResult { public static final String NAME = "none"; public NoneResult() { super(NAME); } /** * Executes result on given action result value. */ @Override public void render(ActionRequest actionRequest, Object resultObject, String resultValue, String resultPath) throws Exception { // none, direct output } }
/* * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test TestConcurrentPhaseControlParallel * @bug 8169517 * @requires vm.gc.Parallel * @summary Verify Parallel GC doesn't support WhiteBox concurrent phase control. * @key gc * @modules java.base * @library /test/lib / * @build sun.hotspot.WhiteBox * @run driver ClassFileInstaller sun.hotspot.WhiteBox * sun.hotspot.WhiteBox$WhiteBoxPermission * @run main/othervm -XX:+UseParallelGC * -Xbootclasspath/a:. * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI * TestConcurrentPhaseControlParallel */ import gc.concurrent_phase_control.CheckUnsupported; public class TestConcurrentPhaseControlParallel { public static void main(String[] args) throws Exception { CheckUnsupported.check("Parallel"); } }
/** * 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.falcon.workflow.engine; import org.apache.falcon.FalconException; import org.apache.falcon.entity.v0.Entity; import org.apache.falcon.entity.v0.cluster.Cluster; import org.apache.falcon.resource.InstancesResult; import org.apache.falcon.resource.InstancesSummaryResult; import java.util.Date; import java.util.HashSet; import java.util.Properties; import java.util.Set; /** * Workflow engine should minimally support the * following operations. */ public abstract class AbstractWorkflowEngine { public static final String NAME_NODE = "nameNode"; public static final String JOB_TRACKER = "jobTracker"; protected Set<WorkflowEngineActionListener> listeners = new HashSet<WorkflowEngineActionListener>(); public void registerListener(WorkflowEngineActionListener listener) { listeners.add(listener); } public abstract boolean isAlive(Cluster cluster) throws FalconException; public abstract void schedule(Entity entity) throws FalconException; public abstract String suspend(Entity entity) throws FalconException; public abstract String resume(Entity entity) throws FalconException; public abstract String delete(Entity entity) throws FalconException; public abstract String delete(Entity entity, String cluster) throws FalconException; public abstract void reRun(String cluster, String wfId, Properties props) throws FalconException; public abstract boolean isActive(Entity entity) throws FalconException; public abstract boolean isSuspended(Entity entity) throws FalconException; public abstract InstancesResult getRunningInstances(Entity entity) throws FalconException; public abstract InstancesResult killInstances(Entity entity, Date start, Date end, Properties props) throws FalconException; public abstract InstancesResult reRunInstances(Entity entity, Date start, Date end, Properties props) throws FalconException; public abstract InstancesResult suspendInstances(Entity entity, Date start, Date end, Properties props) throws FalconException; public abstract InstancesResult resumeInstances(Entity entity, Date start, Date end, Properties props) throws FalconException; public abstract InstancesResult getStatus(Entity entity, Date start, Date end) throws FalconException; public abstract InstancesSummaryResult getSummary(Entity entity, Date start, Date end) throws FalconException; public abstract Date update(Entity oldEntity, Entity newEntity, String cluster, Date effectiveTime) throws FalconException; public abstract String getWorkflowStatus(String cluster, String jobId) throws FalconException; public abstract Properties getWorkflowProperties(String cluster, String jobId) throws FalconException; public abstract InstancesResult getJobDetails(String cluster, String jobId) throws FalconException; }
package com.printto.printmov.wearpet; import android.os.Bundle; import android.app.Activity; import android.widget.Toast; import android.widget.EditText; import android.content.Context; import android.view.View; import android.util.Log; import android.content.res.Configuration; import com.printto.printmov.wearpet.R; import android.content.Intent; import android.os.Bundle; import android.widget.TextView; public class StatsActivity extends Activity { String msg = "Android : "; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.stats); Intent intent = getIntent(); String data = intent.getStringExtra("data"); final TextView textName = (TextView) findViewById(R.id.textName); textName.setText(data); } /** Called when the activity is about to become visible. */ @Override protected void onStart() { super.onStart(); // view.loadMonster(); Log.d(msg, "The onStart() event"); } /** Called when the activity has become visible. */ @Override protected void onResume() { super.onResume(); Log.d(msg, "The onResume() event"); } /** Called when another activity is taking focus. */ @Override protected void onPause() { super.onPause(); Log.d(msg, "The onPause() event"); } /** Called when the activity is no longer visible. */ @Override protected void onStop() { super.onStop(); Log.d(msg, "The onStop() event"); } /** Called just before the activity is destroyed. */ @Override public void onDestroy() { super.onDestroy(); Log.d(msg, "The onDestroy() event"); } }
/* * Copyright (c) 2002-2017 Gargoyle Software Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gargoylesoftware.htmlunit.html; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.w3c.dom.NodeList; import com.gargoylesoftware.htmlunit.BrowserRunner; import com.gargoylesoftware.htmlunit.BrowserRunner.Alerts; import com.gargoylesoftware.htmlunit.SimpleWebTestCase; /** * Unit tests for {@link HtmlElement}. * * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a> * @author Denis N. Antonioli * @author Daniel Gredler * @author Ahmed Ashour * @author Sudhan Moghe * @author Frank Danek * @author Ronald Brill */ @RunWith(BrowserRunner.class) public class HtmlElementTest extends SimpleWebTestCase { /** * Test hasAttribute() on an element with the attribute. * @throws Exception if the test fails */ @Test public void hasAttributeWith() throws Exception { final String html = "<html><head></head><body id='tag'>text</body></html>"; final HtmlPage page = loadPage(html); final HtmlElement node = page.getHtmlElementById("tag"); assertTrue("Element should have attribute", node.hasAttribute("id")); } /** * Test hasAttribute() on an element with the attribute but without an value. * @throws Exception if the test fails */ @Test public void hasAttributeWithMissingValue() throws Exception { final String html = "<html><head></head><body id='tag' attrib>text</body></html>"; final HtmlPage page = loadPage(html); final HtmlElement node = page.getHtmlElementById("tag"); assertTrue("Element should have attribute", node.hasAttribute("attrib")); } /** * Test hasAttribute() on an element without the attributes. * @throws Exception if the test fails */ @Test public void hasAttributeNone() throws Exception { final String html = "<html><head></head><body id='tag'>text</body></html>"; final HtmlPage page = loadPage(html); final HtmlElement node = page.getHtmlElementById("tag"); assertFalse("Element should not have attribute", node.hasAttribute("foo")); } /** * Test hasAttribute() on an element with the attribute. * @throws Exception if the test fails */ @Test public void hasAttributeNSWith() throws Exception { final String html = "<html><head></head><body xmlns:ns='http://foobar' id='tag' ns:foo='bar'>text</body></html>"; final HtmlPage page = loadPage(html); final HtmlElement node = page.getHtmlElementById("tag"); assertTrue("Element should have attribute", node.hasAttributeNS("http://foobar", "foo")); } /** * Test hasAttribute() on an element without the attributes. * @throws Exception if the test fails */ @Test public void hasAttributeNSNone() throws Exception { final String html = "<html><head></head><body id='tag'>text</body></html>"; final HtmlPage page = loadPage(html); final HtmlElement node = page.getHtmlElementById("tag"); assertFalse("Element should not have attribute", node.hasAttributeNS("http://foobar", "foo")); } /** * Test getAttribute() on an element with the attribute. * @throws Exception if the test fails */ @Test public void getAttributeWith() throws Exception { final String html = "<html><head></head><body id='tag'>text</body></html>"; final HtmlPage page = loadPage(html); final HtmlElement node = page.getHtmlElementById("tag"); assertEquals("Element should have attribute", "tag", node.getId()); } /** * Test getAttribute() on an element with the attribute but without an value. * @throws Exception if the test fails */ @Test public void getAttributeWithMissingValue() throws Exception { final String html = "<html><head></head><body id='tag' attrib>text</body></html>"; final HtmlPage page = loadPage(html); final HtmlElement node = page.getHtmlElementById("tag"); assertEquals("", node.getAttribute("attrib")); assertTrue(DomElement.ATTRIBUTE_VALUE_EMPTY == node.getAttribute("attrib")); } /** * Test getAttribute() on an element with the attribute but without an value. * @throws Exception if the test fails */ @Test public void getAttributeWithEmptyValue() throws Exception { final String html = "<html><head></head><body id='tag' attrib=''>text</body></html>"; final HtmlPage page = loadPage(html); final HtmlElement node = page.getHtmlElementById("tag"); assertEquals("", node.getAttribute("attrib")); assertTrue(DomElement.ATTRIBUTE_VALUE_EMPTY == node.getAttribute("attrib")); } /** * Test getAttribute() on an element without the attributes. * @throws Exception if the test fails */ @Test public void getAttributeNone() throws Exception { final String html = "<html><head></head><body id='tag'>text</body></html>"; final HtmlPage page = loadPage(html); final HtmlElement node = page.getHtmlElementById("tag"); assertEquals("Element should not have attribute", "", node.getAttribute("foo")); } /** * Test getAttribute() on an element with the attribute. * @throws Exception if the test fails */ @Test public void getAttributeNSWith() throws Exception { final String html = "<html><head></head><body xmlns:ns='http://foobar' id='tag' ns:foo='bar'>text</body></html>"; final HtmlPage page = loadPage(html); final HtmlElement node = page.getHtmlElementById("tag"); assertEquals("Element should have attribute", "bar", node.getAttributeNS("http://foobar", "foo")); } /** * Test getAttribute() on an element without the attributes. * @throws Exception if the test fails */ @Test public void getAttributeNSNone() throws Exception { final String html = "<html><head></head><body id='tag'>text</body></html>"; final HtmlPage page = loadPage(html); final HtmlElement node = page.getHtmlElementById("tag"); assertEquals("Element should not have attribute", "", node.getAttributeNS("http://foobar", "foo")); } /** * Test getNamespaceURI on an attribute that has a namespace. * @throws Exception if the test fails */ @Test public void getNamespaceURIWith() throws Exception { final String html = "<html><head></head><body xmlns:ns='http://foobar' id='tag' ns:foo='bar'>text</body></html>"; final HtmlPage page = loadPage(html); final HtmlElement node = page.getHtmlElementById("tag"); for (final DomAttr attr : node.getAttributesMap().values()) { if ("ns:foo".equals(attr.getName())) { assertEquals("Element should have a namespace URI", "http://foobar", attr.getNamespaceURI()); return; } } fail("Attribute ns:foo not found."); } /** * Test getNamespaceURI on an attribute that has a namespace. * @throws Exception if the test fails */ @Test public void getNamespaceURINone() throws Exception { final String html = "<html><head></head><body xmlns:ns='http://foobar' id='tag' ns:foo='bar'>text</body></html>"; final HtmlPage page = loadPage(html); final HtmlElement node = page.getHtmlElementById("tag"); for (final DomAttr attr : node.getAttributesMap().values()) { if ("id".equals(attr.getName())) { assertEquals("Element should not have a namespace URI", null, attr.getNamespaceURI()); return; } } fail("Attribute ns:foo not found."); } /** * Test getLocalName on an attribute that has a local name. * @throws Exception if the test fails */ @Test public void getLocalNameWith() throws Exception { final String html = "<html><head></head><body xmlns:ns='http://foobar' id='tag' ns:foo='bar'>text</body></html>"; final HtmlPage page = loadPage(html); final HtmlElement node = page.getHtmlElementById("tag"); for (final DomAttr attr : node.getAttributesMap().values()) { if ("ns:foo".equals(attr.getName())) { assertEquals("Element should have a local name", "foo", attr.getLocalName()); return; } } fail("Attribute ns:foo not found."); } /** * Test getLocalName on an attribute that has a local name. * @throws Exception if the test fails */ @Test public void getLocalNameNone() throws Exception { final String html = "<html><head></head><body xmlns:ns='http://foobar' id='tag' ns:foo='bar'>text</body></html>"; final HtmlPage page = loadPage(html); final HtmlElement node = page.getHtmlElementById("tag"); for (final DomAttr attr : node.getAttributesMap().values()) { if ("id".equals(attr.getName())) { // This is not standard, but to change it now would break backwards compatibility. assertEquals("Element should not have a local name", "id", attr.getLocalName()); return; } } fail("Attribute ns:foo not found."); } /** * Test getPrefix on an attribute that has a prefix. * @throws Exception if the test fails */ @Test public void getPrefixWith() throws Exception { final String html = "<html><head></head><body xmlns:ns='http://foobar' id='tag' ns:foo='bar'>text</body></html>"; final HtmlPage page = loadPage(html); final HtmlElement node = page.getHtmlElementById("tag"); for (final DomAttr attr : node.getAttributesMap().values()) { if ("ns:foo".equals(attr.getName())) { assertEquals("Element should have a prefix", "ns", attr.getPrefix()); return; } } fail("Attribute ns:foo not found."); } /** * Test getPrefix on an attribute that has a prefix. * @throws Exception if the test fails */ @Test public void getPrefixNone() throws Exception { final String html = "<html><head></head><body xmlns:ns='http://foobar' id='tag' ns:foo='bar'>text</body></html>"; final HtmlPage page = loadPage(html); final HtmlElement node = page.getHtmlElementById("tag"); for (final DomAttr attr : node.getAttributesMap().values()) { if ("id".equals(attr.getName())) { assertEquals("Element should not have a prefix", null, attr.getPrefix()); return; } } fail("Attribute ns:foo not found."); } /** * Test setPrefix on an attribute that has a prefix. * @throws Exception if the test fails */ @Test public void setPrefix() throws Exception { final String html = "<html><head></head><body xmlns:ns='http://foobar' id='tag' ns:foo='bar'>text</body></html>"; final HtmlPage page = loadPage(html); final HtmlElement node = page.getHtmlElementById("tag"); for (final DomAttr attr : node.getAttributesMap().values()) { if ("ns:foo".equals(attr.getName())) { attr.setPrefix("other"); assertEquals("Element should have a changed prefix", "other", attr.getPrefix()); assertEquals("setPrefix should change qualified name", "other:foo", attr.getName()); return; } } fail("Attribute ns:foo not found."); } /** * Test setAttribute() on an element with the attribute. * @throws Exception if the test fails */ @Test public void setAttributeWith() throws Exception { final String html = "<html><head></head><body id='tag'>text</body></html>"; final HtmlPage page = loadPage(html); final HtmlElement node = page.getHtmlElementById("tag"); node.setAttribute("id", "other"); assertEquals("Element should have attribute", "other", node.getId()); } /** * Test setAttribute() on an element without the attributes. * @throws Exception if the test fails */ @Test public void setAttributeNone() throws Exception { final String html = "<html><head></head><body id='tag'>text</body></html>"; final HtmlPage page = loadPage(html); final HtmlElement node = page.getHtmlElementById("tag"); node.setAttribute("foo", "other"); assertEquals("Element should have attribute", "other", node.getAttribute("foo")); } /** * Test setAttribute() on an element with the attribute. * @throws Exception if the test fails */ @Test public void setAttributeNSWith() throws Exception { final String html = "<html><head></head><body xmlns:ns='http://foobar' id='tag' ns:foo='bar'>text</body></html>"; final HtmlPage page = loadPage(html); final HtmlElement node = page.getHtmlElementById("tag"); node.setAttributeNS("http://foobar", "ns:foo", "other"); assertEquals("Element should have attribute", "other", node.getAttributeNS("http://foobar", "foo")); } /** * Test setAttribute() on an element without the attributes. * @throws Exception if the test fails */ @Test public void setAttributeNSNone() throws Exception { final String html = "<html><head></head><body id='tag'>text</body></html>"; final HtmlPage page = loadPage(html); final HtmlElement node = page.getHtmlElementById("tag"); node.setAttributeNS("http://foobar", "ns:foo", "other"); assertEquals("Element should not have attribute", "other", node.getAttributeNS("http://foobar", "foo")); } /** * Test removeAttribute() on an element with the attribute. * @throws Exception if the test fails */ @Test public void removeAttributeWith() throws Exception { final String html = "<html><head></head><body id='tag'>text</body></html>"; final HtmlPage page = loadPage(html); final HtmlElement node = page.getHtmlElementById("tag"); node.removeAttribute("id"); assertEquals("Element should not have removed attribute", "", node.getId()); } /** * Test removeAttribute() on an element without the attributes. * @throws Exception if the test fails */ @Test public void removeAttributeNone() throws Exception { final String html = "<html><head></head><body id='tag'>text</body></html>"; final HtmlPage page = loadPage(html); final HtmlElement node = page.getHtmlElementById("tag"); node.removeAttribute("foo"); assertEquals("Element should not have attribute", "", node.getAttribute("foo")); } /** * Test removeAttribute() on an element with the attribute. * @throws Exception if the test fails */ @Test public void removeAttributeNSWith() throws Exception { final String html = "<html><head></head><body xmlns:ns='http://foobar' id='tag' ns:foo='bar'>text</body></html>"; final HtmlPage page = loadPage(html); final HtmlElement node = page.getHtmlElementById("tag"); node.removeAttributeNS("http://foobar", "foo"); assertEquals("Element should not have removed attribute", "", node.getAttributeNS("http://foobar", "foo")); } /** * Test removeAttribute() on an element without the attributes. * @throws Exception if the test fails */ @Test public void removeAttributeNSNone() throws Exception { final String html = "<html><head></head><body id='tag'>text</body></html>"; final HtmlPage page = loadPage(html); final HtmlElement node = page.getHtmlElementById("tag"); node.removeAttributeNS("http://foobar", "foo"); assertEquals("Element should not have attribute", "", node.getAttributeNS("http://foobar", "foo")); } /** * @throws Exception if the test fails */ @Test public void getEnclosingForm() throws Exception { final String htmlContent = "<html><head><title>foo</title></head><body>\n" + "<form id='form1'>\n" + "<table><tr><td><input type='text' id='foo'/></td></tr></table>\n" + "</form></body></html>"; final HtmlPage page = loadPage(htmlContent); final HtmlForm form = page.getHtmlElementById("form1"); final HtmlInput input = page.getHtmlElementById("foo"); assertSame(form, input.getEnclosingForm()); } /** * @throws Exception if the test fails */ @Test public void getEnclosing() throws Exception { final String htmlContent = "<html><head><title>foo</title></head><body>\n" + "<form id='form1'>\n" + "<table id='table1'>\n" + "<tr id='tr1'><td id='td1'>foo</td></tr>\n" + "<tr id='tr2'><td id='td2'>foo</td></tr>\n" + "</table>\n" + "</form></body></html>"; final HtmlPage page = loadPage(htmlContent); final HtmlElement td1 = page.getHtmlElementById("td1"); assertEquals("tr1", td1.getEnclosingElement("tr").getId()); assertEquals("tr1", td1.getEnclosingElement("TR").getId()); assertEquals("table1", td1.getEnclosingElement("table").getId()); assertEquals("form1", td1.getEnclosingElement("form").getId()); final HtmlElement td2 = page.getHtmlElementById("td2"); assertEquals("tr2", td2.getEnclosingElement("tr").getId()); assertEquals("tr2", td2.getEnclosingElement("TR").getId()); assertEquals("table1", td2.getEnclosingElement("table").getId()); assertEquals("form1", td2.getEnclosingElement("form").getId()); } /** * @throws Exception if the test fails */ @Test public void asText_WithComments() throws Exception { final String htmlContent = "<html><head><title>foo</title></head><body>\n" + "<p id='p1'>foo<!--bar--></p>\n" + "</body></html>"; final HtmlPage page = loadPage(htmlContent); final HtmlElement element = page.getHtmlElementById("p1"); assertEquals("foo", element.asText()); } /** * Tests constants. */ @Test public void constants() { assertEquals("", DomElement.ATTRIBUTE_NOT_DEFINED); assertEquals("", DomElement.ATTRIBUTE_VALUE_EMPTY); assertTrue("Not the same object", DomElement.ATTRIBUTE_NOT_DEFINED != DomElement.ATTRIBUTE_VALUE_EMPTY); } static class HtmlAttributeChangeListenerTestImpl implements HtmlAttributeChangeListener { private final List<String> collectedValues_ = new ArrayList<>(); @Override @Test public void attributeAdded(final HtmlAttributeChangeEvent event) { collectedValues_.add("attributeAdded: " + event.getHtmlElement().getTagName() + ',' + event.getName() + ',' + event.getValue()); } @Override @Test public void attributeRemoved(final HtmlAttributeChangeEvent event) { collectedValues_.add("attributeRemoved: " + event.getHtmlElement().getTagName() + ',' + event.getName() + ',' + event.getValue()); } @Override @Test public void attributeReplaced(final HtmlAttributeChangeEvent event) { collectedValues_.add("attributeReplaced: " + event.getHtmlElement().getTagName() + ',' + event.getName() + ',' + event.getValue()); } List<String> getCollectedValues() { return collectedValues_; } } /** * @throws Exception if the test fails */ @Test public void htmlAttributeChangeListener_AddAttribute() throws Exception { final String htmlContent = "<html><head><title>foo</title>\n" + "<script>\n" + " function clickMe() {\n" + " var p1 = document.getElementById('p1');\n" + " p1.setAttribute('title', 'myTitle');\n" + " }\n" + "</script>\n" + "</head>\n" + "<body id='myBody'>\n" + "<p id='p1'></p>\n" + "<input id='myButton' type='button' onclick='clickMe()'>\n" + "</body></html>"; final String[] expectedValues = {"attributeAdded: p,title,myTitle", "attributeAdded: p,title,myTitle", "attributeAdded: p,title,myTitle"}; final HtmlPage page = loadPage(htmlContent); final HtmlBody body = page.getHtmlElementById("myBody"); final HtmlElement p1 = page.getHtmlElementById("p1"); final HtmlAttributeChangeListenerTestImpl listenerImpl = new HtmlAttributeChangeListenerTestImpl(); p1.addHtmlAttributeChangeListener(listenerImpl); body.addHtmlAttributeChangeListener(listenerImpl); page.addHtmlAttributeChangeListener(listenerImpl); final HtmlButtonInput myButton = page.getHtmlElementById("myButton"); myButton.click(); assertEquals(expectedValues, listenerImpl.getCollectedValues()); } /** * @throws Exception if the test fails */ @Test public void htmlAttributeChangeListener_ReplaceAttribute() throws Exception { final String htmlContent = "<html><head><title>foo</title>\n" + "<script>\n" + " function clickMe() {\n" + " var p1 = document.getElementById('p1');\n" + " p1.setAttribute('title', p1.getAttribute('title') + 'a');\n" + " }\n" + "</script>\n" + "</head>\n" + "<body id='myBody'>\n" + "<p id='p1' title='myTitle'></p>\n" + "<input id='myButton' type='button' onclick='clickMe()'>\n" + "</body></html>"; final String[] expectedValues = {"attributeReplaced: p,title,myTitle", "attributeReplaced: p,title,myTitle", "attributeReplaced: p,title,myTitle"}; final HtmlPage page = loadPage(htmlContent); final HtmlBody body = page.getHtmlElementById("myBody"); final HtmlElement p1 = page.getHtmlElementById("p1"); final HtmlAttributeChangeListenerTestImpl listenerImpl = new HtmlAttributeChangeListenerTestImpl(); page.addHtmlAttributeChangeListener(listenerImpl); body.addHtmlAttributeChangeListener(listenerImpl); p1.addHtmlAttributeChangeListener(listenerImpl); final HtmlButtonInput myButton = page.getHtmlElementById("myButton"); myButton.click(); assertEquals(expectedValues, listenerImpl.getCollectedValues()); assertEquals("myTitle" + 'a', p1.getAttribute("title")); } /** * @throws Exception if the test fails */ @Test public void htmlAttributeChangeListener_RemoveAttribute() throws Exception { final String htmlContent = "<html><head><title>foo</title>\n" + "<script>\n" + " function clickMe() {\n" + " var p1 = document.getElementById('p1');\n" + " p1.removeAttribute('title');\n" + " }\n" + "</script>\n" + "</head>\n" + "<body id='myBody'>\n" + "<p id='p1' title='myTitle'></p>\n" + "<input id='myButton' type='button' onclick='clickMe()'>\n" + "</body></html>"; final String[] expectedValues = {"attributeRemoved: p,title,myTitle", "attributeRemoved: p,title,myTitle", "attributeRemoved: p,title,myTitle"}; final HtmlPage page = loadPage(htmlContent); final HtmlBody body = page.getHtmlElementById("myBody"); final HtmlElement p1 = page.getHtmlElementById("p1"); final HtmlAttributeChangeListenerTestImpl listenerImpl = new HtmlAttributeChangeListenerTestImpl(); page.addHtmlAttributeChangeListener(listenerImpl); body.addHtmlAttributeChangeListener(listenerImpl); p1.addHtmlAttributeChangeListener(listenerImpl); final HtmlButtonInput myButton = page.getHtmlElementById("myButton"); myButton.click(); assertEquals(expectedValues, listenerImpl.getCollectedValues()); assertSame(DomElement.ATTRIBUTE_NOT_DEFINED, p1.getAttribute("title")); } /** * @throws Exception if the test fails */ @Test public void htmlAttributeChangeListener_RemoveListener() throws Exception { final String htmlContent = "<html><head><title>foo</title>\n" + "<script>\n" + " function clickMe() {\n" + " var p1 = document.getElementById('p1');\n" + " p1.setAttribute('title', p1.getAttribute('title') + 'a');\n" + " }\n" + "</script>\n" + "</head>\n" + "<body>\n" + "<p id='p1' title='myTitle'></p>\n" + "<input id='myButton' type='button' onclick='clickMe()'>\n" + "</body></html>"; final String[] expectedValues = {"attributeReplaced: p,title,myTitle"}; final HtmlPage page = loadPage(htmlContent); final HtmlElement p1 = page.getHtmlElementById("p1"); final HtmlAttributeChangeListenerTestImpl listenerImpl = new HtmlAttributeChangeListenerTestImpl(); p1.addHtmlAttributeChangeListener(listenerImpl); final HtmlButtonInput myButton = page.getHtmlElementById("myButton"); myButton.click(); p1.removeHtmlAttributeChangeListener(listenerImpl); myButton.click(); assertEquals(expectedValues, listenerImpl.getCollectedValues()); assertEquals("myTitle" + 'a' + 'a', p1.getAttribute("title")); } /** * @throws Exception if the test fails */ @Test public void mouseOver() throws Exception { final String html = "<html>\n" + "<head>\n" + "<script>\n" + " function mouseOverMe() {\n" + " document.getElementById('myTextarea').value+='mouseover-';\n" + " }\n" + "</script>\n" + "</head>\n" + "<body id='myBody' onmouseover='mouseOverMe()'>\n" + "<textarea id='myTextarea'></textarea>\n" + "</body></html>"; final HtmlPage page = loadPage(html); final HtmlBody body = page.getHtmlElementById("myBody"); body.mouseOver(); final HtmlTextArea textArea = page.getHtmlElementById("myTextarea"); assertEquals("mouseover-", textArea.getText()); } /** * @throws Exception if the test fails */ @Test public void mouseMove() throws Exception { final String html = "<html>\n" + "<head>\n" + "<script>\n" + " function mouseMoveMe() {\n" + " document.getElementById('myTextarea').value+='mousemove-';\n" + " }\n" + "</script>\n" + "</head>\n" + "<body id='myBody' onmousemove='mouseMoveMe()'>\n" + "<textarea id='myTextarea'></textarea>\n" + "</body></html>"; final HtmlPage page = loadPage(html); final HtmlBody body = page.getHtmlElementById("myBody"); body.mouseMove(); final HtmlTextArea textArea = page.getHtmlElementById("myTextarea"); assertEquals("mousemove-", textArea.getText()); } /** * @throws Exception if the test fails */ @Test public void mouseOut() throws Exception { final String html = "<html>\n" + "<head>\n" + "<script>\n" + " function mouseOutMe() {\n" + " document.getElementById('myTextarea').value+='mouseout-';\n" + " }\n" + "</script>\n" + "</head>\n" + "<body id='myBody' onmouseout='mouseOutMe()'>\n" + "<textarea id='myTextarea'></textarea>\n" + "</body></html>"; final HtmlPage page = loadPage(html); final HtmlBody body = page.getHtmlElementById("myBody"); body.mouseOut(); final HtmlTextArea textArea = page.getHtmlElementById("myTextarea"); assertEquals("mouseout-", textArea.getText()); } /** * @throws Exception if the test fails */ @Test @Alerts("mousedown-0") public void mouseDown() throws Exception { final String html = "<html>\n" + "<head>\n" + "<script>\n" + " function mouseDownMe(e) {\n" + " document.getElementById('myTextarea').value+='mousedown-' + e.button;\n" + " }\n" + "</script>\n" + "</head>\n" + "<body id='myBody' onmousedown='mouseDownMe(event)'>\n" + "<textarea id='myTextarea'></textarea>\n" + "</body></html>"; final HtmlPage page = loadPage(html); final HtmlBody body = page.getHtmlElementById("myBody"); body.mouseDown(); final HtmlTextArea textArea = page.getHtmlElementById("myTextarea"); assertEquals(getExpectedAlerts()[0], textArea.getText()); } /** * @throws Exception if the test fails */ @Test public void mouseUp() throws Exception { final String html = "<html>\n" + "<head>\n" + "<script>\n" + " function mouseUpMe() {\n" + " document.getElementById('myTextarea').value+='mouseup-';\n" + " }\n" + "</script>\n" + "</head>\n" + "<body id='myBody' onmouseup='mouseUpMe()'>\n" + "<textarea id='myTextarea'></textarea>\n" + "</body></html>"; final HtmlPage page = loadPage(html); final HtmlBody body = page.getHtmlElementById("myBody"); body.mouseUp(); final HtmlTextArea textArea = page.getHtmlElementById("myTextarea"); assertEquals("mouseup-", textArea.getText()); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "mousedown-2-mouseup-2-contextmenu-2-", FF = "mousedown-3-mouseup-3-contextmenu-3-") public void rightClick() throws Exception { final String html = "<html>\n" + "<head>\n" + "<script>\n" + " function divMouseEvent(e) {\n" + " var textarea = document.getElementById('myTextarea');\n" + " if (window.event)\n" + " textarea.value += event.type + '-' + event.button + '-';\n" + " else\n" + " textarea.value += e.type + '-' + e.which + '-';\n" + " }\n" + " function loadFunction(e) {\n" + " document.getElementById('myDiv').onmousedown = divMouseEvent;\n" + " document.getElementById('myDiv').onmouseup = divMouseEvent;\n" + " document.getElementById('myDiv').oncontextmenu = divMouseEvent;\n" + " }\n" + "</script>\n" + "</head>\n" + "<body onload='loadFunction()'>\n" + " <div id='myDiv'>Hello</div><br>\n" + " <textarea id='myTextarea'></textarea>\n" + "</body></html>"; final HtmlPage page = loadPage(html); final HtmlDivision div = page.getHtmlElementById("myDiv"); div.rightClick(); final HtmlTextArea textArea = page.getHtmlElementById("myTextarea"); assertEquals(getExpectedAlerts()[0], textArea.getText()); } /** * Test the mouse down, then mouse up. * * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "mousedown-0-mouseup-0-", FF = "mousedown-1-mouseup-1-") public void mouse_Down_Up() throws Exception { final String html = "<html>\n" + "<head>\n" + "<script>\n" + " function divMouseEvent(e) {\n" + " var textarea = document.getElementById('myTextarea');\n" + " if (window.event)\n" + " textarea.value += event.type + '-' + event.button + '-';\n" + " else\n" + " textarea.value += e.type + '-' + e.which + '-';\n" + " }\n" + " function loadFunction(e) {\n" + " document.getElementById('myDiv').onmousedown=divMouseEvent;\n" + " document.getElementById('myDiv').onmouseup =divMouseEvent;\n" + " }\n" + "</script>\n" + "</head>\n" + "<body onload='loadFunction()'>\n" + " <div id='myDiv'>Hello</div><br>\n" + " <textarea id='myTextarea'></textarea>\n" + "</body></html>"; final HtmlPage page = loadPage(html); final HtmlDivision div = page.getHtmlElementById("myDiv"); div.mouseDown(); div.mouseUp(); final HtmlTextArea textArea = page.getHtmlElementById("myTextarea"); assertEquals(getExpectedAlerts()[0], textArea.getText()); } /** * @throws Exception if the test fails */ @Test public void asXml_separateLineforEmptyElements() throws Exception { final String html = "<html><head><title>foo</title></head>\n" + "<body><table><tr><td></tr></table>\n" + "</body></html>"; final HtmlPage page = loadPage(html); assertTrue(page.asXml().indexOf("/> ") == -1); } /** * @throws Exception if an error occurs */ @Test public void type() throws Exception { final String html = "<html><head><script>\n" + " function test() {\n" + " alert(document.getElementById('myInput').value);\n" + " }\n" + "</script></head>\n" + "<body>\n" + " <input id='myButton' type='button' onclick='test()'>\n" + " <input id='myInput' onclick='test()'>\n" + "</body></html>"; final String[] expectedAlerts = {"Hello Cruel World"}; final List<String> collectedAlerts = new ArrayList<>(); final HtmlPage page = loadPage(html, collectedAlerts); final HtmlTextInput input = page.getHtmlElementById("myInput"); input.type("Hello Cruel World"); assertEquals("Hello Cruel World", input.getValueAttribute()); page.getHtmlElementById("myButton").click(); assertEquals(expectedAlerts, collectedAlerts); } /** * @throws Exception if the test fails */ @Test public void typeOnFocus() throws Exception { final String html = "<html><head><title>foo</title></head><body>\n" + "<form>\n" + " <input type='text' id='textfield1' onfocus='alert(1)'>\n" + "</form>\n" + "</body></html>"; final String[] expectedAlerts = {"1"}; final List<String> collectedAlerts = new ArrayList<>(); final HtmlPage page = loadPage(html, collectedAlerts); page.getHtmlElementById("textfield1").type('a'); assertEquals(expectedAlerts, collectedAlerts); } /** * @throws Exception on test failure */ @Test public void asText() throws Exception { final String html = "<html>\n" + "<head>\n" + " <title>test</title>\n" + "</head>\n" + "<body>Welcome\n" + "<div style='visibility:hidden'>to the big</div>\n" + "<div style='display:none'>\n" + " <div style='display:block'><span style='visibility:visible'>world</span></div>\n" + "</div>\n" + "</body>\n" + "</html>"; final HtmlPage page = loadPage(html); assertEquals("test" + LINE_SEPARATOR + "Welcome", page.asText()); } /** * @throws Exception on test failure */ @Test public void asTextOverridingVisibility() throws Exception { final String html = "<html>\n" + "<head>\n" + " <title>test</title>\n" + "</head>\n" + "<body>Welcome\n" + "<p style='visibility:hidden'>hidden text\n" + "<FONT COLOR='#FF0000' style='visibility:visible'>to the world</FONT>\n" + "some more hidden text</p>\n" + "</body>\n" + "</html>"; final HtmlPage page = loadPage(html); assertEquals("test" + LINE_SEPARATOR + "Welcome" + LINE_SEPARATOR + "to the world", page.asText()); } /** * @throws Exception on test failure */ @Test public void asTextVisibilityCollapse() throws Exception { final String html = "<html>\n" + "<head>\n" + " <title>test</title>\n" + "</head>\n" + "<body>Welcome\n" + "<p style='visibility:collapse'>hidden text\n" + "<font color='#FF0000' style='visibility:visible'>to the world</font>\n" + "some more hidden text</p>\n" + "</body>\n" + "</html>"; final String expected = "test" + LINE_SEPARATOR + "Welcome" + LINE_SEPARATOR + "to the world"; final HtmlPage page = loadPage(html); assertEquals(expected, page.asText()); } /** * @throws Exception if the test fails */ @Test public void getNodeName() throws Exception { final String html = "<html xmlns='http://www.w3.org/1999/xhtml' xmlns:app='http://www.appcelerator.org'>\n" + "<head>\n" + "<script>\n" + "</script>\n" + "</head>\n" + "<body>\n" + "<dIv id='dIv1'></dIv>\n" + "<app:dIv id='dIv2'></app:dIv>\n" + "<another:dIv id='dIv3'></another:dIv>\n" + "</body></html>"; final HtmlPage page = loadPage(html); assertEquals("div", page.getHtmlElementById("dIv1").getNodeName()); assertEquals("app:div", page.getHtmlElementById("dIv2").getNodeName()); assertEquals("another:div", page.getHtmlElementById("dIv3").getNodeName()); assertTrue(page.asXml().contains("<app:div ")); } /** * @throws Exception if the test fails */ @Test @Alerts({"1", "2"}) public void getElementsByTagName() throws Exception { final String html = "<html>\n" + "<head>\n" + "<script>\n" + " function test() {\n" + " var form = document.getElementById('myForm');\n" + " alert(form.getElementsByTagName('input').length);\n" + " alert(document.body.getElementsByTagName('input').length);\n" + " }\n" + "</script>\n" + "</head>\n" + "<body onload='test()'>\n" + "<form id='myForm'>\n" + " <input type='button' name='button1' value='pushme'>\n" + "</form>\n" + "<input type='button' name='button2'>\n" + "</body></html>"; final HtmlPage page = loadPageWithAlerts(html); assertEquals(1, page.getElementById("myForm").getElementsByTagName("input").getLength()); assertEquals(2, page.getBody().getElementsByTagName("input").getLength()); } /** * @throws Exception if an error occurs */ @Test public void getElementsByTagName2() throws Exception { final String html = "<html><head><title>First</title></head>\n" + "<body>\n" + "<form><input type='button' name='button1' value='pushme'></form>\n" + "<div>a</div> <div>b</div> <div>c</div>\n" + "</body></html>"; final HtmlPage page = loadPage(html); final HtmlElement body = page.getBody(); NodeList inputs = body.getElementsByTagName("input"); assertEquals(1, inputs.getLength()); assertEquals("button", inputs.item(0).getAttributes().getNamedItem("type").getNodeValue()); final NodeList divs = body.getElementsByTagName("div"); assertEquals(3, divs.getLength()); final HtmlDivision newDiv = new HtmlDivision(HtmlDivision.TAG_NAME, page, null); body.appendChild(newDiv); assertEquals(4, divs.getLength()); // case sensitive inputs = page.getElementsByTagName("inPUT"); assertEquals(1, inputs.getLength()); // empty inputs = page.getElementsByTagName(""); assertEquals(0, inputs.getLength()); // null inputs = page.getElementsByTagName(null); assertEquals(0, inputs.getLength()); } /** * @throws Exception if the test fails */ @Test public void getElementsByAttribute() throws Exception { final String html = "<html>\n" + "<head></head>\n" + "<body>\n" + "<form id='myForm'>\n" + " <input type='button' name='buttonName' value='pushme'>\n" + " <select id='selectId' multiple>\n" + " <option value='option1' id='option1' selected>Option1</option>\n" + " <option value='option2' id='option2' selected='selected'>Option2</option>\n" + " </select>\n" + "</form>\n" + "</body></html>"; final HtmlPage page = loadPage(html); final HtmlElement form = page.getHtmlElementById("myForm"); List<HtmlElement> elements = form.getElementsByAttribute("input", "value", "pushme"); assertEquals(1, elements.size()); assertEquals("<input type=\"button\" name=\"buttonName\" value=\"pushme\"/>", elements.get(0).asXml().replaceAll("\\r|\\n", "")); // ignore case elements = form.getElementsByAttribute("iNPuT", "value", "pushme"); assertEquals(1, elements.size()); assertEquals("<input type=\"button\" name=\"buttonName\" value=\"pushme\"/>", elements.get(0).asXml().replaceAll("\\r|\\n", "")); // attribute value is case sensitive elements = form.getElementsByAttribute("input", "value", "pushMe"); assertEquals(0, elements.size()); // selected='selected' elements = form.getElementsByAttribute("option", "selected", "selected"); assertEquals(1, elements.size()); assertEquals("<option value=\"option2\" id=\"option2\" selected=\"selected\"> Option2</option>", elements.get(0).asXml().replaceAll("\\r|\\n", "")); // selected elements = form.getElementsByAttribute("option", "selected", ""); assertEquals(1, elements.size()); assertEquals("<option value=\"option1\" id=\"option1\" selected=\"\"> Option1</option>", elements.get(0).asXml().replaceAll("\\r|\\n", "")); } /** * @throws Exception if an error occurs */ @Test public void serialization() throws Exception { final String html = "<html><body><div id='d' a='b'></div></body></html>"; HtmlPage page = loadPage(html); assertEquals("b", page.getElementById("d").getAttribute("a")); page = clone(page); assertEquals("b", page.getElementById("d").getAttribute("a")); } /** * Ensure that we don't escape when not needed. * @throws Exception on test failure */ @Test public void asXml() throws Exception { final String html = "<html>\n" + "<head>\n" + " <title>test</title>\n" + "</head>\n" + "<body>Welcome\n" + "<div id='div1' onclick=\"alert('hello')\">click me</div>\n" + "<div id='div2' onclick='alert(\"hello again\")'>click me again</div>\n" + "</body>\n" + "</html>"; final HtmlPage page = loadPage(html); final String htmlDiv1XML = "<div id=\"div1\" onclick=\"alert('hello')\">\r\n click me" + "\r\n</div>\r\n"; assertEquals(htmlDiv1XML, page.getElementById("div1").asXml()); final String htmlDiv2XML = "<div id=\"div2\" onclick=\"alert(&quot;hello again&quot;)\">\r\n click me again" + "\r\n</div>\r\n"; assertEquals(htmlDiv2XML, page.getElementById("div2").asXml()); } /** * @throws Exception if the test fails */ @Test @Alerts("false") public void isDisplayed() throws Exception { final String html = "<html><head>\n" + "</head>\n" + "</body>\n" + "<div id='d1'>hello</div>\n" + "<div id='d2' hidden>world</div>\n" + "</body></html>"; getWebClient().getOptions().setJavaScriptEnabled(false); final HtmlPage page = loadPage(html); assertTrue(page.getElementById("d1").isDisplayed()); assertEquals(Boolean.parseBoolean(getExpectedAlerts()[0]), page.getElementById("d2").isDisplayed()); } }
package com.planet_ink.coffee_mud.core.collections; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2003-2021 Bo Zimmerman 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. */ public class DVector implements Cloneable, NList<Object>, java.io.Serializable { public static final long serialVersionUID=43353454350L; protected int dimensions=1; private final SVector<Object[]> stuff; private final static int MAX_SIZE=9; public final static DVector empty = new DVector(1); public DVector(final int dim) { if(dim<1) throw new java.lang.IndexOutOfBoundsException(); if(dim>MAX_SIZE) throw new java.lang.IndexOutOfBoundsException(); dimensions=dim; stuff=new SVector<Object[]>(1); } public DVector(final int dim, final int startingSize) { if(dim<1) throw new java.lang.IndexOutOfBoundsException(); if(dim>MAX_SIZE) throw new java.lang.IndexOutOfBoundsException(); dimensions=dim; stuff=new SVector<Object[]>(startingSize); } @Override public synchronized void clear() { stuff.clear(); } @Override public synchronized void trimToSize() { stuff.trimToSize(); } @Override public synchronized int indexOf(final Object O) { int x=0; if(O==null) { for(final Enumeration<Object[]> e=stuff.elements();e.hasMoreElements();x++) if(e.nextElement()[0]==null) return x; } else for(final Enumeration<Object[]> e=stuff.elements();e.hasMoreElements();x++) { if(O.equals(e.nextElement()[0])) return x; } return -1; } @Override public synchronized Object[] elementsAt(final int x) { if((x<0)||(x>=stuff.size())) throw new java.lang.IndexOutOfBoundsException(); return stuff.elementAt(x); } @Override public synchronized Object[] removeElementsAt(final int x) { if((x<0)||(x>=stuff.size())) throw new java.lang.IndexOutOfBoundsException(); final Object[] O=stuff.elementAt(x); stuff.removeElementAt(x); return O; } @Override public synchronized DVector copyOf() { final DVector V=new DVector(dimensions); if(stuff!=null) { for (final Object[] name : stuff) V.stuff.addElement(name.clone()); } return V; } @Override public synchronized void sortBy(int dim) { if((dim<1)||(dim>dimensions)) throw new java.lang.IndexOutOfBoundsException(); dim--; if(stuff!=null) { final int d=dim; final List<Object[]> subStuff=new ArrayList<Object[]>(stuff.size()); subStuff.addAll(stuff); Collections.sort(subStuff,new Comparator<Object[]>(){ @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public int compare(final Object[] o1, final Object[] o2) { final Object oo1=o1[d]; final Object oo2=o2[d]; if(oo1 == oo2) return 0; if(oo1==null) { if(oo2==null) return 0; return -1; } else if(oo2==null) return 1; if(oo1 instanceof Comparable) return ((Comparable)oo1).compareTo(oo2); return Integer.valueOf(oo1.hashCode()).compareTo(Integer.valueOf(oo2.hashCode())); } }); stuff.clear(); stuff.addAll(subStuff); } } public synchronized void sortBy(final Comparator<Object[]> comparator) { if(stuff!=null) { final List<Object[]> subStuff=new ArrayList<Object[]>(stuff.size()); subStuff.addAll(stuff); Collections.sort(subStuff,comparator); stuff.clear(); stuff.addAll(subStuff); } } public static DVector toNVector(final Map<? extends Object,? extends Object> h) { final DVector DV=new DVector(2); for(final Object key : h.keySet()) { DV.addElement(key,h.get(key)); } return DV; } @Override public synchronized void addSharedElements(final Object[] O) { if(dimensions!=O.length) throw new java.lang.IndexOutOfBoundsException(); stuff.addElement(O); } @Override public synchronized void addElement(final Object... Os) { if(dimensions!=Os.length) throw new java.lang.IndexOutOfBoundsException(); stuff.addElement(Os); } @Override public synchronized void add(final Object... Os) { if(dimensions!=Os.length) throw new java.lang.IndexOutOfBoundsException(); stuff.addElement(Os); } @Override public boolean contains(final Object O) { return indexOf(O)>=0; } @Override public synchronized boolean containsIgnoreCase(final String S) { if(S==null) return indexOf(null)>=0; for (final Object[] name : stuff) { if(S.equalsIgnoreCase(name[0].toString())) return true; } return false; } @Override public int size() { return stuff.size(); } @Override public synchronized void removeElementAt(final int i) { if(i>=0) stuff.removeElementAt(i); } @Override public synchronized void remove(final int i) { if(i>=0) stuff.removeElementAt(i); } @Override public synchronized void removeElement(final Object O) { removeElementAt(indexOf(O)); } @Override public synchronized List<Object> getDimensionList(final int dim) { final Vector<Object> V=new Vector<Object>(stuff.size()); if(dimensions<dim) throw new java.lang.IndexOutOfBoundsException(); for (final Object[] name : stuff) V.addElement(name[dim-1]); return V; } @Override public synchronized List<Object> getRowList(final int row) { final Vector<Object> V=new Vector<Object>(dimensions); final Object[] O=elementsAt(row); for (final Object element : O) V.add(element); return V; } @Override public synchronized Object elementAt(final int i, final int dim) { if(dimensions<dim) throw new java.lang.IndexOutOfBoundsException(); return (stuff.elementAt(i))[dim-1]; } @Override public synchronized Object get(final int i, final int dim) { if(dimensions<dim) throw new java.lang.IndexOutOfBoundsException(); return (stuff.elementAt(i))[dim-1]; } @Override public synchronized void setElementAt(final int index, final int dim, final Object O) { if(dimensions<dim) throw new java.lang.IndexOutOfBoundsException(); stuff.elementAt(index)[dim-1]=O; } @Override public synchronized void set(final int index, final int dim, final Object O) { if(dimensions<dim) throw new java.lang.IndexOutOfBoundsException(); stuff.elementAt(index)[dim-1]=O; } @Override public synchronized void insertElementAt(final int here, final Object... Os) { if(dimensions!=Os.length) throw new java.lang.IndexOutOfBoundsException(); stuff.insertElementAt(Os,here); } @Override public synchronized void add(final int here, final Object... Os) { if(dimensions!=Os.length) throw new java.lang.IndexOutOfBoundsException(); stuff.insertElementAt(Os,here); } }
package net.ethobat.system0.api.registry; import net.ethobat.system0.api.energy.EnergyType; import net.ethobat.system0.api.gui.widgets.GUIWidget; import net.ethobat.system0.api.progression.ProgressItem; import net.ethobat.system0.api.psionics.PsionicSchema; import net.minecraft.util.Identifier; import java.lang.reflect.Method; import java.util.Collection; import java.util.HashMap; public class S0Registry<T> { public static final S0Registry<PsionicSchema> SCHEMA = new S0Registry<>(); public static final S0Registry<EnergyType> ENERGY_TYPE = new S0Registry<>(); public static final S0Registry<ProgressItem> PROGRESSION = new S0Registry<>(); public static final S0Registry<Class<? extends GUIWidget>> WIDGETS = new S0Registry<>(); private final HashMap<Identifier, T> REGISTRY; public S0Registry() { this.REGISTRY = new HashMap<>(); } public T get(Identifier id) { return this.REGISTRY.get(id); } public T register(T obj, Identifier id) { return this.REGISTRY.put(id, obj); } public Collection<T> getAll() { System.out.println("Schema registry contents: "+this.REGISTRY.values().toString()); return this.REGISTRY.values(); } }
/* * (C) Copyright 2015-2021, by Fabian Späh and Contributors. * * JGraphT : a free Java graph-theory library * * See the CONTRIBUTORS.md file distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0, or the * GNU Lesser General Public License v2.1 or later * which is available at * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html. * * SPDX-License-Identifier: EPL-2.0 OR LGPL-2.1-or-later */ package org.jgrapht.alg.isomorphism; import org.jgrapht.*; import java.util.*; /** * This is an implementation of the VF2 algorithm using its feature of detecting * <a href="http://mathworld.wolfram.com/GraphIsomorphism.html">isomorphism between two graphs</a> * as described in Cordella et al. A (sub)graph isomorphism algorithm for matching large graphs * (2004), DOI:10.1109/TPAMI.2004.75, * <a href="http://ieeexplore.ieee.org/xpl/articleDetails.jsp?arnumber=1323804"> * http://ieeexplore.ieee.org/xpl/articleDetails.jsp?arnumber=1323804</a> * * <p> * This implementation of the VF2 algorithm does not support graphs with multiple edges. * * @param <V> the type of the vertices * @param <E> the type of the edges */ public class VF2GraphIsomorphismInspector<V, E> extends VF2AbstractIsomorphismInspector<V, E> { /** * Construct a new VF2 isomorphism inspector. * * @param graph1 the first graph * @param graph2 the second graph * @param vertexComparator comparator for semantic equivalence of vertices * @param edgeComparator comparator for semantic equivalence of edges * @param cacheEdges if true, edges get cached for faster access */ public VF2GraphIsomorphismInspector( Graph<V, E> graph1, Graph<V, E> graph2, Comparator<V> vertexComparator, Comparator<E> edgeComparator, boolean cacheEdges) { super(graph1, graph2, vertexComparator, edgeComparator, cacheEdges); } /** * Construct a new VF2 isomorphism inspector. * * @param graph1 the first graph * @param graph2 the second graph * @param vertexComparator comparator for semantic equivalence of vertices * @param edgeComparator comparator for semantic equivalence of edges */ public VF2GraphIsomorphismInspector( Graph<V, E> graph1, Graph<V, E> graph2, Comparator<V> vertexComparator, Comparator<E> edgeComparator) { super(graph1, graph2, vertexComparator, edgeComparator, true); } /** * Construct a new VF2 isomorphism inspector. * * @param graph1 the first graph * @param graph2 the second graph * @param cacheEdges if true, edges get cached for faster access */ public VF2GraphIsomorphismInspector(Graph<V, E> graph1, Graph<V, E> graph2, boolean cacheEdges) { super(graph1, graph2, null, null, cacheEdges); } /** * Construct a new VF2 isomorphism inspector. * * @param graph1 the first graph * @param graph2 the second graph */ public VF2GraphIsomorphismInspector(Graph<V, E> graph1, Graph<V, E> graph2) { super(graph1, graph2, true); } @Override public VF2GraphMappingIterator<V, E> getMappings() { return new VF2GraphMappingIterator<>( ordering1, ordering2, vertexComparator, edgeComparator); } }
/* Derby - Class org.apache.derby.iapi.services.locks.CompatibilitySpace 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.derby.iapi.services.locks; /** * <p> This interface must be implemented by objects returned from * <code>LockFactory.createCompatibilitySpace()</code>. </p> * * <p> A <code>CompatibilitySpace</code> can have an owner (for instance a * transaction). Currently, the owner is used by the virtual lock table to find * out which transaction a lock belongs to. Some parts of the code also use the * owner as a group object which guarantees that the lock is released on a * commit or an abort. The owner has no special meaning to the lock manager and * can be any object, including <code>null</code>. </p> * * @see LockFactory#createCompatibilitySpace */ public interface CompatibilitySpace { /** * Gets an object representing the owner of the compatibility space. * * @return object representing the owner of the compatibility space, or * <code>null</code> if no owner has been specified. */ LockOwner getOwner(); }
package org.tabchanj.aladdin.controller.impl; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Controller @RequestMapping("/login/") public class LoginController { @RequestMapping("login") public String index(HttpServletRequest request, HttpServletResponse response) { return "login"; } }
package com.matianl.explore.java7concurrency.Chapter7.ch7_recipe05.src.com.packtpub.java7.concurrency.chapter7.recipe05.task; import java.util.concurrent.TimeUnit; /** * Runnable object to check the MyScheduledTask and MyScheduledThreadPoolExecutor classes. * */ public class Task implements Runnable { /** * Main method of the task. Writes a message, sleeps the current thread for two seconds and * writes another message */ @Override public void run() { System.out.printf("Task: Begin.\n"); try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } System.out.printf("Task: End.\n"); } }
/** * Copyright 2015 Internet2 * * 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 edu.internet2.middleware.grouper.internal.dao; import java.util.List; import java.util.Set; import edu.internet2.middleware.grouper.messaging.GrouperMessageHibernate; /** * Basic <code>Message</code> DAO interface. * @author chris hyzer. * @version $Id: MemberDAO.java,v 1.11 2009-12-28 06:08:37 mchyzer Exp $ * @since 2.3 */ public interface MessageDAO extends GrouperDAO { /** * find a list by the from member id * @param fromMemberId * @return the set */ public Set<GrouperMessageHibernate> findByFromMemberId(String fromMemberId); /** * find messages by queue * @param queue * @param pageSize * @return collection of grouper messages */ public List<GrouperMessageHibernate> findByQueue(String queue, int pageSize); /** * @param id * @param exceptionIfNotFound * @return the message */ public GrouperMessageHibernate findById(String id, boolean exceptionIfNotFound); /** * save the object to the database * @param message */ public void saveOrUpdate(GrouperMessageHibernate message); /** * delete the object from the database * @param message */ public void delete(GrouperMessageHibernate message); }
/* * 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.storm.utils.staticmocking; import org.apache.storm.utils.Utils; public class UtilsInstaller implements AutoCloseable { private Utils _oldInstance; private Utils _curInstance; public UtilsInstaller(Utils instance) { _oldInstance = Utils.setInstance(instance); _curInstance = instance; } @Override public void close() throws Exception { if (Utils.setInstance(_oldInstance) != _curInstance) { throw new IllegalStateException( "Instances of this resource must be closed in reverse order of opening."); } } }
/* * 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.ambari.logsearch.web.filters; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.ambari.logsearch.conf.AuthPropsConfig; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint; public class LogsearchAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint { private static final Logger logger = LogManager.getLogger(LogsearchAuthenticationEntryPoint.class); private final AuthPropsConfig authPropsConfig; public LogsearchAuthenticationEntryPoint(String loginFormUrl, AuthPropsConfig authPropsConfig) { super(loginFormUrl); this.authPropsConfig = authPropsConfig; } @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { if (!authPropsConfig.isAuthJwtEnabled()) { // TODO: find better solution if JWT enabled, as it always causes an basic auth failure before JWT auth logger.debug("Got 401 from request: {}", request.getRequestURI()); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } }
package org.support.project.knowledge.logic; import java.io.IOException; import java.lang.invoke.MethodHandles; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.support.project.common.config.Flag; import org.support.project.common.log.Log; import org.support.project.common.log.LogFactory; import org.support.project.common.util.StringUtils; import org.support.project.di.Container; import org.support.project.di.DI; import org.support.project.di.Instance; import org.support.project.knowledge.config.AppConfig; import org.support.project.knowledge.dao.WebhookConfigsDao; import org.support.project.knowledge.dao.WebhooksDao; import org.support.project.knowledge.entity.WebhookConfigsEntity; import org.support.project.knowledge.entity.WebhooksEntity; import org.support.project.knowledge.logic.notification.webhook.AbstractWebHookNotification; import org.support.project.knowledge.logic.notification.webhook.CommentInsertWebhookNotification; import org.support.project.knowledge.logic.notification.webhook.CommentLikedWebhookNotification; import org.support.project.knowledge.logic.notification.webhook.EmptyWebHookNotification; import org.support.project.knowledge.logic.notification.webhook.KnowledgeLikedWebHookNotification; import org.support.project.knowledge.logic.notification.webhook.KnowledgeUpdateWebHookNotification; import org.support.project.web.dao.ProxyConfigsDao; import org.support.project.web.entity.ProxyConfigsEntity; @DI(instance = Instance.Singleton) public class WebhookLogic extends HttpLogic { /** ログ */ private static final Log LOG = LogFactory.getLog(MethodHandles.lookup()); public static WebhookLogic get() { return Container.getComp(WebhookLogic.class); } /** webhookの状態:未送信(送信待ち) */ public static final int WEBHOOK_STATUS_UNSENT = 0; /** webhookの状態:なんらかの通信エラーが発生した */ public static final int WEBHOOK_STATUS_ERROR = -1; /** * Webhookの実行 */ public void startNotifyWebhook() { Map<String, List<WebhookConfigsEntity>> configs = getMappedConfigs(); if (0 == configs.size()) { // webhookの設定が登録されていなければ、送信処理は終了 return; } ProxyConfigsDao proxyConfigDao = ProxyConfigsDao.get(); ProxyConfigsEntity proxyConfig = proxyConfigDao.selectOnKey(AppConfig.get().getSystemName()); WebhooksDao dao = WebhooksDao.get(); List<WebhooksEntity> entities = dao.selectOnStatus(WEBHOOK_STATUS_UNSENT); int count = 0; for (WebhooksEntity entity : entities) { try { List<WebhookConfigsEntity> configEntities = configs.get(entity.getHook()); for (WebhookConfigsEntity configEntity : configEntities) { String json = ""; try { json = createJson(entity, configEntity); } catch (Exception e) { LOG.warn("Failed to generate JSON to send webhook. [webhook config]" + configEntity.getHookId() + "[gen data]" + entity.getContent()); } if (StringUtils.isEmpty(json)) { LOG.warn("Failed to generate JSON to send webhook. [webhook config]" + configEntity.getHookId() + "[gen data]" + entity.getContent()); } else { notify(proxyConfig, configEntity, json); } } dao.physicalDelete(entity); count++; } catch (Exception e) { LOG.warn("Failed to send webhook. [webhook id]" + entity.getWebhookId(), e); entity.setStatus(WEBHOOK_STATUS_ERROR); dao.save(entity); } } LOG.info("Webhook sended. count: " + count); } /** * WebHook通知クラスを取得 * @param configEntity * @return */ public AbstractWebHookNotification getWebHookNotification(WebhookConfigsEntity configEntity) { if (configEntity.getHook().equals(WebhookConfigsEntity.HOOK_KNOWLEDGES)) { return KnowledgeUpdateWebHookNotification.get(); } else if (configEntity.getHook().equals(WebhookConfigsEntity.HOOK_COMMENTS)) { return CommentInsertWebhookNotification.get(); } else if (configEntity.getHook().equals(WebhookConfigsEntity.HOOK_LIKED_KNOWLEDGE)) { return KnowledgeLikedWebHookNotification.get(); } else if (configEntity.getHook().equals(WebhookConfigsEntity.HOOK_LIKED_COMMENT)) { return CommentLikedWebhookNotification.get(); } return new EmptyWebHookNotification(); } /** * JSON生成のテンプレートを読み出す * @param configEntity * @return * @throws Exception */ public String loadTemplate(WebhookConfigsEntity configEntity) throws Exception { return getWebHookNotification(configEntity).loadTemplate(configEntity); } /** * 送信するJSONを生成する * @param entity * @param configEntity * @return */ public String createJson(WebhooksEntity entity, WebhookConfigsEntity configEntity) throws Exception { return getWebHookNotification(configEntity).createSendJson(entity, configEntity); } /** * 設定を返す * @return */ private Map<String, List<WebhookConfigsEntity>> getMappedConfigs() { Map<String, List<WebhookConfigsEntity>> hooks = new HashMap<String, List<WebhookConfigsEntity>>(); WebhookConfigsDao webhookConfigsDao = WebhookConfigsDao.get(); List<WebhookConfigsEntity> entities = webhookConfigsDao.selectAll(); if (0 == entities.size()) { return hooks; } // TODO 後でリファクタリング(WebHookの種類を追加する毎に、ロジックを修正しなくてはいけなくて面倒) List<WebhookConfigsEntity> knowledgeHooks = new ArrayList<WebhookConfigsEntity>(); List<WebhookConfigsEntity> commentHooks = new ArrayList<WebhookConfigsEntity>(); List<WebhookConfigsEntity> likedHooks = new ArrayList<WebhookConfigsEntity>(); List<WebhookConfigsEntity> likedCommentHooks = new ArrayList<WebhookConfigsEntity>(); for (WebhookConfigsEntity entity : entities) { if (WebhookConfigsEntity.HOOK_KNOWLEDGES.equals(entity.getHook())) { knowledgeHooks.add(entity); } else if (WebhookConfigsEntity.HOOK_COMMENTS.equals(entity.getHook())) { commentHooks.add(entity); } else if (WebhookConfigsEntity.HOOK_LIKED_KNOWLEDGE.equals(entity.getHook())) { likedHooks.add(entity); } else if (WebhookConfigsEntity.HOOK_LIKED_COMMENT.equals(entity.getHook())) { likedCommentHooks.add(entity); } } hooks.put(WebhookConfigsEntity.HOOK_KNOWLEDGES, knowledgeHooks); hooks.put(WebhookConfigsEntity.HOOK_COMMENTS, commentHooks); hooks.put(WebhookConfigsEntity.HOOK_LIKED_KNOWLEDGE, likedHooks); hooks.put(WebhookConfigsEntity.HOOK_LIKED_COMMENT, likedCommentHooks); return hooks; } /** * 通知を送る * * @param proxyConfig * @param webhookConfig * @param json * @throws Exception */ public void notify(ProxyConfigsEntity proxyConfig, WebhookConfigsEntity webhookConfig, String json) throws Exception { URI uri = new URI(webhookConfig.getUrl()); // HttpClient生成 if (Flag.is(webhookConfig.getIgnoreProxy())) { this.httpclient = createHttpClient(null); // IgnoreProxy が ON の場合、Proxy設定を使わない } else { this.httpclient = createHttpClient(proxyConfig); } HttpPost httpPost = new HttpPost(uri); httpPost.addHeader("Content-type", "application/json"); httpPost.setEntity(new StringEntity(json, StandardCharsets.UTF_8)); try { ResponseHandler<ResponseData> responseHandler = new HttpResponseHandler(uri); HttpResponse response = httpclient.execute(httpPost); ResponseData responseData = responseHandler.handleResponse(response); if (responseData.statusCode != HttpStatus.SC_OK) { LOG.error("Request failed: statusCode -> " + responseData.statusCode); } else { LOG.info("Request success: " + responseData.statusCode); } } catch (Exception e) { // HttpClientをクリア httpPost.abort(); httpPost.releaseConnection(); this.httpclient = null; throw e; } finally { if (this.httpclient != null) { httpPost.abort(); httpPost.releaseConnection(); } } } /** * ResponseHandlerが返すレスポンスを解析した結果のオブジェクト * * @author nagodon */ protected class ResponseData { public Integer statusCode; } /** * HTTPのレスポンスを処理するResponseHandler * * @author nagodon */ protected class HttpResponseHandler implements ResponseHandler<ResponseData> { URI uri; /** * @param url */ public HttpResponseHandler(URI uri) { super(); this.uri = uri; } @Override public ResponseData handleResponse(HttpResponse response) throws ClientProtocolException, IOException { ResponseData responseData = new ResponseData(); StatusLine statusLine = response.getStatusLine(); responseData.statusCode = statusLine.getStatusCode(); return responseData; } } }
/* * Copyright 2020 TiKV Project 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.tikv.txn; public class TxnExpireTime { private boolean initialized = false; private long txnExpire = 0; public TxnExpireTime() {} public TxnExpireTime(boolean initialized, long txnExpire) { this.initialized = initialized; this.txnExpire = txnExpire; } public void update(long lockExpire) { if (lockExpire < 0) { lockExpire = 0; } if (!this.initialized) { this.txnExpire = lockExpire; this.initialized = true; return; } if (lockExpire < this.txnExpire) { this.txnExpire = lockExpire; } } public long value() { if (!this.initialized) { return 0L; } else { return this.txnExpire; } } }
/* This code is from exercise sheet written by Dr. Steve Maddock */ package gmaths; /** * A class for a 2D vector. * This includes two components: x and y. * * @author Dr Steve Maddock * @version 1.0 (01/10/2017) */ public final class Vec2 { public float x; public float y; /** * Constructor. */ public Vec2() { this(0, 0); } /** * Constructor. * * @param x x value for the 2D vector. * @param y y value for the 2D vector. */ public Vec2(float x, float y) { this.x = x; this.y = y; } /** * Constructor. * * @param v 2D vector used to initialise the values of this vector. */ public Vec2(Vec2 v) { x = v.x; y = v.y; } /** * Calculates and returns the length of the vector. * * @return The length (= magnitude) of the vector. */ public float length() { return magnitude(); } /** * Calculates and returns the magnitude of the vector. * * @return The magnitude (= length) of the vector. */ public float magnitude() { return magnitude(this); } /** * Calculates and returns the magnitude of the vector. * * @param v The 2D vector to calculate teh magnitude of. * @return The magnitude (= length) of the supplied vector. */ public static float magnitude(Vec2 v) { return (float) Math.sqrt(v.x * v.x + v.y * v.y); } /** * Normalizes the vector. The vector is updated accordingly. */ public void normalize() { float mag = magnitude(); // fails if mag = 0 x /= mag; y /= mag; } /** * Normalizes the vector that is supplied a parameter and returns the new normalized vector as the result. * * @param v The 2D vector to normalize. * @return The normalized version of vector v */ public static Vec2 normalize(Vec2 v) { float mag = magnitude(v); // fails if mag = 0 return new Vec2(v.x / mag, v.y / mag); } /** * Adds the supplied vector v to this vector and stores the result in this vector. * * @param v The 2D vector to be added. */ public void add(Vec2 v) { x += v.x; y += v.y; } /** * Adds the supplied vectors (a+b) and returns the resulting vector. * * @param a The first 2D vector * @param b The second 2D vector, which is added to the first vector. * @return The result of a+b */ public static Vec2 add(Vec2 a, Vec2 b) { return new Vec2(a.x + b.x, a.y + b.y); } /** * Subtracts the supplied vector v from this vector and stores the result in this vector * * @param v The 2D vector to be subtracted. */ public void subtract(Vec2 v) { x -= v.x; y -= v.y; } /** * Subtracts the supplied vectors (a-b) and returns the resulting vector. * * @param a The first 2D vector * @param b The second 2D vector, which is subtracted from the first vector. * @return The result of a-b */ public static Vec2 subtract(Vec2 a, Vec2 b) { return new Vec2(a.x - b.x, a.y - b.y); } /** * Calculates the dot product between this vector and the supplied vector * * @param v The vector to be used in the dot product. * @return The result of the dot product. */ public float dotProduct(Vec2 v) { return dotProduct(this, v); } /** * Calculates the dot product between vectors a and b and returns the result. * * @param a A 2D vector to be used in the dot product. * @param b A 2D vector to be used in the dot product. * @return The result of the dot product. */ public static float dotProduct(Vec2 a, Vec2 b) { return a.x * b.x + a.y * b.y; } /** * Each component of this vector is multiplied by f. * * @param f The floating point value to multiple this vector by. */ public void multiply(float f) { x *= f; y *= f; } /** * Each component of the vector v is multiplied by f. * * @param v The vector. * @param f The floating point value to multiple the vector by. * @return The result: (v.x*f, v.y*f). */ public static Vec2 multiply(Vec2 v, float f) { return new Vec2(v.x * f, v.y * f); } /** * Creates a String from the vector's components. * * @return A String representing the vector. */ public String toString() { return "(" + x + "," + y + ")"; } } // end of Vec2 class
package edu.utexas.clm.reconstructreader.reconstruct; import edu.utexas.clm.reconstructreader.Utils; import org.w3c.dom.Element; import java.util.ArrayList; public class ReconstructZTrace implements ContourSet { private final int oid; private final String name; private final ArrayList<Element> polyLineList; private final ArrayList<Integer> polyLineOIDList; private final ArrayList<Integer> polyLineIDList; private final ReconstructTranslator translator; public ReconstructZTrace(final Element e, final ReconstructTranslator t) { translator = t; oid = translator.nextOID(); name = e.getAttribute("name"); polyLineList = new ArrayList<Element>(); polyLineOIDList = new ArrayList<Integer>(); polyLineIDList = new ArrayList<Integer>(); addContour(e, null); } public void appendProjectXML(final StringBuilder sb) { sb.append("<reconstruct_ztrace id=\"").append(oid).append("\" title=\"") .append(name).append("\" expanded=\"true\">\n"); for (int i = 0; i < polyLineList.size(); ++i) { sb.append("<polyline id=\"").append(polyLineIDList.get(i)).append("\" oid=\"") .append(polyLineOIDList.get(i)).append("\"/>\n"); } sb.append("</reconstruct_ztrace>\n"); } public void appendXML(final StringBuilder sb) { for (int i = 0; i < polyLineList.size(); ++i) { Element e = polyLineList.get(i); double[] pts3D = Utils.createNodeValueVector(e.getAttribute("points")); double[] pts2D, wh; double mag = translator.getMag(); int[] layerID; int n = Utils.nodeValueToVector(e.getAttribute("points"), pts3D); String hexColor = Utils.hexColor(e.getAttribute("border")); if (n != 3) { translator.log("While processing Z-Traces, expected n = 3, but n = " + n); } layerID = new int[pts3D.length / n]; pts2D = new double[layerID.length * 2]; for (int j = 0; j < layerID.length; ++j) { pts2D[j*2] = pts3D[j*n]; pts2D[j*2 + 1] = pts3D[j*n + 1]; layerID[j] = (int)pts3D[j*n + 2]; } for (int j = 0; j < pts2D.length; ++j) { pts2D[j] /= mag; } wh = Utils.getPathExtent(pts2D); sb.append("<t2_polyline\n" + "oid=\"").append(polyLineOIDList.get(i)).append("\"\n" + "width=\"").append(wh[0]).append("\"\n" + "height=\"").append(wh[1]).append("\"\n" + "transform=\"matrix(1.0,0.0,0.0,1.0,0.0,0.0)\"\n" + "title=\"").append(name).append("\"\n" + "links=\"\"\n" + "layer_set_id=\"").append(translator.getLayerSetOID()).append("\"\n" + "style=\"fill:none;stroke-opacity:1.0;stroke:#").append(hexColor) .append(";stroke-width:1.0px;stroke-opacity:1.0\"\n" + "d=\""); Utils.appendOpenPathXML(sb, pts2D); sb.append("\"\n" + "layer_ids=\""); for (int id : layerID) { sb.append(translator.layerIndexToOID(id)).append(","); } sb.append("\"\n>\n</t2_polyline>\n"); } } public void addContour(final Element e, final ReconstructSection sec) { polyLineList.add(e); polyLineOIDList.add(translator.nextOID()); polyLineIDList.add(translator.nextOID()); } public String getName() { return name; } }
/* * Copyright 2015 Henrik Olsson * * 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.meisolsson.githubsdk.model; import android.os.Parcelable; import android.support.annotation.Nullable; import com.meisolsson.githubsdk.model.git.GitCommit; import com.google.auto.value.AutoValue; import com.squareup.moshi.JsonAdapter; import com.squareup.moshi.Moshi; @AutoValue public abstract class ContentCommit implements Parcelable { @Nullable public abstract Content content(); @Nullable public abstract GitCommit commit(); public static JsonAdapter<ContentCommit> jsonAdapter(Moshi moshi) { return new AutoValue_ContentCommit.MoshiJsonAdapter(moshi); } }
package com.kis.data.enums; /** * Created by wanglong on 16-1-30. */ public enum ResultEnum { CODE("code"), ERRORMSG("errMsg"), DATA("data"), OPERFLAG("operationFlag"), CLASSNAME("className"), JSONOBJECT("jsonObject"); ResultEnum(String val) { this.val = val; } private String val; public String getVal() { return val; } public void setVal(String val) { this.val = val; } }
package com.laegler.openbanking.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.springframework.validation.annotation.Validated; import javax.validation.Valid; import javax.validation.constraints.*; /** * RegistrationError */ @Validated @javax.annotation.Generated(value = "class com.laegler.openbanking.codegen.module.OpenbankingSpringCodegen", date = "2019-10-19T13:25:17.080+13:00") public class RegistrationError { /** * Gets or Sets error */ public enum ErrorEnum { INVALID_REDIRECT_URI("invalid_redirect_uri"), INVALID_CLIENT_METADATA("invalid_client_metadata"), INVALID_SOFTWARE_STATEMENT("invalid_software_statement"), UNAPPROVED_SOFTWARE_STATEMENT("unapproved_software_statement"); private String value; ErrorEnum(String value) { this.value = value; } @Override @JsonValue public String toString() { return String.valueOf(value); } @JsonCreator public static ErrorEnum fromValue(String text) { for (ErrorEnum b : ErrorEnum.values()) { if (String.valueOf(b.value).equals(text)) { return b; } } return null; } } @JsonProperty("error") private ErrorEnum error = null; @JsonProperty("error_description") private String errorDescription = null; public RegistrationError error(ErrorEnum error) { this.error = error; return this; } /** * Get error * @return error **/ @ApiModelProperty(required = true, value = "") @NotNull public ErrorEnum getError() { return error; } public void setError(ErrorEnum error) { this.error = error; } public RegistrationError errorDescription(String errorDescription) { this.errorDescription = errorDescription; return this; } /** * Get errorDescription * @return errorDescription **/ @ApiModelProperty(value = "") @Size(min=1,max=500) public String getErrorDescription() { return errorDescription; } public void setErrorDescription(String errorDescription) { this.errorDescription = errorDescription; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RegistrationError registrationError = (RegistrationError) o; return Objects.equals(this.error, registrationError.error) && Objects.equals(this.errorDescription, registrationError.errorDescription); } @Override public int hashCode() { return Objects.hash(error, errorDescription); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class RegistrationError {\n"); sb.append(" error: ").append(toIndentedString(error)).append("\n"); sb.append(" errorDescription: ").append(toIndentedString(errorDescription)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
/* * Copyright (c) 2015. Annie Hui @ RStar Technology Solutions * * 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.rstar.mobile.csc205sp2015.developer; import android.app.Fragment; import android.content.Context; import android.os.AsyncTask; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.rstar.mobile.csc205sp2015.app.AppSettings; import com.rstar.mobile.csc205sp2015.R; import com.rstar.mobile.csc205sp2015.io.IO; import com.rstar.mobile.csc205sp2015.io.Message; import com.rstar.mobile.csc205sp2015.io.Savelog; import com.rstar.mobile.csc205sp2015.module.Module; import java.lang.ref.WeakReference; public class MasterFragment extends Fragment { private static final String TAG = MasterFragment.class.getSimpleName()+"_class"; private static final boolean debug = AppSettings.defaultDebug; public static final String EXTRA_Type = MasterFragment.class.getSimpleName()+".Type"; // Make a copy of the types from activity. Use these locally. private static final int Type_new = MasterApi.request_mastersignup; private static final int Type_existing = MasterApi.request_mastersignin; private static final int Type_passwd = MasterApi.request_masterpasswd; private static final int Type_reset = MasterApi.request_masterunset; private static final int Type_score = MasterApi.request_masterscore; private static final int Type_feedback = MasterApi.request_masterfeedback; private static final int Type_submitted = MasterApi.request_mastersubmitted; public static final int Type_default = MasterApi.request_mastersignup; private static final int field_userId = 0; private static final int field_email = 1; private static final int field_password = 2; private static final int field_newpassword = 3; private static final int field_module = 4; private int mType = Type_default; private String mUserId = ""; private String mEmail = ""; private String mPassword = ""; private String mNewPassword = ""; private int mModuleNumber = Module.DefaultModuleNumber; private String mResponse = ""; private TextView mTypeView = null; private TextView mUserIdLabelView = null; private TextView mEmailLabelView = null; private TextView mPasswordLabelView = null; private TextView mNewPasswordLabelView = null; private TextView mModuleLabelView = null; private TextView mResponseLabelView = null; private EditText mUserIdView = null; private EditText mEmailView = null; private EditText mPasswordView = null; private EditText mNewPasswordView = null; private EditText mModuleView = null; private TextView mResponseView = null; private Button mButton = null; private FieldTextWatcher mUserIdTextWatcher = null; private FieldTextWatcher mEmailTextWatcher = null; private FieldTextWatcher mPasswordTextWatcher = null; private FieldTextWatcher mNewPasswordTextWatcher = null; private FieldTextWatcher mModuleTextWatcher = null; private OkButtonClickedListener mButtonClickedListener = null; private LoginAsyncTask mLoginAsyncTask = null; public static MasterFragment newInstance(int type) { Bundle args = new Bundle(); MasterFragment fragment = new MasterFragment(); args.putInt(EXTRA_Type, type); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Savelog.d(TAG, debug, "onCreate()"); mType = getArguments().getInt(EXTRA_Type, Type_default); if (debug) { mEmail = DeveloperSettings.developerEmail; } setRetainInstance(true); setHasOptionsMenu(true); } // end to implementing onCreate() @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Savelog.d(TAG, debug, "onCreateView()"); // Inflate the layout for this fragment View v = inflater.inflate(R.layout.fragment_master, container, false); mTypeView = (TextView) v.findViewById(R.id.fragmentMaster_type); mUserIdLabelView = (TextView) v.findViewById(R.id.fragmentMaster_userId_label); mEmailLabelView = (TextView) v.findViewById(R.id.fragmentMaster_email_label); mPasswordLabelView = (TextView) v.findViewById(R.id.fragmentMaster_password_label); mNewPasswordLabelView = (TextView) v.findViewById(R.id.fragmentMaster_newpassword_label); mModuleLabelView = (TextView) v.findViewById(R.id.fragmentMaster_module_label); mResponseLabelView = (TextView) v.findViewById(R.id.fragmentMaster_response_label); mUserIdView = (EditText) v.findViewById(R.id.fragmentMaster_userId); mEmailView = (EditText) v.findViewById(R.id.fragmentMaster_email); mPasswordView = (EditText) v.findViewById(R.id.fragmentMaster_password); mNewPasswordView = (EditText) v.findViewById(R.id.fragmentMaster_newpassword); mModuleView = (EditText) v.findViewById(R.id.fragmentMaster_module); mResponseView = (TextView) v.findViewById(R.id.fragmentMaster_response); // Always require userId mUserIdView.setText(mUserId); mUserIdTextWatcher = new FieldTextWatcher(this, field_userId); mUserIdView.addTextChangedListener(mUserIdTextWatcher); mUserIdLabelView.setVisibility(View.VISIBLE); // Some requires password if (mType==Type_new) { mPasswordView.setText(mPassword); mPasswordTextWatcher = new FieldTextWatcher(this, field_password); mPasswordView.addTextChangedListener(mPasswordTextWatcher); } else { mPasswordView.setVisibility(View.GONE); mPasswordLabelView.setVisibility(View.GONE); } // Some requires newPassword if (mType==Type_passwd) { mNewPasswordView.setText(mNewPassword); mNewPasswordTextWatcher = new FieldTextWatcher(this, field_newpassword); mNewPasswordView.addTextChangedListener(mNewPasswordTextWatcher); } else { mNewPasswordView.setVisibility(View.GONE); mNewPasswordLabelView.setVisibility(View.GONE); } // Some requires email if (mType==Type_new) { mEmailView.setText(mEmail); mEmailTextWatcher = new FieldTextWatcher(this, field_email); mEmailView.addTextChangedListener(mEmailTextWatcher); } else { mEmailView.setVisibility(View.GONE); mEmailLabelView.setVisibility(View.GONE); } // Some requires module if (mType==Type_score || mType==Type_feedback || mType==Type_submitted) { mModuleView.setText(Integer.toString(mModuleNumber)); mModuleTextWatcher = new FieldTextWatcher(this, field_module); mModuleView.addTextChangedListener(mModuleTextWatcher); } else { mModuleView.setVisibility(View.GONE); mModuleLabelView.setVisibility(View.GONE); } // All use response mResponseView.setText(mResponse); // set up heading if (mType==Type_new) { mTypeView.setText("Master sign up and create new account"); } else if (mType==Type_existing) { mTypeView.setText("Master sign in to existing account"); } else if (mType== Type_passwd) { mTypeView.setText("Master change password"); } else if (mType==Type_reset) { mTypeView.setText("Master clear password and email."); } else if (mType==Type_score) { mTypeView.setText("Master check score"); } else if (mType==Type_feedback) { mTypeView.setText("Master check feedback"); } else if (mType==Type_submitted) { mTypeView.setText("Master check submitted"); } mButton = (Button) v.findViewById(R.id.fragmentMaster_button); mButtonClickedListener = new OkButtonClickedListener(this, mType); mButton.setOnClickListener(mButtonClickedListener); return v; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.master, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. switch (item.getItemId()) { case R.id.menu_master_new: { // Do not re-open if already there if (mType!=Type_new) ((DeveloperActivity) getActivity()).refreshMasterFragment(Type_new); return true; } case R.id.menu_master_existing: { // Do not re-open if already there if (mType!=Type_existing) ((DeveloperActivity) getActivity()).refreshMasterFragment(Type_existing); return true; } case R.id.menu_master_passwd: { // Do not re-open if already there if (mType!= Type_passwd) ((DeveloperActivity) getActivity()).refreshMasterFragment(Type_passwd); return true; } case R.id.menu_master_reset: { // Do not re-open if already there if (mType!= Type_reset) ((DeveloperActivity) getActivity()).refreshMasterFragment(Type_reset); return true; } case R.id.menu_master_score: { // Do not re-open if already there if (mType!=Type_score) ((DeveloperActivity) getActivity()).refreshMasterFragment(Type_score); return true; } case R.id.menu_master_feedback: { // Do not re-open if already there if (mType!=Type_feedback) ((DeveloperActivity) getActivity()).refreshMasterFragment(Type_feedback); return true; } case R.id.menu_master_submitted: { // Do not re-open if already there if (mType!=Type_submitted) ((DeveloperActivity) getActivity()).refreshMasterFragment(Type_submitted); return true; } // no default action } return super.onOptionsItemSelected(item); } @Override public void onDestroyView() { super.onDestroyView(); if (mUserIdView!=null) { if (mUserIdTextWatcher!=null) { mUserIdView.removeTextChangedListener(mUserIdTextWatcher); } mUserIdView = null; } if (mEmailView!=null) { if (mEmailTextWatcher!=null) { mEmailView.removeTextChangedListener(mEmailTextWatcher); } mEmailView = null; } if (mPasswordView!=null) { if (mPasswordTextWatcher!=null) { mPasswordView.removeTextChangedListener(mPasswordTextWatcher); } mPasswordView = null; } if (mNewPasswordView!=null) { if (mNewPasswordTextWatcher!=null) { mNewPasswordView.removeTextChangedListener(mNewPasswordTextWatcher); } mNewPasswordView = null; } if (mModuleView!=null) { if (mModuleTextWatcher!=null) { mModuleView.removeTextChangedListener(mModuleTextWatcher); } mModuleView = null; } if (mButton!=null) { mButton.setOnClickListener(null); mButton = null; } if (mUserIdTextWatcher!=null) { mUserIdTextWatcher.cleanup(); mUserIdTextWatcher = null; } if (mEmailTextWatcher!=null) { mEmailTextWatcher.cleanup(); mEmailTextWatcher = null; } if (mPasswordTextWatcher!=null) { mPasswordTextWatcher.cleanup(); mPasswordTextWatcher = null; } if (mModuleTextWatcher!=null) { mModuleTextWatcher.cleanup(); mModuleTextWatcher = null; } if (mButtonClickedListener!=null) { mButtonClickedListener.cleanup(); mButtonClickedListener = null; } } @Override public void onDestroy() { super.onDestroy(); if (mLoginAsyncTask!=null) { mLoginAsyncTask.cancel(true); mLoginAsyncTask = null; } } private void updateResponse(String data) { if (data!=null) { mResponse = data; mResponseView.setText(mResponse); mResponseView.setVisibility(View.VISIBLE); mResponseLabelView.setVisibility(View.VISIBLE); } } private static class FieldTextWatcher implements TextWatcher { MasterFragment hostFragment; int field; public FieldTextWatcher(MasterFragment hostFragment, int field) { super(); this.hostFragment = hostFragment; this.field = field; } @Override public void afterTextChanged(Editable arg0) {} @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {} @Override public void onTextChanged(CharSequence c, int start, int before, int count) { String data = ""; if (c!=null && c.toString().trim().length()>0) { data = c.toString().trim(); } if (field==field_userId) { hostFragment.mUserId = data; } else if (field==field_email) { hostFragment.mEmail = data; } else if (field==field_password) { hostFragment.mPassword = data; } else if (field==field_newpassword) { hostFragment.mNewPassword = data; } else if (field==field_module) { if (data.length()==0) hostFragment.mModuleNumber = Module.DefaultModuleNumber; else hostFragment.mModuleNumber = Integer.valueOf(data); } } public void cleanup() { hostFragment = null; } } private static class OkButtonClickedListener implements View.OnClickListener { MasterFragment hostFragment; int type; public OkButtonClickedListener(MasterFragment hostFragment, int type) { super(); this.hostFragment = hostFragment; this.type = type; } @Override public void onClick(View view) { Savelog.d(TAG, debug, "Going to login: userid=" + hostFragment.mUserId + " password="+ hostFragment.mPassword + " newPassword="+ hostFragment.mNewPassword + " email="+ hostFragment.mEmail + " module=" + hostFragment.mModuleNumber + " type="+hostFragment.mType); if (hostFragment.mLoginAsyncTask ==null || hostFragment.mLoginAsyncTask.isCancelled() || hostFragment.mLoginAsyncTask.getStatus().equals(AsyncTask.Status.FINISHED)) { // If not already running, then start it. hostFragment.mLoginAsyncTask = new LoginAsyncTask(hostFragment, type); hostFragment.mLoginAsyncTask.execute(); } } public void cleanup() { hostFragment = null; } } private static class LoginAsyncTask extends AsyncTask<Object, Void, Boolean> { private Context appContext; private final WeakReference<MasterFragment> hostFragmentReference; int type; String userId = ""; String email = ""; String password = ""; String newPassword = ""; int moduleNumber = Module.DefaultModuleNumber; MasterApi masterApi = null; Exception err = null; public LoginAsyncTask(MasterFragment hostFragment, int type) { super(); this.appContext = hostFragment.getActivity().getApplicationContext(); hostFragmentReference = new WeakReference<MasterFragment>(hostFragment); this.type = type; this.userId = hostFragment.mUserId; this.email = hostFragment.mEmail; this.password = hostFragment.mPassword; this.newPassword = hostFragment.mNewPassword; this.moduleNumber = hostFragment.mModuleNumber; } @Override protected Boolean doInBackground(Object... args) { try { boolean result = false; if (type==Type_new || type==Type_existing || type==Type_reset || type==Type_passwd) { masterApi = new MasterApi(appContext, userId, password, newPassword, email, type); result = masterApi.isOK(); } else if (type==Type_score || type==Type_feedback || type==Type_submitted) { masterApi = new MasterApi(appContext, userId, moduleNumber, type); result = masterApi.isOK(); } else { // unrecognized type } return result; } catch (Exception e) { err = e; return false; } } @Override protected void onPostExecute(Boolean result) { super.onPostExecute(result); if (hostFragmentReference != null) { final MasterFragment hostFragment = hostFragmentReference.get(); if (hostFragment != null) { if (result) { Savelog.d(TAG, debug, "Result: " + result + " access code = " + masterApi.getAccessCode()); Toast.makeText(hostFragment.getActivity(), Message.toastRequestSuccess, Toast.LENGTH_SHORT).show(); } else { if (err!=null) { if (err instanceof IO.NetworkUnavailableException) { Toast.makeText(hostFragment.getActivity(), Message.toastNoNetwork, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(hostFragment.getActivity(), Message.toastDataUnavailable, Toast.LENGTH_SHORT).show(); } Savelog.e(TAG, "POST failed.\n", err); } else { Toast.makeText(hostFragment.getActivity(), Message.toastRequestFailed, Toast.LENGTH_SHORT).show(); } } if (masterApi!=null) { // now, just update the response hostFragment.updateResponse(masterApi.getData()); } } } Savelog.d(TAG, debug, "AsyncTask completed."); } } }
/* * 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.uima.ruta.ide.core; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.dltk.ast.references.SimpleReference; import org.eclipse.dltk.compiler.SourceElementRequestorAdaptor; import org.eclipse.dltk.compiler.env.MethodSourceCode; import org.eclipse.dltk.core.DLTKCore; import org.eclipse.dltk.core.DLTKLanguageManager; import org.eclipse.dltk.core.ICalleeProcessor; import org.eclipse.dltk.core.IMethod; import org.eclipse.dltk.core.IModelElement; import org.eclipse.dltk.core.ISourceElementParser; import org.eclipse.dltk.core.ISourceModule; import org.eclipse.dltk.core.ModelException; import org.eclipse.dltk.core.search.IDLTKSearchScope; import org.eclipse.dltk.core.search.SearchEngine; import org.eclipse.dltk.core.search.SearchParticipant; import org.eclipse.dltk.core.search.SearchPattern; import org.eclipse.dltk.core.search.SearchRequestor; public class RutaCalleeProcessor implements ICalleeProcessor { protected static int EXACT_RULE = SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE; private Map fSearchResults = new HashMap(); private IMethod method; // private IDLTKSearchScope scope; public RutaCalleeProcessor(IMethod method, IProgressMonitor monitor, IDLTKSearchScope scope) { this.method = method; // this.scope = scope; } private class CaleeSourceElementRequestor extends SourceElementRequestorAdaptor { @Override public void acceptMethodReference(String methodName, int argCount, int sourcePosition, int sourceEndPosition) { String name = new String(methodName); int off = 0; try { off = method.getSourceRange().getOffset(); } catch (ModelException e) { if (DLTKCore.DEBUG) { e.printStackTrace(); } } SimpleReference ref = new SimpleReference(off + sourcePosition, off + sourceEndPosition, name); IMethod[] methods = findMethods(name, argCount, off + sourcePosition); fSearchResults.put(ref, methods); } } public Map doOperation() { try { if (method.getSource() != null) { CaleeSourceElementRequestor requestor = new CaleeSourceElementRequestor(); ISourceElementParser parser = DLTKLanguageManager .getSourceElementParser(RutaNature.NATURE_ID); parser.setRequestor(requestor); parser.parseSourceModule(new MethodSourceCode(method)); } else { // TODO: Report error here. } return fSearchResults; } catch (ModelException e) { if (DLTKCore.DEBUG) { e.printStackTrace(); } } catch (CoreException e) { if (DLTKCore.DEBUG) { e.printStackTrace(); } } return fSearchResults; } public IMethod[] findMethods(final String methodName, int argCount, int sourcePosition) { final List methods = new ArrayList(); ISourceModule module = this.method.getSourceModule(); try { IModelElement[] elements = module.codeSelect(sourcePosition, methodName.length()); for (int i = 0; i < elements.length; ++i) { if (elements[i] instanceof IMethod) { methods.add(elements[i]); } } } catch (ModelException e) { if (DLTKCore.DEBUG) { e.printStackTrace(); } } // final String nsName; // if( methodName.indexOf("::") != -1 ) { // String mmName = methodName; // if( mmName.startsWith("::")) { // mmName = mmName.substring(2); // } // if( mmName.indexOf("::") != -1 ) { // int posb = mmName.indexOf("::"); // nsName = mmName.substring(0, posb); // } // else { // nsName = null; // } // } // else { // nsName = null; // } // SearchRequestor requestor = new SearchRequestor() { // public void acceptSearchMatch(SearchMatch match) throws CoreException // { // Object element = match.getElement(); // if( element instanceof IMethod ) { // IMethod method = (IMethod)element; // String mn = method.getTypeQualifiedName('$', false).replaceAll("\\$", // "::"); // if( mn.equals(methodName) && !isIgnoredBySearchScope(method) ) { // methods.add(method); // } // } // else { // IType type = (IType) element; // if( !( type.getParent() instanceof ISourceModule )) { // return; // } // processTypeFunctions(type); // } // } // private void processTypeFunctions(IType type) throws ModelException { // IMethod[] tmethods = type.getMethods(); // for (int i = 0; i < tmethods.length; ++i) { // String mn = tmethods[i].getTypeQualifiedName('$', // false).replaceAll("\\$", "::"); // if( mn.equals(methodName) && !isIgnoredBySearchScope(tmethods[i]) ) { // methods.add(tmethods[i]); // } // } // IType[] types = type.getTypes(); // for( int i = 0; i < types.length; ++i ) { // processTypeFunctions(types[i]); // } // } // }; // // try { // String pattern = methodName; // if( pattern.startsWith("::")) { // pattern = pattern.substring(2); // } // if( pattern.indexOf("::")==-1) { // search(pattern, IDLTKSearchConstants.METHOD, // IDLTKSearchConstants.DECLARATIONS, scope, requestor); // } // if( nsName != null ) { // search(nsName, IDLTKSearchConstants.TYPE, // IDLTKSearchConstants.DECLARATIONS, scope, requestor); // } // } catch (CoreException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } return (IMethod[]) methods.toArray(new IMethod[methods.size()]); } protected void search(String patternString, int searchFor, int limitTo, IDLTKSearchScope scope, SearchRequestor resultCollector) throws CoreException { search(patternString, searchFor, limitTo, EXACT_RULE, scope, resultCollector); } protected void search(String patternString, int searchFor, int limitTo, int matchRule, IDLTKSearchScope scope, SearchRequestor requestor) throws CoreException { if (patternString.indexOf('*') != -1 || patternString.indexOf('?') != -1) { matchRule |= SearchPattern.R_PATTERN_MATCH; } SearchPattern pattern = SearchPattern.createPattern(patternString, searchFor, limitTo, matchRule, scope.getLanguageToolkit()); new SearchEngine().search(pattern, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, scope, requestor, null); } }
/* * Copyright (c) 2017 seleniumQuery 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 io.github.seleniumquery.by.secondgen.csstree; import io.github.seleniumquery.by.secondgen.csstree.selector.CssSelector; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.stream.Stream; /** * A list of CSS Selectors (objects that represent parsed CSS selectors). * * Each {@link CssSelector} ia a root of a CSS selector object tree. */ public class CssSelectorList { private List<CssSelector> cssSelectors; public CssSelectorList(List<CssSelector> cssSelectors) { this.cssSelectors = Collections.unmodifiableList(new ArrayList<>(cssSelectors)); } public CssSelector firstSelector() { return stream().findFirst().get(); } public Stream<CssSelector> stream() { return cssSelectors.stream(); } }
package com.datastax.oss.driver.shaded.guava.common.util.concurrent; import com.datastax.oss.driver.shaded.guava.common.util.concurrent.RateLimiter.SleepingStopwatch; public class BurstyRateLimiterFactory { public static RateLimiter create(double permitsPerSecond, double maxBurstSeconds) { return create(SleepingStopwatch.createFromSystemTimer(), permitsPerSecond, maxBurstSeconds); } public static RateLimiter create(SleepingStopwatch stopwatch, double permitsPerSecond, double maxBurstSeconds) { RateLimiter rateLimiter = new SmoothRateLimiter.SmoothBursty(stopwatch, maxBurstSeconds /* maxBurstSeconds */); rateLimiter.setRate(permitsPerSecond); return rateLimiter; } }
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package libcore.tlswire.util; import java.io.DataInput; import java.io.IOException; public class IoUtils { public static int readUnsignedInt24(DataInput in) throws IOException { return (in.readUnsignedByte() << 16) | in.readUnsignedShort(); } public static byte[] readTlsVariableLengthByteVector(DataInput in, int maxSizeBytes) throws IOException { int sizeBytes = readTlsVariableLengthVectorSizeBytes(in, maxSizeBytes); byte[] result = new byte[sizeBytes]; in.readFully(result); return result; } public static int[] readTlsVariableLengthUnsignedShortVector(DataInput in, int maxSizeBytes) throws IOException { int sizeBytes = readTlsVariableLengthVectorSizeBytes(in, maxSizeBytes); int elementCount = sizeBytes / 2; int[] result = new int[elementCount]; for (int i = 0; i < elementCount; i++) { result[i] = in.readUnsignedShort(); } return result; } private static int readTlsVariableLengthVectorSizeBytes(DataInput in, int maxSizeBytes) throws IOException { if (maxSizeBytes < 0x100) { return in.readUnsignedByte(); } else if (maxSizeBytes < 0x10000) { return in.readUnsignedShort(); } else if (maxSizeBytes < 0x1000000) { return readUnsignedInt24(in); } else { return in.readInt(); } } }
package com.hedera.hashgraph.stablecoin.app.handler; import com.hedera.hashgraph.stablecoin.app.State; import com.hedera.hashgraph.stablecoin.app.Status; import com.hedera.hashgraph.stablecoin.app.handler.arguments.ExternalTransferTransactionArguments; import com.hedera.hashgraph.stablecoin.proto.TransactionBody; import com.hedera.hashgraph.stablecoin.sdk.Address; public final class ExternalTransferTransactionHandler extends TransactionHandler<ExternalTransferTransactionArguments> { @Override public ExternalTransferTransactionArguments parseArguments(TransactionBody transactionBody) { return new ExternalTransferTransactionArguments(transactionBody); } @Override protected void validatePre(State state, Address caller, ExternalTransferTransactionArguments args) throws StableCoinPreCheckException { // i. Owner != 0x ensureOwnerSet(state); // ii. caller = SupplyManager || caller = Owner ensureSupplyManagerOrOwner(state, caller); // iii. amount >= 0 ensureZeroOrGreater(args.amount, Status.APPROVE_ALLOWANCE_VALUE_LESS_THAN_ZERO); // iv. CheckTransferAllowed(from) ensureTransferAllowed(state, args.from, Status.EXTERNAL_TRANSFER_NOT_ALLOWED); // v. value <= MAX_INT ensureLessThanMaxInt(args.amount, Status.NUMBER_VALUES_LIMITED_TO_256_BITS); // vi. externalAllowanceOf(args.from, args.networkURI, args.to) >= amount var allowance = state.getExternalAllowance(args.from, args.networkURI, args.to.toByteArray()); ensureEqualOrGreater(allowance, args.amount, Status.EXTERNAL_TRANSFER_NOT_ALLOWED); // vii. Balances[from] >= amount ensureEqualOrGreater(state.getBalanceOf(args.from), args.amount, Status.EXTERNAL_TRANSFER_INSUFFICIENT_FROM_BALANCE); // viii. TotalSupply >= Balances[from] ensureEqualOrGreater(state.getTotalSupply(), state.getBalanceOf(args.from), Status.EXTERNAL_TRANSFER_INSUFFICIENT_TOTAL_SUPPLY); } @Override protected void updateState(State state, Address caller, ExternalTransferTransactionArguments args) { // i. TotalSupply’ = TotalSupply - value state.decreaseTotalSupply(args.amount); // ii. Balances[from]’ = Balances[from] - value state.decreaseBalanceOf(args.from, args.amount); // iii. Allowances[(from, networkURI, to)] -= value var allowance = state.getExternalAllowance(args.from, args.networkURI, args.to.toByteArray()); state.setExternalAllowance(args.from, args.networkURI, args.to.toByteArray(), allowance.subtract(args.amount)); } }
package com.deer.wms.message.model; /** * 帮助文档扩展 * @author songyuyang * @create 2017/11/29 */ public class HelpContentDto extends HelpContent { /** * 导航名称 */ private String categoryName; /** * 父级导航id */ private Integer parentId; /** * 父级导航名称 */ private String parentName; public String getCategoryName() { return categoryName; } public void setCategoryName(String categoryName) { this.categoryName = categoryName; } public Integer getParentId() { return parentId; } public void setParentId(Integer parentId) { this.parentId = parentId; } public String getParentName() { return parentName; } public void setParentName(String parentName) { this.parentName = parentName; } }
package com.codingpixel.healingbudz.network.BudzFeedModel.FollowingUserModel; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.List; public class FollowingUserResponse { @SerializedName("status") @Expose private String status; @SerializedName("successMessage") @Expose private String successMessage; @SerializedName("errorMessage") @Expose private String errorMessage; @SerializedName("successData") @Expose private List<FollowingUser> successData = null; public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getSuccessMessage() { return successMessage; } public void setSuccessMessage(String successMessage) { this.successMessage = successMessage; } public List<FollowingUser> getSuccessData() { return successData; } public void setSuccessData(List<FollowingUser> successData) { this.successData = successData; } public String getErrorMessage() { return errorMessage; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } }
/*- * ============LICENSE_START======================================================= * SDC * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END========================================================= */ package org.openecomp.sdc.be.model.jsontitan.operations; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import fj.data.Either; import org.apache.commons.collections.CollectionUtils; import org.apache.tinkerpop.gremlin.structure.Direction; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.apache.tinkerpop.gremlin.structure.VertexProperty; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; import org.openecomp.sdc.be.dao.jsongraph.types.EdgePropertyEnum; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; import org.openecomp.sdc.be.model.ComponentParametersView; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.catalog.CatalogComponent; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.category.SubCategoryDefinition; import org.openecomp.sdc.be.model.jsontitan.datamodel.NodeType; import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate; import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.openecomp.sdc.common.jsongraph.util.CommonUtility; import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.common.util.ValidationUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StopWatch; import java.lang.reflect.Type; import java.util.*; import java.util.Map.Entry; import java.util.stream.Collectors; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; public abstract class ToscaElementOperation extends BaseOperation { private static final String FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR = "failed to fetch {} for tosca element with id {}, error {}"; private static final String CANNOT_FIND_USER_IN_THE_GRAPH_STATUS_IS = "Cannot find user {} in the graph. status is {}"; private static final String FAILED_TO_CREATE_EDGE_WITH_LABEL_FROM_USER_VERTEX_TO_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS = "Failed to create edge with label {} from user vertex {} to tosca element vertex {} on graph. Status is {}. "; private static Logger log = Logger.getLogger(ToscaElementOperation.class.getName()); private static final Gson gson = new Gson(); @Autowired protected CategoryOperation categoryOperation; protected Gson getGson() { return gson; } protected Either<GraphVertex, StorageOperationStatus> getComponentByLabelAndId(String uniqueId, ToscaElementTypeEnum nodeType, JsonParseFlagEnum parseFlag) { Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); propertiesToMatch.put(GraphPropertyEnum.UNIQUE_ID, uniqueId); VertexTypeEnum vertexType = ToscaElementTypeEnum.getVertexTypeByToscaType(nodeType); Either<List<GraphVertex>, TitanOperationStatus> getResponse = titanDao.getByCriteria(vertexType, propertiesToMatch, parseFlag); if (getResponse.isRight()) { log.debug("Couldn't fetch component with type {} and unique id {}, error: {}", vertexType, uniqueId, getResponse.right().value()); return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getResponse.right().value())); } List<GraphVertex> componentList = getResponse.left().value(); if (componentList.isEmpty()) { log.debug("Component with type {} and unique id {} was not found", vertexType, uniqueId); return Either.right(StorageOperationStatus.NOT_FOUND); } GraphVertex vertexG = componentList.get(0); return Either.left(vertexG); } public Either<ToscaElement, StorageOperationStatus> getToscaElement(String uniqueId) { return getToscaElement(uniqueId, new ComponentParametersView()); } public Either<GraphVertex, StorageOperationStatus> markComponentToDelete(GraphVertex componentToDelete) { Either<GraphVertex, StorageOperationStatus> result = null; Boolean isDeleted = (Boolean) componentToDelete.getMetadataProperty(GraphPropertyEnum.IS_DELETED); if (isDeleted != null && isDeleted && !(Boolean) componentToDelete.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION)) { // component already marked for delete result = Either.left(componentToDelete); return result; } else { componentToDelete.addMetadataProperty(GraphPropertyEnum.IS_DELETED, Boolean.TRUE); componentToDelete.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); Either<GraphVertex, TitanOperationStatus> updateNode = titanDao.updateVertex(componentToDelete); StorageOperationStatus updateComponent; if (updateNode.isRight()) { log.debug("Failed to update component {}. status is {}", componentToDelete.getUniqueId(), updateNode.right().value()); updateComponent = DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value()); result = Either.right(updateComponent); return result; } result = Either.left(componentToDelete); return result; } } /** * Performs a shadow clone of previousToscaElement * * @param previousToscaElement * @param nextToscaElement * @param user * @return */ public Either<GraphVertex, StorageOperationStatus> cloneToscaElement(GraphVertex previousToscaElement, GraphVertex nextToscaElement, GraphVertex user) { Either<GraphVertex, StorageOperationStatus> result = null; GraphVertex createdToscaElementVertex = null; TitanOperationStatus status; Either<GraphVertex, TitanOperationStatus> createNextVersionRes = titanDao.createVertex(nextToscaElement); if (createNextVersionRes.isRight()) { status = createNextVersionRes.right().value(); CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create tosca element vertex {} with version {} on graph. Status is {}. ", previousToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), previousToscaElement.getMetadataProperty(GraphPropertyEnum.VERSION), status); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); } if (result == null) { createdToscaElementVertex = createNextVersionRes.left().value(); Map<EdgePropertyEnum, Object> properties = new HashMap<>(); properties.put(EdgePropertyEnum.STATE, createdToscaElementVertex.getMetadataProperty(GraphPropertyEnum.STATE)); status = titanDao.createEdge(user.getVertex(), createdToscaElementVertex.getVertex(), EdgeLabelEnum.STATE, properties); if (status != TitanOperationStatus.OK) { CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_CREATE_EDGE_WITH_LABEL_FROM_USER_VERTEX_TO_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS, EdgeLabelEnum.STATE, user.getUniqueId(), previousToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); } } if (result == null) { status = titanDao.createEdge(user.getVertex(), createdToscaElementVertex.getVertex(), EdgeLabelEnum.LAST_MODIFIER, new HashMap<>()); if (status != TitanOperationStatus.OK) { CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_CREATE_EDGE_WITH_LABEL_FROM_USER_VERTEX_TO_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS, EdgeLabelEnum.LAST_MODIFIER, user.getUniqueId(), nextToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); } } if (result == null) { status = titanDao.createEdge(user.getVertex(), createdToscaElementVertex.getVertex(), EdgeLabelEnum.CREATOR, new HashMap<>()); if (status != TitanOperationStatus.OK) { CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_CREATE_EDGE_WITH_LABEL_FROM_USER_VERTEX_TO_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS, EdgeLabelEnum.CREATOR, user.getUniqueId(), nextToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); } } if (result == null) { Iterator<Edge> edgesToCopyIter = previousToscaElement.getVertex().edges(Direction.OUT); while (edgesToCopyIter.hasNext()) { Edge currEdge = edgesToCopyIter.next(); Vertex currVertex = currEdge.inVertex(); status = titanDao.createEdge(createdToscaElementVertex.getVertex(), currVertex, EdgeLabelEnum.getEdgeLabelEnum(currEdge.label()), currEdge); if (status != TitanOperationStatus.OK) { CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge with label {} from tosca element vertex {} to vertex with label {} on graph. Status is {}. ", currEdge.label(), createdToscaElementVertex.getUniqueId(), currVertex.property(GraphPropertyEnum.LABEL.getProperty()), status); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); break; } } } if (result == null) { result = Either.left(createdToscaElementVertex); } else { CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to clone tosca element {} with the name {}. ", previousToscaElement.getUniqueId(), previousToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME)); } return result; } protected TitanOperationStatus setLastModifierFromGraph(GraphVertex componentV, ToscaElement toscaElement) { Either<GraphVertex, TitanOperationStatus> parentVertex = titanDao.getParentVertex(componentV, EdgeLabelEnum.LAST_MODIFIER, JsonParseFlagEnum.NoParse); if (parentVertex.isRight()) { log.debug("Failed to fetch last modifier for tosca element with id {} error {}", componentV.getUniqueId(), parentVertex.right().value()); return parentVertex.right().value(); } GraphVertex userV = parentVertex.left().value(); String userId = (String) userV.getMetadataProperty(GraphPropertyEnum.USERID); toscaElement.setLastUpdaterUserId(userId); toscaElement.setLastUpdaterFullName(buildFullName(userV)); return TitanOperationStatus.OK; } public String buildFullName(GraphVertex userV) { String fullName = (String) userV.getMetadataProperty(GraphPropertyEnum.FIRST_NAME); if (fullName == null) { fullName = ""; } else { fullName = fullName + " "; } String lastName = (String) userV.getMetadataProperty(GraphPropertyEnum.LAST_NAME); if (lastName != null) { fullName += lastName; } return fullName; } protected TitanOperationStatus setCreatorFromGraph(GraphVertex componentV, ToscaElement toscaElement) { Either<GraphVertex, TitanOperationStatus> parentVertex = titanDao.getParentVertex(componentV, EdgeLabelEnum.CREATOR, JsonParseFlagEnum.NoParse); if (parentVertex.isRight()) { log.debug("Failed to fetch creator for tosca element with id {} error {}", componentV.getUniqueId(), parentVertex.right().value()); return parentVertex.right().value(); } GraphVertex userV = parentVertex.left().value(); String creatorUserId = (String) userV.getMetadataProperty(GraphPropertyEnum.USERID); toscaElement.setCreatorUserId(creatorUserId); toscaElement.setCreatorFullName(buildFullName(userV)); return TitanOperationStatus.OK; } protected <T extends ToscaElement> T getResourceMetaDataFromResource(T toscaElement) { if (toscaElement.getNormalizedName() == null || toscaElement.getNormalizedName().isEmpty()) { toscaElement.setNormalizedName(ValidationUtils.normaliseComponentName(toscaElement.getName())); } if (toscaElement.getSystemName() == null || toscaElement.getSystemName().isEmpty()) { toscaElement.setSystemName(ValidationUtils.convertToSystemName(toscaElement.getName())); } LifecycleStateEnum lifecycleStateEnum = toscaElement.getLifecycleState(); if (lifecycleStateEnum == null) { toscaElement.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); } long currentDate = System.currentTimeMillis(); if (toscaElement.getCreationDate() == null) { toscaElement.setCreationDate(currentDate); } toscaElement.setLastUpdateDate(currentDate); return toscaElement; } protected void fillCommonMetadata(GraphVertex nodeTypeVertex, ToscaElement toscaElement) { if (toscaElement.isHighestVersion() == null) { toscaElement.setHighestVersion(true); } nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_DELETED, toscaElement.getMetadataValue(JsonPresentationFields.IS_DELETED)); nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION, toscaElement.getMetadataValueOrDefault(JsonPresentationFields.HIGHEST_VERSION, Boolean.TRUE)); nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.STATE, toscaElement.getMetadataValue(JsonPresentationFields.LIFECYCLE_STATE)); nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.RESOURCE_TYPE, toscaElement.getMetadataValue(JsonPresentationFields.RESOURCE_TYPE)); nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.VERSION, toscaElement.getMetadataValue(JsonPresentationFields.VERSION)); nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME, toscaElement.getMetadataValue(JsonPresentationFields.NORMALIZED_NAME)); nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, toscaElement.getMetadataValue(JsonPresentationFields.UNIQUE_ID)); nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaElement.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME)); nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.UUID, toscaElement.getMetadataValue(JsonPresentationFields.UUID)); nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_ABSTRACT, toscaElement.getMetadataValue(JsonPresentationFields.IS_ABSTRACT)); nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.INVARIANT_UUID, toscaElement.getMetadataValue(JsonPresentationFields.INVARIANT_UUID)); nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.NAME, toscaElement.getMetadataValue(JsonPresentationFields.NAME)); nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.SYSTEM_NAME, toscaElement.getMetadataValue(JsonPresentationFields.SYSTEM_NAME)); nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_ARCHIVED, toscaElement.getMetadataValue(JsonPresentationFields.IS_ARCHIVED)); nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.ARCHIVE_TIME, toscaElement.getMetadataValue(JsonPresentationFields.ARCHIVE_TIME)); nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_VSP_ARCHIVED, toscaElement.getMetadataValue(JsonPresentationFields.IS_VSP_ARCHIVED)); toscaElement.getMetadata().entrySet().stream().filter(e -> e.getValue() != null).forEach(e -> nodeTypeVertex.setJsonMetadataField(JsonPresentationFields.getByPresentation(e.getKey()), e.getValue())); nodeTypeVertex.setUniqueId(toscaElement.getUniqueId()); nodeTypeVertex.setType(toscaElement.getComponentType()); } protected StorageOperationStatus assosiateToUsers(GraphVertex nodeTypeVertex, ToscaElement toscaElement) { // handle user String userId = toscaElement.getCreatorUserId(); Either<GraphVertex, TitanOperationStatus> findUser = findUserVertex(userId); if (findUser.isRight()) { TitanOperationStatus status = findUser.right().value(); log.error(CANNOT_FIND_USER_IN_THE_GRAPH_STATUS_IS, userId, status); return DaoStatusConverter.convertTitanStatusToStorageStatus(status); } GraphVertex creatorVertex = findUser.left().value(); GraphVertex updaterVertex = creatorVertex; String updaterId = toscaElement.getLastUpdaterUserId(); if (updaterId != null && !updaterId.equals(userId)) { findUser = findUserVertex(updaterId); if (findUser.isRight()) { TitanOperationStatus status = findUser.right().value(); log.error(CANNOT_FIND_USER_IN_THE_GRAPH_STATUS_IS, userId, status); return DaoStatusConverter.convertTitanStatusToStorageStatus(status); } else { updaterVertex = findUser.left().value(); } } Map<EdgePropertyEnum, Object> props = new EnumMap<>(EdgePropertyEnum.class); props.put(EdgePropertyEnum.STATE, (String) toscaElement.getMetadataValue(JsonPresentationFields.LIFECYCLE_STATE)); TitanOperationStatus result = titanDao.createEdge(updaterVertex, nodeTypeVertex, EdgeLabelEnum.STATE, props); log.debug("After associating user {} to resource {}. Edge type is {}", updaterVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.STATE); if (TitanOperationStatus.OK != result) { return DaoStatusConverter.convertTitanStatusToStorageStatus(result); } result = titanDao.createEdge(updaterVertex, nodeTypeVertex, EdgeLabelEnum.LAST_MODIFIER, null); log.debug("After associating user {} to resource {}. Edge type is {}", updaterVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.LAST_MODIFIER); if (!result.equals(TitanOperationStatus.OK)) { log.error("Failed to associate user {} to resource {}. Edge type is {}", updaterVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.LAST_MODIFIER); return DaoStatusConverter.convertTitanStatusToStorageStatus(result); } toscaElement.setLastUpdaterUserId(toscaElement.getCreatorUserId()); toscaElement.setLastUpdaterFullName(toscaElement.getCreatorFullName()); result = titanDao.createEdge(creatorVertex, nodeTypeVertex, EdgeLabelEnum.CREATOR, null); log.debug("After associating user {} to resource {}. Edge type is {} ", creatorVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.CREATOR); if (!result.equals(TitanOperationStatus.OK)) { log.error("Failed to associate user {} to resource {}. Edge type is {} ", creatorVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.CREATOR); return DaoStatusConverter.convertTitanStatusToStorageStatus(result); } return StorageOperationStatus.OK; } protected StorageOperationStatus assosiateResourceMetadataToCategory(GraphVertex nodeTypeVertex, ToscaElement nodeType) { String subcategoryName = nodeType.getCategories().get(0).getSubcategories().get(0).getName(); String categoryName = nodeType.getCategories().get(0).getName(); Either<GraphVertex, StorageOperationStatus> getCategoryVertex = getResourceCategoryVertex(nodeType.getUniqueId(), subcategoryName, categoryName); if (getCategoryVertex.isRight()) { return getCategoryVertex.right().value(); } GraphVertex subCategoryV = getCategoryVertex.left().value(); TitanOperationStatus createEdge = titanDao.createEdge(nodeTypeVertex, subCategoryV, EdgeLabelEnum.CATEGORY, new HashMap<>()); if (createEdge != TitanOperationStatus.OK) { log.trace("Failed to associate resource {} to category {} with id {}", nodeType.getUniqueId(), subcategoryName, subCategoryV.getUniqueId()); return DaoStatusConverter.convertTitanStatusToStorageStatus(createEdge); } return StorageOperationStatus.OK; } protected Either<GraphVertex, StorageOperationStatus> getResourceCategoryVertex(String elementId, String subcategoryName, String categoryName) { Either<GraphVertex, StorageOperationStatus> category = categoryOperation.getCategory(categoryName, VertexTypeEnum.RESOURCE_CATEGORY); if (category.isRight()) { log.trace("Failed to fetch category {} for resource {} error {}", categoryName, elementId, category.right().value()); return Either.right(category.right().value()); } GraphVertex categoryV = category.left().value(); if (subcategoryName != null) { Either<GraphVertex, StorageOperationStatus> subCategory = categoryOperation.getSubCategoryForCategory(categoryV, subcategoryName); if (subCategory.isRight()) { log.trace("Failed to fetch subcategory {} of category for resource {} error {}", subcategoryName, categoryName, elementId, subCategory.right().value()); return Either.right(subCategory.right().value()); } GraphVertex subCategoryV = subCategory.left().value(); return Either.left(subCategoryV); } return Either.left(categoryV); } private StorageOperationStatus associateArtifactsToResource(GraphVertex nodeTypeVertex, ToscaElement toscaElement) { Map<String, ArtifactDataDefinition> artifacts = toscaElement.getArtifacts(); Either<GraphVertex, StorageOperationStatus> status; if (artifacts != null) { artifacts.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> { String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase()); a.setUniqueId(uniqueId); }); status = associateElementToData(nodeTypeVertex, VertexTypeEnum.ARTIFACTS, EdgeLabelEnum.ARTIFACTS, artifacts); if (status.isRight()) { return status.right().value(); } } Map<String, ArtifactDataDefinition> toscaArtifacts = toscaElement.getToscaArtifacts(); if (toscaArtifacts != null) { toscaArtifacts.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> { String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase()); a.setUniqueId(uniqueId); }); status = associateElementToData(nodeTypeVertex, VertexTypeEnum.TOSCA_ARTIFACTS, EdgeLabelEnum.TOSCA_ARTIFACTS, toscaArtifacts); if (status.isRight()) { return status.right().value(); } } Map<String, ArtifactDataDefinition> deploymentArtifacts = toscaElement.getDeploymentArtifacts(); if (deploymentArtifacts != null) { deploymentArtifacts.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> { String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase()); a.setUniqueId(uniqueId); }); status = associateElementToData(nodeTypeVertex, VertexTypeEnum.DEPLOYMENT_ARTIFACTS, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS, deploymentArtifacts); if (status.isRight()) { return status.right().value(); } } return StorageOperationStatus.OK; } protected TitanOperationStatus disassociateAndDeleteCommonElements(GraphVertex toscaElementVertex) { TitanOperationStatus status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ARTIFACTS); if (status != TitanOperationStatus.OK) { log.debug("Failed to disaccociate artifact for {} error {}", toscaElementVertex.getUniqueId(), status); return status; } status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.TOSCA_ARTIFACTS); if (status != TitanOperationStatus.OK) { log.debug("Failed to disaccociate tosca artifact for {} error {}", toscaElementVertex.getUniqueId(), status); return status; } status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS); if (status != TitanOperationStatus.OK) { log.debug("Failed to deployment artifact for {} error {}", toscaElementVertex.getUniqueId(), status); return status; } status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.PROPERTIES); if (status != TitanOperationStatus.OK) { log.debug("Failed to disaccociate properties for {} error {}", toscaElementVertex.getUniqueId(), status); return status; } status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ATTRIBUTES); if (status != TitanOperationStatus.OK) { log.debug("Failed to disaccociate attributes for {} error {}", toscaElementVertex.getUniqueId(), status); return status; } status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ADDITIONAL_INFORMATION); if (status != TitanOperationStatus.OK) { log.debug("Failed to disaccociate additional information for {} error {}", toscaElementVertex.getUniqueId(), status); return status; } status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CAPABILITIES); if (status != TitanOperationStatus.OK) { log.debug("Failed to disaccociate capabilities for {} error {}", toscaElementVertex.getUniqueId(), status); return status; } status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.REQUIREMENTS); if (status != TitanOperationStatus.OK) { log.debug("Failed to disaccociate requirements for {} error {}", toscaElementVertex.getUniqueId(), status); return status; } status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.FORWARDING_PATH); if (status != TitanOperationStatus.OK) { log.debug("Failed to disaccociate requirements for {} error {}", toscaElementVertex.getUniqueId(), status); return status; } return TitanOperationStatus.OK; } protected StorageOperationStatus assosiateCommonForToscaElement(GraphVertex nodeTypeVertex, ToscaElement toscaElement, List<GraphVertex> derivedResources) { StorageOperationStatus associateUsers = assosiateToUsers(nodeTypeVertex, toscaElement); if (associateUsers != StorageOperationStatus.OK) { return associateUsers; } StorageOperationStatus associateArtifacts = associateArtifactsToResource(nodeTypeVertex, toscaElement); if (associateArtifacts != StorageOperationStatus.OK) { return associateArtifacts; } StorageOperationStatus associateProperties = associatePropertiesToResource(nodeTypeVertex, toscaElement, derivedResources); if (associateProperties != StorageOperationStatus.OK) { return associateProperties; } StorageOperationStatus associateAdditionaInfo = associateAdditionalInfoToResource(nodeTypeVertex, toscaElement); if (associateAdditionaInfo != StorageOperationStatus.OK) { return associateAdditionaInfo; } if (needConnectToCatalog(toscaElement)) { StorageOperationStatus associateToCatalog = associateToCatalogRoot(nodeTypeVertex); if (associateToCatalog != StorageOperationStatus.OK) { return associateToCatalog; } } return StorageOperationStatus.OK; } private boolean needConnectToCatalog(ToscaElement toscaElement) { Boolean isAbstract = (Boolean) toscaElement.getMetadataValue(JsonPresentationFields.IS_ABSTRACT); if (isAbstract != null && isAbstract) { return false; } return toscaElement.isHighestVersion(); } private StorageOperationStatus associateToCatalogRoot(GraphVertex nodeTypeVertex) { Either<GraphVertex, TitanOperationStatus> catalog = titanDao.getVertexByLabel(VertexTypeEnum.CATALOG_ROOT); if (catalog.isRight()) { log.debug("Failed to fetch catalog vertex. error {}", catalog.right().value()); return DaoStatusConverter.convertTitanStatusToStorageStatus(catalog.right().value()); } TitanOperationStatus createEdge = titanDao.createEdge(catalog.left().value(), nodeTypeVertex, EdgeLabelEnum.CATALOG_ELEMENT, null); return DaoStatusConverter.convertTitanStatusToStorageStatus(createEdge); } protected StorageOperationStatus associatePropertiesToResource(GraphVertex nodeTypeVertex, ToscaElement nodeType, List<GraphVertex> derivedResources) { // Note : currently only one derived supported!!!! Either<Map<String, PropertyDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.PROPERTIES); if (dataFromDerived.isRight()) { return dataFromDerived.right().value(); } Map<String, PropertyDataDefinition> propertiesAll = dataFromDerived.left().value(); Map<String, PropertyDataDefinition> properties = nodeType.getProperties(); if (properties != null) { properties.values().stream().filter(p -> p.getUniqueId() == null).forEach(p -> { String uid = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId(), p.getName()); p.setUniqueId(uid); }); Either<Map<String, PropertyDataDefinition>, String> eitherMerged = ToscaDataDefinition.mergeDataMaps(propertiesAll, properties); if (eitherMerged.isRight()) { // TODO re-factor error handling - moving BL to operation resulted in loss of info about the invalid property log.debug("property {} cannot be overriden", eitherMerged.right().value()); return StorageOperationStatus.INVALID_PROPERTY; } } if (!propertiesAll.isEmpty()) { Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.PROPERTIES, EdgeLabelEnum.PROPERTIES, propertiesAll); if (assosiateElementToData.isRight()) { return assosiateElementToData.right().value(); } } return StorageOperationStatus.OK; } private StorageOperationStatus associateAdditionalInfoToResource(GraphVertex nodeTypeVertex, ToscaElement nodeType) { Map<String, AdditionalInfoParameterDataDefinition> additionalInformation = nodeType.getAdditionalInformation(); if (additionalInformation != null) { Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.ADDITIONAL_INFORMATION, EdgeLabelEnum.ADDITIONAL_INFORMATION, additionalInformation); if (assosiateElementToData.isRight()) { return assosiateElementToData.right().value(); } } return StorageOperationStatus.OK; } protected <T extends ToscaDataDefinition> Either<Map<String, T>, StorageOperationStatus> getDataFromDerived(List<GraphVertex> derivedResources, EdgeLabelEnum edge) { Map<String, T> propertiesAll = new HashMap<>(); if (derivedResources != null && !derivedResources.isEmpty()) { for (GraphVertex derived : derivedResources) { Either<List<GraphVertex>, TitanOperationStatus> derivedProperties = titanDao.getChildrenVertecies(derived, edge, JsonParseFlagEnum.ParseJson); if (derivedProperties.isRight()) { if (derivedProperties.right().value() != TitanOperationStatus.NOT_FOUND) { log.debug("Failed to get properties for derived from {} error {}", derived.getUniqueId(), derivedProperties.right().value()); return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(derivedProperties.right().value())); } else { continue; } } List<GraphVertex> propList = derivedProperties.left().value(); for (GraphVertex propV : propList) { Map<String, T> propertiesFromDerived = (Map<String, T>) propV.getJson(); if (propertiesFromDerived != null) { propertiesFromDerived.entrySet().forEach(x -> x.getValue().setOwnerIdIfEmpty(derived.getUniqueId())); propertiesAll.putAll(propertiesFromDerived); } } } } return Either.left(propertiesAll); } protected TitanOperationStatus setArtifactsFromGraph(GraphVertex componentV, ToscaElement toscaElement) { Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.ARTIFACTS); if (result.isLeft()) { toscaElement.setArtifacts(result.left().value()); } else { if (result.right().value() != TitanOperationStatus.NOT_FOUND) { return result.right().value(); } } result = getDataFromGraph(componentV, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS); if (result.isLeft()) { toscaElement.setDeploymentArtifacts(result.left().value()); } else { if (result.right().value() != TitanOperationStatus.NOT_FOUND) { return result.right().value(); } } result = getDataFromGraph(componentV, EdgeLabelEnum.TOSCA_ARTIFACTS); if (result.isLeft()) { toscaElement.setToscaArtifacts(result.left().value()); } else { if (result.right().value() != TitanOperationStatus.NOT_FOUND) { return result.right().value(); } } return TitanOperationStatus.OK; } protected TitanOperationStatus setAllVersions(GraphVertex componentV, ToscaElement toscaElement) { Map<String, String> allVersion = new HashMap<>(); allVersion.put((String) componentV.getMetadataProperty(GraphPropertyEnum.VERSION), componentV.getUniqueId()); ArrayList<GraphVertex> allChildrenAndParants = new ArrayList<>(); Either<GraphVertex, TitanOperationStatus> childResourceRes = titanDao.getChildVertex(componentV, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); while (childResourceRes.isLeft()) { GraphVertex child = childResourceRes.left().value(); allChildrenAndParants.add(child); childResourceRes = titanDao.getChildVertex(child, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); } TitanOperationStatus operationStatus = childResourceRes.right().value(); if (operationStatus != TitanOperationStatus.NOT_FOUND) { return operationStatus; } else { Either<GraphVertex, TitanOperationStatus> parentResourceRes = titanDao.getParentVertex(componentV, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); while (parentResourceRes.isLeft()) { GraphVertex parent = parentResourceRes.left().value(); allChildrenAndParants.add(parent); parentResourceRes = titanDao.getParentVertex(parent, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); } operationStatus = parentResourceRes.right().value(); if (operationStatus != TitanOperationStatus.NOT_FOUND) { return operationStatus; } else { allChildrenAndParants.stream().filter(vertex -> { Boolean isDeleted = (Boolean) vertex.getMetadataProperty(GraphPropertyEnum.IS_DELETED); return (isDeleted == null || !isDeleted); }).forEach(vertex -> allVersion.put((String) vertex.getMetadataProperty(GraphPropertyEnum.VERSION), vertex.getUniqueId())); toscaElement.setAllVersions(allVersion); return TitanOperationStatus.OK; } } } protected <T extends ToscaElement> Either<List<T>, StorageOperationStatus> getFollowedComponent(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, ComponentTypeEnum neededType) { Either<List<T>, StorageOperationStatus> result = null; Map<GraphPropertyEnum, Object> props = null; if (userId != null) { props = new EnumMap<>(GraphPropertyEnum.class); // for Designer retrieve specific user props.put(GraphPropertyEnum.USERID, userId); } // in case of user id == null -> get all users by label // for Tester and Admin retrieve all users Either<List<GraphVertex>, TitanOperationStatus> usersByCriteria = titanDao.getByCriteria(VertexTypeEnum.USER, props, JsonParseFlagEnum.NoParse); if (usersByCriteria.isRight()) { log.debug("Failed to fetch users by criteria {} error {}", props, usersByCriteria.right().value()); return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(usersByCriteria.right().value())); } List<GraphVertex> users = usersByCriteria.left().value(); List<T> components = new ArrayList<>(); List<T> componentsPerUser; for (GraphVertex userV : users) { HashSet<String> ids = new HashSet<>(); Either<List<GraphVertex>, TitanOperationStatus> childrenVertecies = titanDao.getChildrenVertecies(userV, EdgeLabelEnum.STATE, JsonParseFlagEnum.NoParse); if (childrenVertecies.isRight() && childrenVertecies.right().value() != TitanOperationStatus.NOT_FOUND) { log.debug("Failed to fetch children vertices for user {} by edge {} error {}", userV.getMetadataProperty(GraphPropertyEnum.USERID), EdgeLabelEnum.STATE, childrenVertecies.right().value()); return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(childrenVertecies.right().value())); } // get all resource with current state if (childrenVertecies.isLeft()) { componentsPerUser = fetchComponents(lifecycleStates, childrenVertecies.left().value(), neededType, EdgeLabelEnum.STATE); if (componentsPerUser != null) { for (T comp : componentsPerUser) { ids.add(comp.getUniqueId()); components.add(comp); } } } if (lastStateStates != null && !lastStateStates.isEmpty()) { // get all resource with last state childrenVertecies = titanDao.getChildrenVertecies(userV, EdgeLabelEnum.LAST_STATE, JsonParseFlagEnum.NoParse); if (childrenVertecies.isRight() && childrenVertecies.right().value() != TitanOperationStatus.NOT_FOUND) { log.debug("Failed to fetch children vertices for user {} by edge {} error {}", userV.getMetadataProperty(GraphPropertyEnum.USERID), EdgeLabelEnum.LAST_STATE, childrenVertecies.right().value()); return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(childrenVertecies.right().value())); } if (childrenVertecies.isLeft()) { boolean isFirst; componentsPerUser = fetchComponents(lastStateStates, childrenVertecies.left().value(), neededType, EdgeLabelEnum.LAST_STATE); if (componentsPerUser != null) { for (T comp : componentsPerUser) { isFirst = true; if (ids.contains(comp.getUniqueId())) { isFirst = false; } if (isFirst) { components.add(comp); } } } } } } // whlile users ; result = Either.left(components); return result; } private <T extends ToscaElement> List<T> fetchComponents(Set<LifecycleStateEnum> lifecycleStates, List<GraphVertex> vertices, ComponentTypeEnum neededType, EdgeLabelEnum edgelabel) { List<T> components = new ArrayList<>(); for (GraphVertex node : vertices) { Iterator<Edge> edges = node.getVertex().edges(Direction.IN, edgelabel.name()); while (edges.hasNext()) { Edge edge = edges.next(); String stateStr = (String) titanDao.getProperty(edge, EdgePropertyEnum.STATE); LifecycleStateEnum nodeState = LifecycleStateEnum.findState(stateStr); if (nodeState == null) { log.debug("no supported STATE {} for element {}", stateStr, node.getUniqueId()); continue; } if (lifecycleStates != null && lifecycleStates.contains(nodeState)) { Boolean isDeleted = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_DELETED); Boolean isArchived = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_ARCHIVED); if (isDeleted != null && isDeleted || isArchived != null && isArchived) { log.trace("Deleted/Archived element {}, discard", node.getUniqueId()); continue; } Boolean isHighest = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION); if (isHighest) { ComponentTypeEnum componentType = node.getType(); // get only latest versions if (componentType == null) { log.debug("No supported type {} for vertex {}", componentType, node.getUniqueId()); continue; } if (neededType == componentType) { switch (componentType) { case SERVICE: case PRODUCT: handleNode(components, node, componentType); break; case RESOURCE: Boolean isAbtract = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_ABSTRACT); if (isAbtract == null || !isAbtract) { handleNode(components, node, componentType); } // if not abstract break; default: log.debug("not supported node type {}", componentType); break; }// case } // needed type } } // if } // while edges } // while resources return components; } protected <T extends ToscaElement> void handleNode(List<T> components, GraphVertex vertexComponent, ComponentTypeEnum nodeType) { Either<T, StorageOperationStatus> component = getLightComponent(vertexComponent, nodeType, new ComponentParametersView(true)); if (component.isRight()) { log.debug("Failed to get component for id = {} error : {} skip resource", vertexComponent.getUniqueId(), component.right().value()); } else { components.add(component.left().value()); } } protected <T extends ToscaElement> Either<T, StorageOperationStatus> getLightComponent(String componentUid, ComponentTypeEnum nodeType, ComponentParametersView parametersFilter) { Either<GraphVertex, TitanOperationStatus> getVertexRes = titanDao.getVertexById(componentUid); if (getVertexRes.isRight()) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexRes.right().value())); } return getLightComponent(getVertexRes.left().value(), nodeType, parametersFilter); } protected <T extends ToscaElement> Either<T, StorageOperationStatus> getLightComponent(GraphVertex vertexComponent, ComponentTypeEnum nodeType, ComponentParametersView parametersFilter) { log.trace("Starting to build light component of type {}, id {}", nodeType, vertexComponent.getUniqueId()); titanDao.parseVertexProperties(vertexComponent, JsonParseFlagEnum.ParseMetadata); T toscaElement = convertToComponent(vertexComponent); TitanOperationStatus status = setCreatorFromGraph(vertexComponent, toscaElement); if (status != TitanOperationStatus.OK) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); } status = setLastModifierFromGraph(vertexComponent, toscaElement); if (status != TitanOperationStatus.OK) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); } status = setCategoriesFromGraph(vertexComponent, toscaElement); if (status != TitanOperationStatus.OK) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); } if (!parametersFilter.isIgnoreAllVersions()) { status = setAllVersions(vertexComponent, toscaElement); if (status != TitanOperationStatus.OK) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); } } if (!parametersFilter.isIgnoreCapabilities()) { status = setCapabilitiesFromGraph(vertexComponent, toscaElement); if (status != TitanOperationStatus.OK) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); } } if (!parametersFilter.isIgnoreRequirements()) { status = setRequirementsFromGraph(vertexComponent, toscaElement); if (status != TitanOperationStatus.OK) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); } } log.debug("Ended to build light component of type {}, id {}", nodeType, vertexComponent.getUniqueId()); return Either.left(toscaElement); } @SuppressWarnings("unchecked") protected <T extends ToscaElement> T convertToComponent(GraphVertex componentV) { ToscaElement toscaElement = null; VertexTypeEnum label = componentV.getLabel(); switch (label) { case NODE_TYPE: toscaElement = new NodeType(); break; case TOPOLOGY_TEMPLATE: toscaElement = new TopologyTemplate(); break; default: log.debug("Not supported tosca type {}", label); break; } Map<String, Object> jsonMetada = componentV.getMetadataJson(); if (toscaElement != null) { toscaElement.setMetadata(jsonMetada); } return (T) toscaElement; } protected TitanOperationStatus setResourceCategoryFromGraphV(Vertex vertex, CatalogComponent catalogComponent) { Either<Vertex, TitanOperationStatus> childVertex = titanDao.getChildVertex(vertex, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse); if (childVertex.isRight()) { log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, EdgeLabelEnum.CATEGORY, catalogComponent.getUniqueId(), childVertex.right().value()); return childVertex.right().value(); } Vertex subCategoryV = childVertex.left().value(); catalogComponent.setSubCategoryNormalizedName((String) subCategoryV.property(JsonPresentationFields.NORMALIZED_NAME.getPresentation()).value()); Either<Vertex, TitanOperationStatus> parentVertex = titanDao.getParentVertex(subCategoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse); Vertex categoryV = parentVertex.left().value(); catalogComponent.setCategoryNormalizedName((String) categoryV.property(JsonPresentationFields.NORMALIZED_NAME.getPresentation()).value()); return TitanOperationStatus.OK; } protected TitanOperationStatus setServiceCategoryFromGraphV(Vertex vertex, CatalogComponent catalogComponent) { Either<Vertex, TitanOperationStatus> childVertex = titanDao.getChildVertex(vertex, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse); if (childVertex.isRight()) { log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, EdgeLabelEnum.CATEGORY, catalogComponent.getUniqueId(), childVertex.right().value()); return childVertex.right().value(); } Vertex categoryV = childVertex.left().value(); catalogComponent.setCategoryNormalizedName((String) categoryV.property(JsonPresentationFields.NORMALIZED_NAME.getPresentation()).value()); return TitanOperationStatus.OK; } protected TitanOperationStatus setResourceCategoryFromGraph(GraphVertex componentV, ToscaElement toscaElement) { List<CategoryDefinition> categories = new ArrayList<>(); SubCategoryDefinition subcategory; Either<GraphVertex, TitanOperationStatus> childVertex = titanDao.getChildVertex(componentV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse); if (childVertex.isRight()) { log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, EdgeLabelEnum.CATEGORY, componentV.getUniqueId(), childVertex.right().value()); return childVertex.right().value(); } GraphVertex subCategoryV = childVertex.left().value(); Map<GraphPropertyEnum, Object> metadataProperties = subCategoryV.getMetadataProperties(); subcategory = new SubCategoryDefinition(); subcategory.setUniqueId(subCategoryV.getUniqueId()); subcategory.setNormalizedName((String) metadataProperties.get(GraphPropertyEnum.NORMALIZED_NAME)); subcategory.setName((String) metadataProperties.get(GraphPropertyEnum.NAME)); Type listTypeSubcat = new TypeToken<List<String>>() { }.getType(); List<String> iconsfromJsonSubcat = getGson().fromJson((String) metadataProperties.get(GraphPropertyEnum.ICONS), listTypeSubcat); subcategory.setIcons(iconsfromJsonSubcat); Either<GraphVertex, TitanOperationStatus> parentVertex = titanDao.getParentVertex(subCategoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse); if (parentVertex.isRight()) { log.debug("failed to fetch {} for category with id {}, error {}", EdgeLabelEnum.SUB_CATEGORY, subCategoryV.getUniqueId(), parentVertex.right().value()); return childVertex.right().value(); } GraphVertex categoryV = parentVertex.left().value(); metadataProperties = categoryV.getMetadataProperties(); CategoryDefinition category = new CategoryDefinition(); category.setUniqueId(categoryV.getUniqueId()); category.setNormalizedName((String) metadataProperties.get(GraphPropertyEnum.NORMALIZED_NAME)); category.setName((String) metadataProperties.get(GraphPropertyEnum.NAME)); Type listTypeCat = new TypeToken<List<String>>() { }.getType(); List<String> iconsfromJsonCat = getGson().fromJson((String) metadataProperties.get(GraphPropertyEnum.ICONS), listTypeCat); category.setIcons(iconsfromJsonCat); category.addSubCategory(subcategory); categories.add(category); toscaElement.setCategories(categories); return TitanOperationStatus.OK; } public <T extends ToscaElement> Either<T, StorageOperationStatus> updateToscaElement(T toscaElementToUpdate, GraphVertex elementV, ComponentParametersView filterResult) { Either<T, StorageOperationStatus> result = null; log.debug("In updateToscaElement. received component uid = {}", (toscaElementToUpdate == null ? null : toscaElementToUpdate.getUniqueId())); if (toscaElementToUpdate == null) { log.error("Service object is null"); result = Either.right(StorageOperationStatus.BAD_REQUEST); return result; } String modifierUserId = toscaElementToUpdate.getLastUpdaterUserId(); if (modifierUserId == null || modifierUserId.isEmpty()) { log.error("UserId is missing in the request."); result = Either.right(StorageOperationStatus.BAD_REQUEST); return result; } Either<GraphVertex, TitanOperationStatus> findUser = findUserVertex(modifierUserId); if (findUser.isRight()) { TitanOperationStatus status = findUser.right().value(); log.error(CANNOT_FIND_USER_IN_THE_GRAPH_STATUS_IS, modifierUserId, status); return result; } GraphVertex modifierV = findUser.left().value(); String toscaElementId = toscaElementToUpdate.getUniqueId(); Either<GraphVertex, TitanOperationStatus> parentVertex = titanDao.getParentVertex(elementV, EdgeLabelEnum.LAST_MODIFIER, JsonParseFlagEnum.NoParse); if (parentVertex.isRight()) { log.debug("Failed to fetch last modifier for tosca element with id {} error {}", toscaElementId, parentVertex.right().value()); return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentVertex.right().value())); } GraphVertex userV = parentVertex.left().value(); String currentModifier = (String) userV.getMetadataProperty(GraphPropertyEnum.USERID); String prevSystemName = (String) elementV.getMetadataProperty(GraphPropertyEnum.SYSTEM_NAME); if (currentModifier.equals(modifierUserId)) { log.debug("Graph LAST MODIFIER edge should not be changed since the modifier is the same as the last modifier."); } else { log.debug("Going to update the last modifier user of the resource from {} to {}", currentModifier, modifierUserId); StorageOperationStatus status = moveLastModifierEdge(elementV, modifierV); log.debug("Finish to update the last modifier user of the resource from {} to {}. status is {}", currentModifier, modifierUserId, status); if (status != StorageOperationStatus.OK) { result = Either.right(status); return result; } } final long currentTimeMillis = System.currentTimeMillis(); log.debug("Going to update the last Update Date of the resource from {} to {}", elementV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE), currentTimeMillis); elementV.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, currentTimeMillis); StorageOperationStatus checkCategories = validateCategories(toscaElementToUpdate, elementV); if (checkCategories != StorageOperationStatus.OK) { result = Either.right(checkCategories); return result; } // update all data on vertex fillToscaElementVertexData(elementV, toscaElementToUpdate, JsonParseFlagEnum.ParseMetadata); Either<GraphVertex, TitanOperationStatus> updateElement = titanDao.updateVertex(elementV); if (updateElement.isRight()) { log.error("Failed to update resource {}. status is {}", toscaElementId, updateElement.right().value()); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateElement.right().value())); return result; } GraphVertex updateElementV = updateElement.left().value(); // DE230195 in case resource name changed update TOSCA artifacts // file names accordingly String newSystemName = (String) updateElementV.getMetadataProperty(GraphPropertyEnum.SYSTEM_NAME); if (newSystemName != null && !newSystemName.equals(prevSystemName)) { Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> resultToscaArt = getDataFromGraph(updateElementV, EdgeLabelEnum.TOSCA_ARTIFACTS); if (resultToscaArt.isRight()) { log.debug("Failed to get tosca artifact from graph for tosca element {} error {}", toscaElementId, resultToscaArt.right().value()); return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resultToscaArt.right().value())); } Map<String, ArtifactDataDefinition> toscaArtifacts = resultToscaArt.left().value(); if (toscaArtifacts != null) { for (Entry<String, ArtifactDataDefinition> artifact : toscaArtifacts.entrySet()) { generateNewToscaFileName(toscaElementToUpdate.getComponentType().getValue().toLowerCase(), newSystemName, artifact.getValue()); } // TODO call to new Artifact operation in order to update list of artifacts } } if (toscaElementToUpdate.getComponentType() == ComponentTypeEnum.RESOURCE) { StorageOperationStatus resultDerived = updateDerived(toscaElementToUpdate, updateElementV); if (resultDerived != StorageOperationStatus.OK) { log.debug("Failed to update from derived data for element {} error {}", toscaElementId, resultDerived); return Either.right(resultDerived); } } Either<T, StorageOperationStatus> updatedResource = getToscaElement(updateElementV, filterResult); if (updatedResource.isRight()) { log.error("Failed to fetch tosca element {} after update , error {}", toscaElementId, updatedResource.right().value()); result = Either.right(StorageOperationStatus.BAD_REQUEST); return result; } T updatedResourceValue = updatedResource.left().value(); result = Either.left(updatedResourceValue); return result; } protected StorageOperationStatus moveLastModifierEdge(GraphVertex elementV, GraphVertex modifierV) { return DaoStatusConverter.convertTitanStatusToStorageStatus(titanDao.moveEdge(elementV, modifierV, EdgeLabelEnum.LAST_MODIFIER, Direction.IN)); } protected StorageOperationStatus moveCategoryEdge(GraphVertex elementV, GraphVertex categoryV) { return DaoStatusConverter.convertTitanStatusToStorageStatus(titanDao.moveEdge(elementV, categoryV, EdgeLabelEnum.CATEGORY, Direction.OUT)); } private void generateNewToscaFileName(String componentType, String componentName, ArtifactDataDefinition artifactInfo) { Map<String, Object> getConfig = (Map<String, Object>) ConfigurationManager.getConfigurationManager().getConfiguration().getToscaArtifacts().entrySet().stream().filter(p -> p.getKey().equalsIgnoreCase(artifactInfo.getArtifactLabel())) .findAny().get().getValue(); artifactInfo.setArtifactName(componentType + "-" + componentName + getConfig.get("artifactName")); } protected <T extends ToscaElement> StorageOperationStatus validateResourceCategory(T toscaElementToUpdate, GraphVertex elementV) { StorageOperationStatus status = StorageOperationStatus.OK; List<CategoryDefinition> newCategoryList = toscaElementToUpdate.getCategories(); CategoryDefinition newCategory = newCategoryList.get(0); Either<GraphVertex, TitanOperationStatus> childVertex = titanDao.getChildVertex(elementV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse); if (childVertex.isRight()) { log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, EdgeLabelEnum.CATEGORY, elementV.getUniqueId(), childVertex.right().value()); return DaoStatusConverter.convertTitanStatusToStorageStatus(childVertex.right().value()); } GraphVertex subCategoryV = childVertex.left().value(); Map<GraphPropertyEnum, Object> metadataProperties = subCategoryV.getMetadataProperties(); String subCategoryNameCurrent = (String) metadataProperties.get(GraphPropertyEnum.NAME); Either<GraphVertex, TitanOperationStatus> parentVertex = titanDao.getParentVertex(subCategoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse); if (parentVertex.isRight()) { log.debug("failed to fetch {} for category with id {}, error {}", EdgeLabelEnum.SUB_CATEGORY, subCategoryV.getUniqueId(), parentVertex.right().value()); return DaoStatusConverter.convertTitanStatusToStorageStatus(childVertex.right().value()); } GraphVertex categoryV = parentVertex.left().value(); metadataProperties = categoryV.getMetadataProperties(); String categoryNameCurrent = (String) metadataProperties.get(GraphPropertyEnum.NAME); boolean categoryWasChanged = false; String newCategoryName = newCategory.getName(); SubCategoryDefinition newSubcategory = newCategory.getSubcategories().get(0); String newSubCategoryName = newSubcategory.getName(); if (newCategoryName != null && !newCategoryName.equals(categoryNameCurrent)) { // the category was changed categoryWasChanged = true; } else { // the sub-category was changed if (newSubCategoryName != null && !newSubCategoryName.equals(subCategoryNameCurrent)) { log.debug("Going to update the category of the resource from {} to {}", categoryNameCurrent, newCategory); categoryWasChanged = true; } } if (categoryWasChanged) { Either<GraphVertex, StorageOperationStatus> getCategoryVertex = getResourceCategoryVertex(elementV.getUniqueId(), newSubCategoryName, newCategoryName); if (getCategoryVertex.isRight()) { return getCategoryVertex.right().value(); } GraphVertex newCategoryV = getCategoryVertex.left().value(); status = moveCategoryEdge(elementV, newCategoryV); log.debug("Going to update the category of the resource from {} to {}. status is {}", categoryNameCurrent, newCategory, status); } return status; } public <T extends ToscaElement> Either<List<T>, StorageOperationStatus> getElementCatalogData(ComponentTypeEnum componentType, List<ResourceTypeEnum> excludeTypes, boolean isHighestVersions) { Either<List<GraphVertex>, TitanOperationStatus> listOfComponents; if (isHighestVersions) { listOfComponents = getListOfHighestComponents(componentType, excludeTypes, JsonParseFlagEnum.NoParse); } else { listOfComponents = getListOfHighestAndAllCertifiedComponents(componentType, excludeTypes); } if (listOfComponents.isRight() && listOfComponents.right().value() != TitanOperationStatus.NOT_FOUND) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(listOfComponents.right().value())); } List<T> result = new ArrayList<>(); if (listOfComponents.isLeft()) { List<GraphVertex> highestAndAllCertified = listOfComponents.left().value(); if (highestAndAllCertified != null && !highestAndAllCertified.isEmpty()) { for (GraphVertex vertexComponent : highestAndAllCertified) { Either<T, StorageOperationStatus> component = getLightComponent(vertexComponent, componentType, new ComponentParametersView(true)); if (component.isRight()) { log.debug("Failed to fetch light element for {} error {}", vertexComponent.getUniqueId(), component.right().value()); return Either.right(component.right().value()); } else { result.add(component.left().value()); } } } } return Either.left(result); } public Either<List<CatalogComponent>, StorageOperationStatus> getElementCatalogData(boolean isCatalog, List<ResourceTypeEnum> excludeTypes) { StopWatch stopWatch = new StopWatch(); stopWatch.start(); Map<String, CatalogComponent> existInCatalog = new HashMap<>(); Either<Iterator<Vertex>, TitanOperationStatus> verticesEither = titanDao.getCatalogOrArchiveVerticies(isCatalog); if (verticesEither.isRight()) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(verticesEither.right().value())); } Iterator<Vertex> vertices = verticesEither.left().value(); while (vertices.hasNext()) { handleCatalogComponent(existInCatalog, vertices.next(), excludeTypes); } stopWatch.stop(); String timeToFetchElements = stopWatch.prettyPrint(); log.info("time to fetch all catalog elements: {}", timeToFetchElements); return Either.left(existInCatalog.values().stream().collect(Collectors.toList())); } private void handleCatalogComponent(Map<String, CatalogComponent> existInCatalog, Vertex vertex, List<ResourceTypeEnum> excludeTypes) { VertexProperty<Object> property = vertex.property(GraphPropertiesDictionary.METADATA.getProperty()); String json = (String) property.value(); Map<String, Object> metadatObj = JsonParserUtils.toMap(json); String uniqueId = (String) metadatObj.get(JsonPresentationFields.UNIQUE_ID.getPresentation()); Boolean isDeleted = (Boolean) metadatObj.get(JsonPresentationFields.IS_DELETED.getPresentation()); if (isAddToCatalog(excludeTypes, metadatObj) && (existInCatalog.get(uniqueId) == null && (isDeleted == null || !isDeleted.booleanValue()))) { CatalogComponent catalogComponent = new CatalogComponent(); catalogComponent.setUniqueId(uniqueId); catalogComponent.setComponentType(ComponentTypeEnum.valueOf((String) metadatObj.get(JsonPresentationFields.COMPONENT_TYPE.getPresentation()))); catalogComponent.setVersion((String) metadatObj.get(JsonPresentationFields.VERSION.getPresentation())); catalogComponent.setName((String) metadatObj.get(JsonPresentationFields.NAME.getPresentation())); catalogComponent.setIcon((String) metadatObj.get(JsonPresentationFields.ICON.getPresentation())); catalogComponent.setLifecycleState((String) metadatObj.get(JsonPresentationFields.LIFECYCLE_STATE.getPresentation())); catalogComponent.setLastUpdateDate((Long) metadatObj.get(JsonPresentationFields.LAST_UPDATE_DATE.getPresentation())); catalogComponent.setDistributionStatus((String) metadatObj.get(JsonPresentationFields.DISTRIBUTION_STATUS.getPresentation())); Object resourceType = metadatObj.get(JsonPresentationFields.RESOURCE_TYPE.getPresentation()); if (resourceType != null) { catalogComponent.setResourceType((String) resourceType); } if (catalogComponent.getComponentType() == ComponentTypeEnum.SERVICE) { setServiceCategoryFromGraphV(vertex, catalogComponent); } else { setResourceCategoryFromGraphV(vertex, catalogComponent); } List<String> tags = (List<String>) metadatObj.get(JsonPresentationFields.TAGS.getPresentation()); if (tags != null) { catalogComponent.setTags(tags); } existInCatalog.put(uniqueId, catalogComponent); } } private boolean isAddToCatalog(List<ResourceTypeEnum> excludeTypes, Map<String, Object> metadatObj) { boolean isAddToCatalog = true; Object resourceTypeStr = metadatObj.get(JsonPresentationFields.RESOURCE_TYPE.getPresentation()); if (resourceTypeStr != null) { ResourceTypeEnum resourceType = ResourceTypeEnum.getType((String) resourceTypeStr); if (!CollectionUtils.isEmpty(excludeTypes)) { Optional<ResourceTypeEnum> op = excludeTypes.stream().filter(rt -> rt == resourceType).findAny(); if (op.isPresent()) isAddToCatalog = false; } } return isAddToCatalog; } public Either<List<GraphVertex>, TitanOperationStatus> getListOfHighestComponents(ComponentTypeEnum componentType, List<ResourceTypeEnum> excludeTypes, JsonParseFlagEnum parseFlag) { Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); Map<GraphPropertyEnum, Object> propertiesHasNotToMatch = new EnumMap<>(GraphPropertyEnum.class); propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); if (componentType == ComponentTypeEnum.RESOURCE) { propertiesToMatch.put(GraphPropertyEnum.IS_ABSTRACT, false); propertiesHasNotToMatch.put(GraphPropertyEnum.RESOURCE_TYPE, excludeTypes); } propertiesHasNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); propertiesHasNotToMatch.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683 return titanDao.getByCriteria(null, propertiesToMatch, propertiesHasNotToMatch, parseFlag); } // highest + (certified && !highest) public Either<List<GraphVertex>, TitanOperationStatus> getListOfHighestAndAllCertifiedComponents (ComponentTypeEnum componentType, List<ResourceTypeEnum> excludeTypes) { long startFetchAllStates = System.currentTimeMillis(); Either<List<GraphVertex>, TitanOperationStatus> highestNodes = getListOfHighestComponents(componentType, excludeTypes, JsonParseFlagEnum.ParseMetadata); Map<GraphPropertyEnum, Object> propertiesToMatchCertified = new EnumMap<>(GraphPropertyEnum.class); Map<GraphPropertyEnum, Object> propertiesHasNotToMatchCertified = new EnumMap<>(GraphPropertyEnum.class); propertiesToMatchCertified.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); propertiesToMatchCertified.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); if (componentType == ComponentTypeEnum.RESOURCE) { propertiesToMatchCertified.put(GraphPropertyEnum.IS_ABSTRACT, false); propertiesHasNotToMatchCertified.put(GraphPropertyEnum.RESOURCE_TYPE, excludeTypes); } propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_DELETED, true); propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683 propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); Either<List<GraphVertex>, TitanOperationStatus> certifiedNotHighestNodes = titanDao.getByCriteria(null, propertiesToMatchCertified, propertiesHasNotToMatchCertified, JsonParseFlagEnum.ParseMetadata); if (certifiedNotHighestNodes.isRight() && certifiedNotHighestNodes.right().value() != TitanOperationStatus.NOT_FOUND) { return Either.right(certifiedNotHighestNodes.right().value()); } long endFetchAllStates = System.currentTimeMillis(); List<GraphVertex> allNodes = new ArrayList<>(); if (certifiedNotHighestNodes.isLeft()) { allNodes.addAll(certifiedNotHighestNodes.left().value()); } if (highestNodes.isLeft()) { allNodes.addAll(highestNodes.left().value()); } log.debug("Fetch catalog {}s all states from graph took {} ms", componentType, endFetchAllStates - startFetchAllStates); return Either.left(allNodes); } protected Either<List<GraphVertex>, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum componentType) { // get all components marked for delete Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class); props.put(GraphPropertyEnum.IS_DELETED, true); props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); Either<List<GraphVertex>, TitanOperationStatus> componentsToDelete = titanDao.getByCriteria(null, props, JsonParseFlagEnum.NoParse); if (componentsToDelete.isRight()) { TitanOperationStatus error = componentsToDelete.right().value(); if (error.equals(TitanOperationStatus.NOT_FOUND)) { log.trace("no components to delete"); return Either.left(new ArrayList<>()); } else { log.info("failed to find components to delete. error : {}", error.name()); return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error)); } } return Either.left(componentsToDelete.left().value()); } protected TitanOperationStatus setAdditionalInformationFromGraph(GraphVertex componentV, ToscaElement toscaElement) { Either<Map<String, AdditionalInfoParameterDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.ADDITIONAL_INFORMATION); if (result.isLeft()) { toscaElement.setAdditionalInformation(result.left().value()); } else { if (result.right().value() != TitanOperationStatus.NOT_FOUND) { return result.right().value(); } } return TitanOperationStatus.OK; } // -------------------------------------------- public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> getToscaElement(String uniqueId, ComponentParametersView componentParametersView); public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> getToscaElement(GraphVertex toscaElementVertex, ComponentParametersView componentParametersView); public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> deleteToscaElement(GraphVertex toscaElementVertex); public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> createToscaElement(ToscaElement toscaElement); protected abstract <T extends ToscaElement> TitanOperationStatus setCategoriesFromGraph(GraphVertex vertexComponent, T toscaElement); protected abstract <T extends ToscaElement> TitanOperationStatus setCapabilitiesFromGraph(GraphVertex componentV, T toscaElement); protected abstract <T extends ToscaElement> TitanOperationStatus setRequirementsFromGraph(GraphVertex componentV, T toscaElement); protected abstract <T extends ToscaElement> StorageOperationStatus validateCategories(T toscaElementToUpdate, GraphVertex elementV); protected abstract <T extends ToscaElement> StorageOperationStatus updateDerived(T toscaElementToUpdate, GraphVertex updateElementV); public abstract <T extends ToscaElement> void fillToscaElementVertexData(GraphVertex elementV, T toscaElementToUpdate, JsonParseFlagEnum flag); }
/* * Copyright 2014-2016 CyberVision, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaaproject.kaa.server.common.dao.service; import org.apache.avro.Schema; import org.apache.avro.generic.GenericRecord; import org.apache.commons.lang.StringUtils; import org.kaaproject.kaa.common.avro.GenericAvroConverter; import org.kaaproject.kaa.common.dto.ChangeConfigurationNotification; import org.kaaproject.kaa.common.dto.ChangeDto; import org.kaaproject.kaa.common.dto.ChangeNotificationDto; import org.kaaproject.kaa.common.dto.ChangeType; import org.kaaproject.kaa.common.dto.ConfigurationDto; import org.kaaproject.kaa.common.dto.ConfigurationRecordDto; import org.kaaproject.kaa.common.dto.ConfigurationSchemaDto; import org.kaaproject.kaa.common.dto.HistoryDto; import org.kaaproject.kaa.common.dto.UpdateStatus; import org.kaaproject.kaa.common.dto.VersionDto; import org.kaaproject.kaa.common.dto.ctl.CTLSchemaDto; import org.kaaproject.kaa.server.common.core.algorithms.AvroUtils; import org.kaaproject.kaa.server.common.core.algorithms.generation.DefaultRecordGenerationAlgorithm; import org.kaaproject.kaa.server.common.core.algorithms.generation.DefaultRecordGenerationAlgorithmImpl; import org.kaaproject.kaa.server.common.core.algorithms.schema.SchemaCreationException; import org.kaaproject.kaa.server.common.core.algorithms.schema.SchemaGenerationAlgorithm; import org.kaaproject.kaa.server.common.core.algorithms.schema.SchemaGenerationAlgorithmFactory; import org.kaaproject.kaa.server.common.core.algorithms.validator.DefaultUuidValidator; import org.kaaproject.kaa.server.common.core.algorithms.validator.UuidValidator; import org.kaaproject.kaa.server.common.core.configuration.BaseData; import org.kaaproject.kaa.server.common.core.configuration.BaseDataFactory; import org.kaaproject.kaa.server.common.core.configuration.KaaData; import org.kaaproject.kaa.server.common.core.configuration.OverrideData; import org.kaaproject.kaa.server.common.core.configuration.OverrideDataFactory; import org.kaaproject.kaa.server.common.core.schema.BaseSchema; import org.kaaproject.kaa.server.common.core.schema.DataSchema; import org.kaaproject.kaa.server.common.core.schema.OverrideSchema; import org.kaaproject.kaa.server.common.core.schema.ProtocolSchema; import org.kaaproject.kaa.server.common.dao.CTLService; import org.kaaproject.kaa.server.common.dao.ConfigurationService; import org.kaaproject.kaa.server.common.dao.HistoryService; import org.kaaproject.kaa.server.common.dao.exception.DatabaseProcessingException; import org.kaaproject.kaa.server.common.dao.exception.IncorrectParameterException; import org.kaaproject.kaa.server.common.dao.exception.NotFoundException; import org.kaaproject.kaa.server.common.dao.exception.UpdateStatusConflictException; import org.kaaproject.kaa.server.common.dao.impl.ConfigurationDao; import org.kaaproject.kaa.server.common.dao.impl.ConfigurationSchemaDao; import org.kaaproject.kaa.server.common.dao.impl.EndpointGroupDao; import org.kaaproject.kaa.server.common.dao.model.sql.Configuration; import org.kaaproject.kaa.server.common.dao.model.sql.ConfigurationSchema; import org.kaaproject.kaa.server.common.dao.model.sql.EndpointGroup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import static org.apache.commons.lang.StringUtils.isBlank; import static org.kaaproject.kaa.common.dto.UpdateStatus.ACTIVE; import static org.kaaproject.kaa.common.dto.UpdateStatus.INACTIVE; import static org.kaaproject.kaa.server.common.dao.impl.DaoUtil.convertDtoList; import static org.kaaproject.kaa.server.common.dao.impl.DaoUtil.getDto; import static org.kaaproject.kaa.server.common.dao.impl.DaoUtil.idToString; import static org.kaaproject.kaa.server.common.dao.service.Validator.isValidId; import static org.kaaproject.kaa.server.common.dao.service.Validator.validateId; import static org.kaaproject.kaa.server.common.dao.service.Validator.validateSqlId; import static org.kaaproject.kaa.server.common.dao.service.Validator.validateSqlObject; @Service @Transactional public class ConfigurationServiceImpl implements ConfigurationService { private static final Logger LOG = LoggerFactory.getLogger(ConfigurationServiceImpl.class); private static final String DEFAULT_STRUCT_DESC = "Generated"; @Autowired private ConfigurationDao<Configuration> configurationDao; @Autowired private EndpointGroupDao<EndpointGroup> endpointGroupDao; @Autowired private ConfigurationSchemaDao<ConfigurationSchema> configurationSchemaDao; @Autowired private HistoryService historyService; @Autowired private CTLService ctlService; @Autowired private SchemaGenerationAlgorithmFactory schemaGeneratorFactory; private UuidValidator uuidValidator; @Override @Deprecated public ConfigurationDto findConfigurationByAppIdAndVersion(String applicationId, int version) { validateSqlId(applicationId, "Application id is incorrect. Can't find configuration by application id " + applicationId + " and version " + version); return getDto(configurationDao.findConfigurationByAppIdAndVersion(applicationId, version)); } @Override public ConfigurationDto findConfigurationByEndpointGroupIdAndVersion(String endpointGroupId, int version) { validateId(endpointGroupId, "Endpoint group id is incorrect. Can't find configuration by endpoint group id " + endpointGroupId + " and version " + version); return getDto(configurationDao.findConfigurationByEndpointGroupIdAndVersion(endpointGroupId, version)); } @Override public ConfigurationDto findDefaultConfigurationBySchemaId(String schemaId) { validateId(schemaId, "Schema id is incorrect. Can't find default configuration by schema id " + schemaId); ConfigurationDto configuration = null; ConfigurationSchema configurationSchema = configurationSchemaDao.findById(schemaId); if (configurationSchema != null) { String appId = configurationSchema.getApplicationId(); EndpointGroup endpointGroup = endpointGroupDao.findByAppIdAndWeight(appId, 0); if (endpointGroup != null) { String endpointGroupId = String.valueOf(endpointGroup.getId()); configuration = getDto(configurationDao.findConfigurationByEndpointGroupIdAndVersion(endpointGroupId, configurationSchema.getVersion())); } else { LOG.warn("Can't find default group for application [{}]", appId); } } else { LOG.warn("Can't find configuration schema for id [{}]", schemaId); } return configuration; } @Override public ConfigurationDto findConfigurationById(String id) { validateSqlId(id, "Configuration id is incorrect. Can't find configuration by id " + id); return getDto(configurationDao.findById(id)); } @Override public Collection<ConfigurationRecordDto> findAllConfigurationRecordsByEndpointGroupId( String endpointGroupId, boolean includeDeprecated) { Collection<ConfigurationDto> configurations = convertDtoList(configurationDao.findActualByEndpointGroupId(endpointGroupId)); List<ConfigurationRecordDto> records = ConfigurationRecordDto.convertToConfigurationRecords(configurations); if (includeDeprecated) { List<VersionDto> schemas = findVacantSchemasByEndpointGroupId(endpointGroupId); for (VersionDto schema : schemas) { ConfigurationDto deprecatedConfiguration = getDto(configurationDao.findLatestDeprecated(schema.getId(), endpointGroupId)); if (deprecatedConfiguration != null) { ConfigurationRecordDto record = new ConfigurationRecordDto(); record.setActiveStructureDto(deprecatedConfiguration); records.add(record); } } } Collections.sort(records); return records; } @Override public ConfigurationRecordDto findConfigurationRecordBySchemaIdAndEndpointGroupId( String schemaId, String endpointGroupId) { ConfigurationRecordDto record = new ConfigurationRecordDto(); Collection<ConfigurationDto> configurations = convertDtoList(configurationDao.findActualBySchemaIdAndGroupId(schemaId, endpointGroupId)); if (configurations != null) { for (ConfigurationDto configuration : configurations) { if (configuration.getStatus() == UpdateStatus.ACTIVE) { record.setActiveStructureDto(configuration); } else if (configuration.getStatus() == UpdateStatus.INACTIVE) { record.setInactiveStructureDto(configuration); } } } if (!record.hasActive()) { ConfigurationDto deprecatedConfiguration = getDto(configurationDao.findLatestDeprecated(schemaId, endpointGroupId)); if (deprecatedConfiguration != null) { record.setActiveStructureDto(deprecatedConfiguration); } } if (record.isEmpty()) { LOG.debug("Can't find related Configuration record."); throw new NotFoundException("Configuration record not found, schemaId: " + schemaId + ", endpointGroupId: " + endpointGroupId); // NOSONAR } return record; } @Override public List<VersionDto> findVacantSchemasByEndpointGroupId(String endpointGroupId) { validateId(endpointGroupId, "Can't find vacant schemas. Invalid endpoint group id: " + endpointGroupId); EndpointGroup group = endpointGroupDao.findById(endpointGroupId); List<Configuration> configurations = configurationDao.findActualByEndpointGroupId(endpointGroupId); List<String> usedSchemaIds = new ArrayList<>(); for (Configuration configuration : configurations) { ConfigurationSchema schema = configuration.getConfigurationSchema(); if (schema != null) { usedSchemaIds.add(idToString(schema.getId())); } } List<ConfigurationSchema> schemas = configurationSchemaDao.findVacantSchemas(group.getApplicationId(), usedSchemaIds); List<VersionDto> schemaDtoList = new ArrayList<>(); for (ConfigurationSchema schema : schemas) { schemaDtoList.add(schema.toVersionDto()); } return schemaDtoList; } @Override public ConfigurationDto saveConfiguration(ConfigurationDto configurationDto) { validateConfiguration(configurationDto); String id = configurationDto.getId(); ConfigurationSchemaDto configurationSchemaDto; Configuration oldActiveConfiguration = null; if (StringUtils.isNotBlank(id)) { ConfigurationDto oldConfiguration = findConfigurationById(configurationDto.getId()); if (oldConfiguration != null && oldConfiguration.getStatus() != INACTIVE) { throw new UpdateStatusConflictException("Can't update configuration, invalid id " + id); } configurationSchemaDto = findConfSchemaById(configurationDto.getSchemaId()); configurationDto.setSchemaVersion(configurationSchemaDto.getVersion()); configurationDto.setCreatedTime(oldConfiguration.getCreatedTime()); configurationDto.setCreatedUsername(oldConfiguration.getCreatedUsername()); LOG.debug("Update existing configuration with id: [{}]", configurationDto.getId()); } else { String schemaId = configurationDto.getSchemaId(); String groupId = configurationDto.getEndpointGroupId(); configurationSchemaDto = findConfSchemaById(schemaId); if (configurationSchemaDto != null) { Configuration oldInactiveConfiguration = configurationDao.findInactiveBySchemaIdAndGroupId(schemaId, groupId); oldActiveConfiguration = configurationDao.findLatestActiveBySchemaIdAndGroupId(schemaId, groupId); if (oldInactiveConfiguration != null) { configurationDto.setId(idToString(oldInactiveConfiguration.getId())); configurationDto.setSequenceNumber(oldInactiveConfiguration.getSequenceNumber()); } else if (oldActiveConfiguration != null) { configurationDto.setSequenceNumber(oldActiveConfiguration.getSequenceNumber()); } configurationDto.setApplicationId(configurationSchemaDto.getApplicationId()); configurationDto.setSchemaVersion(configurationSchemaDto.getVersion()); configurationDto.setProtocolSchema(configurationSchemaDto.getProtocolSchema()); configurationDto.setCreatedTime(System.currentTimeMillis()); } else { LOG.debug("Can't find related Configuration schema."); throw new IncorrectParameterException("Configuration schema not found, id:" + schemaId); } } ConfigurationDto oldActiveConfigurationDto = oldActiveConfiguration != null ? oldActiveConfiguration.toDto() : null; validateUuids(configurationDto, oldActiveConfigurationDto, configurationSchemaDto); configurationDto.setStatus(UpdateStatus.INACTIVE); configurationDto.setLastModifyTime(System.currentTimeMillis()); return getDto(configurationDao.save(new Configuration(configurationDto))); } private void validateUuids(ConfigurationDto currentConfiguration, ConfigurationDto previousConfiguration, ConfigurationSchemaDto configurationSchema) { try { EndpointGroup endpointGroup = endpointGroupDao.findById(currentConfiguration.getEndpointGroupId()); GenericAvroConverter<GenericRecord> avroConverter; Schema avroSchema; KaaData body = null; if (endpointGroup != null) { if (endpointGroup.getWeight() == 0) { LOG.debug("Create default UUID validator with base schema: {}", configurationSchema.getBaseSchema()); BaseSchema baseSchema = new BaseSchema(configurationSchema.getBaseSchema()); uuidValidator = new DefaultUuidValidator(baseSchema, new BaseDataFactory()); avroConverter = new GenericAvroConverter<GenericRecord>(baseSchema.getRawSchema()); avroSchema = new Schema.Parser().parse(baseSchema.getRawSchema()); } else { LOG.debug("Create default UUID validator with override schema: {}", configurationSchema.getOverrideSchema()); OverrideSchema overrideSchema = new OverrideSchema(configurationSchema.getOverrideSchema()); uuidValidator = new DefaultUuidValidator(overrideSchema, new OverrideDataFactory()); avroConverter = new GenericAvroConverter<GenericRecord>(overrideSchema.getRawSchema()); avroSchema = new Schema.Parser().parse(overrideSchema.getRawSchema()); } GenericRecord previousRecord = null; if (previousConfiguration != null) { previousRecord = avroConverter.decodeJson(previousConfiguration.getBody()); } GenericRecord currentRecord = avroConverter.decodeJson(AvroUtils.injectUuids(currentConfiguration.getBody(), avroSchema)); body = uuidValidator.validateUuidFields(currentRecord, previousRecord); } if (body != null) { currentConfiguration.setBody(body.getRawData()); } else { throw new RuntimeException("Can't generate json configuration body."); // NOSONAR } } catch (Exception e) { LOG.warn("Can't generate uuid fields for configuration {}", currentConfiguration); LOG.error("Can't generate uuid fields for configuration!", e); throw new IncorrectParameterException("Incorrect configuration. Can't generate uuid fields."); } } @Override public ChangeConfigurationNotification activateConfiguration(String id, String activatedUsername) { ChangeConfigurationNotification configurationNotification; validateSqlId(id, "Incorrect configuration id. Can't activate configuration with id " + id); Configuration oldConfiguration = configurationDao.findById(id); if (oldConfiguration != null) { UpdateStatus status = oldConfiguration.getStatus(); if (status != null && status == INACTIVE) { String schemaId = oldConfiguration.getSchemaId(); String groupId = oldConfiguration.getEndpointGroupId(); if (schemaId != null && groupId != null) { configurationDao.deactivateOldConfiguration(schemaId, groupId, activatedUsername); } else { throw new DatabaseProcessingException( "Incorrect old configuration. Configuration schema or endpoint group id is empty."); } ConfigurationDto configurationDto = getDto(configurationDao.activate(id, activatedUsername)); HistoryDto historyDto = addHistory(configurationDto, ChangeType.ADD_CONF); ChangeNotificationDto changeNotificationDto = createNotification(configurationDto, historyDto); configurationNotification = new ChangeConfigurationNotification(); configurationNotification.setConfigurationDto(configurationDto); configurationNotification.setChangeNotificationDto(changeNotificationDto); } else { throw new UpdateStatusConflictException("Incorrect status for activating configuration " + status); } } else { throw new IncorrectParameterException("Can't find configuration with id " + id); } return configurationNotification; } @Override public ChangeConfigurationNotification deactivateConfiguration(String id, String deactivatedUsername) { ChangeConfigurationNotification configurationNotification; validateSqlId(id, "Incorrect configuration id. Can't deactivate configuration with id " + id); Configuration oldConfiguration = configurationDao.findById(id); if (oldConfiguration != null) { UpdateStatus status = oldConfiguration.getStatus(); if (status != null && status == ACTIVE) { ConfigurationDto configurationDto = getDto(configurationDao.deactivate(id, deactivatedUsername)); HistoryDto historyDto = addHistory(configurationDto, ChangeType.REMOVE_CONF); ChangeNotificationDto changeNotificationDto = createNotification(configurationDto, historyDto); configurationNotification = new ChangeConfigurationNotification(); configurationNotification.setConfigurationDto(configurationDto); configurationNotification.setChangeNotificationDto(changeNotificationDto); } else { throw new UpdateStatusConflictException("Incorrect status for activating configuration " + status); } } else { throw new IncorrectParameterException("Can't find configuration with id " + id); } return configurationNotification; } @Override public ChangeConfigurationNotification deleteConfigurationRecord(String schemaId, String groupId, String deactivatedUsername) { ChangeConfigurationNotification configurationNotification = null; validateSqlId(schemaId, "Incorrect configuration schema id " + schemaId + "."); validateSqlId(groupId, "Incorrect group id " + groupId + "."); ConfigurationDto configurationDto = getDto(configurationDao.deactivateOldConfiguration(schemaId, groupId, deactivatedUsername)); if (configurationDto != null) { HistoryDto historyDto = addHistory(configurationDto, ChangeType.REMOVE_CONF); ChangeNotificationDto changeNotificationDto = createNotification(configurationDto, historyDto); configurationNotification = new ChangeConfigurationNotification(); configurationNotification.setConfigurationDto(configurationDto); configurationNotification.setChangeNotificationDto(changeNotificationDto); } Configuration configuration = configurationDao.findInactiveBySchemaIdAndGroupId(schemaId, groupId); if (configuration != null) { configurationDao.removeById(idToString(configuration)); } return configurationNotification; } @Override public List<ConfigurationDto> findConfigurationsByEndpointGroupId(String endpointGroupId) { validateSqlId(endpointGroupId, "Incorrect endpoint group id " + endpointGroupId); return convertDtoList(configurationDao.findActiveByEndpointGroupId(endpointGroupId)); } @Override public List<ConfigurationSchemaDto> findConfSchemasByAppId(String applicationId) { validateSqlId(applicationId, "Incorrect application id " + applicationId + ". Can't find configuration schemas."); return convertDtoList(configurationSchemaDao.findByApplicationId(applicationId)); } @Override public List<VersionDto> findConfigurationSchemaVersionsByAppId(String applicationId) { validateSqlId(applicationId, "Incorrect application id " + applicationId + ". Can't find configuration schema versions."); List<ConfigurationSchema> configurationSchemas = configurationSchemaDao.findByApplicationId(applicationId); List<VersionDto> schemas = new ArrayList<>(); for (ConfigurationSchema configurationSchema : configurationSchemas) { schemas.add(configurationSchema.toVersionDto()); } return schemas; } @Override public ConfigurationSchemaDto findConfSchemaByAppIdAndVersion(String applicationId, int version) { validateSqlId(applicationId, "Incorrect application id " + applicationId + ". Can't find configuration schema."); return getDto(configurationSchemaDao.findByAppIdAndVersion(applicationId, version)); } @Override public ConfigurationSchemaDto saveConfSchema(ConfigurationSchemaDto schemaDto, String groupId) { ConfigurationSchemaDto savedSchema = saveConfigurationSchema(schemaDto); if (savedSchema != null) { LOG.debug("Configuration schema with id [{}] saved. Generating default configuration", savedSchema.getId()); try { BaseSchema baseSchema = new BaseSchema(savedSchema.getBaseSchema()); DefaultRecordGenerationAlgorithm<BaseData> configurationProcessor = new DefaultRecordGenerationAlgorithmImpl<BaseSchema, BaseData>( baseSchema, new BaseDataFactory()); KaaData body = configurationProcessor.getRootData(); LOG.debug("Default configuration {} ", body.getRawData()); ConfigurationDto configurationDto = new ConfigurationDto(); configurationDto.setBody(body.getRawData()); configurationDto.setSchemaId(savedSchema.getId()); configurationDto.setDescription(DEFAULT_STRUCT_DESC); configurationDto.setEndpointGroupId(groupId); configurationDto.setCreatedUsername(savedSchema.getCreatedUsername()); ConfigurationDto savedConfiguration = saveConfiguration(configurationDto); if (savedConfiguration != null) { activateConfiguration(savedConfiguration.getId(), savedSchema.getCreatedUsername()); } else { LOG.warn("Can't save default configuration."); removeCascadeConfigurationSchema(savedSchema.getId()); throw new IncorrectParameterException("Can't save default configuration."); } } catch (Exception e) { LOG.error("Can't generate configuration based on protocol schema.", e); removeCascadeConfigurationSchema(savedSchema.getId()); throw new IncorrectParameterException("Can't save default configuration."); } } return savedSchema; } @Override public ConfigurationSchemaDto saveConfSchema(ConfigurationSchemaDto configurationSchema) { ConfigurationSchemaDto savedConfigSchema = null; if (configurationSchema != null) { String appId = configurationSchema.getApplicationId(); if (isValidId(appId)) { LOG.debug("Finding default endpoint group for application id [{}]", appId); EndpointGroup endpointGroup = endpointGroupDao.findByAppIdAndWeight(appId, 0); if (endpointGroup != null) { savedConfigSchema = saveConfSchema(configurationSchema, idToString(endpointGroup)); } else { LOG.warn("Can't find default group for application [{}]", appId); } } else { LOG.warn("Can't find endpoint group. Invalid application id [{}]", appId); } } else { LOG.warn("Configuration schema object is null"); } return savedConfigSchema; } @Override public String normalizeAccordingToOverrideConfigurationSchema(String appId, int schemaVersion, String configurationBody) { ConfigurationSchemaDto schemaDto = this.findConfSchemaByAppIdAndVersion(appId, schemaVersion); if (schemaDto != null) { OverrideSchema overrideSchema = new OverrideSchema(schemaDto.getOverrideSchema()); LOG.debug("Create default UUID validator with override schema: {}", overrideSchema.getRawSchema()); UuidValidator<OverrideData> uuidValidator = new DefaultUuidValidator<>(overrideSchema, new OverrideDataFactory()); GenericAvroConverter<GenericRecord> avroConverter = new GenericAvroConverter<>(overrideSchema.getRawSchema()); try { GenericRecord configRecord = avroConverter.decodeJson(configurationBody); // TODO: Need to use last active configuration instead of null. Will be changed after supporting delta configuration KaaData<OverrideSchema> body = uuidValidator.validateUuidFields(configRecord, null); if (body != null) { return body.getRawData(); } else { LOG.warn("Validated configuration body is empty"); throw new IncorrectParameterException("Validated configuration body is empty"); } } catch (IOException e) { LOG.error("Invalid configuration for override schema.", e); throw new IncorrectParameterException("Invalid configuration for override schema."); } } else { LOG.warn("Can't find configuration schema with version {}.", schemaVersion); throw new IncorrectParameterException("Can't find configuration schema for specified version."); } } @Override public ConfigurationSchemaDto findConfSchemaById(String id) { validateSqlId(id, "Incorrect configuration schema id " + id + ". Can't find configuration schema."); return getDto(configurationSchemaDao.findById(id)); } @Override public void removeConfSchemasByAppId(String appId) { validateSqlId(appId, "Incorrect application id " + appId + ". Can't remove configuration schema."); LOG.debug("Removing configuration schemas and correspond configuration by application id"); List<ConfigurationSchema> configurationSchemaList = configurationSchemaDao.findByApplicationId(appId); for (ConfigurationSchema configurationSchema : configurationSchemaList) { if (configurationSchema != null) { removeCascadeConfigurationSchema(idToString(configurationSchema)); } } } private ChangeNotificationDto createNotification(ConfigurationDto configurationDto, HistoryDto historyDto) { LOG.debug("Create notification after configuration update."); ChangeNotificationDto changeNotificationDto = null; if (historyDto != null) { changeNotificationDto = new ChangeNotificationDto(); changeNotificationDto.setAppId(configurationDto.getApplicationId()); changeNotificationDto.setAppSeqNumber(historyDto.getSequenceNumber()); String endpointGroupId = configurationDto.getEndpointGroupId(); if (isValidId(endpointGroupId)) { EndpointGroup group = endpointGroupDao.findById(endpointGroupId); if (group != null) { changeNotificationDto.setGroupId(idToString(group)); changeNotificationDto.setGroupSeqNumber(group.getSequenceNumber()); } else { LOG.debug("Can't find endpoint group by id [{}].", endpointGroupId); } } else { LOG.debug("Incorrect endpoint group id [{}].", endpointGroupId); } } else { LOG.debug("Can't save history information."); } return changeNotificationDto; } private void generateSchemas(ConfigurationSchemaDto schema) throws SchemaCreationException { CTLSchemaDto ctlSchema = ctlService.findCTLSchemaById(schema.getCtlSchemaId()); String sch = ctlService.flatExportAsString(ctlSchema); DataSchema dataSchema = new DataSchema(sch); if (!dataSchema.isEmpty()) { SchemaGenerationAlgorithm schemaGenerator = schemaGeneratorFactory.createSchemaGenerator(dataSchema); ProtocolSchema protocol = schemaGenerator.getProtocolSchema(); BaseSchema base = schemaGenerator.getBaseSchema(); OverrideSchema override = schemaGenerator.getOverrideSchema(); if (!protocol.isEmpty() && !base.isEmpty() && !override.isEmpty()) { schema.setBaseSchema(base.getRawSchema()); schema.setProtocolSchema(protocol.getRawSchema()); schema.setOverrideSchema(override.getRawSchema()); } else { LOG.trace("One or more generated schemas are empty. base: {} protocol {} override {}", base, protocol, override); throw new IncorrectParameterException("Can't generate schemas. Check your data schema"); } } else { LOG.warn("Can't generate schemas because data schema is empty."); } } private void removeCascadeConfigurationSchema(String id) { LOG.debug("Removing configurations and configuration schema by id " + id); // configurationDao.removeByConfigurationSchemaId(id); configurationSchemaDao.removeById(id); } private HistoryDto addHistory(ConfigurationDto dto, ChangeType type) { LOG.debug("Add history information about configuration update"); HistoryDto history = new HistoryDto(); history.setApplicationId(dto.getApplicationId()); ChangeDto change = new ChangeDto(); change.setConfigurationId(dto.getId()); change.setCfVersion(dto.getSchemaVersion()); change.setEndpointGroupId(dto.getEndpointGroupId()); change.setType(type); history.setChange(change); return historyService.saveHistory(history); } private void validateConfiguration(ConfigurationDto dto) { validateSqlObject(dto, "Can't save configuration, object is invalid."); validateSqlId(dto.getSchemaId(), "Configuration object invalid. Incorrect configuration schema id : " + dto.getSchemaId()); validateSqlId(dto.getEndpointGroupId(), "Configuration object invalid. Incorrect endpoint group id : " + dto.getEndpointGroupId()); } private ConfigurationSchemaDto saveConfigurationSchema(ConfigurationSchemaDto configurationSchema) { ConfigurationSchemaDto configurationSchemaDto; validateSqlObject(configurationSchema, "Can't save configuration schema. Configuration schema invalid."); String id = configurationSchema.getId(); if (isBlank(id)) { ConfigurationSchemaDto oldConfigurationSchemaDto = findLatestConfSchemaByAppId(configurationSchema.getApplicationId()); int version = 0; if (oldConfigurationSchemaDto != null) { version = oldConfigurationSchemaDto.getVersion(); } configurationSchema.setVersion(++version); configurationSchema.setCreatedTime(System.currentTimeMillis()); try { generateSchemas(configurationSchema); } catch (SchemaCreationException e) { LOG.warn("Can't generate protocol schema from configuration schema.", e); throw new IncorrectParameterException("Incorrect configuration schema. Can't generate protocol schema."); } } else { ConfigurationSchemaDto oldConfigurationSchemaDto = getDto(configurationSchemaDao.findById(id)); if (oldConfigurationSchemaDto != null) { oldConfigurationSchemaDto.editFields(configurationSchema); configurationSchema = oldConfigurationSchemaDto; } else { LOG.error("Can't find configuration schema with given id [{}].", id); throw new IncorrectParameterException("Invalid configuration schema id: " + id); } } configurationSchemaDto = getDto(configurationSchemaDao.save(new ConfigurationSchema(configurationSchema))); return configurationSchemaDto; } private ConfigurationSchemaDto findLatestConfSchemaByAppId(String applicationId) { validateSqlId(applicationId, "Incorrect application id " + applicationId + ". Can't find latest configuration schema."); return getDto(configurationSchemaDao.findLatestByApplicationId(applicationId)); } }
/* * Copyright 2012-2019 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.context.embedded; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import org.junit.jupiter.api.TestTemplate; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for Spring Boot's embedded servlet container support using war * packaging. * * @author Andy Wilkinson */ @EmbeddedServletContainerTest(packaging = "war", launchers = { PackagedApplicationLauncher.class, ExplodedApplicationLauncher.class }) public class EmbeddedServletContainerWarPackagingIntegrationTests { @TestTemplate public void nestedMetaInfResourceIsAvailableViaHttp(RestTemplate rest) { ResponseEntity<String> entity = rest.getForEntity("/nested-meta-inf-resource.txt", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @TestTemplate public void nestedMetaInfResourceIsAvailableViaServletContext(RestTemplate rest) { ResponseEntity<String> entity = rest.getForEntity("/servletContext?/nested-meta-inf-resource.txt", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @TestTemplate public void nestedJarIsNotAvailableViaHttp(RestTemplate rest) { ResponseEntity<String> entity = rest.getForEntity("/WEB-INF/lib/resources-1.0.jar", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } @TestTemplate public void applicationClassesAreNotAvailableViaHttp(RestTemplate rest) { ResponseEntity<String> entity = rest .getForEntity("/WEB-INF/classes/com/example/ResourceHandlingApplication.class", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } @TestTemplate public void webappResourcesAreAvailableViaHttp(RestTemplate rest) { ResponseEntity<String> entity = rest.getForEntity("/webapp-resource.txt", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @TestTemplate public void loaderClassesAreNotAvailableViaHttp(RestTemplate rest) { ResponseEntity<String> entity = rest.getForEntity("/org/springframework/boot/loader/Launcher.class", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); entity = rest.getForEntity("/org/springframework/../springframework/boot/loader/Launcher.class", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } @TestTemplate public void loaderClassesAreNotAvailableViaResourcePaths(RestTemplate rest) { ResponseEntity<String> entity = rest.getForEntity("/resourcePaths", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(readLines(entity.getBody())) .noneMatch((resourcePath) -> resourcePath.startsWith("/org/springframework/boot/loader")); } private List<String> readLines(String input) { if (input == null) { return Collections.emptyList(); } try (BufferedReader reader = new BufferedReader(new StringReader(input))) { return reader.lines().collect(Collectors.toList()); } catch (IOException ex) { throw new RuntimeException("Failed to read lines from input '" + input + "'"); } } }
/******************************************************************************* * Cloud Foundry * Copyright (c) [2009-2016] Pivotal Software, Inc. All Rights Reserved. * * This product is licensed to you under the Apache License, Version 2.0 (the "License"). * You may not use this product except in compliance with the License. * * This product includes a number of subcomponents with * separate copyright notices and license terms. Your use of these * subcomponents is subject to the terms and conditions of the * subcomponent's license, as noted in the LICENSE file. *******************************************************************************/ package org.cloudfoundry.identity.uaa.user; import org.cloudfoundry.identity.uaa.test.UaaTestAccounts; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class UaaUserEditorTests { private static UaaTestAccounts testAccounts = UaaTestAccounts.standard(null); private static String unm = testAccounts.getUserName(); private static String pwd = testAccounts.getPassword(); private static String email = "marissa@test.org"; private static String fnm = "Marissa"; private static String lnm = "Bloggs"; private static String auth1 = "uaa.admin,dash.user"; private static String auth2 = "openid"; @Test public void testShortFormat() { UaaUserEditor editor = new UaaUserEditor(); editor.setAsText(String.format("%s|%s", unm, pwd)); validate((UaaUser) editor.getValue(), unm, pwd, unm, null, null, null); } @Test public void testShortFormatWithAuthorities() { UaaUserEditor editor = new UaaUserEditor(); editor.setAsText(String.format("%s|%s|%s", unm, pwd, auth1)); validate((UaaUser) editor.getValue(), unm, pwd, unm, null, null, auth1.split(",")); editor.setAsText(String.format("%s|%s|%s", unm, pwd, auth2)); validate((UaaUser) editor.getValue(), unm, pwd, unm, null, null, auth2.split(",")); } @Test public void testLongFormat() { UaaUserEditor editor = new UaaUserEditor(); editor.setAsText(String.format("%s|%s|%s|%s|%s", unm, pwd, email, fnm, lnm)); validate((UaaUser) editor.getValue(), unm, pwd, email, fnm, lnm, null); } @Test public void testLongFormatWithAuthorities() { UaaUserEditor editor = new UaaUserEditor(); editor.setAsText(String.format("%s|%s|%s|%s|%s|%s", unm, pwd, email, fnm, lnm, auth1)); validate((UaaUser) editor.getValue(), unm, pwd, email, fnm, lnm, auth1.split(",")); editor.setAsText(String.format("%s|%s|%s|%s|%s|%s", unm, pwd, email, fnm, lnm, auth2)); validate((UaaUser) editor.getValue(), unm, pwd, email, fnm, lnm, auth2.split(",")); } @Test(expected = IllegalArgumentException.class) public void testInvalidFormat() { UaaUserEditor editor = new UaaUserEditor(); editor.setAsText(String.format("%s|%s|%s|%s", unm, pwd, fnm, lnm)); } @Test public void testAuthorities() { UaaUserEditor editor = new UaaUserEditor(); editor.setAsText("marissa|koala|marissa@test.org|Marissa|Bloggs|uaa.admin"); UaaUser user = (UaaUser) editor.getValue(); assertEquals(UaaAuthority.ADMIN_AUTHORITIES, user.getAuthorities()); } @Test public void usernameOnly() { UaaUserEditor editor = new UaaUserEditor(); editor.setAsText("marissa"); UaaUser user = (UaaUser) editor.getValue(); validate(user, unm, null, unm, null, null, null); } private void validate(UaaUser user, String expectedUnm, String expectedPwd, String expectedEmail, String expectedFnm, String expectedLnm, String[] expectedAuth) { assertEquals(expectedUnm, user.getUsername()); assertEquals(expectedPwd, user.getPassword()); assertEquals(expectedEmail, user.getEmail()); assertEquals(expectedFnm, user.getGivenName()); assertEquals(expectedLnm, user.getFamilyName()); assertTrue(user.getAuthorities().toString().contains("uaa.user")); if (expectedAuth != null) { for (String auth : expectedAuth) { assertTrue(user.getAuthorities().toString().contains(auth)); } } } }
package com.gotogether.entity; import lombok.Getter; import lombok.Setter; import javax.persistence.*; @Getter @Setter @Entity @Table(name = "roles") public class Role extends BaseEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Enumerated(EnumType.STRING) @Column(length = 20) private RoleType name; public Role() { } public Role(RoleType name) { this.name = name; } }
package sqlite.kripton41; import android.database.sqlite.SQLiteStatement; import com.abubusoft.kripton.android.Logger; import com.abubusoft.kripton.android.sqlite.Dao; import com.abubusoft.kripton.android.sqlite.KriptonContentValues; import com.abubusoft.kripton.android.sqlite.KriptonDatabaseWrapper; import com.abubusoft.kripton.common.StringUtils; /** * <p> * DAO implementation for entity <code>Bean01</code>, based on interface <code>DaoBeanDeleteOK</code> * </p> * * @see Bean01 * @see DaoBeanDeleteOK * @see Bean01Table */ public class DaoBeanDeleteOKImpl extends Dao implements DaoBeanDeleteOK { private static SQLiteStatement deleteDistancePreparedStatement0; public DaoBeanDeleteOKImpl(BindDummy08DaoFactory daoFactory) { super(daoFactory.context()); } /** * <h2>SQL delete</h2> * <pre>DELETE FROM bean01 WHERE id=:value</pre> * * <h2>Where parameters:</h2> * <dl> * <dt>:value</dt><dd>is mapped to method's parameter <strong>value</strong></dd> * </dl> * * @param value * is used as where parameter <strong>:value</strong> * * @return <code>true</code> if record is deleted, <code>false</code> otherwise */ @Override public boolean deleteDistance(double value) { if (deleteDistancePreparedStatement0==null) { // generate static SQL for statement String _sql="DELETE FROM bean01 WHERE id=?"; deleteDistancePreparedStatement0 = KriptonDatabaseWrapper.compile(_context, _sql); } KriptonContentValues _contentValues=contentValuesForUpdate(deleteDistancePreparedStatement0); _contentValues.addWhereArgs(String.valueOf(value)); // generation CODE_001 -- BEGIN // generation CODE_001 -- END // log section BEGIN if (_context.isLogEnabled()) { // display log Logger.info("DELETE FROM bean01 WHERE id=?"); // log for where parameters -- BEGIN int _whereParamCounter=0; for (String _whereParamItem: _contentValues.whereArgs()) { Logger.info("==> param%s: '%s'",(_whereParamCounter++), StringUtils.checkSize(_whereParamItem)); } // log for where parameters -- END } // log section END int result = KriptonDatabaseWrapper.updateDelete(deleteDistancePreparedStatement0, _contentValues); return result!=0; } public static void clearCompiledStatements() { if (deleteDistancePreparedStatement0!=null) { deleteDistancePreparedStatement0.close(); deleteDistancePreparedStatement0=null; } } }
package liqp.filters; import liqp.Template; import liqp.TemplateContext; import org.antlr.v4.runtime.RecognitionException; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class LastTest { @Test public void applyTest() throws RecognitionException { Template template = Template.parse("{{values | last}}"); String rendered = String.valueOf(template.render("{\"values\" : [\"Mu\", \"foo\", \"bar\"]}")); assertThat(rendered, is("bar")); } @Test public void applyObjectTest() { Template template = Template.parse("{%- assign product = values | last -%}{{product.title}} {{product.price}}"); String rendered = String.valueOf(template.render("{\"values\" : [{ \"title\": \"Product 1\", \"price\": 1299 }, { \"title\": \"Product 2\", \"price\": 2999 }]}")); assertThat(rendered, is("Product 2 2999")); } /* * def test_first_last * assert_equal 1, @filters.first([1,2,3]) * assert_equal 3, @filters.last([1,2,3]) * assert_equal nil, @filters.first([]) * assert_equal nil, @filters.last([]) * end */ @Test public void applyOriginalTest() { TemplateContext context = new TemplateContext(); Filter filter = Filter.getFilter("last"); assertThat(filter.apply(new Integer[]{1, 2, 3}, context), is((Object)3)); assertThat(filter.apply(new Integer[]{}, context), is((Object)null)); } }
/* * Copyright ConsenSys AG. * * 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. * * SPDX-License-Identifier: Apache-2.0 */ package org.hyperledger.besu.ethereum.api.handlers; public enum HandlerName { TIMEOUT }
package clarifai2.integration_tests; import clarifai2.api.request.input.SearchClause; import clarifai2.api.request.model.Action; import clarifai2.dto.input.ClarifaiImage; import clarifai2.dto.input.ClarifaiInput; import clarifai2.dto.model.ConceptModel; import clarifai2.dto.model.ModelType; import clarifai2.dto.model.output_info.ConceptOutputInfo; import clarifai2.dto.prediction.Concept; import org.junit.Ignore; import org.junit.Test; import java.io.File; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; @Ignore // These would all fail because they use strings like "@@sampleTrain" for the sake of the docs public class GuideExamples extends BaseIntTest { @Test public void retrieveAnAccessToken() { // NOTE: you probably won't have to handle this. The API client automatically refreshes your access token // before making any network calls if it is expired client.getToken(); } @Test public void addAnInputUsingAPubliclyAccessibleURL() { client.addInputs() .plus(ClarifaiInput.forImage("@@sampleTrain")) .allowDuplicateURLs(true) .executeSync(); } @Test public void addAnInputUsingBytes() { client.addInputs() .plus(ClarifaiInput.forImage(new File("image.png"))) .allowDuplicateURLs(true) .executeSync(); } @Test public void addInputsWithConcepts() { client.addInputs() .plus(ClarifaiInput.forImage("@@samplePuppy") .withConcepts( // To mark a concept as being absent, chain `.withValue(false)` Concept.forID("boscoe") ) ) .allowDuplicateURLs(true) .executeSync(); } @Test public void addInputsWithConceptsUnicode() throws UnsupportedEncodingException { // Please note: if the id used for a concept is in Unicode, for example '人', it must be URL escaped. It may be // smarter to use Unicode characters only for naming, and use hashes for concept IDs. The Java Documentation // recommends using UTF-8 for the encoding scheme. client.addInputs() .plus(ClarifaiInput.forImage("@@samplePuppy") .withConcepts( // To mark a concept as being absent, chain `.withValue(false)` Concept.forID(URLEncoder.encode("人", "UTF-8")) ) ) .allowDuplicateURLs(true) .executeSync(); } @Test public void getInputs() { client.getInputs() // optionally takes a perPage parameter .getPage(1) .executeSync(); } @Test public void getInputByID() { client.getInputByID("{{id}}").executeSync(); } @Test public void getInputsStatus() { client.getInputsStatus().executeSync(); } @Test public void bulkUpdateInputWithConcepts() { client.mergeConceptsForInput("{{id}}") .plus( Concept.forID("tree"), Concept.forID("water").withValue(false) ) .executeSync(); } @Test public void bulkDeleteConceptsFromAnInput() { client.mergeConceptsForInput("{{id}}") .plus( Concept.forID("tree"), Concept.forID("water") ) .executeSync(); } @Test public void deleteInputByID() { client.deleteInput("{{id}}").executeSync(); } @Test public void deleteAllInputs() { client.deleteAllInputs().executeSync(); } @Test public void addImagesToSearchIndex() { client.addInputs() .plus( ClarifaiInput.forImage("@@sampleTrain"), ClarifaiInput.forImage("@@sampleWedding") ) .allowDuplicateURLs(true) .executeSync(); } @Test public void searchByConcept() { client.searchInputs(SearchClause.matchConcept(Concept.forName("dress"))) .build() .getPage(1) .executeSync(); } @Test public void reverseImageSearch() { client.searchInputs(SearchClause.matchImageVisually(ClarifaiImage.of("http://i.imgur.com/HEoT5xR.png"))) .getPage(1) .executeSync(); } @Test public void createModel() { client.createModel("pets").executeSync(); } @Test public void createModelWithConcepts() { client.createModel("pets") .withOutputInfo(ConceptOutputInfo.forConcepts( Concept.forID("boscoe") )) .executeSync(); } @Test public void addConceptsToModel() { client.modifyModel("{{model_id}}") .withConcepts(Action.MERGE, Concept.forID("dogs")) .executeSync(); // Or, if you have a ConceptModel object, you can do it in an OO fashion final ConceptModel model = client.getModelByID("{{model_id}}").executeSync().get().asConceptModel(); model.modify() .withConcepts(Action.MERGE, Concept.forID("dogs")) .executeSync(); } @Test public void removeConceptsFromAModel() { client.modifyModel("{{model_id}}") .withConcepts(Action.REMOVE, Concept.forID("dogs")) .executeSync(); // Or, if you have a ConceptModel object, you can do it in an OO fashion final ConceptModel model = client.getModelByID("{{model_id}}").executeSync().get().asConceptModel(); model.modify() .withConcepts(Action.REMOVE, Concept.forID("dogs")) .executeSync(); } @Test public void getModels() { client.getModels().getPage(1).executeSync(); } @Test public void getModelByID() { client.getModelByID("{{model_id}}").executeSync(); } @Test public void listModelVersions() { client.getModelVersions("{{model_id}}").getPage(1).executeSync(); } @Test public void getModelVersionByID() { client.getModelVersionByID("{{model_id}}", "{{version_id}}").executeSync(); // Or in a more object-oriented manner: client.getModelByID("{{model_id}}") .executeSync().get() // Returns Model object .getVersionByID("{{version_id}}").executeSync(); } @Test public void getModelTrainingInputs() { client.getModelInputs("{{model_id}}").getPage(1).executeSync(); } @Test public void getModelTrainingInputsByVersion() { client.getModelInputs("{{model_id}}") .fromSpecificModelVersion("{{version_id}}") .getPage(1) .executeSync(); } @Test public void deleteAModel() { client.deleteModel("{{model_id}}").executeSync(); } @Test public void deleteAModelVersion() { client.deleteModelVersion("{{model_id}}", "{{version_id}}").executeSync(); // Or in a more object-oriented manner: client.getModelByID("{{model_id}}") .executeSync().get() // Returns Model object .deleteVersion("{{version_id}}") .executeSync(); } @Test public void deleteAllModels() { client.deleteAllModels().executeSync(); } @Test public void predictViaURL() { client.getDefaultModels().generalModel().predict() .withInputs( ClarifaiInput.forImage("@@sampleTrain") ) .executeSync(); } @Test public void predictViaImageBytes() { client.getDefaultModels().generalModel().predict() .withInputs( ClarifaiInput.forImage(new File("/home/user/image.jpeg")) ) .executeSync(); } @Test public void predictGeneralModel() { client.getDefaultModels().generalModel().predict() .withInputs( ClarifaiInput.forImage("@@sampleTrain") ) .executeSync(); } @Test public void addImageWithConcepts() { client.addInputs() .plus( ClarifaiInput.forImage("@@samplePuppy") .withConcepts(Concept.forID("boscoe")) ) .allowDuplicateURLs(true) .executeSync(); } @Test public void createAModel() { client.createModel("pets") .withOutputInfo(ConceptOutputInfo.forConcepts( Concept.forID("boscoe") )) .executeSync(); } @Test public void trainTheModel() { client.trainModel("{{model_id}}").executeSync(); } @Test public void predictWithTheModel() { client.predict("{{model_id}}") .withInputs( ClarifaiInput.forImage("@@samplePuppy") ) .executeSync(); } @Test public void searchByUserSuppliedConcept() { // Search concept by name client.searchInputs(SearchClause.matchUserTaggedConcept(Concept.forName("cat"))) .getPage(1) .executeSync(); // Search concept by ID client.searchInputs(SearchClause.matchUserTaggedConcept(Concept.forID("ai_mFqxrph2"))) .getPage(1) .executeSync(); // Search multiple concepts client.searchInputs(SearchClause.matchUserTaggedConcept(Concept.forID("cat"))) .and(SearchClause.matchUserTaggedConcept(Concept.forID("cute"))) .getPage(1) .executeSync(); // Search NOT by concept client.searchInputs(SearchClause.matchUserTaggedConcept(Concept.forID("cat").withValue(false))) .getPage(1) .executeSync(); } @Test public void searchByReverseImage() { // Search by image (image URL represented by: String or java.net.URL) client.searchInputs(SearchClause.matchImageVisually(ClarifaiImage.of("@@sampleTrain"))) .getPage(1) .executeSync(); // Search by image (image represented by: java.io.File or byte[]) client.searchInputs(SearchClause.matchImageVisually(ClarifaiImage.of(new File("image.png")))) .getPage(1) .executeSync(); } @Test public void searchMatchURL() { // Lookup images with this URL client.searchInputs(SearchClause.matchImageURL(ClarifaiImage.of(""))) .getPage(1) .executeSync(); } @Test public void searchByPredictedConcepts() { // Search concept by name client.searchInputs(SearchClause.matchConcept(Concept.forName("cat"))) .getPage(1) .executeSync(); // Search concept by ID client.searchInputs(SearchClause.matchConcept(Concept.forID("ai_mFqxrph2"))) .getPage(1) .executeSync(); // Search multiple concepts client.searchInputs(SearchClause.matchConcept(Concept.forID("cat"))) .and(SearchClause.matchConcept(Concept.forID("cute"))) .getPage(1) .executeSync(); // Search NOT by concept client.searchInputs(SearchClause.matchConcept(Concept.forID("cat").withValue(false))) .getPage(1) .executeSync(); } @Test public void searchByConceptAndPrediction() { client.searchInputs() // Matches images we tagged as "cat", and that the API tagged as not having "dog" .ands( SearchClause.matchUserTaggedConcept(Concept.forName("cat")), SearchClause.matchConcept(Concept.forName("dog").withValue(false)) ) .getPage(1) .executeSync(); } @Test public void searchANDing() { client.searchInputs() .ands( SearchClause.matchUserTaggedConcept(Concept.forName("cat")), SearchClause.matchConcept(Concept.forName("dog").withValue(false)), SearchClause.matchImageVisually(ClarifaiImage.of("@@sampleTrain")) ) .getPage(1) .executeSync(); } @Test public void addMultipleInputsWithIDs() { client.addInputs() .plus( ClarifaiInput.forImage("@@sampleTrain") .withConcepts(Concept.forID("id1")), ClarifaiInput.forImage("@@sampleWedding") .withConcepts(Concept.forID("id2")) ) .allowDuplicateURLs(true) .executeSync(); } @Test public void searchModelsByNameAndType() { client.findModel() .withModelType(ModelType.CONCEPT) .withName("general-v1.3") .getPage(1) .executeSync(); } @Test public void weddingModel() { client.getDefaultModels().weddingModel().predict() .withInputs(ClarifaiInput.forImage("@@sampleTrain")) .executeSync(); } @Test public void nsfwModel() { client.getDefaultModels().nsfwModel().predict() .withInputs(ClarifaiInput.forImage("@@sampleTrain")) .executeSync(); } @Test public void colorModel() { client.getDefaultModels().colorModel().predict() .withInputs(ClarifaiInput.forImage("@@sampleTrain")) .executeSync(); } @Test public void foodModel() { client.getDefaultModels().foodModel().predict() .withInputs(ClarifaiInput.forImage("@@sampleTrain")) .executeSync(); } @Test public void travelModel() { client.getDefaultModels().travelModel().predict() .withInputs(ClarifaiInput.forImage("@@sampleTrain")) .executeSync(); } /*@Test public void demographicsModel() { client.getDefaultModels().demographicsModel().predict() .withInputs(ClarifaiInput.forImage(ClarifaiImage.of("@@sampleTrain"))) .executeSync(); }*/ @Test public void retrieveCompleteModel() { ConceptModel model = client.getDefaultModels().generalModel(); client.getModelByID(model.id()).executeSync().get().asConceptModel(); } }
/* * 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.model; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.function.Consumer; import java.util.function.Supplier; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.XmlType; import org.apache.camel.Endpoint; import org.apache.camel.RouteTemplateContext; import org.apache.camel.builder.EndpointConsumerBuilder; import org.apache.camel.spi.AsEndpointUri; import org.apache.camel.spi.Metadata; /** * Defines a route template (parameterized routes) */ @Metadata(label = "configuration") @XmlRootElement(name = "routeTemplate") @XmlType(propOrder = { "templateParameters", "templateBeans", "route" }) @XmlAccessorType(XmlAccessType.FIELD) public class RouteTemplateDefinition extends OptionalIdentifiedDefinition { @XmlTransient private Consumer<RouteTemplateContext> configurer; @XmlElement(name = "templateParameter") @Metadata(description = "Adds a template parameter the route template uses") private List<RouteTemplateParameterDefinition> templateParameters; @XmlElement(name = "templateBean") @Metadata(description = "Adds a local bean the route template uses") private List<RouteTemplateBeanDefinition> templateBeans; @XmlElement(name = "route", required = true) private RouteDefinition route = new RouteDefinition(); public List<RouteTemplateParameterDefinition> getTemplateParameters() { return templateParameters; } public void setTemplateParameters(List<RouteTemplateParameterDefinition> templateParameters) { this.templateParameters = templateParameters; } public List<RouteTemplateBeanDefinition> getTemplateBeans() { return templateBeans; } public void setTemplateBeans(List<RouteTemplateBeanDefinition> templateBeans) { this.templateBeans = templateBeans; } public RouteDefinition getRoute() { return route; } public void setRoute(RouteDefinition route) { this.route = route; } public void setConfigurer(Consumer<RouteTemplateContext> configurer) { this.configurer = configurer; } public Consumer<RouteTemplateContext> getConfigurer() { return configurer; } // Fluent API // ------------------------------------------------------------------------- /** * Creates an input to the route * * @param uri the from uri * @return the builder */ public RouteDefinition from(@AsEndpointUri String uri) { return route.from(uri); } /** * Creates an input to the route * * @param endpoint the from endpoint * @return the builder */ public RouteDefinition from(Endpoint endpoint) { return route.from(endpoint); } /** * Creates an input to the route * * @param endpoint the from endpoint * @return the builder */ public RouteDefinition from(EndpointConsumerBuilder endpoint) { return route.from(endpoint); } /** * To define the route in the template */ public RouteDefinition route() { return route; } @Override public RouteTemplateDefinition description(String text) { DescriptionDefinition def = new DescriptionDefinition(); def.setText(text); setDescription(def); return this; } /** * Adds a required parameter the route template uses * * @param name the name of the parameter */ public RouteTemplateDefinition templateParameter(String name) { addTemplateParameter(name, null); return this; } /** * Adds an optional parameter the route template uses * * @param name the name of the parameter */ public RouteTemplateDefinition templateOptionalParameter(String name) { addTemplateOptionalParameter(name, null); return this; } /** * Adds an optional parameter the route template uses * * @param name the name of the parameter * @param description the description of the parameter */ public RouteTemplateDefinition templateOptionalParameter(String name, String description) { addTemplateOptionalParameter(name, description); return this; } /** * Adds a parameter (will use default value if not provided) the route template uses * * @param name the name of the parameter * @param defaultValue default value of the parameter */ public RouteTemplateDefinition templateParameter(String name, String defaultValue) { addTemplateParameter(name, defaultValue); return this; } /** * Adds a parameter (will use default value if not provided) the route template uses * * @param name the name of the parameter * @param defaultValue default value of the parameter * @param description the description of the parameter */ public RouteTemplateDefinition templateParameter(String name, String defaultValue, String description) { addTemplateParameter(name, defaultValue, description); return this; } /** * Adds the parameters the route template uses. * * The keys in the map is the parameter names, and the values are optional default value. If a parameter has no * default value then the parameter is required. * * @param parameters the parameters (only name and default values) */ public RouteTemplateDefinition templateParameters(Map<String, String> parameters) { parameters.forEach(this::addTemplateParameter); return this; } /** * Adds a local bean the route template uses * * @param name the name of the bean * @param type the type of the bean to associate the binding */ public RouteTemplateDefinition templateBean(String name, Class<?> type) { if (templateBeans == null) { templateBeans = new ArrayList<>(); } RouteTemplateBeanDefinition def = new RouteTemplateBeanDefinition(); def.setName(name); def.setBeanType(type); templateBeans.add(def); return this; } /** * Adds a local bean the route template uses * * @param name the name of the bean * @param bean the bean, or reference to bean (#class or #type), or a supplier for the bean */ @SuppressWarnings("unchecked") public RouteTemplateDefinition templateBean(String name, Object bean) { if (templateBeans == null) { templateBeans = new ArrayList<>(); } RouteTemplateBeanDefinition def = new RouteTemplateBeanDefinition(); def.setName(name); if (bean instanceof RouteTemplateContext.BeanSupplier) { def.setBeanSupplier((RouteTemplateContext.BeanSupplier<Object>) bean); } else if (bean instanceof Supplier) { def.setBeanSupplier(ctx -> ((Supplier<?>) bean).get()); } else if (bean instanceof String) { // its a string type def.setType((String) bean); } else { def.setBeanSupplier(ctx -> bean); } templateBeans.add(def); return this; } /** * Adds a local bean the route template uses * * @param name the name of the bean * @param bean the supplier for the bean */ public RouteTemplateDefinition templateBean(String name, Supplier<Object> bean) { if (templateBeans == null) { templateBeans = new ArrayList<>(); } RouteTemplateBeanDefinition def = new RouteTemplateBeanDefinition(); def.setName(name); def.setBeanSupplier(ctx -> ((Supplier<?>) bean).get()); templateBeans.add(def); return this; } /** * Adds a local bean the route template uses * * @param name the name of the bean * @param type the type of the bean to associate the binding * @param bean a supplier for the bean */ public RouteTemplateDefinition templateBean(String name, Class<?> type, RouteTemplateContext.BeanSupplier<Object> bean) { if (templateBeans == null) { templateBeans = new ArrayList<>(); } RouteTemplateBeanDefinition def = new RouteTemplateBeanDefinition(); def.setName(name); def.setBeanType(type); def.setBeanSupplier(bean); templateBeans.add(def); return this; } /** * Adds a local bean the route template uses * * @param name the name of the bean * @param language the language to use * @param script the script to use for creating the local bean */ public RouteTemplateDefinition templateBean(String name, String language, String script) { if (templateBeans == null) { templateBeans = new ArrayList<>(); } RouteTemplateBeanDefinition def = new RouteTemplateBeanDefinition(); def.setName(name); def.setType(language); def.setScript(script); templateBeans.add(def); return this; } /** * Adds a local bean the route template uses * * @param name the name of the bean * @param type the type of the bean to associate the binding * @param language the language to use * @param script the script to use for creating the local bean */ public RouteTemplateDefinition templateBean(String name, Class<?> type, String language, String script) { if (templateBeans == null) { templateBeans = new ArrayList<>(); } RouteTemplateBeanDefinition def = new RouteTemplateBeanDefinition(); def.setName(name); def.setBeanType(type); def.setType(language); def.setScript(script); templateBeans.add(def); return this; } /** * Adds a local bean the route template uses (via fluent builder) * * @param name the name of the bean * @return fluent builder to choose which language and script to use for creating the bean */ public RouteTemplateBeanDefinition templateBean(String name) { if (templateBeans == null) { templateBeans = new ArrayList<>(); } RouteTemplateBeanDefinition def = new RouteTemplateBeanDefinition(); def.setParent(this); def.setName(name); templateBeans.add(def); return def; } /** * Sets a configurer which allows to do configuration while the route template is being used to create a route. This * gives control over the creating process, such as binding local beans and doing other kind of customization. * * @param configurer the configurer with callback to invoke with the given route template context */ public RouteTemplateDefinition configure(Consumer<RouteTemplateContext> configurer) { this.configurer = configurer; return this; } @Override public String getShortName() { return "routeTemplate"; } @Override public String getLabel() { return "RouteTemplate[" + route.getInput().getLabel() + "]"; } private void addTemplateParameter(String name, String defaultValue) { addTemplateParameter(name, defaultValue, null); } private void addTemplateParameter(String name, String defaultValue, String description) { if (this.templateParameters == null) { this.templateParameters = new ArrayList<>(); } this.templateParameters.add(new RouteTemplateParameterDefinition(name, defaultValue, description)); } private void addTemplateOptionalParameter(String name, String description) { if (this.templateParameters == null) { this.templateParameters = new ArrayList<>(); } RouteTemplateParameterDefinition def = new RouteTemplateParameterDefinition(name, null, description); def.setRequired(false); this.templateParameters.add(def); } /** * Creates a copy of this template as a {@link RouteDefinition} which can be used to add as a new route. */ public RouteDefinition asRouteDefinition() { RouteDefinition copy = new RouteDefinition(); // must set these first in this order copy.setErrorHandlerRef(route.getErrorHandlerRef()); copy.setErrorHandlerFactory(route.getErrorHandlerFactory()); // and then copy over the rest // (do not copy id as it is used for route template id) copy.setAutoStartup(route.getAutoStartup()); copy.setDelayer(route.getDelayer()); copy.setGroup(route.getGroup()); copy.setInheritErrorHandler(route.isInheritErrorHandler()); copy.setInput(route.getInput()); copy.setInputType(route.getInputType()); copy.setLogMask(route.getLogMask()); copy.setMessageHistory(route.getMessageHistory()); copy.setOutputType(route.getOutputType()); copy.setOutputs(route.getOutputs()); copy.setRoutePolicies(route.getRoutePolicies()); copy.setRoutePolicyRef(route.getRoutePolicyRef()); copy.setRouteProperties(route.getRouteProperties()); copy.setShutdownRoute(route.getShutdownRoute()); copy.setShutdownRunningTask(route.getShutdownRunningTask()); copy.setStartupOrder(route.getStartupOrder()); copy.setStreamCache(route.getStreamCache()); copy.setTemplate(true); copy.setTrace(route.getTrace()); if (route.getDescription() != null) { copy.setDescription(route.getDescription()); } else { copy.setDescription(getDescription()); } copy.setPrecondition(route.getPrecondition()); return copy; } @FunctionalInterface public interface Converter { /** * Default implementation that uses {@link #asRouteDefinition()} to convert a {@link RouteTemplateDefinition} to * a {@link RouteDefinition} */ Converter DEFAULT_CONVERTER = new Converter() { @Override public RouteDefinition apply(RouteTemplateDefinition in, Map<String, Object> parameters) throws Exception { return in.asRouteDefinition(); } }; /** * Convert a {@link RouteTemplateDefinition} to a {@link RouteDefinition}. * * @param in the {@link RouteTemplateDefinition} to convert * @param parameters parameters that are given to the {@link Model#addRouteFromTemplate(String, String, Map)}. * Implementors are free to add or remove additional parameter. * @return the generated {@link RouteDefinition} */ RouteDefinition apply(RouteTemplateDefinition in, Map<String, Object> parameters) throws Exception; } }
/* * Copyright (C) 2016 Jason Taylor. * Released as open-source under the Apache License, Version 2.0. * * ============================================================================ * | Joise * ============================================================================ * * Copyright (C) 2016 Jason Taylor * * 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. * * ============================================================================ * | Accidental Noise Library * | -------------------------------------------------------------------------- * | Joise is a derivative work based on Josua Tippetts' C++ library: * | http://accidentalnoise.sourceforge.net/index.html * ============================================================================ * * Copyright (C) 2011 Joshua Tippetts * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ package com.sudoplay.joise.mapping; @SuppressWarnings("WeakerAccess") public enum MappingMode { NORMAL, SEAMLESS_X, SEAMLESS_Y, SEAMLESS_Z, SEAMLESS_XY, SEAMLESS_XZ, SEAMLESS_YZ, SEAMLESS_XYZ }
package com.example.seatapplication; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class SeatApplicationTests { @Test void contextLoads() { } }