gt
stringclasses
1 value
context
stringlengths
2.05k
161k
/* * This file is part of Industrial Foregoing. * * Copyright 2019, Buuz135 * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in the * Software without restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject to the * following conditions: * * The above copyright notice and this permission notice shall be included in all copies * or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.buuz135.industrial.block.transport.conveyor; import com.buuz135.industrial.api.conveyor.ConveyorUpgrade; import com.buuz135.industrial.api.conveyor.ConveyorUpgradeFactory; import com.buuz135.industrial.api.conveyor.IConveyorContainer; import com.buuz135.industrial.api.conveyor.gui.IGuiComponent; import com.buuz135.industrial.block.transport.ConveyorBlock; import com.buuz135.industrial.gui.component.*; import com.buuz135.industrial.module.ModuleTransport; import com.buuz135.industrial.proxy.block.filter.IFilter; import com.buuz135.industrial.proxy.block.filter.ItemStackFilter; import com.buuz135.industrial.utils.Reference; import com.hrznstudio.titanium.recipe.generator.TitaniumShapedRecipeBuilder; import net.minecraft.block.Blocks; import net.minecraft.data.IFinishedRecipe; import net.minecraft.entity.Entity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.item.Items; import net.minecraft.nbt.CompoundNBT; import net.minecraft.util.Direction; import net.minecraft.util.ResourceLocation; import net.minecraft.util.SoundCategory; import net.minecraft.util.SoundEvents; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.shapes.VoxelShape; import net.minecraft.util.math.shapes.VoxelShapes; import net.minecraft.util.text.TextFormatting; import net.minecraft.world.World; import net.minecraftforge.common.Tags; import javax.annotation.Nonnull; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.function.Consumer; public class ConveyorBlinkingUpgrade extends ConveyorUpgrade { public static VoxelShape BB = VoxelShapes.create(0.0625 * 3, 0.0625, 0.0625 * 3, 0.0625 * 13, 0.0625 * 1.2, 0.0625 * 13); private ItemStackFilter filter; private boolean whitelist; private int verticalDisplacement; private int horizontalDisplacement; public ConveyorBlinkingUpgrade(IConveyorContainer container, ConveyorUpgradeFactory factory, Direction side) { super(container, factory, side); this.filter = new ItemStackFilter(20, 20, 3, 3); this.whitelist = false; this.verticalDisplacement = 0; this.horizontalDisplacement = 1; } @Override public void handleEntity(Entity entity) { super.handleEntity(entity); if (whitelist != filter.matches(entity)) return; Direction direction = this.getContainer().getConveyorWorld().getBlockState(this.getContainer().getConveyorPosition()).get(ConveyorBlock.FACING); Vec3d vec3d = new Vec3d(horizontalDisplacement * direction.getDirectionVec().getX(), verticalDisplacement, horizontalDisplacement * direction.getDirectionVec().getZ()); BlockPos pos = this.getPos().add(vec3d.x, vec3d.y, vec3d.z); entity.setPosition(pos.getX() + 0.5, pos.getY() + 0.25, pos.getZ() + 0.5); this.getWorld().playSound(null, pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, SoundEvents.ITEM_CHORUS_FRUIT_TELEPORT, SoundCategory.AMBIENT, 0.5f, 1f); } @Override public VoxelShape getBoundingBox() { return BB; } @Override public CompoundNBT serializeNBT() { CompoundNBT compound = super.serializeNBT() == null ? new CompoundNBT() : super.serializeNBT(); compound.put("Filter", filter.serializeNBT()); compound.putBoolean("Whitelist", whitelist); compound.putDouble("VerticalDisplacement", verticalDisplacement); compound.putDouble("HorizontalDisplacement", horizontalDisplacement); return compound; } @Override public void deserializeNBT(CompoundNBT nbt) { super.deserializeNBT(nbt); if (nbt.contains("Filter")) filter.deserializeNBT(nbt.getCompound("Filter")); whitelist = nbt.getBoolean("Whitelist"); horizontalDisplacement = nbt.getInt("HorizontalDisplacement"); verticalDisplacement = nbt.getInt("VerticalDisplacement"); } @Override public boolean hasGui() { return true; } @Override public void handleButtonInteraction(int buttonId, CompoundNBT compound) { super.handleButtonInteraction(buttonId, compound); if (buttonId >= 0 && buttonId < filter.getFilter().length) { this.filter.setFilter(buttonId, ItemStack.read(compound)); this.getContainer().requestSync(); } if (buttonId == 10) { whitelist = !whitelist; this.getContainer().requestSync(); } if (buttonId == 11 && horizontalDisplacement < 8) { horizontalDisplacement += 1; this.getContainer().requestSync(); } if (buttonId == 12 && horizontalDisplacement > 1) { horizontalDisplacement -= 1; this.getContainer().requestSync(); } if (buttonId == 13 && verticalDisplacement < 8) { verticalDisplacement += 1; this.getContainer().requestSync(); } if (buttonId == 14 && verticalDisplacement > -8) { verticalDisplacement -= 1; this.getContainer().requestSync(); } } @Override public void addComponentsToGui(List<IGuiComponent> componentList) { super.addComponentsToGui(componentList); componentList.add(new FilterGuiComponent(this.filter.getLocX(), this.filter.getLocY(), this.filter.getSizeX(), this.filter.getSizeY()) { @Override public IFilter getFilter() { return ConveyorBlinkingUpgrade.this.filter; } }); ResourceLocation res = new ResourceLocation(Reference.MOD_ID, "textures/gui/machines.png"); componentList.add(new TexturedStateButtonGuiComponent(10, 80, 19, 18, 18, new StateButtonInfo(0, res, 1, 214, new String[]{"whitelist"}), new StateButtonInfo(1, res, 20, 214, new String[]{"blacklist"})) { @Override public int getState() { return whitelist ? 0 : 1; } }); componentList.add(new TextureGuiComponent(80, 40, 16, 16, res, 2, 234, "distance_horizontal")); componentList.add(new TextureGuiComponent(80, 56, 16, 16, res, 21, 234, "distance_vertical")); componentList.add(new TextGuiComponent(104, 44) { @Override public String getText() { return TextFormatting.DARK_GRAY + " " + horizontalDisplacement; } }); componentList.add(new TextGuiComponent(104, 61) { @Override public String getText() { return TextFormatting.DARK_GRAY + (verticalDisplacement >= 0 ? " " : "") + verticalDisplacement; } }); componentList.add(new TexturedStateButtonGuiComponent(11, 130, 40, 14, 14, new StateButtonInfo(0, res, 1, 104, new String[]{"increase"})) { @Override public int getState() { return 0; } }); componentList.add(new TexturedStateButtonGuiComponent(12, 146, 40, 14, 14, new StateButtonInfo(0, res, 16, 104, new String[]{"decrease"})) { @Override public int getState() { return 0; } }); componentList.add(new TexturedStateButtonGuiComponent(13, 130, 56, 14, 14, new StateButtonInfo(0, res, 1, 104, new String[]{"increase"})) { @Override public int getState() { return 0; } }); componentList.add(new TexturedStateButtonGuiComponent(14, 146, 56, 14, 14, new StateButtonInfo(0, res, 16, 104, new String[]{"decrease"})) { @Override public int getState() { return 0; } }); } public static class Factory extends ConveyorUpgradeFactory { public Factory() { setRegistryName("blinking"); } @Override public ConveyorUpgrade create(IConveyorContainer container, Direction face) { return new ConveyorBlinkingUpgrade(container, this, face); } @Override public Set<ResourceLocation> getTextures() { return Collections.singleton(new ResourceLocation(Reference.MOD_ID, "blocks/conveyor_blinking_upgrade")); } @Nonnull @Override public Set<Direction> getValidFacings() { return DOWN; } @Override public Direction getSideForPlacement(World world, BlockPos pos, PlayerEntity player) { return Direction.DOWN; } @Override @Nonnull public ResourceLocation getModel(Direction upgradeSide, Direction conveyorFacing) { return new ResourceLocation(Reference.MOD_ID, "block/conveyor_upgrade_blinking"); } @Nonnull @Override public ResourceLocation getItemModel() { return new ResourceLocation(Reference.MOD_ID, "conveyor_blinking_upgrade"); } @Override public void registerRecipe(Consumer<IFinishedRecipe> consumer) { TitaniumShapedRecipeBuilder.shapedRecipe(getUpgradeItem()).patternLine("IPI").patternLine("IDI").patternLine("ICI") .key('I', Tags.Items.INGOTS_IRON) .key('P', Items.CHORUS_FRUIT) .key('D', Blocks.PISTON) .key('C', ModuleTransport.CONVEYOR) .build(consumer); } } }
package com.piratkopia13.pixelplanet; import com.piratkopia13.pixelplanet.engine.core.*; import com.piratkopia13.pixelplanet.engine.physics.shape.AABB; import com.piratkopia13.pixelplanet.engine.physics.shape.Rectangle; import com.piratkopia13.pixelplanet.engine.physics.shape.Shape; import com.piratkopia13.pixelplanet.engine.rendering.Camera; import com.piratkopia13.pixelplanet.engine.rendering.Image; import org.lwjgl.input.Keyboard; import static org.lwjgl.opengl.GL11.*; public class Player { private Image shipImage; private float rotation; private Vector2f position; private Vector2f centerPos; private Vector2f size; private Camera camera; private float movementSpeed; // private Vector2f[] collisionPoints = new Vector2f[4]; private Shape testBox; public boolean renderCollisionTests = false; private GameMap map; private Vector2f velocity; private float tmpSpeed; public Player(){ this.position = new Vector2f(0, 0); this.centerPos = new Vector2f(0, 0); this.size = new Vector2f(80, 80); this.rotation = 0f; this.movementSpeed = 1; setShipIcon("axiom.png"); setPosition(0, 0); setSpeed(movementSpeed); // updateCollisionPoints(); this.velocity = new Vector2f(0, 0); } // private void updateCollisionPoints(){ // collisionPoints[0] = new Vector2f(position.getX(), position.getY()); // collisionPoints[1] = new Vector2f(position.getX(), position.getY()+size.getY()); // collisionPoints[2] = new Vector2f(position.getX()+size.getX(), position.getY()+size.getY()); // collisionPoints[3] = new Vector2f(position.getX()+size.getX(), position.getY()); // } private Vector2f[] getExpectedCollisionPoints(float dx, float dy){ Vector2f[] points = new Vector2f[4]; points[0] = new Vector2f(position.getX()+dx, position.getY()+dy); points[1] = new Vector2f(position.getX()+dx, position.getY()+size.getY()+dy); points[2] = new Vector2f(position.getX()+size.getX()+dx, position.getY()+size.getY()+dy); points[3] = new Vector2f(position.getX()+size.getX()+dx, position.getY()+dy); return points; } public void setShipIcon(String filename){ shipImage = new Image("ships/"+filename, 0, 0, (int)size.getX(), (int)size.getY()); } public void draw(){ if (renderCollisionTests && testBox != null) testBox.draw(); glPushMatrix(); glTranslatef(centerPos.getX(), centerPos.getY(), 0); // Translate to the center position of the ship for rotation glRotatef(rotation + 90, 0, 0, 1); glTranslatef(-size.getX() / 2, -size.getY() / 2, 0); // Translate to the rendering position of the ship shipImage.draw(); glPopMatrix(); } public void move(float dx, float dy){ this.position.addTo(new Vector2f(dx, dy)); this.centerPos.addTo(new Vector2f(dx, dy)); this.velocity = new Vector2f(dx, dy); // updateCollisionPoints(); if (camera != null) camera.setPosition(centerPos.toCamera()); Game.netSendPosition(); } public void moveTo(Vector2f pos){ Vector2f d = pos.add(position.inverted()); move(d.getX(), d.getY()); } public void follow(Camera camera){ this.camera = camera; camera.setPosition(centerPos.toCamera()); } public void pointTowardsMouse(boolean enabled){ SynchronizedTask task = new SynchronizedTask() { @Override public void update() { int mX = Game.getMouseX(); int mY = Game.getMouseY(); Vector2f mVec = centerPos.add(Game.getGameCamera().getPosition()).sub(mX, mY); rotation = (float)Math.toDegrees( Math.atan2(mVec.getY(), mVec.getX()) ) - 180; } }; if (enabled) Game.addSynchronizedTask(task); else Game.removeSynchronizedTask(task); } public void updateFromInput() { // Player movement and collision detection - response { boolean keyUp = Keyboard.isKeyDown(Keyboard.KEY_UP) | Keyboard.isKeyDown(Keyboard.KEY_W), keyDown = Keyboard.isKeyDown(Keyboard.KEY_DOWN) | Keyboard.isKeyDown(Keyboard.KEY_S), keyLeft = Keyboard.isKeyDown(Keyboard.KEY_LEFT) | Keyboard.isKeyDown(Keyboard.KEY_A), keyRight = Keyboard.isKeyDown(Keyboard.KEY_RIGHT) | Keyboard.isKeyDown(Keyboard.KEY_D), keySlow = Keyboard.isKeyDown(Keyboard.KEY_LSHIFT); float x = 0, y = 0, dimul = (float) Math.sqrt(2); if (keySlow) { // if (movementSpeed != 1f) tmpSpeed = movementSpeed; movementSpeed = 1f; } else { movementSpeed = 10f; } movementSpeed = movementSpeed * (float) Time.getDelta(); int blockSize = map.getBlockSize(); Vector2f collisionDiff; // boundingBox.move(position); if (keyUp && !keyDown) { y = -movementSpeed; collisionDiff = collisionDifference(x, y); if (collisionDiff != null) y = collisionDiff.getY() + blockSize; } if (keyDown && !keyUp) { y = movementSpeed; collisionDiff = collisionDifference(x, y); if (collisionDiff != null) y = collisionDiff.getY() - size.getY(); } if (keyLeft && !keyRight) { x = -movementSpeed; collisionDiff = collisionDifference(x, y); if (collisionDiff != null) x = collisionDiff.getX() + blockSize; } if (keyRight && !keyLeft) { x = movementSpeed; collisionDiff = collisionDifference(x, y); if (collisionDiff != null) x = collisionDiff.getX() - size.getX(); } if (keyLeft && keyUp && !keyDown && !keyRight) { x = -movementSpeed / dimul; y = -movementSpeed / dimul; collisionDiff = collisionDifference(x, 0); if (collisionDiff != null) { x = collisionDiff.getX() + blockSize; } collisionDiff = collisionDifference(0, y); if (collisionDiff != null) { y = collisionDiff.getY() + blockSize; } } if (keyRight && keyUp && !keyDown && !keyLeft) { x = movementSpeed / dimul; y = -movementSpeed / dimul; collisionDiff = collisionDifference(x, 0); if (collisionDiff != null) { x = collisionDiff.getX() - size.getX(); } collisionDiff = collisionDifference(0, y); if (collisionDiff != null) { y = collisionDiff.getY() + blockSize; } } if (keyLeft && keyDown && !keyUp && !keyRight) { x = -movementSpeed / dimul; y = movementSpeed / dimul; collisionDiff = collisionDifference(x, 0); if (collisionDiff != null) { x = collisionDiff.getX() + blockSize; } collisionDiff = collisionDifference(0, y); if (collisionDiff != null) { y = collisionDiff.getY() - size.getY(); } } if (keyRight && keyDown && !keyUp && !keyLeft) { x = movementSpeed / dimul; y = movementSpeed / dimul; collisionDiff = collisionDifference(x, 0); if (collisionDiff != null) { x = collisionDiff.getX() - size.getX(); } collisionDiff = collisionDifference(0, y); if (collisionDiff != null) { y = collisionDiff.getY() - size.getY(); } } if (x != 0 || y != 0) move(x, y); else this.velocity.set(0, 0); } } public Vector2f collisionDifference(float x, float y){ x += position.getX(); y += position.getY(); // collisions.clear(); int blockSize = map.getBlockSize(); int x1 = (int)Math.ceil(position.getX()); int y1 = (int)Math.ceil(position.getY()); int x2 = (int)Math.ceil(x+blockSize+size.getX()); int y2 = (int)Math.ceil(y+blockSize+size.getY()); if (position.getY() > y || position.getX() > x) { // to make sure x1 and y1 is the smallest coordinate x1 = (int)Math.ceil(x); y1 = (int)Math.ceil(y); x2 = (int)Math.ceil(position.getX()+blockSize+size.getX()); y2 = (int)Math.ceil(position.getY()+blockSize+size.getY()); } y1 /= blockSize; y2 /= blockSize; x1 /= blockSize; x2 /= blockSize; testBox = new Rectangle(x1*blockSize, y1*blockSize, (x2-x1)*blockSize, (y2-y1)*blockSize); testBox.setRenderable(); testBox.setColor(1, 1, 0, 0.1f); for (int iy = y1; iy < y2; iy++) { for (int ix = x1; ix < x2; ix++) { GameMap.MapBlock block = map.getBlockAt(ix, iy); if (block != null && (block.type.equals(GameMap.BlockType.WALL) || block.type.equals(GameMap.BlockType.STONE))) { AABB a = new AABB(block.x, block.y, blockSize, blockSize); AABB b = new AABB(x, y, size.getX(), size.getY()); if (a.intersects(b)) return new Vector2f(block.x - position.getX(), block.y - position.getY()); } } } return null; } public Vector2f getPosition() { return position; } public Vector2f getCenterPosition() { return centerPos; } public void setPosition(Vector2f position) { this.position = position; this.centerPos = position.add(size.divide(2)); // this.boundingBox.move(position); } public void setPosition(float x, float y) { setPosition(new Vector2f(x, y)); } public float getWidth(){ return size.getX(); } public float getHeight(){ return size.getX(); } public float getRotation() { return rotation; } public void setRotation(float rotation) { this.rotation = rotation; } public float getSpeed() { return movementSpeed; } public void setSpeed(float movementSpeed) { this.movementSpeed = movementSpeed; this.tmpSpeed = movementSpeed; } public Vector2f getVelocity() { return velocity; } public GameMap getMap() { return map; } public void setMap(GameMap map) { this.map = map; } }
/* FARIS : Factual Arrangement and Representation of Ideas in Sentences * FAris : Farabi & Aristotle * Faris : A knight (in Arabic) * -------------------------------------------------------------------- * Copyright (C) 2015 Abdelkrime Aries ([email protected]) * * 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 kariminf.faris.knowledge; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import kariminf.faris.philosophical.Action; import kariminf.faris.philosophical.QuantSubstance; import kariminf.faris.process.Processor; import kariminf.faris.tools.Search; /** * * @author Abdelkrime Aries ([email protected]) * <br> * Copyright (c) 2015-2016 Abdelkrime Aries * <br><br> * 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 * <br><br> * http://www.apache.org/licenses/LICENSE-2.0 * <br><br> * 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 Mind { public static enum MentalState { THINK, BELIEVE, HOPE, FEAR, FACT } public static final class MindWrapper { public Mind mind; public String name; public QuantSubstance owner; public HashMap<MentalState, Set<Thought>> thoughts = new HashMap<>(); public HashMap<MentalState, Set<Opinion>> opinions = new HashMap<>(); //even conditional have a truth level: "I think if ..., then ... ." public HashMap<MentalState, Set<Conditional>> conditions = new HashMap<>(); public HashSet<MentalState> mentalStates = new HashSet<>(); public MindWrapper(Mind mind){ this.mind = mind; } public void unsafeAddAll(){ name = mind.name; owner = mind.owner; thoughts = mind.thoughts; opinions = mind.opinions; conditions = mind.conditions; mentalStates = mind.mentalStates; } } protected String name; private QuantSubstance owner; private HashMap<MentalState, Set<Thought>> thoughts = new HashMap<>(); private HashMap<MentalState, Set<Opinion>> opinions = new HashMap<>(); //even conditional have a truth level: "I think if ..., then ... ." private HashMap<MentalState, Set<Conditional>> conditions = new HashMap<>(); private HashSet<MentalState> mentalStates = new HashSet<>(); /** * * @param name * @param owner */ public Mind(String name, QuantSubstance owner) { this.name = name; this.owner = owner; } /** * * @return */ public String getName(){ return name; } /** * * @param agent * @return */ public boolean hasOwner(QuantSubstance agent){ return owner.equals(agent); } /** * * @param ms * @return */ public Set<Thought> getThoughts(MentalState ms){ return getIdeas(ms, thoughts); } /** * * @param ms * @param truthTable * @return */ private <E> Set<E> getIdeas(MentalState ms, HashMap<MentalState, Set<E>> truthTable){ Set<E> ideas; if (truthTable.containsKey(ms)){ ideas = truthTable.get(ms); } else{ ideas = new HashSet<E>(); truthTable.put(ms, ideas); } return ideas; } /** * * @param ms * @param action */ public void addAction(MentalState ms, Action action){ Set<Thought> ideas = getIdeas(ms, thoughts); Thought newIdea = new Thought(action); Thought thought = Search.getElement(ideas, newIdea); thought.update(newIdea); ideas.add(thought); mentalStates.add(ms); } /** * * @param ms * @param other * @return */ public Mind addOpinion(MentalState ms, QuantSubstance other){ Set<Opinion> ideas = getIdeas(ms, opinions); Opinion newIdea = new Opinion(name, other); Opinion opinion = Search.getElement(ideas, newIdea); mentalStates.add(ms); ideas.add(opinion); return opinion.getMind(); } /** * * @param ms * @param other * @return */ public Mind addOpinion(MentalState ms, Mind other){ Set<Opinion> ideas = getIdeas(ms, opinions); Opinion newIdea = new Opinion(name, other); Opinion opinion = Search.getElement(ideas, newIdea); mentalStates.add(ms); ideas.add(opinion); return opinion.getMind(); } /** * * @param ms * @param condition */ public void addCondition(MentalState ms, Conditional condition){ Set<Conditional> ideas = getIdeas(ms, conditions); ideas.add(condition); mentalStates.add(ms); } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { String result = "==================\n"; result += "Name: " + name + "\n"; result += "Owner = " + owner + "\n"; for (MentalState ms: MentalState.values()){ if (! mentalStates.contains(ms)) continue; result += ms + "\n"; if (thoughts.containsKey(ms)) for (Idea i : thoughts.get(ms)){ result += i; } if (conditions.containsKey(ms)) for (Idea i : conditions.get(ms)){ result += i; } if (opinions.containsKey(ms)) for (Idea i : opinions.get(ms)){ result += i; } } return result; } public void process(Processor pr){ MindWrapper wrapper = new MindWrapper(this); wrapper.unsafeAddAll(); pr.processMind(wrapper); } }
/* * 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.ignite.internal.processors.cache.distributed.dht; import java.io.Externalizable; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.BitSet; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.UUID; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.internal.GridDirectCollection; import org.apache.ignite.internal.GridDirectTransient; import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion; import org.apache.ignite.internal.processors.cache.GridCacheContext; import org.apache.ignite.internal.processors.cache.GridCacheSharedContext; import org.apache.ignite.internal.processors.cache.distributed.GridDistributedTxPrepareRequest; import org.apache.ignite.internal.processors.cache.mvcc.MvccSnapshot; import org.apache.ignite.internal.processors.cache.transactions.IgniteTxEntry; import org.apache.ignite.internal.processors.cache.transactions.IgniteTxKey; import org.apache.ignite.internal.processors.cache.version.GridCacheVersion; import org.apache.ignite.internal.util.GridLeanMap; import org.apache.ignite.internal.util.tostring.GridToStringInclude; import org.apache.ignite.internal.util.typedef.internal.S; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.lang.IgniteUuid; import org.apache.ignite.plugin.extensions.communication.MessageCollectionItemType; import org.apache.ignite.plugin.extensions.communication.MessageReader; import org.apache.ignite.plugin.extensions.communication.MessageWriter; import org.jetbrains.annotations.Nullable; /** * DHT prepare request. */ public class GridDhtTxPrepareRequest extends GridDistributedTxPrepareRequest { /** */ private static final long serialVersionUID = 0L; /** Max order. */ private UUID nearNodeId; /** Future ID. */ private IgniteUuid futId; /** Mini future ID. */ private int miniId; /** Topology version. */ private AffinityTopologyVersion topVer; /** Invalidate near entries flags. */ private BitSet invalidateNearEntries; /** Near writes. */ @GridToStringInclude @GridDirectCollection(IgniteTxEntry.class) private Collection<IgniteTxEntry> nearWrites; /** Owned versions by key. */ @GridToStringInclude @GridDirectTransient private Map<IgniteTxKey, GridCacheVersion> owned; /** Owned keys. */ @GridDirectCollection(IgniteTxKey.class) private Collection<IgniteTxKey> ownedKeys; /** Owned values. */ @GridDirectCollection(GridCacheVersion.class) private Collection<GridCacheVersion> ownedVals; /** */ @GridDirectCollection(PartitionUpdateCountersMessage.class) private Collection<PartitionUpdateCountersMessage> updCntrs; /** Near transaction ID. */ private GridCacheVersion nearXidVer; /** Task name hash. */ private int taskNameHash; /** Preload keys. */ private BitSet preloadKeys; /** */ @GridDirectTransient private List<IgniteTxKey> nearWritesCacheMissed; /** */ private MvccSnapshot mvccSnapshot; /** {@code True} if remote tx should skip adding itself to completed versions map on finish. */ private boolean skipCompletedVers; /** Transaction label. */ @GridToStringInclude @Nullable private String txLbl; /** * Empty constructor required for {@link Externalizable}. */ public GridDhtTxPrepareRequest() { // No-op. } /** * @param futId Future ID. * @param miniId Mini future ID. * @param topVer Topology version. * @param tx Transaction. * @param timeout Transaction timeout. * @param dhtWrites DHT writes. * @param nearWrites Near writes. * @param txNodes Transaction nodes mapping. * @param nearXidVer Near transaction ID. * @param last {@code True} if this is last prepare request for node. * @param addDepInfo Deployment info flag. * @param storeWriteThrough Cache store write through flag. * @param retVal Need return value flag * @param mvccSnapshot Mvcc snapshot. * @param updCntrs Update counters for mvcc Tx. */ public GridDhtTxPrepareRequest( IgniteUuid futId, int miniId, AffinityTopologyVersion topVer, GridDhtTxLocalAdapter tx, long timeout, Collection<IgniteTxEntry> dhtWrites, Collection<IgniteTxEntry> nearWrites, Map<UUID, Collection<UUID>> txNodes, GridCacheVersion nearXidVer, boolean last, boolean onePhaseCommit, int taskNameHash, boolean addDepInfo, boolean storeWriteThrough, boolean retVal, MvccSnapshot mvccSnapshot, Collection<PartitionUpdateCountersMessage> updCntrs) { super(tx, timeout, null, dhtWrites, txNodes, retVal, last, onePhaseCommit, addDepInfo); assert futId != null; assert miniId != 0; this.topVer = topVer; this.futId = futId; this.nearWrites = nearWrites; this.miniId = miniId; this.nearXidVer = nearXidVer; this.taskNameHash = taskNameHash; this.mvccSnapshot = mvccSnapshot; this.updCntrs = updCntrs; storeWriteThrough(storeWriteThrough); needReturnValue(retVal); invalidateNearEntries = new BitSet(dhtWrites == null ? 0 : dhtWrites.size()); nearNodeId = tx.nearNodeId(); skipCompletedVers = tx.xidVersion() == tx.nearXidVersion(); txLbl = tx.label(); } /** * @return Mvcc info. */ public MvccSnapshot mvccSnapshot() { return mvccSnapshot; } /** * @return Update counters list. */ public Collection<PartitionUpdateCountersMessage> updateCounters() { return updCntrs; } /** * @return Near cache writes for which cache was not found (possible if client near cache was closed). */ @Nullable public List<IgniteTxKey> nearWritesCacheMissed() { return nearWritesCacheMissed; } /** * @return Near transaction ID. */ public GridCacheVersion nearXidVersion() { return nearXidVer; } /** * @return Near node ID. */ public UUID nearNodeId() { return nearNodeId; } /** * @return Task name hash. */ public int taskNameHash() { return taskNameHash; } /** * @return Near writes. */ public Collection<IgniteTxEntry> nearWrites() { return nearWrites == null ? Collections.<IgniteTxEntry>emptyList() : nearWrites; } /** * @param idx Entry index to set invalidation flag. * @param invalidate Invalidation flag value. */ void invalidateNearEntry(int idx, boolean invalidate) { invalidateNearEntries.set(idx, invalidate); } /** * @param idx Index to get invalidation flag value. * @return Invalidation flag value. */ public boolean invalidateNearEntry(int idx) { return invalidateNearEntries.get(idx); } /** * Marks last added key for preloading. * * @param idx Key index. */ void markKeyForPreload(int idx) { if (preloadKeys == null) preloadKeys = new BitSet(); preloadKeys.set(idx, true); } /** * Checks whether entry info should be sent to primary node from backup. * * @param idx Index. * @return {@code True} if value should be sent, {@code false} otherwise. */ public boolean needPreloadKey(int idx) { return preloadKeys != null && preloadKeys.get(idx); } /** * @return Future ID. */ public IgniteUuid futureId() { return futId; } /** * @return Mini future ID. */ public int miniId() { return miniId; } /** * @return Topology version. */ @Override public AffinityTopologyVersion topologyVersion() { return topVer; } /** * Sets owner and its mapped version. * * @param key Key. * @param ownerMapped Owner mapped version. */ public void owned(IgniteTxKey key, GridCacheVersion ownerMapped) { if (owned == null) owned = new GridLeanMap<>(3); owned.put(key, ownerMapped); } /** * @return Owned versions map. */ public Map<IgniteTxKey, GridCacheVersion> owned() { return owned; } /** * @return {@code True} if remote tx should skip adding itself to completed versions map on finish. */ public boolean skipCompletedVersion() { return skipCompletedVers; } /** * @return Transaction label. */ @Nullable public String txLabel() { return txLbl; } /** * {@inheritDoc} * * @param ctx */ @Override public void prepareMarshal(GridCacheSharedContext ctx) throws IgniteCheckedException { super.prepareMarshal(ctx); if (owned != null && ownedKeys == null) { ownedKeys = owned.keySet(); ownedVals = owned.values(); for (IgniteTxKey key: ownedKeys) { GridCacheContext cctx = ctx.cacheContext(key.cacheId()); key.prepareMarshal(cctx); if (addDepInfo) prepareObject(key, cctx); } } if (nearWrites != null) marshalTx(nearWrites, ctx); } /** {@inheritDoc} */ @Override public void finishUnmarshal(GridCacheSharedContext ctx, ClassLoader ldr) throws IgniteCheckedException { super.finishUnmarshal(ctx, ldr); if (ownedKeys != null) { assert ownedKeys.size() == ownedVals.size(); owned = U.newHashMap(ownedKeys.size()); Iterator<IgniteTxKey> keyIter = ownedKeys.iterator(); Iterator<GridCacheVersion> valIter = ownedVals.iterator(); while (keyIter.hasNext()) { IgniteTxKey key = keyIter.next(); GridCacheContext<?, ?> cacheCtx = ctx.cacheContext(key.cacheId()); if (cacheCtx != null) { key.finishUnmarshal(cacheCtx, ldr); owned.put(key, valIter.next()); } } } if (nearWrites != null) { for (Iterator<IgniteTxEntry> it = nearWrites.iterator(); it.hasNext();) { IgniteTxEntry e = it.next(); GridCacheContext<?, ?> cacheCtx = ctx.cacheContext(e.cacheId()); if (cacheCtx == null) { it.remove(); if (nearWritesCacheMissed == null) nearWritesCacheMissed = new ArrayList<>(); nearWritesCacheMissed.add(e.txKey()); } else { e.context(cacheCtx); e.unmarshal(ctx, true, ldr); } } } } /** {@inheritDoc} */ @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) { writer.setBuffer(buf); if (!super.writeTo(buf, writer)) return false; if (!writer.isHeaderWritten()) { if (!writer.writeHeader(directType(), fieldsCount())) return false; writer.onHeaderWritten(); } switch (writer.state()) { case 21: if (!writer.writeIgniteUuid("futId", futId)) return false; writer.incrementState(); case 22: if (!writer.writeBitSet("invalidateNearEntries", invalidateNearEntries)) return false; writer.incrementState(); case 23: if (!writer.writeInt("miniId", miniId)) return false; writer.incrementState(); case 24: if (!writer.writeMessage("mvccSnapshot", mvccSnapshot)) return false; writer.incrementState(); case 25: if (!writer.writeUuid("nearNodeId", nearNodeId)) return false; writer.incrementState(); case 26: if (!writer.writeCollection("nearWrites", nearWrites, MessageCollectionItemType.MSG)) return false; writer.incrementState(); case 27: if (!writer.writeMessage("nearXidVer", nearXidVer)) return false; writer.incrementState(); case 28: if (!writer.writeCollection("ownedKeys", ownedKeys, MessageCollectionItemType.MSG)) return false; writer.incrementState(); case 29: if (!writer.writeCollection("ownedVals", ownedVals, MessageCollectionItemType.MSG)) return false; writer.incrementState(); case 30: if (!writer.writeBitSet("preloadKeys", preloadKeys)) return false; writer.incrementState(); case 31: if (!writer.writeBoolean("skipCompletedVers", skipCompletedVers)) return false; writer.incrementState(); case 32: if (!writer.writeInt("taskNameHash", taskNameHash)) return false; writer.incrementState(); case 33: if (!writer.writeAffinityTopologyVersion("topVer", topVer)) return false; writer.incrementState(); case 34: if (!writer.writeString("txLbl", txLbl)) return false; writer.incrementState(); case 35: if (!writer.writeCollection("updCntrs", updCntrs, MessageCollectionItemType.MSG)) return false; writer.incrementState(); } return true; } /** {@inheritDoc} */ @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; if (!super.readFrom(buf, reader)) return false; switch (reader.state()) { case 21: futId = reader.readIgniteUuid("futId"); if (!reader.isLastRead()) return false; reader.incrementState(); case 22: invalidateNearEntries = reader.readBitSet("invalidateNearEntries"); if (!reader.isLastRead()) return false; reader.incrementState(); case 23: miniId = reader.readInt("miniId"); if (!reader.isLastRead()) return false; reader.incrementState(); case 24: mvccSnapshot = reader.readMessage("mvccSnapshot"); if (!reader.isLastRead()) return false; reader.incrementState(); case 25: nearNodeId = reader.readUuid("nearNodeId"); if (!reader.isLastRead()) return false; reader.incrementState(); case 26: nearWrites = reader.readCollection("nearWrites", MessageCollectionItemType.MSG); if (!reader.isLastRead()) return false; reader.incrementState(); case 27: nearXidVer = reader.readMessage("nearXidVer"); if (!reader.isLastRead()) return false; reader.incrementState(); case 28: ownedKeys = reader.readCollection("ownedKeys", MessageCollectionItemType.MSG); if (!reader.isLastRead()) return false; reader.incrementState(); case 29: ownedVals = reader.readCollection("ownedVals", MessageCollectionItemType.MSG); if (!reader.isLastRead()) return false; reader.incrementState(); case 30: preloadKeys = reader.readBitSet("preloadKeys"); if (!reader.isLastRead()) return false; reader.incrementState(); case 31: skipCompletedVers = reader.readBoolean("skipCompletedVers"); if (!reader.isLastRead()) return false; reader.incrementState(); case 32: taskNameHash = reader.readInt("taskNameHash"); if (!reader.isLastRead()) return false; reader.incrementState(); case 33: topVer = reader.readAffinityTopologyVersion("topVer"); if (!reader.isLastRead()) return false; reader.incrementState(); case 34: txLbl = reader.readString("txLbl"); if (!reader.isLastRead()) return false; reader.incrementState(); case 35: updCntrs = reader.readCollection("updCntrs", MessageCollectionItemType.MSG); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(GridDhtTxPrepareRequest.class); } /** {@inheritDoc} */ @Override public short directType() { return 34; } /** {@inheritDoc} */ @Override public byte fieldsCount() { return 36; } /** {@inheritDoc} */ @Override public int partition() { return U.safeAbs(version().hashCode()); } /** {@inheritDoc} */ @Override public String toString() { return S.toString(GridDhtTxPrepareRequest.class, this, "super", super.toString()); } }
/* THIS FILE IS GENERATED AUTOMATICALLY - DO NOT MODIFY. The contents of this file are subject to the Health Level-7 Public License Version 1.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.hl7.org/HPL/ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is all this file. The Initial Developer of the Original Code is automatically generated from HL7 copyrighted standards specification which may be subject to different license. Portions created by Initial Developer are Copyright (C) 2002-2004 Health Level Seven, Inc. All Rights Reserved. THIS FILE IS GENERATED AUTOMATICALLY - DO NOT MODIFY. */ package org.hl7.types.enums; import org.hl7.types.ValueFactory; import org.hl7.types.ANY; import org.hl7.types.CS; import org.hl7.types.ST; import org.hl7.types.UID; import org.hl7.types.BL; import org.hl7.types.CD; import org.hl7.types.SET; import org.hl7.types.LIST; import org.hl7.types.CR; import org.hl7.types.NullFlavor; import org.hl7.types.impl.NullFlavorImpl; import org.hl7.types.impl.STnull; import org.hl7.types.impl.BLimpl; import org.hl7.types.impl.SETnull; import org.hl7.types.impl.LISTnull; import java.util.EnumSet; import java.util.Map; import java.util.HashMap; /** A code specifying how branches in an action plan are selected among other branches.<p> <emph>Discussion:</emph> This attribute is part of the workflow control suite of attributes. An action plan is a composite Act with component Acts. In a sequential plan, each component has a sequenceNumber that specifies the ordering of the plan steps. Branches exist when multiple components have the same sequenceNumber. The splitCode specifies whether a branch is executed exclusively (case-switch) or inclusively, i.e., in parallel with other branches. </p> <p>In addition to exlusive and inclusive split the splitCode specifies how the pre-condition (also known as "guard conditions" on the branch) are evaluated. A guard condition may be evaluated once when the branching step is entered and if the conditions do not hold at that time, the branch is abandoned. Conversely execution of a branch may wait until the guard condition turns true. </p> <p>In exclusive wait branches, the first branch whose guard conditions turn true will be executed and all other branches abandoned. In inclusive wait branches some branches may already be executed while other branches still wait for their guard conditions to turn true. </p> <p>This table controls values for structural elements of the HL7 Reference Information Model. Therefore, it is part of the Normative Ballot for the RIM. </p> */ public enum ActRelationshipSplit implements CS { // ACTUAL DATA root(null, "ActRelationshipSplit", null, null), /** The pre-condition associated with the branch is evaluated once and if true the branch may be entered. All other exclusive branches compete with each other and only one will be selected. This implements a COND, IF and CASE conditionals, or "XOR-split." The order in which the branches are considered may be specified in the priorityNumber attribute. */ ExclusiveTryOnce(null, "Exclusive try once", "E1", "exclusive try once"), /** A branch is selected as soon as the pre-condition associated with the branch evaluates to true. If the condition is false, the branch may be entered later, when the condition turns true. All other exclusive branches compete with each other and only one will be selected. Each waiting branch executes in parallel with the default join code wait (see below). The order in which the branches are considered may be specified in the Service_relationship.priority_nmb. */ ExclusiveWait(null, "Exclusive wait", "EW", "exclusive wait"), /** A branch is executed if its associated preconditions permit. If associated preconditions do not permit, the branch is dropped. Inclusive branches are not suppressed and do not suppress other branches. */ InclusiveTryOnce(null, "Inclusive try once", "I1", "inclusive try once"), /** A branch is executed as soon as its associated conditions permit. If the condition is false, the branch may be entered later, when the condition turns true. Inclusive branches are not suppressed and do not suppress other branches. Each waiting branch executes in parallel with the default join code wait (see below). */ InclusiveWait(null, "Inclusive wait", "IW", "inclusive wait"); // BOILER PLATE CODE IN WHICH ONLY THE ENUM NAME MUST BE INSERTED public static final UID CODE_SYSTEM = ValueFactory.getInstance().UIDvalueOfLiteral("2.16.840.1.113883.5.13"); public static final ST CODE_SYSTEM_NAME = ValueFactory.getInstance().STvalueOfLiteral("ActRelationshipSplit"); private final ActRelationshipSplit _parent; // duh! what a cheap way to make a set, but really we don't expect there to be too many more than 2 parents! private final ActRelationshipSplit _parent2; private final ActRelationshipSplit _parent3; // well, found a 3rd :( private EnumSet<ActRelationshipSplit> _impliedConcepts = null; private ActRelationshipSplit(ActRelationshipSplit parent, String domainName, String code, String displayName) { this(parent, null, domainName, code, displayName); } private ActRelationshipSplit(ActRelationshipSplit parent, ActRelationshipSplit parent2, String domainName, String code, String displayName) { this(parent, null, null, domainName, code, displayName); } // duh! what a cheap way to make a set, but really we don't expect there to be too many more than 2 parents! private ActRelationshipSplit(ActRelationshipSplit parent, ActRelationshipSplit parent2, ActRelationshipSplit parent3, String domainName, String code, String displayName) { _parent = parent; _parent2 = parent2; _parent3 = parent3; _domainName = domainName; _code = ValueFactory.getInstance().STvalueOfLiteral(code); _displayName = ValueFactory.getInstance().STvalueOfLiteral(displayName); } private EnumSet<ActRelationshipSplit> getImpliedConcepts() { if(_impliedConcepts == null) { if(_parent == null) { // then _parent2, 3 is also null _impliedConcepts = EnumSet.of(root); _impliedConcepts.add(this); } else { _impliedConcepts = EnumSet.copyOf(_parent.getImpliedConcepts()); _impliedConcepts.add(this); if(_parent2 != null) _impliedConcepts.addAll(_parent2.getImpliedConcepts()); if(_parent3 != null) _impliedConcepts.addAll(_parent3.getImpliedConcepts()); } } return _impliedConcepts; } public final BL equal(ANY that) { if(this == that) return BLimpl.TRUE; if (!(that instanceof CD)) return BLimpl.FALSE; else if (that instanceof ActRelationshipSplit) return BLimpl.FALSE; else throw new UnsupportedOperationException("cannot handle argument of class " + that.getClass()); } public BL implies(CD that) { if(this == that || this.equals(that)) return BLimpl.TRUE; if(! (that instanceof ActRelationshipSplit)) throw new UnsupportedOperationException("cannot handle argument of class " + that.getClass()); final ActRelationshipSplit thatActRelationshipSplit = (ActRelationshipSplit)that; return BLimpl.valueOf(getImpliedConcepts().contains(thatActRelationshipSplit)); } public ActRelationshipSplit mostSpecificGeneralization(CD that) { if(this == that || this.equals(that)) return this; if(! (that instanceof ActRelationshipSplit)) throw new UnsupportedOperationException("cannot handle argument of class " + that.getClass()); final ActRelationshipSplit thatActRelationshipSplit = (ActRelationshipSplit)that; // First build the intersection of the implied concepts // the remainder is a single path of which we have to // find the most specific concept, i.e., the one who // has all others as parents, i.e., the one with the // largest set of implied concepts. EnumSet<ActRelationshipSplit> intersection = EnumSet.copyOf(getImpliedConcepts()); intersection.removeAll(EnumSet.complementOf(thatActRelationshipSplit.getImpliedConcepts())); intersection.remove(root); // XXX: this iterative search is likely to be least optimal because // we probably have to search the path from the root here. // I don't know of any better way to do it right now though. ActRelationshipSplit mostSpecificKnownGeneralization = root; int maxKnownSpecificity = 1; for(ActRelationshipSplit candidate : intersection) { int specificity = candidate.getImpliedConcepts().size(); if(specificity > maxKnownSpecificity) { maxKnownSpecificity = specificity; mostSpecificKnownGeneralization = candidate; } } return mostSpecificKnownGeneralization; } private static Map<ST,ActRelationshipSplit> _codeMap = null; public static ActRelationshipSplit valueOf(ST code) { // set up the _codeMap if needed for the first time if(_codeMap == null) { synchronized(ActRelationshipSplit.class) { // that one time might just as well keep it thread-safe if(_codeMap == null) { _codeMap = new HashMap(); for(ActRelationshipSplit concept : EnumSet.allOf(ActRelationshipSplit.class)) { ST conceptCode = concept.code(); if(conceptCode != null && conceptCode.nonNull().isTrue()) { _codeMap.put(conceptCode,concept); } } } } } if(code.nonNull().isTrue()) { ActRelationshipSplit concept = _codeMap.get(code); if(concept == null) throw new IllegalArgumentException(("unknown code " + code + " at codeSystem = " + "2.16.840.1.113883.5.13" + ", domain = " + "ActRelationshipSplit")); else return concept; } else return null; } // INVARIANT BOILER PLATE CODE public String toString() { return code().toString(); } private final String _domainName; private final ST _code; private final ST _displayName; public String domainName() { return _domainName; } public ST code() { return _code; } public ST displayName() { return _displayName; } public UID codeSystem() { return CODE_SYSTEM; } public ST codeSystemName() { return CODE_SYSTEM_NAME; } public ST codeSystemVersion() { return STnull.NI; } public ST originalText() { return STnull.NI; } public SET<CD> translation() { return SETnull.NA; } public LIST<CR> qualifier() { return LISTnull.NA; } public NullFlavor nullFlavor() { return NullFlavorImpl.NOT_A_NULL_FLAVOR; } public boolean isNullJ() { return false; } public boolean nonNullJ() { return true; } public boolean notApplicableJ() { return false; } public boolean unknownJ() { return false; } public boolean otherJ() { return false; } public BL isNull() { return BLimpl.FALSE; } public BL nonNull() { return BLimpl.TRUE; } public BL notApplicable() { return BLimpl.FALSE; } public BL unknown() { return BLimpl.FALSE; } public BL other() { return BLimpl.FALSE; } }
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.util.containers; import com.intellij.openapi.util.Condition; import com.intellij.util.Function; import com.intellij.util.Functions; import com.intellij.util.PairFunction; import junit.framework.TestCase; import org.jetbrains.annotations.NotNull; import java.util.Arrays; import java.util.Collection; import java.util.Map; /** * @author gregsh */ public class TreeTraverserTest extends TestCase { private static Map<Integer, Collection<Integer>> numbers() { return ContainerUtil.<Integer, Collection<Integer>>immutableMapBuilder(). put(1, Arrays.asList(2, 3, 4)). put(2, Arrays.asList(5, 6, 7)). put(3, Arrays.asList(8, 9, 10)). put(4, Arrays.asList(11, 12, 13)). build(); } private static final Condition<Integer> IS_ODD = new Condition<Integer>() { @Override public boolean value(Integer integer) { return integer.intValue() % 2 == 1; } }; private static final Function<Integer, Integer> INCREMENT = new Function<Integer, Integer>() { @Override public Integer fun(Integer k) { return k + 1; } }; private static final Function<Integer, Integer> SQUARE = new Function<Integer, Integer>() { @Override public Integer fun(Integer k) { return k * k; } }; private static final PairFunction<Integer, Integer, Integer> FIBONACCI = new PairFunction<Integer, Integer, Integer>() { @Override public Integer fun(Integer k1, Integer k2) { return k2 + k1; } }; @NotNull private static Condition<Integer> LESS_THAN(final int max) { return new Condition<Integer>() { @Override public boolean value(Integer integer) { return integer < max; } }; } @NotNull private static Condition<Integer> LESS_THAN_MOD(final int max) { return new Condition<Integer>() { @Override public boolean value(Integer integer) { return integer % max < max / 2; } }; } // JBIterable ---------------------------------------------- public void testGenerateRepeat() { JBIterable<Integer> it = JBIterable.generate(1, INCREMENT).take(3).repeat(3); assertEquals(9, it.size()); assertEquals(Arrays.asList(1, 2, 3, 1, 2, 3, 1, 2, 3), it.toList()); } public void testSkipTakeSize() { JBIterable<Integer> it = JBIterable.generate(1, INCREMENT).skip(10).take(10); assertEquals(10, it.size()); assertEquals(new Integer(11), it.first()); } public void testSkipWhile() { JBIterable<Integer> it = JBIterable.generate(1, INCREMENT).skipWhile(LESS_THAN_MOD(10)).take(10); assertEquals(Arrays.asList(5, 6, 7, 8, 9, 10, 11, 12, 13, 14), it.toList()); } public void testTakeWhile() { JBIterable<Integer> it = JBIterable.generate(1, INCREMENT).takeWhile(LESS_THAN_MOD(10)).take(10); assertEquals(Arrays.asList(1, 2, 3, 4), it.toList()); } public void testFilterTransformTakeWhile() { JBIterable<Integer> it = JBIterable.generate(1, INCREMENT).filter(IS_ODD).transform(SQUARE).takeWhile(LESS_THAN(100)); assertEquals(Arrays.asList(1, 9, 25, 49, 81), it.toList()); assertEquals(new Integer(1), it.first()); assertEquals(new Integer(81), it.last()); } public void testFilterTransformSkipWhile() { JBIterable<Integer> it = JBIterable.generate(1, INCREMENT).filter(IS_ODD).transform(SQUARE).skipWhile(LESS_THAN(100)).take(3); assertEquals(Arrays.asList(121, 169, 225), it.toList()); assertEquals(new Integer(121), it.first()); assertEquals(new Integer(225), it.last()); } public void testOnce() { JBIterable<Integer> it = JBIterable.once(JBIterable.generate(1, INCREMENT).take(3).iterator()); assertEquals(Arrays.asList(1, 2, 3), it.toList()); try { assertEquals(Arrays.asList(1, 2, 3), it.toList()); fail(); } catch (UnsupportedOperationException ignored) { } } // TreeTraverser ---------------------------------------------- @NotNull private static TreeTraverser<Integer> traverser() { return new TreeTraverser<Integer>(Functions.fromMap(numbers())); } public void testSimplePreOrderDfs() { TreeTraverser<Integer> t = traverser(); assertEquals(Arrays.asList(1, 2, 5, 6, 7, 3, 8, 9, 10, 4, 11, 12, 13), t.preOrderDfsTraversal(1).toList()); } public void testSimplePostOrderDfs() { TreeTraverser<Integer> t = traverser(); assertEquals(Arrays.asList(5, 6, 7, 2, 8, 9, 10, 3, 11, 12, 13, 4, 1), t.postOrderDfsTraversal(1).toList()); } public void testSimpleBfs() { TreeTraverser<Integer> t = traverser(); assertEquals(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13), t.bfsTraversal(1).toList()); } // FilteredTraverser ---------------------------------------------- @NotNull private static FilteredTraverser<Integer> filteredTraverser() { return new FilteredTraverser<Integer>(Functions.fromMap(numbers())); } public void testSimpleFilter() { FilteredTraverser<Integer> t = filteredTraverser(); assertEquals(Arrays.asList(1, 5, 7, 3, 9, 11, 13), t.withRoot(1).filter(IS_ODD).toList()); } public void testSimpleExpand() { FilteredTraverser<Integer> t = filteredTraverser(); assertEquals(Arrays.asList(1, 2, 3, 8, 9, 10, 4), t.withRoot(1).expand(IS_ODD).toList()); } public void testExpandFilter() { FilteredTraverser<Integer> t = filteredTraverser(); assertEquals(Arrays.asList(1, 3, 9), t.withRoot(1).expand(IS_ODD).filter(IS_ODD).toList()); } public void testSkipExpandedDfs() { FilteredTraverser<Integer> t = filteredTraverser(); assertEquals(Arrays.asList(2, 8, 9, 10, 4), t.withRoot(1).expand(IS_ODD).leavesOnly(true).leavesOnlyDfsTraversal().toList()); } public void testSkipExpandedBfs() { FilteredTraverser<Integer> t = filteredTraverser(); assertEquals(Arrays.asList(2, 4, 8, 9, 10), t.withRoot(1).expand(IS_ODD).leavesOnly(true).leavesOnlyBfsTraversal().toList()); } public void testExpandSkipFilterReset() { FilteredTraverser<Integer> t = filteredTraverser(); assertEquals(Arrays.asList(1, 5, 7, 3, 9, 11, 13), t.withRoot(1).expand(IS_ODD). leavesOnly(true).reset().filter(IS_ODD).toList()); } public void testFilterChildren() { FilteredTraverser<Integer> t = filteredTraverser(); assertEquals(Arrays.asList(1, 5, 7, 3, 9, 11, 13), t.withRoot(1).children(IS_ODD).toList()); } public void testEndlessGraph() { FilteredTraverser<Integer> t = new FilteredTraverser<Integer>(new Function<Integer, Iterable<Integer>>() { @Override public Iterable<Integer> fun(Integer k) { return JBIterable.generate(k, INCREMENT).transform(SQUARE).take(3); } }); assertEquals(Arrays.asList(1, 1, 4, 9, 1, 4, 9, 16, 25, 36, 81), t.withRoot(1).bfsTraversal().take(11).toList()); } public void testEndlessGraphParents() { FilteredTraverser<Integer> t = new FilteredTraverser<Integer>(new Function<Integer, Iterable<Integer>>() { @Override public Iterable<Integer> fun(Integer k) { return JBIterable.generate(1, k, FIBONACCI).skip(2).take(3); } }); TreeTraverser.TracingIt<Integer> it = t.withRoot(1).preOrderDfsTraversal().skip(20).typedIterator(); TreeTraverser.TracingIt<Integer> cursor = JBIterator.cursor(it).first(); assertNotNull(cursor); assertSame(cursor, it); assertEquals(Arrays.asList(20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1), cursor.backtrace().toList()); } }
/** * 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.drill.exec.store.parquet; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import org.apache.drill.common.exceptions.ExecutionSetupException; import org.apache.drill.common.exceptions.PhysicalOperatorSetupException; import org.apache.drill.common.expression.SchemaPath; import org.apache.drill.common.logical.FormatPluginConfig; import org.apache.drill.common.logical.StoragePluginConfig; import org.apache.drill.exec.metrics.DrillMetrics; import org.apache.drill.exec.physical.EndpointAffinity; import org.apache.drill.exec.physical.base.AbstractGroupScan; import org.apache.drill.exec.physical.base.GroupScan; import org.apache.drill.exec.physical.base.PhysicalOperator; import org.apache.drill.exec.physical.base.ScanStats; import org.apache.drill.exec.physical.base.ScanStats.GroupScanProperty; import org.apache.drill.exec.proto.CoordinationProtos.DrillbitEndpoint; import org.apache.drill.exec.store.StoragePluginRegistry; import org.apache.drill.exec.store.dfs.ReadEntryFromHDFS; import org.apache.drill.exec.store.dfs.ReadEntryWithPath; import org.apache.drill.exec.store.dfs.easy.FileWork; import org.apache.drill.exec.store.schedule.AffinityCreator; import org.apache.drill.exec.store.schedule.AssignmentCreator; import org.apache.drill.exec.store.schedule.BlockMapBuilder; import org.apache.drill.exec.store.schedule.CompleteWork; import org.apache.drill.exec.store.schedule.EndpointByteMap; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import parquet.hadoop.Footer; import parquet.hadoop.ParquetFileReader; import parquet.hadoop.metadata.BlockMetaData; import parquet.hadoop.metadata.ColumnChunkMetaData; import parquet.hadoop.metadata.ParquetMetadata; import parquet.org.codehaus.jackson.annotate.JsonCreator; import com.codahale.metrics.Histogram; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.Timer; import com.fasterxml.jackson.annotation.JacksonInject; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeName; import com.google.common.base.Preconditions; import com.google.common.base.Stopwatch; import com.google.common.collect.ListMultimap; import com.google.common.collect.Lists; @JsonTypeName("parquet-scan") public class ParquetGroupScan extends AbstractGroupScan { static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ParquetGroupScan.class); static final MetricRegistry metrics = DrillMetrics.getInstance(); static final String READ_FOOTER_TIMER = MetricRegistry.name(ParquetGroupScan.class, "readFooter"); static final String ENDPOINT_BYTES_TIMER = MetricRegistry.name(ParquetGroupScan.class, "endpointBytes"); static final String ASSIGNMENT_TIMER = MetricRegistry.name(ParquetGroupScan.class, "applyAssignments"); static final String ASSIGNMENT_AFFINITY_HIST = MetricRegistry.name(ParquetGroupScan.class, "assignmentAffinity"); final Histogram assignmentAffinityStats = metrics.histogram(ASSIGNMENT_AFFINITY_HIST); private ListMultimap<Integer, RowGroupInfo> mappings; private List<RowGroupInfo> rowGroupInfos; private final List<ReadEntryWithPath> entries; private final Stopwatch watch = new Stopwatch(); private final ParquetFormatPlugin formatPlugin; private final ParquetFormatConfig formatConfig; private final FileSystem fs; private List<EndpointAffinity> endpointAffinities; private String selectionRoot; private List<SchemaPath> columns; /* * total number of rows (obtained from parquet footer) */ private long rowCount; /* * total number of non-null value for each column in parquet files. */ private Map<SchemaPath, Long> columnValueCounts; public List<ReadEntryWithPath> getEntries() { return entries; } @JsonProperty("format") public ParquetFormatConfig getFormatConfig() { return this.formatConfig; } @JsonProperty("storage") public StoragePluginConfig getEngineConfig() { return this.formatPlugin.getStorageConfig(); } @JsonCreator public ParquetGroupScan( // @JsonProperty("entries") List<ReadEntryWithPath> entries, // @JsonProperty("storage") StoragePluginConfig storageConfig, // @JsonProperty("format") FormatPluginConfig formatConfig, // @JacksonInject StoragePluginRegistry engineRegistry, // @JsonProperty("columns") List<SchemaPath> columns, // @JsonProperty("selectionRoot") String selectionRoot // ) throws IOException, ExecutionSetupException { this.columns = columns; if (formatConfig == null) { formatConfig = new ParquetFormatConfig(); } Preconditions.checkNotNull(storageConfig); Preconditions.checkNotNull(formatConfig); this.formatPlugin = (ParquetFormatPlugin) engineRegistry.getFormatPlugin(storageConfig, formatConfig); Preconditions.checkNotNull(formatPlugin); this.fs = formatPlugin.getFileSystem().getUnderlying(); this.formatConfig = formatPlugin.getConfig(); this.entries = entries; this.selectionRoot = selectionRoot; this.readFooterFromEntries(); } public String getSelectionRoot() { return selectionRoot; } public ParquetGroupScan(List<FileStatus> files, // ParquetFormatPlugin formatPlugin, // String selectionRoot, List<SchemaPath> columns) // throws IOException { this.formatPlugin = formatPlugin; this.columns = columns; this.formatConfig = formatPlugin.getConfig(); this.fs = formatPlugin.getFileSystem().getUnderlying(); this.entries = Lists.newArrayList(); for (FileStatus file : files) { entries.add(new ReadEntryWithPath(file.getPath().toString())); } this.selectionRoot = selectionRoot; readFooter(files); } /* * This is used to clone another copy of the group scan. */ private ParquetGroupScan(ParquetGroupScan that) { this.columns = that.columns; this.endpointAffinities = that.endpointAffinities; this.entries = that.entries; this.formatConfig = that.formatConfig; this.formatPlugin = that.formatPlugin; this.fs = that.fs; this.mappings = that.mappings; this.rowCount = that.rowCount; this.rowGroupInfos = that.rowGroupInfos; this.selectionRoot = that.selectionRoot; this.columnValueCounts = that.columnValueCounts; } private void readFooterFromEntries() throws IOException { List<FileStatus> files = Lists.newArrayList(); for (ReadEntryWithPath e : entries) { files.add(fs.getFileStatus(new Path(e.getPath()))); } readFooter(files); } private void readFooter(List<FileStatus> statuses) throws IOException { watch.reset(); watch.start(); Timer.Context tContext = metrics.timer(READ_FOOTER_TIMER).time(); rowGroupInfos = Lists.newArrayList(); long start = 0, length = 0; rowCount = 0; columnValueCounts = new HashMap<SchemaPath, Long>(); ColumnChunkMetaData columnChunkMetaData; for (FileStatus status : statuses) { List<Footer> footers = ParquetFileReader.readFooters(formatPlugin.getHadoopConfig(), status); if (footers.size() == 0) { throw new IOException(String.format("Unable to find footer for file %s", status.getPath().getName())); } for (Footer footer : footers) { int index = 0; ParquetMetadata metadata = footer.getParquetMetadata(); for (BlockMetaData rowGroup : metadata.getBlocks()) { long valueCountInGrp = 0; // need to grab block information from HDFS columnChunkMetaData = rowGroup.getColumns().iterator().next(); start = columnChunkMetaData.getFirstDataPageOffset(); // this field is not being populated correctly, but the column chunks know their sizes, just summing them for // now // end = start + rowGroup.getTotalByteSize(); length = 0; for (ColumnChunkMetaData col : rowGroup.getColumns()) { length += col.getTotalSize(); valueCountInGrp = Math.max(col.getValueCount(), valueCountInGrp); SchemaPath path = SchemaPath.getSimplePath(col.getPath().toString().replace("[", "").replace("]", "").toLowerCase()); long valueCount = columnValueCounts.containsKey(path) ? columnValueCounts.get(path) : 0; columnValueCounts.put(path, valueCount + col.getValueCount()); } String filePath = footer.getFile().toUri().getPath(); rowGroupInfos.add(new ParquetGroupScan.RowGroupInfo(filePath, start, length, index)); logger.debug("rowGroupInfo path: {} start: {} length {}", filePath, start, length); index++; rowCount += valueCountInGrp; } } } Preconditions.checkState(!rowGroupInfos.isEmpty(), "No row groups found"); tContext.stop(); watch.stop(); logger.debug("Took {} ms to get row group infos", watch.elapsed(TimeUnit.MILLISECONDS)); } @JsonIgnore public FileSystem getFileSystem() { return this.fs; } public static class RowGroupInfo extends ReadEntryFromHDFS implements CompleteWork, FileWork { private EndpointByteMap byteMap; private int rowGroupIndex; private String root; @JsonCreator public RowGroupInfo(@JsonProperty("path") String path, @JsonProperty("start") long start, @JsonProperty("length") long length, @JsonProperty("rowGroupIndex") int rowGroupIndex) { super(path, start, length); this.rowGroupIndex = rowGroupIndex; } public RowGroupReadEntry getRowGroupReadEntry() { return new RowGroupReadEntry(this.getPath(), this.getStart(), this.getLength(), this.rowGroupIndex); } public int getRowGroupIndex() { return this.rowGroupIndex; } @Override public int compareTo(CompleteWork o) { return Long.compare(getTotalBytes(), o.getTotalBytes()); } @Override public long getTotalBytes() { return this.getLength(); } @Override public EndpointByteMap getByteMap() { return byteMap; } public void setEndpointByteMap(EndpointByteMap byteMap) { this.byteMap = byteMap; } } /** * Calculates the affinity each endpoint has for this scan, by adding up the affinity each endpoint has for each * rowGroup * * @return a list of EndpointAffinity objects */ @Override public List<EndpointAffinity> getOperatorAffinity() { if (this.endpointAffinities == null) { BlockMapBuilder bmb = new BlockMapBuilder(fs, formatPlugin.getContext().getBits()); try { for (RowGroupInfo rgi : rowGroupInfos) { EndpointByteMap ebm = bmb.getEndpointByteMap(rgi); rgi.setEndpointByteMap(ebm); } } catch (IOException e) { logger.warn("Failure while determining operator affinity.", e); return Collections.emptyList(); } this.endpointAffinities = AffinityCreator.getAffinityMap(rowGroupInfos); } return this.endpointAffinities; } @Override public void applyAssignments(List<DrillbitEndpoint> incomingEndpoints) throws PhysicalOperatorSetupException { this.mappings = AssignmentCreator.getMappings(incomingEndpoints, rowGroupInfos); } @Override public ParquetRowGroupScan getSpecificScan(int minorFragmentId) { assert minorFragmentId < mappings.size() : String.format( "Mappings length [%d] should be longer than minor fragment id [%d] but it isn't.", mappings.size(), minorFragmentId); List<RowGroupInfo> rowGroupsForMinor = mappings.get(minorFragmentId); Preconditions.checkArgument(!rowGroupsForMinor.isEmpty(), String.format("MinorFragmentId %d has no read entries assigned", minorFragmentId)); return new ParquetRowGroupScan(formatPlugin, convertToReadEntries(rowGroupsForMinor), columns, selectionRoot); } private List<RowGroupReadEntry> convertToReadEntries(List<RowGroupInfo> rowGroups) { List<RowGroupReadEntry> entries = Lists.newArrayList(); for (RowGroupInfo rgi : rowGroups) { RowGroupReadEntry rgre = new RowGroupReadEntry(rgi.getPath(), rgi.getStart(), rgi.getLength(), rgi.getRowGroupIndex()); entries.add(rgre); } return entries; } @Override public int getMaxParallelizationWidth() { return rowGroupInfos.size(); } public List<SchemaPath> getColumns() { return columns; } @Override public ScanStats getScanStats() { int columnCount = columns == null ? 20 : columns.size(); return new ScanStats(GroupScanProperty.EXACT_ROW_COUNT, rowCount, 1, rowCount * columnCount); } @Override @JsonIgnore public PhysicalOperator getNewWithChildren(List<PhysicalOperator> children) { Preconditions.checkArgument(children.isEmpty()); return new ParquetGroupScan(this); } @Override public String getDigest() { return toString(); } @Override public String toString() { return "ParquetGroupScan [entries=" + entries + ", selectionRoot=" + selectionRoot + ", columns=" + columns + "]"; } @Override public GroupScan clone(List<SchemaPath> columns) { ParquetGroupScan newScan = new ParquetGroupScan(this); newScan.columns = columns; return newScan; } @Override @JsonIgnore public boolean canPushdownProjects(List<SchemaPath> columns) { return true; } /** * Return column value count for the specified column. If does not contain such column, return 0. */ @Override public long getColumnValueCount(SchemaPath column) { return columnValueCounts.containsKey(column) ? columnValueCounts.get(column) : 0; } }
/* * Copyright (c) Microsoft. All rights reserved. * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ package com.microsoft.azure.eventprocessorhost; import static org.junit.Assert.*; import java.time.Instant; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.ThreadPoolExecutor; import org.junit.Test; import com.microsoft.azure.eventhubs.EventData; import com.microsoft.azure.eventhubs.EventHubClient; import com.microsoft.azure.eventhubs.PartitionReceiveHandler; import com.microsoft.azure.eventhubs.PartitionReceiver; public class SmokeTest extends TestBase { /* @Test public void smokeTest() throws Exception { PerTestSettings settings = new PerTestSettings("smoketest"); //settings.inBlobPrefix = "testprefix"; settings = testSetup(settings); settings.outUtils.sendToAny(settings.outTelltale); waitForTelltale(settings); testFinish(settings, SmokeTest.ANY_NONZERO_COUNT); } //@Test public void receiveFromNowTest() throws Exception { // Doing two iterations with the same "now" requires storing the "now" value instead of // using the current time when the initial offset provider is executed. final Instant storedNow = Instant.now(); // Do the first iteration. PerTestSettings firstSettings = receiveFromNowIteration(storedNow, 1, 1, null); // Do a second iteration with the same "now". Because the first iteration does not checkpoint, // it should receive the telltale from the first iteration AND the telltale from this iteration. // The purpose of running a second iteration is to look for bugs that occur when leases have been // created and persisted but checkpoints have not, so it is vital that the second iteration uses the // same storage container. receiveFromNowIteration(storedNow, 2, 2, firstSettings.inoutStorageContainerName); } private PerTestSettings receiveFromNowIteration(final Instant storedNow, int iteration, int expectedMessages, String containerName) throws Exception { PerTestSettings settings = new PerTestSettings("receiveFromNowTest-iter-" + iteration); settings.inForcedContainerName = containerName; settings.inOptions.setInitialOffsetProvider((partitionId) -> { return storedNow; }); settings = testSetup(settings); settings.outUtils.sendToAny(settings.outTelltale); waitForTelltale(settings); testFinish(settings, expectedMessages); return settings; } //@Test public void receiveFromCheckpoint() throws Exception { PerTestSettings firstSettings = receiveFromCheckpointIteration(1, SmokeTest.ANY_NONZERO_COUNT, null); receiveFromCheckpointIteration(2, firstSettings.outPartitionIds.size(), firstSettings.inoutStorageContainerName); } private PerTestSettings receiveFromCheckpointIteration(int iteration, int expectedMessages, String containerName) throws Exception { PerTestSettings settings = new PerTestSettings("receiveFromCkptTest-iter-" + iteration); settings.inForcedContainerName = containerName; settings.inDoCheckpoint = true; settings = testSetup(settings); for (String id: settings.outPartitionIds) { settings.outUtils.sendToPartition(id, settings.outTelltale); waitForTelltale(settings, id); } testFinish(settings, expectedMessages); return settings; } //@Test public void receiveAllPartitionsTest() throws Exception { PerTestSettings settings = new PerTestSettings("receiveAllPartitionsTest"); settings.inOptions.setInitialOffsetProvider((partitionId) -> { return Instant.now(); }); settings = testSetup(settings); final int maxGeneration = 10; for (int generation = 0; generation < maxGeneration; generation++) { for (String id : settings.outPartitionIds) { settings.outUtils.sendToPartition(id, "receiveAllPartitionsTest-" + id + "-" + generation); } System.out.println("Generation " + generation + " sent"); } for (String id : settings.outPartitionIds) { settings.outUtils.sendToPartition(id, settings.outTelltale); System.out.println("Telltale " + id + " sent"); } for (String id : settings.outPartitionIds) { waitForTelltale(settings, id); } testFinish(settings, (settings.outPartitionIds.size() * (maxGeneration + 1))); // +1 for the telltales } //@Test public void conflictingHosts() throws Exception { System.out.println("conflictingHosts starting"); RealEventHubUtilities utils = new RealEventHubUtilities(); utils.setup(-1); String telltale = "conflictingHosts-telltale-" + EventProcessorHost.safeCreateUUID(); String conflictingName = "conflictingHosts-NOTSAFE"; String storageName = conflictingName.toLowerCase() + EventProcessorHost.safeCreateUUID(); boolean doCheckpointing = false; boolean doMarker = false; PrefabGeneralErrorHandler general1 = new PrefabGeneralErrorHandler(); PrefabProcessorFactory factory1 = new PrefabProcessorFactory(telltale, doCheckpointing, doMarker); EventProcessorHost host1 = new EventProcessorHost(conflictingName, utils.getConnectionString().getEntityPath(), utils.getConsumerGroup(), utils.getConnectionString().toString(), TestUtilities.getStorageConnectionString(), storageName); EventProcessorOptions options1 = EventProcessorOptions.getDefaultOptions(); options1.setExceptionNotification(general1); PrefabGeneralErrorHandler general2 = new PrefabGeneralErrorHandler(); PrefabProcessorFactory factory2 = new PrefabProcessorFactory(telltale, doCheckpointing, doMarker); EventProcessorHost host2 = new EventProcessorHost(conflictingName, utils.getConnectionString().getEntityPath(), utils.getConsumerGroup(), utils.getConnectionString().toString(), TestUtilities.getStorageConnectionString(), storageName); EventProcessorOptions options2 = EventProcessorOptions.getDefaultOptions(); options2.setExceptionNotification(general2); host1.registerEventProcessorFactory(factory1, options1); host2.registerEventProcessorFactory(factory2, options2); int i = 0; while (true) { utils.sendToAny("conflict-" + i++, 10); System.out.println("\n." + factory1.getEventsReceivedCount() + "." + factory2.getEventsReceivedCount() + ":" + ((ThreadPoolExecutor)EventProcessorHost.getExecutorService()).getPoolSize() + ":" + Thread.activeCount()); //DebugThread.printThreadStatuses(); Thread.sleep(100); } } */ //@Test public void rawEpochStealing() throws Exception { RealEventHubUtilities utils = new RealEventHubUtilities(); utils.setup(-1); int clientSerialNumber = 0; while (true) { Thread[] blah = new Thread[Thread.activeCount() + 10]; int actual = Thread.enumerate(blah); if (actual >= blah.length) { System.out.println("Lost some threads"); } int parkedCount = 0; String selectingList = ""; boolean display = true; for (int i = 0; i < actual; i++) { display = true; StackTraceElement[] bloo = blah[i].getStackTrace(); String show = "nostack"; if (bloo.length > 0) { show = bloo[0].getClassName() + "." + bloo[0].getMethodName(); if (show.compareTo("sun.misc.Unsafe.park") == 0) { parkedCount++; display = false; } else if (show.compareTo("sun.nio.ch.WindowsSelectorImpl$SubSelector.poll0") == 0) { selectingList += (" " + blah[i].getId()); display = false; } } if (display) { System.out.print(" " + blah[i].getId() + ":" + show); } } System.out.println("\nParked: " + parkedCount + " SELECTING: " + selectingList); System.out.println("Client " + clientSerialNumber + " starting"); EventHubClient client = EventHubClient.createFromConnectionStringSync(utils.getConnectionString().toString()); PartitionReceiver receiver = client.createEpochReceiver(utils.getConsumerGroup(), "0", PartitionReceiver.START_OF_STREAM, 1).get(); boolean useReceiveHandler = false; if (useReceiveHandler) { Blah b = new Blah(clientSerialNumber++, receiver, client); receiver.setReceiveHandler(b).get(); // wait for messages to start flowing b.waitForReceivedMessages().get(); } else { receiver.receiveSync(1); System.out.println("Received a message"); } // Enable these lines to avoid overlap /* */ try { System.out.println("Non-overlap close of PartitionReceiver"); if (useReceiveHandler) { receiver.setReceiveHandler(null).get(); } receiver.close().get(); } catch (InterruptedException | ExecutionException e) { System.out.println("Client " + clientSerialNumber + " failed while closing PartitionReceiver: " + e.toString()); } try { System.out.println("Non-overlap close of EventHubClient"); client.close().get(); } catch (InterruptedException | ExecutionException e) { System.out.println("Client " + clientSerialNumber + " failed while closing EventHubClient: " + e.toString()); } System.out.println("Client " + clientSerialNumber + " closed"); /* */ System.out.println("Threads: " + Thread.activeCount()); } } private class Blah extends PartitionReceiveHandler { private int clientSerialNumber; private PartitionReceiver receiver; private EventHubClient client; private CompletableFuture<Void> receivedMessages = null; private boolean firstEvents = true; protected Blah(int clientSerialNumber, PartitionReceiver receiver, EventHubClient client) { super(300); this.clientSerialNumber = clientSerialNumber; this.receiver = receiver; this.client = client; } CompletableFuture<Void> waitForReceivedMessages() { this.receivedMessages = new CompletableFuture<Void>(); return this.receivedMessages; } @Override public void onReceive(Iterable<EventData> events) { if (this.firstEvents) { System.out.println("Client " + this.clientSerialNumber + " got events"); this.receivedMessages.complete(null); this.firstEvents = false; } } @Override public void onError(Throwable error) { System.out.println("Client " + this.clientSerialNumber + " got " + error.toString()); try { this.receiver.close().get(); } catch (InterruptedException | ExecutionException e) { System.out.println("Client " + this.clientSerialNumber + " failed while closing PartitionReceiver: " + e.toString()); } try { this.client.close().get(); } catch (InterruptedException | ExecutionException e) { System.out.println("Client " + this.clientSerialNumber + " failed while closing EventHubClient: " + e.toString()); } System.out.println("Client " + this.clientSerialNumber + " closed"); } } }
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.refactoring.move.moveFilesOrDirectories; import com.intellij.ide.util.EditorHelper; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.paths.PsiDynaReference; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiReference; import com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReference; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.searches.ReferencesSearch; import com.intellij.refactoring.BaseRefactoringProcessor; import com.intellij.refactoring.RefactoringBundle; import com.intellij.refactoring.listeners.RefactoringElementListener; import com.intellij.refactoring.listeners.RefactoringEventData; import com.intellij.refactoring.move.FileReferenceContextUtil; import com.intellij.refactoring.move.MoveCallback; import com.intellij.refactoring.rename.RenameUtil; import com.intellij.refactoring.util.CommonRefactoringUtil; import com.intellij.refactoring.util.NonCodeUsageInfo; import com.intellij.usageView.UsageInfo; import com.intellij.usageView.UsageViewDescriptor; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MoveFilesOrDirectoriesProcessor extends BaseRefactoringProcessor { private static final Logger LOG = Logger.getInstance( "#com.intellij.refactoring.move.moveFilesOrDirectories.MoveFilesOrDirectoriesProcessor"); protected final PsiElement[] myElementsToMove; private final boolean mySearchForReferences; protected final boolean mySearchInComments; protected final boolean mySearchInNonJavaFiles; private final PsiDirectory myNewParent; private final MoveCallback myMoveCallback; private NonCodeUsageInfo[] myNonCodeUsages; private final Map<PsiFile, List<UsageInfo>> myFoundUsages = new HashMap<PsiFile, List<UsageInfo>>(); public MoveFilesOrDirectoriesProcessor( Project project, PsiElement[] elements, PsiDirectory newParent, boolean searchInComments, boolean searchInNonJavaFiles, MoveCallback moveCallback, Runnable prepareSuccessfulCallback) { this(project, elements, newParent, true, searchInComments, searchInNonJavaFiles, moveCallback, prepareSuccessfulCallback); } public MoveFilesOrDirectoriesProcessor( Project project, PsiElement[] elements, PsiDirectory newParent, final boolean searchForReferences, boolean searchInComments, boolean searchInNonJavaFiles, MoveCallback moveCallback, Runnable prepareSuccessfulCallback) { super(project, prepareSuccessfulCallback); myElementsToMove = elements; myNewParent = newParent; mySearchForReferences = searchForReferences; mySearchInComments = searchInComments; mySearchInNonJavaFiles = searchInNonJavaFiles; myMoveCallback = moveCallback; } @Override @NotNull protected UsageViewDescriptor createUsageViewDescriptor(@NotNull UsageInfo[] usages) { return new MoveFilesOrDirectoriesViewDescriptor(myElementsToMove, myNewParent); } @Override @NotNull protected UsageInfo[] findUsages() { ArrayList<UsageInfo> result = new ArrayList<UsageInfo>(); for (int i = 0; i < myElementsToMove.length; i++) { PsiElement element = myElementsToMove[i]; if (mySearchForReferences) { for (PsiReference reference : ReferencesSearch.search(element, GlobalSearchScope.projectScope(myProject))) { result.add(new MyUsageInfo(reference.getElement(), i, reference)); } } findElementUsages(result, element); } return result.toArray(new UsageInfo[result.size()]); } private void findElementUsages(ArrayList<UsageInfo> result, PsiElement element) { if (!mySearchForReferences) { return; } if (element instanceof PsiFile) { final List<UsageInfo> usages = MoveFileHandler.forElement((PsiFile)element) .findUsages(((PsiFile)element), myNewParent, mySearchInComments, mySearchInNonJavaFiles); if (usages != null) { result.addAll(usages); myFoundUsages.put((PsiFile)element, usages); } } else if (element instanceof PsiDirectory) { for (PsiElement childElement : element.getChildren()) { findElementUsages(result, childElement); } } } @Override protected void refreshElements(@NotNull PsiElement[] elements) { LOG.assertTrue(elements.length == myElementsToMove.length); System.arraycopy(elements, 0, myElementsToMove, 0, elements.length); } @Override protected void performPsiSpoilingRefactoring() { if (myNonCodeUsages != null) { RenameUtil.renameNonCodeUsages(myProject, myNonCodeUsages); } } @Override protected void performRefactoring(@NotNull UsageInfo[] usages) { // If files are being moved then I need to collect some information to delete these // filese from CVS. I need to know all common parents of the moved files and releative // paths. // Move files with correction of references. try { final List<PsiFile> movedFiles = new ArrayList<PsiFile>(); final Map<PsiElement, PsiElement> oldToNewMap = new HashMap<PsiElement, PsiElement>(); for (final PsiElement element : myElementsToMove) { final RefactoringElementListener elementListener = getTransaction().getElementListener(element); if (element instanceof PsiDirectory) { MoveFilesOrDirectoriesUtil.doMoveDirectory((PsiDirectory)element, myNewParent); for (PsiElement psiElement : element.getChildren()) { processDirectoryFiles(movedFiles, oldToNewMap, psiElement); } } else if (element instanceof PsiFile) { final PsiFile movedFile = (PsiFile)element; if (mySearchForReferences) FileReferenceContextUtil.encodeFileReferences(element); MoveFileHandler.forElement(movedFile).prepareMovedFile(movedFile, myNewParent, oldToNewMap); PsiFile moving = myNewParent.findFile(movedFile.getName()); if (moving == null) { MoveFilesOrDirectoriesUtil.doMoveFile(movedFile, myNewParent); } moving = myNewParent.findFile(movedFile.getName()); movedFiles.add(moving); } elementListener.elementMoved(element); } // sort by offset descending to process correctly several usages in one PsiElement [IDEADEV-33013] CommonRefactoringUtil.sortDepthFirstRightLeftOrder(usages); // fix references in moved files to outer files for (PsiFile movedFile : movedFiles) { MoveFileHandler.forElement(movedFile).updateMovedFile(movedFile); if (mySearchForReferences) FileReferenceContextUtil.decodeFileReferences(movedFile); } retargetUsages(usages, oldToNewMap); if (MoveFilesOrDirectoriesDialog.isOpenInEditor()) { EditorHelper.openFilesInEditor(movedFiles.toArray(new PsiFile[movedFiles.size()])); } // Perform CVS "add", "remove" commands on moved files. if (myMoveCallback != null) { myMoveCallback.refactoringCompleted(); } } catch (IncorrectOperationException e) { @NonNls final String message = e.getMessage(); final int index = message != null ? message.indexOf("java.io.IOException") : -1; if (index >= 0) { ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { Messages.showMessageDialog(myProject, message.substring(index + "java.io.IOException".length()), RefactoringBundle.message("error.title"), Messages.getErrorIcon()); } }); } else { LOG.error(e); } } } @Nullable @Override protected String getRefactoringId() { return "refactoring.move"; } @Nullable @Override protected RefactoringEventData getBeforeData() { RefactoringEventData data = new RefactoringEventData(); data.addElements(myElementsToMove); return data; } @Nullable @Override protected RefactoringEventData getAfterData(@NotNull UsageInfo[] usages) { RefactoringEventData data = new RefactoringEventData(); data.addElement(myNewParent); return data; } private void processDirectoryFiles(List<PsiFile> movedFiles, Map<PsiElement, PsiElement> oldToNewMap, PsiElement psiElement) { if (psiElement instanceof PsiFile) { final PsiFile movedFile = (PsiFile)psiElement; if (mySearchForReferences) FileReferenceContextUtil.encodeFileReferences(psiElement); MoveFileHandler.forElement(movedFile).prepareMovedFile(movedFile, movedFile.getParent(), oldToNewMap); movedFiles.add(movedFile); } else if (psiElement instanceof PsiDirectory) { for (PsiElement element : psiElement.getChildren()) { processDirectoryFiles(movedFiles, oldToNewMap, element); } } } protected void retargetUsages(UsageInfo[] usages, Map<PsiElement, PsiElement> oldToNewMap) { final List<NonCodeUsageInfo> nonCodeUsages = new ArrayList<NonCodeUsageInfo>(); for (UsageInfo usageInfo : usages) { if (usageInfo instanceof MyUsageInfo) { final MyUsageInfo info = (MyUsageInfo)usageInfo; final PsiElement element = myElementsToMove[info.myIndex]; if (info.getReference() instanceof FileReference || info.getReference() instanceof PsiDynaReference) { final PsiElement usageElement = info.getElement(); if (usageElement != null) { final PsiFile usageFile = usageElement.getContainingFile(); final PsiFile psiFile = usageFile.getViewProvider().getPsi(usageFile.getViewProvider().getBaseLanguage()); if (psiFile != null && psiFile.equals(element)) { continue; // already processed in MoveFilesOrDirectoriesUtil.doMoveFile } } } final PsiElement refElement = info.myReference.getElement(); if (refElement != null && refElement.isValid()) { info.myReference.bindToElement(element); } } else if (usageInfo instanceof NonCodeUsageInfo) { nonCodeUsages.add((NonCodeUsageInfo)usageInfo); } } for (PsiFile movedFile : myFoundUsages.keySet()) { MoveFileHandler.forElement(movedFile).retargetUsages(myFoundUsages.get(movedFile), oldToNewMap); } myNonCodeUsages = nonCodeUsages.toArray(new NonCodeUsageInfo[nonCodeUsages.size()]); } @Override protected String getCommandName() { return RefactoringBundle.message("move.title"); //TODO!! } static class MyUsageInfo extends UsageInfo { int myIndex; PsiReference myReference; public MyUsageInfo(PsiElement element, final int index, PsiReference reference) { super(element); myIndex = index; myReference = reference; } } }
/* * Decompiled with CFR 0_132. */ package lib; import java.awt.Color; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.TreeMap; import lib.anim.AnimFrame; import lib.anim.Animation; import lib.anim.Character; import lib.map.Palette; import lib.map.Sprite; import main.Guide; public class Manager { public static int NAME_ADDRESS1 = 29618; public static int NAME_ADDRESS2 = 26186; public static int NAME_ADDRESS3 = 26218; public static int[] NAME_ADDRESSES4 = new int[]{29894, 29901, 29909, 29917}; public static int[] NAME_ADDRESSES5 = new int[]{29928, 29935, 29943, 29951}; public static Color shadowColor = new Color(0, 0, 0); private String romFileName; private Palette palette; private long animsListAddress; private long hitsListAddress; private long weaponsListAddress; private long iconsListAddress; private long namesListAddress; private long statsListAddress; private long speedListAddress; private int playableChars; private int namesSize; private int namesOffset; private TreeMap<Integer, Long> providedArtAddresses; private ArrayList<Long> paletteAddresses; private boolean globalCollisions; private boolean globalWeapons; private Character currCharacter; private int currCharacterId; private long currPaletteAddress; public Manager(String romFileName, Guide guide) throws IOException { int numChars = guide.getNumChars(); numChars = guide.getRealCharId(numChars); this.providedArtAddresses = new TreeMap(); this.paletteAddresses = new ArrayList(numChars); this.romFileName = romFileName; Rom rom = new Rom(new File(romFileName)); try { int i; this.animsListAddress = guide.getAnimsListAddress(); this.hitsListAddress = guide.getHitsListAddress(); this.weaponsListAddress = guide.getWeaponsListAddress(); this.iconsListAddress = guide.getPortraitsListAddress(); this.namesListAddress = guide.getNamesListAddress(); this.statsListAddress = guide.getStatsListAddress(); this.speedListAddress = guide.getSpeedListAddress(); this.playableChars = guide.getPlayableChars(); this.namesSize = guide.getNumNameLetters(); this.globalCollisions = guide.isGlobalCollisions(); this.globalWeapons = guide.isGlobalWeapons(); byte[] data = rom.getAllData(); if (this.animsListAddress == 0L) { this.animsListAddress = rom.findLabel(data, guide.getAnimsListLabel()); } if (this.hitsListAddress == 0L) { this.hitsListAddress = rom.findLabel(data, guide.getHitsListLabel()); } if (this.weaponsListAddress == 0L) { this.weaponsListAddress = rom.findLabel(data, guide.getWeaponsListLabel()); } if (this.iconsListAddress == 0L) { this.iconsListAddress = rom.findLabel(data, guide.getPortraitsListLabel()); } if (this.namesListAddress == 0L) { this.namesListAddress = rom.findLabel(data, guide.getNamesListLabel()); } if (this.statsListAddress == 0L) { this.statsListAddress = rom.findLabel(data, guide.getStatsListLabel()); } if (this.speedListAddress == 0L) { this.speedListAddress = rom.findLabel(data, guide.getSpeedListLabel()); } if (this.namesListAddress < -1L) { this.namesOffset = (int)(- this.namesListAddress); } for (i = 0; i < numChars; ++i) { String s = guide.getCompressedArtLabel(i); if (!s.isEmpty()) { this.providedArtAddresses.put(i, rom.findLabel(data, s)); continue; } s = guide.getSubArtLabel(i); if (!s.isEmpty()) { this.providedArtAddresses.put(i, rom.findLabel(data, s)); continue; } long id = guide.getCompressedArtAddress(i); if (id != 0L) { this.providedArtAddresses.put(i, id); continue; } id = guide.getSubArtAddress(i); if (id == 0L) continue; this.providedArtAddresses.put(i, id); } for (i = 0; i < numChars; ++i) { int fake = guide.getFakeCharId(i); String s = guide.getPaletteLabel(fake); if (!s.isEmpty()) { this.paletteAddresses.add(rom.findLabel(data, s)); continue; } this.paletteAddresses.add(guide.getPaletteAddress(fake)); } data = null; System.gc(); this.currCharacterId = -1; } catch (IOException e) { rom.close(); throw e; } rom.close(); System.out.println("Manager set up"); } public boolean hasGlobalCollision() { return this.globalCollisions; } public boolean hasGlobalWeapons() { return this.globalWeapons; } public void setPaletteAddress(long paletteAddress) throws IOException { this.currPaletteAddress = paletteAddress; Rom rom = new Rom(new File(this.romFileName)); try { this.palette = rom.readPalette(paletteAddress); } catch (IOException e) { rom.close(); throw e; } rom.close(); } public void setCharacter(int charId, int animsCount) throws IOException { this.setCharacter(charId, animsCount, -1); } public void setCharacter(int charId, int animsCount, int animsType) throws IOException { long paletteAddress = this.paletteAddresses.get(charId); Long subArt = this.providedArtAddresses.get(charId); AnimFrame.providedArtAddress = subArt != null ? subArt : 0L; Rom rom = new Rom(new File(this.romFileName)); try { Character newChar = rom.readCharacter(this.animsListAddress, this.hitsListAddress, this.weaponsListAddress, charId, animsCount, animsType, this.globalCollisions, this.globalWeapons, this.playableChars); this.currCharacterId = charId; this.currCharacter = newChar; if (this.currPaletteAddress != paletteAddress) { if (rom == null) { rom = new Rom(new File(this.romFileName)); } this.palette = rom.readPalette(paletteAddress); } } catch (IOException e) { rom.close(); throw e; } rom.close(); } public Character getCharacter() { return this.currCharacter; } public int getCurrentCharacterId() { return this.currCharacterId; } public Palette readDefaultPalette() throws FileNotFoundException, IOException { return readPalette(0); } public Palette readPalette(int charId) throws FileNotFoundException, IOException { Rom rom = new Rom(new File(this.romFileName)); long paletteAddress = this.paletteAddresses.get(0); Palette palette = null; try { palette = rom.readPalette(paletteAddress); } catch (IOException e) { rom.close(); throw e; } rom.close(); return palette; } public Palette getPalette() { return this.palette; } public BufferedImage getImage(int animId, int frameId) { return this.currCharacter.getAnimation(animId).getImage(frameId); } public BufferedImage getShadow(int animId, int frameId) { return this.currCharacter.getAnimation(animId).getShadow(frameId); } public void bufferAnimation(int animId) throws IOException { Animation anim = this.currCharacter.getAnimation(animId); if (anim.isBuffered()) { return; } Rom rom = new Rom(new File(this.romFileName)); try { anim.buffer(rom, this.palette, shadowColor); } catch (IOException e) { rom.close(); throw e; } rom.close(); } public void bufferAnimFrame(int animId, int frameId) throws IOException { Animation anim = this.currCharacter.getAnimation(animId); Rom rom = new Rom(new File(this.romFileName)); try { anim.bufferImage(frameId, rom, this.palette, shadowColor); } catch (IOException e) { rom.close(); throw e; } rom.close(); } public void save() throws IOException { Rom rom = new Rom(new File(this.romFileName)); try { if (this.currCharacter.wasModified()) { rom.writeCharacter(this.currCharacter, this.animsListAddress, this.hitsListAddress, this.weaponsListAddress, this.currCharacterId, this.globalCollisions, this.globalWeapons, this.playableChars); if (this.currCharacter.wasSpritesModified()) { rom.writeCharacterSprites(this.currCharacter, this.palette); } } } catch (IOException e) { rom.close(); throw e; } rom.close(); this.currCharacter.setModified(false); this.currCharacter.setSpritesModified(false); } public void replaceCharacterFromManager(Manager otherManager) throws IOException { Rom rom = new Rom(new File(this.romFileName)); long romSize = rom.length(); rom.close(); boolean newHits = this.currCharacter.getHitsSize() < otherManager.currCharacter.getHitsSize(); boolean newWeapons = this.currCharacter.getWeaponsSize() < otherManager.currCharacter.getWeaponsSize(); boolean newAnimationScripts = newHits || newWeapons; int newType = this.currCharacter.getAnimation((int)0).getFrame((int)0).type; if (!newAnimationScripts) { for (int i = 0; i < this.currCharacter.getNumAnimations(); ++i) { if (this.currCharacter.getAnimation(i).getMaxNumFrames() >= otherManager.currCharacter.getAnimation(i).getNumFrames()) continue; newAnimationScripts = true; break; } } this.currCharacter = otherManager.currCharacter; if (newAnimationScripts) { this.writeNewScripts(romSize, newHits, newWeapons); } rom = new Rom(new File(otherManager.romFileName)); try { this.importSprites(this.currCharacter, rom); } catch (IOException e) { rom.close(); throw e; } rom.close(); this.currCharacter.setModified(true); this.save(); String name = otherManager.readName(); if (name.length() > this.namesSize) { name = name.substring(0, this.namesSize); } this.writeName(name); int speed = otherManager.readSpeed(); this.writeSpeed(speed); BufferedImage icon = otherManager.readPortrait(); this.writePortrait(icon); int val = otherManager.readPowerStats(); this.writePowerStats(val); val = otherManager.readTechniqueStats(); this.writeTechniqueStats(val); val = otherManager.readSpeedStats(); this.writeSpeedStats(val); val = otherManager.readJumpStats(); this.writeJumpStats(val); val = otherManager.readStaminaStats(); this.writeStaminaStats(val); } private void importSprites(Character otherCharacter, Rom otherRom) throws IOException { Rom ourRom = new Rom(new File(this.romFileName)); try { HashSet<AnimFrame> processed = new HashSet<AnimFrame>(); for (int i = 0; i < otherCharacter.getNumAnimations(); ++i) { Animation anim = otherCharacter.getAnimation(i); for (int j = 0; j < anim.getNumFrames(); ++j) { AnimFrame frame = anim.getFrame(j); if (processed.contains(frame)) continue; processed.add(frame); Sprite newSprite = otherRom.readSprite(frame.mapAddress, frame.artAddress); BufferedImage img = newSprite.asImage(this.palette); // Free space from ours // Sprite sprite = rom.readSprite(frame.mapAddress, frame.artAddress); // FreeAddressesManager.freeChunk(frame.mapAddress, sprite.getMappingsSizeInBytes()); // FreeAddressesManager.freeChunk(frame.artAddress, sprite.getArtSizeInBytes()); long mapAddress = FreeAddressesManager.useBestSuitedAddress(newSprite.getMappingsSizeInBytes(), romSize()); ourRom.writeSpriteOnly(newSprite, mapAddress); long artAddress = FreeAddressesManager.useBestSuitedAddress(newSprite.getArtSizeInBytes(), romSize()); ourRom.writeSpriteArt(newSprite, artAddress, img, this.palette); frame.mapAddress = mapAddress; frame.artAddress = artAddress; } } } catch (IOException e) { ourRom.close(); throw e; } ourRom.close(); } public Sprite readSprite(int animationId, int frameId) throws IOException { Sprite res; Rom rom = new Rom(new File(this.romFileName)); try { AnimFrame frame = this.currCharacter.getAnimFrame(animationId, frameId); res = rom.readSprite(frame.mapAddress, frame.artAddress); } catch (IOException e) { rom.close(); throw e; } rom.close(); return res; } public void writeSprite(Sprite sprite, long mapAddress, long artAddress) throws IOException { Rom rom = new Rom(new File(this.romFileName)); try { rom.writeSprite(sprite, mapAddress, artAddress); } catch (IOException e) { rom.close(); throw e; } rom.close(); } public void writeSpriteOnly(Sprite sprite, long mapAddress) throws IOException { Rom rom = new Rom(new File(this.romFileName)); try { rom.writeSpriteOnly(sprite, mapAddress); } catch (IOException e) { rom.close(); throw e; } rom.close(); } public void writeSpriteArtOnly(Sprite sprite, long artAddress) throws IOException { Rom rom = new Rom(new File(this.romFileName)); try { rom.writeSpriteArtOnly(sprite, artAddress); } catch (IOException e) { rom.close(); throw e; } rom.close(); } public void writeNewAnimations(long newAddress) throws IOException { Rom rom = new Rom(new File(this.romFileName)); try { rom.writeNewCharAnims(this.currCharacter, this.animsListAddress, newAddress, this.currCharacterId, 0); } catch (IOException e) { rom.close(); throw e; } rom.close(); } public void writeNewScripts(long newAddress, boolean newHits, boolean newWeapons) throws IOException { Rom rom = new Rom(new File(this.romFileName)); try { rom.writeNewScripts(this.currCharacter, this.animsListAddress, this.hitsListAddress, this.weaponsListAddress, this.currCharacterId, 0, this.globalCollisions, this.globalWeapons, newAddress, newHits, newWeapons); } catch (IOException e) { rom.close(); throw e; } rom.close(); } public long romSize() throws IOException { Rom rom = new Rom(new File(this.romFileName)); long res = rom.length(); rom.close(); return res; } public int readSpeed() throws IOException { int res; Rom rom = new Rom(new File(this.romFileName)); try { res = rom.readSpeed(this.speedListAddress + (long)(this.currCharacterId * 2)); } catch (IOException e) { rom.close(); throw e; } rom.close(); return res; } public void decompressArt(String outName, long address) throws IOException { Rom rom = new Rom(new File(this.romFileName)); try { RandomDataStream data = rom.decompressArt(address); byte[] byteArray = data.getData(); FileOutputStream fos = new FileOutputStream(outName); fos.write(byteArray); fos.close(); } catch (IOException e) { rom.close(); throw e; } rom.close(); } public void writeSpeed(int newSpeed) throws IOException { Rom rom = new Rom(new File(this.romFileName)); try { rom.writeSpeed(this.speedListAddress + (long)(this.currCharacterId * 2), newSpeed); } catch (IOException e) { rom.close(); throw e; } rom.close(); } public String readName() throws IOException { String res; Rom rom = new Rom(new File(this.romFileName)); try { res = this.namesListAddress > 0L ? rom.readNameWithTable(this.namesListAddress + (long)(this.currCharacterId * 4), this.namesSize) : rom.readName(NAME_ADDRESS1 + this.namesOffset + this.currCharacterId * 8, this.namesSize); } catch (IOException e) { rom.close(); throw e; } rom.close(); return res; } public void writeName(String newName) throws IOException { Rom rom = new Rom(new File(this.romFileName)); try { String fullyName = newName; while (fullyName.length() < this.namesSize) { fullyName = fullyName + " "; } if (this.namesListAddress > 0L) { rom.writeNameWithTable(this.namesListAddress + (long)(this.currCharacterId * 4), fullyName, this.namesSize); } else { rom.writeName(NAME_ADDRESS1 + this.namesOffset + this.currCharacterId * 8, fullyName, this.namesSize); rom.writeName(NAME_ADDRESSES4[this.currCharacterId] + this.namesOffset, fullyName, this.namesSize); rom.writeName(NAME_ADDRESSES5[this.currCharacterId] + this.namesOffset, fullyName, this.namesSize); fullyName = newName; while (fullyName.length() < this.namesSize) { fullyName = " " + fullyName; } rom.writeName(NAME_ADDRESS2 + this.namesOffset + this.currCharacterId * 8, fullyName, this.namesSize); rom.writeName(NAME_ADDRESS3 + this.namesOffset + this.currCharacterId * 8, fullyName, this.namesSize); } } catch (IOException e) { rom.close(); throw e; } rom.close(); } public void writePortrait(BufferedImage img) throws IOException { Rom rom = new Rom(new File(this.romFileName)); long paletteAddress = this.paletteAddresses.get(0); try { Palette palette = rom.readPalette(paletteAddress); rom.writePortrait(this.iconsListAddress, this.currCharacterId, img, palette); } catch (IOException e) { rom.close(); throw e; } rom.close(); } public BufferedImage readPortrait() throws IOException { Rom rom = new Rom(new File(this.romFileName)); BufferedImage ret = null; long paletteAddress = this.paletteAddresses.get(0); try { Palette palette = rom.readPalette(paletteAddress); ret = rom.readPortrait(this.iconsListAddress, this.currCharacterId, palette); } catch (IOException e) { rom.close(); throw e; } rom.close(); return ret; } public int getNameMaxLen() { return this.namesSize; } private int readStats(int id) throws IOException { Rom rom = new Rom(new File(this.romFileName)); int ret = 0; try { ret = rom.readStats(this.statsListAddress, this.currCharacterId, id); } catch (IOException e) { rom.close(); throw e; } rom.close(); return ret; } private void writeStats(int id, int stats) throws IOException { Rom rom = new Rom(new File(this.romFileName)); try { rom.writeStats(this.statsListAddress, this.currCharacterId, id, stats); } catch (IOException e) { rom.close(); throw e; } rom.close(); } public int readPowerStats() throws IOException { return this.readStats(0); } public int readTechniqueStats() throws IOException { return this.readStats(1); } public int readSpeedStats() throws IOException { return this.readStats(2); } public int readJumpStats() throws IOException { return this.readStats(3); } public int readStaminaStats() throws IOException { return this.readStats(4); } public void writePowerStats(int value) throws IOException { this.writeStats(0, value); } public void writeTechniqueStats(int value) throws IOException { this.writeStats(1, value); } public void writeSpeedStats(int value) throws IOException { this.writeStats(2, value); } public void writeJumpStats(int value) throws IOException { this.writeStats(3, value); } public void writeStaminaStats(int value) throws IOException { this.writeStats(4, value); } }
/* * The MIT License * * Copyright 2017 OnCore Consulting LLC, 2017 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.oncore.calorders.rest; import java.io.Serializable; import java.util.Collection; import java.util.Date; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author oncore */ @Entity @Table(name = "GRP_TYPE_CD") @XmlRootElement @NamedQueries({ @NamedQuery(name = "GrpTypeCd.findAll", query = "SELECT g FROM GrpTypeCd g") , @NamedQuery(name = "GrpTypeCd.findByCode", query = "SELECT g FROM GrpTypeCd g WHERE g.code = :code") , @NamedQuery(name = "GrpTypeCd.findByShortDesc", query = "SELECT g FROM GrpTypeCd g WHERE g.shortDesc = :shortDesc") , @NamedQuery(name = "GrpTypeCd.findByLongDesc", query = "SELECT g FROM GrpTypeCd g WHERE g.longDesc = :longDesc") , @NamedQuery(name = "GrpTypeCd.findByCreateUserId", query = "SELECT g FROM GrpTypeCd g WHERE g.createUserId = :createUserId") , @NamedQuery(name = "GrpTypeCd.findByCreateTs", query = "SELECT g FROM GrpTypeCd g WHERE g.createTs = :createTs") , @NamedQuery(name = "GrpTypeCd.findByUpdateUserId", query = "SELECT g FROM GrpTypeCd g WHERE g.updateUserId = :updateUserId") , @NamedQuery(name = "GrpTypeCd.findByUpdateTs", query = "SELECT g FROM GrpTypeCd g WHERE g.updateTs = :updateTs")}) public class GrpTypeCd implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull @Size(min = 1, max = 4) @Column(name = "CODE") private String code; @Basic(optional = false) @NotNull @Size(min = 1, max = 64) @Column(name = "SHORT_DESC") private String shortDesc; @Basic(optional = false) @NotNull @Size(min = 1, max = 128) @Column(name = "LONG_DESC") private String longDesc; @Basic(optional = false) @NotNull @Size(min = 1, max = 32) @Column(name = "CREATE_USER_ID") private String createUserId; @Basic(optional = false) @NotNull @Column(name = "CREATE_TS") @Temporal(TemporalType.TIMESTAMP) private Date createTs; @Basic(optional = false) @NotNull @Size(min = 1, max = 32) @Column(name = "UPDATE_USER_ID") private String updateUserId; @Basic(optional = false) @NotNull @Column(name = "UPDATE_TS") @Temporal(TemporalType.TIMESTAMP) private Date updateTs; @OneToMany(cascade = CascadeType.ALL, mappedBy = "grpTypeCd") private Collection<Groups> groupsCollection; public GrpTypeCd() { } public GrpTypeCd(String code) { this.code = code; } public GrpTypeCd(String code, String shortDesc, String longDesc, String createUserId, Date createTs, String updateUserId, Date updateTs) { this.code = code; this.shortDesc = shortDesc; this.longDesc = longDesc; this.createUserId = createUserId; this.createTs = createTs; this.updateUserId = updateUserId; this.updateTs = updateTs; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getShortDesc() { return shortDesc; } public void setShortDesc(String shortDesc) { this.shortDesc = shortDesc; } public String getLongDesc() { return longDesc; } public void setLongDesc(String longDesc) { this.longDesc = longDesc; } public String getCreateUserId() { return createUserId; } public void setCreateUserId(String createUserId) { this.createUserId = createUserId; } public Date getCreateTs() { return createTs; } public void setCreateTs(Date createTs) { this.createTs = createTs; } public String getUpdateUserId() { return updateUserId; } public void setUpdateUserId(String updateUserId) { this.updateUserId = updateUserId; } public Date getUpdateTs() { return updateTs; } public void setUpdateTs(Date updateTs) { this.updateTs = updateTs; } @XmlTransient public Collection<Groups> getGroupsCollection() { return groupsCollection; } public void setGroupsCollection(Collection<Groups> groupsCollection) { this.groupsCollection = groupsCollection; } @Override public int hashCode() { int hash = 0; hash += (code != null ? code.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof GrpTypeCd)) { return false; } GrpTypeCd other = (GrpTypeCd) object; if ((this.code == null && other.code != null) || (this.code != null && !this.code.equals(other.code))) { return false; } return true; } @Override public String toString() { return "com.oncore.calorders.rest.GrpTypeCd[ code=" + code + " ]"; } }
/*L * Copyright Washington University in St. Louis * Copyright SemanticBits * Copyright Persistent Systems * Copyright Krishagni * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/catissue-simple-query/LICENSE.txt for details. */ package edu.wustl.simplequery.query; import java.sql.SQLException; import java.util.HashSet; import java.util.Vector; import edu.wustl.simplequery.global.Constants; /** *<p>Title: </p> *<p>Description: </p> *<p>Copyright: (c) Washington University, School of Medicine 2005</p> *<p>Company: Washington University, School of Medicine, St. Louis.</p> *@author Aarti Sharma *@version 1.0 */ public class SimpleConditionsImpl extends ConditionsImpl { /** * Vector of SimpleConditionsNode objects * This forms the storage of conditions in Simple Query Interface */ private Vector whereConditions = new Vector(); public SimpleConditionsImpl() { } /** * Adds condition to whereConditions Vector * @param condition * @return true (as per the general contract of Collection.add). */ public boolean addCondition(SimpleConditionsNode condition) { String operator = condition.getCondition().getOperator().getOperator(); if(Operator.operatorMap.containsKey(operator)) { condition.getCondition().getOperator().setOperator((String)Operator.operatorMap.get(operator)); } return whereConditions.add(condition); } /** * * @return */ public SimpleConditionsNode getCondition() { return null; } public boolean editCondition() { return false; } /* (non-Javadoc) * @see edu.wustl.caTISSUECore.query.ConditionsImpl#getString() */ public String getString(int tableSufix) throws SQLException { StringBuffer whereConditionsString = new StringBuffer(); SimpleConditionsNode simpleConditionsNode; Vector activityStatusConditions = new Vector(); boolean isActivityStatusField = false; for (int i = 0; i < whereConditions.size(); i++) { simpleConditionsNode = (SimpleConditionsNode) whereConditions.get(i); if (i == 0 && hasConditionsExceptActivityStatus()) whereConditionsString.append(" ( "); // Separating the activity status fields from rest of the fields so that //they are not included in brackets. //Assumption is that activity status conditions are always at the end String field = simpleConditionsNode.getCondition().getDataElement().getField(); if (field != null && field.equalsIgnoreCase(Constants.ACTIVITY_STATUS_COLUMN)) { for (int j = i; j < whereConditions.size(); j++) { activityStatusConditions.add(whereConditions.get(j)); } break; } if (i != whereConditions.size() - 1 && !((SimpleConditionsNode) whereConditions.get(i + 1)).getCondition() .getDataElement().getField().equals(Constants.ACTIVITY_STATUS_COLUMN)) whereConditionsString.append((simpleConditionsNode).toSQLString(tableSufix)); else if (hasConditionsExceptActivityStatus()) whereConditionsString.append((simpleConditionsNode).getCondition().toSQLString( tableSufix) + " ) "); whereConditionsString.append(" "); } //Adding activity status fields in the end if (activityStatusConditions.size() > 0 && hasConditionsExceptActivityStatus()) { whereConditionsString.append(" " + Operator.AND + " "); } else { whereConditionsString.append(" "); } for (int i = 0; i < activityStatusConditions.size(); i++) { if (i != activityStatusConditions.size() - 1) whereConditionsString.append(((SimpleConditionsNode) activityStatusConditions .get(i)).toSQLString(tableSufix)); else whereConditionsString.append(((SimpleConditionsNode) activityStatusConditions .get(i)).getCondition().toSQLString(tableSufix)); } return whereConditionsString.toString(); } // public HashSet getConditionObjects() // { // HashSet set = new HashSet(); // // /** // * For all elements in whereConditions add // * objects to the set // */ // for(int i=0; i<whereConditions.size();i++) // { // SimpleConditionsNode conditionsNode = (SimpleConditionsNode)whereConditions.get(i); // set.add(conditionsNode.getCondition().getDataElement().getTable()); // } // return set; // } /** * Inserts the specified condition at the specified position in whereConditions Vector. Shifts the element currently at * that position (if any) and any subsequent elements to the right (adds one to their indices). * @param position index at which the specified element is to be inserted. * @param condition condition to be inserted */ public boolean addCondition(int position, SimpleConditionsNode condition) { try { whereConditions.insertElementAt(condition, position); return true; } catch (ArrayIndexOutOfBoundsException ex) { return false; } } /* (non-Javadoc) * @see edu.wustl.catissuecore.query.ConditionsImpl#getQueryObjects(java.lang.String) */ public HashSet getQueryObjects() { HashSet queryObjects = new HashSet(); SimpleConditionsNode condition; for (int i = 0; i < whereConditions.size(); i++) { condition = (SimpleConditionsNode) whereConditions.get(i); if (condition != null) { queryObjects.add(condition.getConditionTable()); } } return queryObjects; } /* (non-Javadoc) * @see edu.wustl.catissuecore.query.ConditionsImpl#hasConditions() */ public boolean hasConditions() { boolean hasConditions = false; if (whereConditions.size() > 0) { SimpleConditionsNode simpleConditionsNode; for (int i = 0; i < whereConditions.size(); i++) { simpleConditionsNode = (SimpleConditionsNode) whereConditions.get(i); if (simpleConditionsNode != null) { String field = simpleConditionsNode.getCondition().getDataElement().getField(); if (field != null) { hasConditions = true; break; } } } } return hasConditions; } /** * Returns true if there are conditions other than activity status condition in query * @return */ public boolean hasConditionsExceptActivityStatus() { boolean hasConditions = false; SimpleConditionsNode simpleConditionsNode; for (int i = 0; i < whereConditions.size(); i++) { simpleConditionsNode = (SimpleConditionsNode) whereConditions.get(i); if (simpleConditionsNode != null) { String field = simpleConditionsNode.getCondition().getDataElement().getField(); if (field != null && !field.equals(Constants.ACTIVITY_STATUS_COLUMN)) { hasConditions = true; break; } } } return hasConditions; } /* (non-Javadoc) * @see edu.wustl.catissuecore.query.ConditionsImpl#hasConditionOnIdentifiedField() */ public boolean hasConditionOnIdentifiedField() { boolean hasConditionOnIdentifiedField = false; SimpleConditionsNode simpleConditionsNode; Condition condition; for (int i = 0; i < whereConditions.size(); i++) { simpleConditionsNode = (SimpleConditionsNode) whereConditions.get(i); condition = (Condition) simpleConditionsNode.getCondition(); if (condition.isConditionOnIdentifiedField()) { hasConditionOnIdentifiedField = true; return hasConditionOnIdentifiedField; } } return hasConditionOnIdentifiedField; } @Override public void formatTree() { // TODO Auto-generated method stub } }
/* * ___________ ______ _______ * / ____/__ // ____/ /_ __(_)___ ___ ___ _____ * / /_ /_ </ /_ / / / / __ `__ \/ _ \/ ___/ * / __/ ___/ / __/ / / / / / / / / / __/ / * /_/ /____/_/ /_/ /_/_/ /_/ /_/\___/_/ * * Open Source F3F timer UI and scores database * */ package com.marktreble.f3ftimer.exportimport; import android.annotation.TargetApi; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.ParcelFileDescriptor; import android.os.ResultReceiver; import androidx.annotation.Nullable; import androidx.fragment.app.FragmentTransaction; import androidx.appcompat.app.AppCompatActivity; import android.view.View; import android.widget.TextView; import com.marktreble.f3ftimer.R; import com.marktreble.f3ftimer.constants.IComm; import com.marktreble.f3ftimer.data.pilot.Pilot; import com.marktreble.f3ftimer.data.pilot.PilotData; import com.marktreble.f3ftimer.data.race.Race; import com.marktreble.f3ftimer.data.race.RaceData; import com.marktreble.f3ftimer.data.racepilot.RacePilotData; import com.marktreble.f3ftimer.dialog.GenericAlert; import com.marktreble.f3ftimer.dialog.GenericRadioPicker; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.FileDescriptor; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; public abstract class BaseExport extends AppCompatActivity { final String[] filetypes = {"json", "csv"}; final static int EXPORT_FILE_TYPE_JSON = 0; final static int EXPORT_FILE_TYPE_CSV = 1; private static final int WRITE_REQUEST_CODE = 2; Context mContext; Activity mActivity; static final String DIALOG = "dialog"; GenericAlert mDLG; GenericRadioPicker mDLG3; protected Integer mExportFileType = -1; protected JSONArray mArrExportFiles = new JSONArray(); String mProgressMessage; protected static final long PROGRESS_DELAY = 500; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.api); mContext = this; mActivity = this; if (savedInstanceState != null) { mProgressMessage = savedInstanceState.getString("progress_message"); View progress = findViewById(R.id.progress); TextView progressLabel = progress.findViewById(R.id.progressLabel); progressLabel.setText(mProgressMessage); try { mArrExportFiles = new JSONArray(savedInstanceState.getString("export_races")); } catch (JSONException e) { e.printStackTrace(); } } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString("progress_message", mProgressMessage); outState.putString("export_races", mArrExportFiles.toString()); } protected void showProgress(final String msg) { mProgressMessage = msg; runOnUiThread(new Runnable() { @Override public void run() { View progress = findViewById(R.id.progress); TextView progressLabel = progress.findViewById(R.id.progressLabel); progressLabel.setText(msg); } }); } public void onResume() { super.onResume(); this.registerReceiver(onBroadcast, new IntentFilter(IComm.RCV_UPDATE)); } public void onPause() { super.onPause(); this.unregisterReceiver(onBroadcast); } @TargetApi(Build.VERSION_CODES.JELLY_BEAN) @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_CANCELED) { finish(); return; } if (requestCode == WRITE_REQUEST_CODE) { if (resultCode == Activity.RESULT_OK) { if (data != null) { showProgress(getString(R.string.exporting)); final Uri uri = data.getData(); final int takeFlags = getIntent().getFlags() & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); // Check for the freshest data. getContentResolver().takePersistableUriPermission(uri, takeFlags); new Handler().postDelayed(new Runnable() { @Override public void run() { writeDocument(uri); } }, PROGRESS_DELAY); } else { finish(); } } } } protected void beginExport() { } protected String getSerialisedRaceData(int race_id, int round) { RaceData datasource = new RaceData(mContext); datasource.open(); String race = datasource.getSerialized(race_id); String racegroups = datasource.getGroupsSerialized(race_id, round); datasource.close(); RacePilotData datasource2 = new RacePilotData(mContext); datasource2.open(); String racepilots = datasource2.getPilotsSerialized(race_id); String racetimes = datasource2.getTimesSerialized(race_id, round); datasource2.close(); return String.format("{\"race\":%s, \"racepilots\":%s,\"racetimes\":%s,\"racegroups\":%s}\n\n", race, racepilots, racetimes, racegroups); } protected String getSerialisedPilotData() { PilotData datasource = new PilotData(mContext); datasource.open(); String pilots = datasource.getSerialized(); datasource.close(); return pilots; } protected String getCSVRaceData(int race_id, int round) { RaceData datasource = new RaceData(mContext); datasource.open(); Race race = datasource.getRace(race_id); RaceData.Group[] racegroups = datasource.getGroups(race_id, round); datasource.close(); RacePilotData datasource2 = new RacePilotData(mContext); datasource2.open(); ArrayList<Pilot> racepilots = datasource2.getAllPilotsForRace(race_id, 0, race.offset, 0); datasource2.close(); StringBuilder csvdata = new StringBuilder(); String race_params = ""; race_params += String.format("\"%d\",", race.race_id); race_params += String.format("\"%s\",", race.name); race_params += String.format("\"%s\",", " "); // F3XV Location race_params += String.format("\"%s\",", " "); // F3XV Start Date race_params += String.format("\"%s\",", " "); // F3XV End Date race_params += String.format("\"%s\",", " "); // F3XV Type race_params += String.format("\"%s\",", " "); // F3XV Num Rounds race_params += String.format("\"%d\",", race.round); race_params += String.format("\"%d\",", race.type); race_params += String.format("\"%d\",", race.offset); race_params += String.format("\"%d\",", race.status); race_params += String.format("\"%d\",", race.rounds_per_flight); race_params += String.format("\"%d\",\r\n", race.start_number); csvdata.append(race_params); csvdata.append("\r\n"); for (Pilot p : racepilots) { String pilot_params = ""; pilot_params += String.format("%d,", p.pilot_id); pilot_params += String.format("\" %s\",", p.number); pilot_params += String.format("\" %s\",", p.firstname); pilot_params += String.format("\" %s\",", p.lastname); pilot_params += ","; // F3XV Pilot Class - not required? pilot_params += String.format("\" %s\",", p.nac_no); pilot_params += String.format("\" %s\",", p.fai_id); pilot_params += ","; // F3XV FAI License? pilot_params += String.format("\" %s\",", p.team); // Extra data not in f3xvault api pilot_params += String.format(" %d,", p.status); pilot_params += String.format("\" %s\",", p.email); pilot_params += String.format("\" %s\",", p.frequency); pilot_params += String.format("\" %s\",", p.models); pilot_params += String.format("\" %s\",", p.nationality); pilot_params += String.format("\" %s\",\r\n", p.language); csvdata.append(pilot_params); } csvdata.append("\r\n"); StringBuilder group_params = new StringBuilder(); StringBuilder start_params = new StringBuilder(); for (RaceData.Group group : racegroups) { if (group_params.length() > 0) group_params.append(","); group_params.append(String.format("%d", group.num_groups)); if (start_params.length() > 0) start_params.append(","); start_params.append(String.format("%d", group.start_pilot)); } csvdata.append(group_params).append("\r\n"); csvdata.append(start_params).append("\r\n"); csvdata.append("\r\n"); return csvdata.toString(); } protected String getCSVPilotData() { PilotData datasource = new PilotData(mContext); datasource.open(); String pilots = datasource.getCSV(); datasource.close(); return pilots; } protected void call(String func, @Nullable String data) { Intent i = new Intent(IComm.RCV_UPDATE); i.putExtra("cmd", func); i.putExtra("dta", data); sendBroadcast(i); } protected void showExportTypeList() { String[] buttons_array = new String[2]; buttons_array[0] = getString(android.R.string.cancel); buttons_array[1] = getString(R.string.button_next); mDLG3 = GenericRadioPicker.newInstance( getString(R.string.ttl_select_file_type), new ArrayList<>(Arrays.asList(filetypes)), buttons_array, new ResultReceiver(new Handler()) { @Override protected void onReceiveResult(int resultCode, Bundle resultData) { super.onReceiveResult(resultCode, resultData); switch (resultCode) { case 0: mActivity.finish(); break; case 1: mExportFileType = -1; if (resultData.containsKey("checked")) { mExportFileType = resultData.getInt("checked"); } if (mExportFileType >= 0) { call("beginExport", null); } else { mActivity.finish(); } break; } } } ); FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.add(mDLG3, DIALOG); ft.commit(); } protected void createDocument() { JSONObject r = null; String fileName = ""; try { r = mArrExportFiles.getJSONObject(0); fileName = r.getString("name"); } catch (JSONException e) { e.printStackTrace(); } if (r == null){ finish(); return; } String mimeType = ""; switch (mExportFileType) { case EXPORT_FILE_TYPE_JSON: mimeType = "application/json"; fileName+= ".json"; break; case EXPORT_FILE_TYPE_CSV: mimeType = "text/csv"; fileName+= ".csv"; break; } Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT); // Filter to only show results that can be "opened", such as // a file (as opposed to a list of contacts or timezones). intent.addCategory(Intent.CATEGORY_OPENABLE); // Create a file with the requested MIME type. intent.setType(mimeType); intent.putExtra(Intent.EXTRA_TITLE, fileName); startActivityForResult(intent, WRITE_REQUEST_CODE); } private void writeDocument(Uri uri) { JSONObject r = null; String data = ""; try { r = mArrExportFiles.getJSONObject(0); data = r.getString("data"); } catch (JSONException e) { e.printStackTrace(); } if (r == null){ finish(); return; } try { ParcelFileDescriptor doc = getContentResolver().openFileDescriptor(uri, "w"); if (doc != null) { FileDescriptor desc = doc.getFileDescriptor(); FileOutputStream fileOutputStream = new FileOutputStream(desc); fileOutputStream.write(data.getBytes()); // Let the document provider know you're done by closing the stream. fileOutputStream.close(); doc.close(); } else { finish(); } } catch (IOException e) { e.printStackTrace(); } mArrExportFiles.remove(0); if (mArrExportFiles.length() > 0) { createDocument(); } else { finish(); } } private BroadcastReceiver onBroadcast = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.hasExtra("cmd")) { Bundle extras = intent.getExtras(); if (extras == null) { return; } String cmd = extras.getString("cmd", ""); String dta = extras.getString("dta"); if (cmd.equals("beginExport")) { beginExport(); } if (cmd.equals("showExportTypeList")) { showExportTypeList(); } if (cmd.equals("createDocument")) { createDocument(); } } } }; }
/** * Copyright (C) 2015 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 io.fabric8.kubernetes.client.dsl.internal; import com.fasterxml.jackson.databind.ObjectMapper; import io.fabric8.kubernetes.api.model.Status; import io.fabric8.kubernetes.api.model.StatusCause; import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.dsl.ExecListener; import io.fabric8.kubernetes.client.dsl.ExecWatch; import io.fabric8.kubernetes.client.dsl.ExecListener.Response; import io.fabric8.kubernetes.client.http.HttpResponse; import io.fabric8.kubernetes.client.http.WebSocket; import io.fabric8.kubernetes.client.http.WebSocketHandshakeException; import io.fabric8.kubernetes.client.utils.InputStreamPumper; import io.fabric8.kubernetes.client.utils.Serialization; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import static io.fabric8.kubernetes.client.utils.Utils.closeQuietly; /** * A {@link WebSocket.Listener} for exec operations. * * This listener, is only responsible for the resources it creates. Externally passed resource, will not get closed, * by this listener. * * All other resources will be cleaned up once, ONLY when the close() method is called. * * ExecListener methods, onClose() and onFailure are mutually exclusive and are meant to be called once and only once. * Failures that propagate after a close() operation will not be propagated. * */ public class ExecWebSocketListener implements ExecWatch, AutoCloseable, WebSocket.Listener { static final String CAUSE_REASON_EXIT_CODE = "ExitCode"; static final String REASON_NON_ZERO_EXIT_CODE = "NonZeroExitCode"; static final String STATUS_SUCCESS = "Success"; private final class SimpleResponse implements Response { private final HttpResponse<?> response; private SimpleResponse(HttpResponse<?> response) { this.response = response; } @Override public int code() { return response.code(); } @Override public String body() throws IOException { return response.bodyString(); } } private static final Logger LOGGER = LoggerFactory.getLogger(ExecWebSocketListener.class); private static final String HEIGHT = "Height"; private static final String WIDTH = "Width"; private final InputStream in; private final OutputStream out; private final OutputStream err; private final OutputStream errChannel; private final PipedOutputStream input; private final PipedInputStream output; private final PipedInputStream error; private final PipedInputStream errorChannel; private final AtomicReference<WebSocket> webSocketRef = new AtomicReference<>(); private final ExecutorService executorService = Executors.newSingleThreadExecutor(); private final ExecListener listener; private final AtomicBoolean closed = new AtomicBoolean(false); private final Set<Closeable> toClose = new LinkedHashSet<>(); private ObjectMapper objectMapper; public ExecWebSocketListener(InputStream in, OutputStream out, OutputStream err, OutputStream errChannel, PipedOutputStream inputPipe, PipedInputStream outputPipe, PipedInputStream errorPipe, PipedInputStream errorChannelPipe, ExecListener listener, Integer bufferSize) { this.listener = listener; this.in = inputStreamOrPipe(in, inputPipe, toClose, bufferSize); this.out = outputStreamOrPipe(out, outputPipe, toClose); this.err = outputStreamOrPipe(err, errorPipe, toClose); this.errChannel = outputStreamOrPipe(errChannel, errorChannelPipe, toClose); this.input = inputPipe; this.output = outputPipe; this.error = errorPipe; this.errorChannel = errorChannelPipe; this.objectMapper = new ObjectMapper(); } @Override public void close() { close(1000, "Closing..."); } private void close(int code, String reason) { closeWebSocketOnce(code, reason); onClosed(code, reason); } /** * Performs the cleanup tasks: * 1. cancels the InputStream pumper * 2. closes all internally managed closeables (piped streams). * * The order of these tasks can't change or its likely that the pumper will throw errors, * if the stream it uses closes before the pumper it self. */ private void cleanUpOnce() { executorService.shutdownNow(); closeQuietly(toClose); } private void closeWebSocketOnce(int code, String reason) { if (closed.get()) { return; } try { WebSocket ws = webSocketRef.get(); if (ws != null) { ws.sendClose(code, reason); } } catch (Throwable t) { LOGGER.debug("Error closing WebSocket.", t); } } @Override public void onOpen(WebSocket webSocket) { try { if (in instanceof PipedInputStream && input != null) { input.connect((PipedInputStream) in); } if (out instanceof PipedOutputStream && output != null) { output.connect((PipedOutputStream) out); } if (err instanceof PipedOutputStream && error != null) { error.connect((PipedOutputStream) err); } if (errChannel instanceof PipedOutputStream && errorChannel != null) { errorChannel.connect((PipedOutputStream) errChannel); } webSocketRef.set(webSocket); if (in != null && !executorService.isShutdown()) { // the task will be cancelled via shutdownNow InputStreamPumper.pump(InputStreamPumper.asInterruptible(in), this::send, executorService); } } catch (IOException e) { onError(webSocket, e); } finally { if (listener != null) { listener.onOpen(); } } } @Override public void onError(WebSocket webSocket, Throwable t) { //If we already called onClosed() or onFailed() before, we need to abort. if (closed.compareAndSet(false, true) ) { //We are not going to notify the listener, sicne we've already called onClose(), so let's log a debug/warning. if (LOGGER.isWarnEnabled()) { LOGGER.warn("Received [{}], with message:[{}] after ExecWebSocketListener is closed, Ignoring.",t.getClass().getCanonicalName(),t.getMessage()); } return; } HttpResponse<?> response = null; try { if (t instanceof WebSocketHandshakeException) { response = ((WebSocketHandshakeException)t).getResponse(); } Status status = OperationSupport.createStatus(response); status.setMessage(t.getMessage()); LOGGER.error("Exec Failure", t); cleanUpOnce(); } finally { if (listener != null) { ExecListener.Response execResponse = null; if (response != null) { execResponse = new SimpleResponse(response); } listener.onFailure(t, execResponse); } } } @Override public void onMessage(WebSocket webSocket, ByteBuffer bytes) { try { byte streamID = bytes.get(0); bytes.position(1); ByteBuffer byteString = bytes.slice(); if (byteString.remaining() > 0) { switch (streamID) { case 1: writeAndFlush(out, byteString); break; case 2: writeAndFlush(err, byteString); break; case 3: handleExitStatus(bytes); writeAndFlush(errChannel, byteString); // once the process is done, we can proactively close this.close(); break; default: throw new IOException("Unknown stream ID " + streamID); } } } catch (IOException e) { throw KubernetesClientException.launderThrowable(e); } } private void handleExitStatus(ByteBuffer bytes) { Status status = null; int code = -1; try { String stringValue = StandardCharsets.UTF_8.decode(bytes).toString(); status = Serialization.unmarshal(stringValue, Status.class); if (status != null) { code = parseExitCode(status); } } catch (Exception e) { LOGGER.warn("Could not determine exit code", e); } if (this.listener != null) { this.listener.onExit(code, status); } } private void writeAndFlush(OutputStream stream, ByteBuffer byteString) throws IOException { if (stream != null) { Channels.newChannel(stream).write(byteString); if (stream instanceof PipedOutputStream) { stream.flush(); // immediately wake up the reader } } } @Override public void onClose(WebSocket webSocket, int code, String reason) { ExecWebSocketListener.this.close(code, reason); } private void onClosed(int code, String reason) { //If we already called onClosed() or onFailed() before, we need to abort. if (!closed.compareAndSet(false, true)) { return; } LOGGER.debug("Exec Web Socket: On Close with code:[{}], due to: [{}]", code, reason); try { cleanUpOnce(); } finally { if (listener != null) { listener.onClose(code, reason); } } } @Override public OutputStream getInput() { return input; } @Override public InputStream getOutput() { return output; } @Override public InputStream getError() { return error; } @Override public InputStream getErrorChannel() { return errorChannel; } @Override public void resize(int cols, int rows) { if (cols < 0 || rows < 0) { return; } try { Map<String, Integer> map = new HashMap<>(4); map.put(HEIGHT, rows); map.put(WIDTH, cols); byte[] bytes = objectMapper.writeValueAsBytes(map); send(bytes, 0, bytes.length, (byte) 4); } catch (Exception e) { throw KubernetesClientException.launderThrowable(e); } } private void send(byte[] bytes, int offset, int length, byte flag) { if (length > 0) { WebSocket ws = webSocketRef.get(); if (ws != null) { byte[] toSend = new byte[length + 1]; toSend[0] = flag; System.arraycopy(bytes, offset, toSend, 1, length); ws.send(ByteBuffer.wrap(toSend)); } } } private void send(byte[] bytes, int offset, int length) { send(bytes, offset, length, (byte)0); } private static InputStream inputStreamOrPipe(InputStream stream, PipedOutputStream out, Set<Closeable> toClose, Integer bufferSize) { if (stream != null) { return stream; } else if (out != null) { PipedInputStream pis = bufferSize == null ? new PipedInputStream() : new PipedInputStream(bufferSize.intValue()); toClose.add(pis); return pis; } else { return null; } } private static OutputStream outputStreamOrPipe(OutputStream stream, PipedInputStream in, Set<Closeable> toClose) { if (stream != null) { return stream; } else if (in != null) { PipedOutputStream pos = new PipedOutputStream(); toClose.add(pos); return pos; } else { return null; } } public static int parseExitCode(Status status) { if (STATUS_SUCCESS.equals(status.getStatus())) { return 0; } if (REASON_NON_ZERO_EXIT_CODE.equals(status.getReason())) { if (status.getDetails() == null) { return -1; } List<StatusCause> causes = status.getDetails().getCauses(); if (causes == null) { return -1; } return causes.stream() .filter(c -> CAUSE_REASON_EXIT_CODE.equals(c.getReason())) .map(StatusCause::getMessage) .map(Integer::valueOf) .findFirst() .orElse(-1); } return -1; } }
/* * 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 com.example.android.sunshine.app.data; import android.content.ComponentName; import android.content.ContentUris; import android.content.ContentValues; import android.content.pm.PackageManager; import android.content.pm.ProviderInfo; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.os.Build; import android.test.AndroidTestCase; import android.util.Log; import com.example.android.sunshine.app.data.WeatherContract.LocationEntry; import com.example.android.sunshine.app.data.WeatherContract.WeatherEntry; public class TestProvider extends AndroidTestCase { public static final String LOG_TAG = TestProvider.class.getSimpleName(); public void deleteAllRecordsFromProvider() { mContext.getContentResolver().delete( WeatherEntry.CONTENT_URI, null, null ); mContext.getContentResolver().delete( LocationEntry.CONTENT_URI, null, null ); Cursor cursor = mContext.getContentResolver().query( WeatherEntry.CONTENT_URI, null, null, null, null ); assertEquals("Error: Records not deleted from Weather table during delete", 0, cursor.getCount()); cursor.close(); cursor = mContext.getContentResolver().query( LocationEntry.CONTENT_URI, null, null, null, null ); assertEquals("Error: Records not deleted from Location table during delete", 0, cursor.getCount()); cursor.close(); } public void deleteAllRecordsFromDB() { WeatherDbHelper dbHelper = new WeatherDbHelper(mContext); SQLiteDatabase db = dbHelper.getWritableDatabase(); db.delete(WeatherEntry.TABLE_NAME, null, null); db.delete(LocationEntry.TABLE_NAME, null, null); db.close(); } public void deleteAllRecords() { deleteAllRecordsFromProvider(); } // Since we want each test to start with a clean slate, run deleteAllRecords // in setUp (called by the test runner before each test). @Override protected void setUp() throws Exception { super.setUp(); deleteAllRecords(); } public void testProviderRegistry() { PackageManager pm = mContext.getPackageManager(); // We define the component name based on the package name from the context and the // WeatherProvider class. ComponentName componentName = new ComponentName(mContext.getPackageName(), WeatherProvider.class.getName()); try { // Fetch the provider info using the component name from the PackageManager // This throws an exception if the provider isn't registered. ProviderInfo providerInfo = pm.getProviderInfo(componentName, 0); // Make sure that the registered authority matches the authority from the Contract. assertEquals("Error: WeatherProvider registered with authority: " + providerInfo.authority + " instead of authority: " + WeatherContract.CONTENT_AUTHORITY, providerInfo.authority, WeatherContract.CONTENT_AUTHORITY); } catch (PackageManager.NameNotFoundException e) { // I guess the provider isn't registered correctly. assertTrue("Error: WeatherProvider not registered at " + mContext.getPackageName(), false); } } public void testGetType() { // content://com.example.android.sunshine.app/weather/ String type = mContext.getContentResolver().getType(WeatherEntry.CONTENT_URI); // vnd.android.cursor.dir/com.example.android.sunshine.app/weather assertEquals("Error: the WeatherEntry CONTENT_URI should return WeatherEntry.CONTENT_DIR_TYPE", WeatherEntry.CONTENT_DIR_TYPE, type); String testLocation = "94074"; // content://com.example.android.sunshine.app/weather/94074 type = mContext.getContentResolver().getType( WeatherEntry.buildWeatherLocation(testLocation)); // vnd.android.cursor.dir/com.example.android.sunshine.app/weather assertEquals("Error: the WeatherEntry CONTENT_URI with location should return WeatherEntry.CONTENT_DIR_TYPE", WeatherEntry.CONTENT_DIR_TYPE, type); long testDate = 1419120000L; // December 21st, 2014 // content://com.example.android.sunshine.app/weather/94074/20140612 type = mContext.getContentResolver().getType( WeatherEntry.buildWeatherLocationWithDate(testLocation, testDate)); // vnd.android.cursor.item/com.example.android.sunshine.app/weather/1419120000 assertEquals("Error: the WeatherEntry CONTENT_URI with location and date should return WeatherEntry.CONTENT_ITEM_TYPE", WeatherEntry.CONTENT_ITEM_TYPE, type); // content://com.example.android.sunshine.app/location/ type = mContext.getContentResolver().getType(LocationEntry.CONTENT_URI); // vnd.android.cursor.dir/com.example.android.sunshine.app/location assertEquals("Error: the LocationEntry CONTENT_URI should return LocationEntry.CONTENT_DIR_TYPE", LocationEntry.CONTENT_DIR_TYPE, type); } public void testBasicWeatherQuery() { // insert our test records into the database WeatherDbHelper dbHelper = new WeatherDbHelper(mContext); SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues testValues = TestUtilities.createNorthPoleLocationValues(); long locationRowId = TestUtilities.insertNorthPoleLocationValues(mContext); // Fantastic. Now that we have a location, add some weather! ContentValues weatherValues = TestUtilities.createWeatherValues(locationRowId); long weatherRowId = db.insert(WeatherEntry.TABLE_NAME, null, weatherValues); assertTrue("Unable to Insert WeatherEntry into the Database", weatherRowId != -1); db.close(); // Test the basic content provider query Cursor weatherCursor = mContext.getContentResolver().query( WeatherEntry.CONTENT_URI, null, null, null, null ); // Make sure we get the correct cursor out of the database TestUtilities.validateCursor("testBasicWeatherQuery", weatherCursor, weatherValues); } public void testBasicLocationQueries() { // insert our test records into the database WeatherDbHelper dbHelper = new WeatherDbHelper(mContext); SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues testValues = TestUtilities.createNorthPoleLocationValues(); long locationRowId = TestUtilities.insertNorthPoleLocationValues(mContext); // Test the basic content provider query Cursor locationCursor = mContext.getContentResolver().query( LocationEntry.CONTENT_URI, null, null, null, null ); // Make sure we get the correct cursor out of the database TestUtilities.validateCursor("testBasicLocationQueries, location query", locationCursor, testValues); // Has the NotificationUri been set correctly? --- we can only test this easily against API // level 19 or greater because getNotificationUri was added in API level 19. if ( Build.VERSION.SDK_INT >= 19 ) { assertEquals("Error: Location Query did not properly set NotificationUri", locationCursor.getNotificationUri(), LocationEntry.CONTENT_URI); } } public void testUpdateLocation() { // Create a new map of values, where column names are the keys ContentValues values = TestUtilities.createNorthPoleLocationValues(); Uri locationUri = mContext.getContentResolver(). insert(LocationEntry.CONTENT_URI, values); long locationRowId = ContentUris.parseId(locationUri); // Verify we got a row back. assertTrue(locationRowId != -1); Log.d(LOG_TAG, "New row id: " + locationRowId); ContentValues updatedValues = new ContentValues(values); updatedValues.put(LocationEntry._ID, locationRowId); updatedValues.put(LocationEntry.COLUMN_CITY_NAME, "Santa's Village"); // Create a cursor with observer to make sure that the content provider is notifying // the observers as expected Cursor locationCursor = mContext.getContentResolver().query(LocationEntry.CONTENT_URI, null, null, null, null); TestUtilities.TestContentObserver tco = TestUtilities.getTestContentObserver(); locationCursor.registerContentObserver(tco); int count = mContext.getContentResolver().update( LocationEntry.CONTENT_URI, updatedValues, LocationEntry._ID + "= ?", new String[] { Long.toString(locationRowId)}); assertEquals(count, 1); // Test to make sure our observer is called. If not, we throw an assertion. // // Students: If your code is failing here, it means that your content provider // isn't calling getContext().getContentResolver().notifyChange(uri, null); tco.waitForNotificationOrFail(); locationCursor.unregisterContentObserver(tco); locationCursor.close(); // A cursor is your primary interface to the query results. Cursor cursor = mContext.getContentResolver().query( LocationEntry.CONTENT_URI, null, // projection LocationEntry._ID + " = " + locationRowId, null, // Values for the "where" clause null // sort order ); TestUtilities.validateCursor("testUpdateLocation. Error validating location entry update.", cursor, updatedValues); cursor.close(); } public void testDeleteRecords() { testInsertReadProvider(); // Register a content observer for our location delete. TestUtilities.TestContentObserver locationObserver = TestUtilities.getTestContentObserver(); mContext.getContentResolver() .registerContentObserver(LocationEntry.CONTENT_URI, true, locationObserver); // Register a content observer for our weather delete. TestUtilities.TestContentObserver weatherObserver = TestUtilities.getTestContentObserver(); mContext.getContentResolver() .registerContentObserver(WeatherEntry.CONTENT_URI, true, weatherObserver); deleteAllRecordsFromProvider(); // Students: If either of these fail, you most-likely are not calling the // getContext().getContentResolver().notifyChange(uri, null); in the ContentProvider // delete. (only if the insertReadProvider is succeeding) locationObserver.waitForNotificationOrFail(); weatherObserver.waitForNotificationOrFail(); mContext.getContentResolver() .unregisterContentObserver(locationObserver); mContext.getContentResolver() .unregisterContentObserver(weatherObserver); } public void testInsertReadProvider() { ContentValues locationValues = TestUtilities.createNorthPoleLocationValues(); // Register a content observer for our insert. This time, directly with the content resolver TestUtilities.TestContentObserver tco = TestUtilities.getTestContentObserver(); mContext.getContentResolver().registerContentObserver(LocationEntry.CONTENT_URI, true, tco); Uri locationUri = mContext.getContentResolver().insert(LocationEntry.CONTENT_URI, locationValues); // Did our content observer get called? If this fails, insert location // isn't calling getContext().getContentResolver().notifyChange(uri, null); tco.waitForNotificationOrFail(); mContext.getContentResolver().unregisterContentObserver(tco); long locationRowId = ContentUris.parseId(locationUri); // Verify we got a row back. assertTrue(locationRowId != -1); // Data's inserted. IN THEORY. Now pull some out to stare at it and verify it made // the round trip. // A cursor is your primary interface to the query results. Cursor locationCursor = mContext.getContentResolver().query( LocationEntry.CONTENT_URI, null, // leaving "columns" null just returns all the columns. null, // cols for "where" clause null, // values for "where" clause null // sort order ); TestUtilities.validateCursor("testInsertReadProvider. Error validating LocationEntry.", locationCursor, locationValues); // Fantastic. Now that we have a location, add some weather! ContentValues weatherValues = TestUtilities.createWeatherValues(locationRowId); // The TestContentObserver is a one-shot class tco = TestUtilities.getTestContentObserver(); mContext.getContentResolver().registerContentObserver(WeatherEntry.CONTENT_URI, true, tco); Uri weatherInsertUri = mContext.getContentResolver() .insert(WeatherEntry.CONTENT_URI, weatherValues); assertTrue(weatherInsertUri != null); tco.waitForNotificationOrFail(); mContext.getContentResolver().unregisterContentObserver(tco); // A cursor is your primary interface to the query results. Cursor weatherCursor = mContext.getContentResolver().query( WeatherEntry.CONTENT_URI, // Table to Query null, // leaving "columns" null just returns all the columns. null, // cols for "where" clause null, // values for "where" clause null // columns to group by ); TestUtilities.validateCursor("testInsertReadProvider. Error validating WeatherEntry insert.", weatherCursor, weatherValues); // Add the location values in with the weather data so that we can make // sure that the join worked and we actually get all the values back weatherValues.putAll(locationValues); // Get the joined Weather and Location data weatherCursor = mContext.getContentResolver().query( WeatherEntry.buildWeatherLocation(TestUtilities.TEST_LOCATION), null, // leaving "columns" null just returns all the columns. null, // cols for "where" clause null, // values for "where" clause null // sort order ); TestUtilities.validateCursor("testInsertReadProvider. Error validating joined Weather and Location Data.", weatherCursor, weatherValues); // Get the joined Weather and Location data with a start date weatherCursor = mContext.getContentResolver().query( WeatherEntry.buildWeatherLocationWithStartDate( TestUtilities.TEST_LOCATION, TestUtilities.TEST_DATE), null, // leaving "columns" null just returns all the columns. null, // cols for "where" clause null, // values for "where" clause null // sort order ); TestUtilities.validateCursor("testInsertReadProvider. Error validating joined Weather and Location Data with start date.", weatherCursor, weatherValues); // Get the joined Weather data for a specific date weatherCursor = mContext.getContentResolver().query( WeatherEntry.buildWeatherLocationWithDate(TestUtilities.TEST_LOCATION, TestUtilities.TEST_DATE), null, null, null, null ); TestUtilities.validateCursor("testInsertReadProvider. Error validating joined Weather and Location data for a specific date.", weatherCursor, weatherValues); } static private final int BULK_INSERT_RECORDS_TO_INSERT = 10; static ContentValues[] createBulkInsertWeatherValues(long locationRowId) { long currentTestDate = TestUtilities.TEST_DATE; long millisecondsInADay = 1000*60*60*24; ContentValues[] returnContentValues = new ContentValues[BULK_INSERT_RECORDS_TO_INSERT]; for ( int i = 0; i < BULK_INSERT_RECORDS_TO_INSERT; i++, currentTestDate+= millisecondsInADay ) { ContentValues weatherValues = new ContentValues(); weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationRowId); weatherValues.put(WeatherEntry.COLUMN_DATE, currentTestDate); weatherValues.put(WeatherEntry.COLUMN_DEGREES, 1.1); weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, 1.2 + 0.01 * (float) i); weatherValues.put(WeatherEntry.COLUMN_PRESSURE, 1.3 - 0.01 * (float) i); weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, 75 + i); weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, 65 - i); weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, "Asteroids"); weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, 5.5 + 0.2 * (float) i); weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, 321); returnContentValues[i] = weatherValues; } return returnContentValues; } // Student: Uncomment this test after you have completed writing the BulkInsert functionality // in your provider. Note that this test will work with the built-in (default) provider // implementation, which just inserts records one-at-a-time, so really do implement the // BulkInsert ContentProvider function. public void testBulkInsert() { // first, let's create a location value ContentValues testValues = TestUtilities.createNorthPoleLocationValues(); Uri locationUri = mContext.getContentResolver().insert(LocationEntry.CONTENT_URI, testValues); long locationRowId = ContentUris.parseId(locationUri); // Verify we got a row back. assertTrue(locationRowId != -1); // Data's inserted. IN THEORY. Now pull some out to stare at it and verify it made // the round trip. // A cursor is your primary interface to the query results. Cursor cursor = mContext.getContentResolver().query( LocationEntry.CONTENT_URI, null, // leaving "columns" null just returns all the columns. null, // cols for "where" clause null, // values for "where" clause null // sort order ); TestUtilities.validateCursor("testBulkInsert. Error validating LocationEntry.", cursor, testValues); // Now we can bulkInsert some weather. In fact, we only implement BulkInsert for weather // entries. With ContentProviders, you really only have to implement the features you // use, after all. ContentValues[] bulkInsertContentValues = createBulkInsertWeatherValues(locationRowId); // Register a content observer for our bulk insert. TestUtilities.TestContentObserver weatherObserver = TestUtilities.getTestContentObserver(); mContext.getContentResolver().registerContentObserver(WeatherEntry.CONTENT_URI, true, weatherObserver); int insertCount = mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, bulkInsertContentValues); // Students: If this fails, it means that you most-likely are not calling the // getContext().getContentResolver().notifyChange(uri, null); in your BulkInsert // ContentProvider method. weatherObserver.waitForNotificationOrFail(); mContext.getContentResolver().unregisterContentObserver(weatherObserver); assertEquals(insertCount, BULK_INSERT_RECORDS_TO_INSERT); // A cursor is your primary interface to the query results. cursor = mContext.getContentResolver().query( WeatherEntry.CONTENT_URI, null, // leaving "columns" null just returns all the columns. null, // cols for "where" clause null, // values for "where" clause WeatherEntry.COLUMN_DATE + " ASC" // sort order == by DATE ASCENDING ); // we should have as many records in the database as we've inserted assertEquals(cursor.getCount(), BULK_INSERT_RECORDS_TO_INSERT); // and let's make sure they match the ones we created cursor.moveToFirst(); for ( int i = 0; i < BULK_INSERT_RECORDS_TO_INSERT; i++, cursor.moveToNext() ) { TestUtilities.validateCurrentRecord("testBulkInsert. Error validating WeatherEntry " + i, cursor, bulkInsertContentValues[i]); } cursor.close(); } }
/** * 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.drill.jdbc.impl; import java.io.IOException; import java.sql.Array; import java.sql.Blob; import java.sql.CallableStatement; import java.sql.Clob; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.NClob; import java.sql.PreparedStatement; import java.sql.SQLClientInfoException; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.sql.SQLNonTransientConnectionException; import java.sql.SQLWarning; import java.sql.SQLXML; import java.sql.Savepoint; import java.sql.Statement; import java.sql.Struct; import java.util.Map; import java.util.Properties; import java.util.TimeZone; import java.util.concurrent.Executor; import net.hydromatic.avatica.AvaticaConnection; import net.hydromatic.avatica.AvaticaFactory; import net.hydromatic.avatica.AvaticaStatement; import net.hydromatic.avatica.Helper; import net.hydromatic.avatica.Meta; import net.hydromatic.avatica.UnregisteredDriver; import org.apache.drill.common.config.DrillConfig; import org.apache.drill.common.exceptions.DrillRuntimeException; import org.apache.drill.common.exceptions.UserException; import org.apache.drill.exec.client.DrillClient; import org.apache.drill.exec.memory.BufferAllocator; import org.apache.drill.exec.memory.OutOfMemoryException; import org.apache.drill.exec.memory.RootAllocatorFactory; import org.apache.drill.exec.rpc.RpcException; import org.apache.drill.exec.server.Drillbit; import org.apache.drill.exec.server.RemoteServiceSet; import org.apache.drill.exec.store.StoragePluginRegistry; import org.apache.drill.exec.util.TestUtilities; import org.apache.drill.jdbc.AlreadyClosedSqlException; import org.apache.drill.jdbc.DrillConnection; import org.apache.drill.jdbc.DrillConnectionConfig; import org.apache.drill.jdbc.InvalidParameterSqlException; import org.apache.drill.jdbc.JdbcApiSqlException; import org.slf4j.Logger; /** * Drill's implementation of {@link Connection}. */ // (Was abstract to avoid errors _here_ if newer versions of JDBC added // interface methods, but now newer versions would probably use Java 8's default // methods for compatibility.) class DrillConnectionImpl extends AvaticaConnection implements DrillConnection { private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(DrillConnection.class); final DrillStatementRegistry openStatementsRegistry = new DrillStatementRegistry(); final DrillConnectionConfig config; private final DrillClient client; private final BufferAllocator allocator; private Drillbit bit; private RemoteServiceSet serviceSet; protected DrillConnectionImpl(DriverImpl driver, AvaticaFactory factory, String url, Properties info) throws SQLException { super(driver, factory, url, info); // Initialize transaction-related settings per Drill behavior. super.setTransactionIsolation( TRANSACTION_NONE ); super.setAutoCommit( true ); this.config = new DrillConnectionConfig(info); try { if (config.isLocal()) { try { Class.forName("org.eclipse.jetty.server.Handler"); } catch (final ClassNotFoundException e) { throw new SQLNonTransientConnectionException( "Running Drill in embedded mode using Drill's jdbc-all JDBC" + " driver Jar file alone is not supported.", e); } final DrillConfig dConfig = DrillConfig.create(info); this.allocator = RootAllocatorFactory.newRoot(dConfig); RemoteServiceSet set = GlobalServiceSetReference.SETS.get(); if (set == null) { // We're embedded; start a local drill bit. serviceSet = RemoteServiceSet.getLocalServiceSet(); set = serviceSet; try { bit = new Drillbit(dConfig, serviceSet); bit.run(); } catch (final UserException e) { throw new SQLException( "Failure in starting embedded Drillbit: " + e.getMessage(), e); } catch (Exception e) { // (Include cause exception's text in wrapping exception's text so // it's more likely to get to user (e.g., via SQLLine), and use // toString() since getMessage() text doesn't always mention error:) throw new SQLException("Failure in starting embedded Drillbit: " + e, e); } } else { serviceSet = null; bit = null; } makeTmpSchemaLocationsUnique(bit.getContext().getStorage(), info); this.client = new DrillClient(dConfig, set.getCoordinator()); this.client.connect(null, info); } else if(config.isDirect()) { final DrillConfig dConfig = DrillConfig.forClient(); this.allocator = RootAllocatorFactory.newRoot(dConfig); this.client = new DrillClient(dConfig, true); // Get a direct connection this.client.connect(config.getZookeeperConnectionString(), info); } else { final DrillConfig dConfig = DrillConfig.forClient(); this.allocator = RootAllocatorFactory.newRoot(dConfig); // TODO: Check: Why does new DrillClient() create another DrillConfig, // with enableServerConfigs true, and cause scanning for function // implementations (needed by a server, but not by a client-only // process, right?)? Probably pass dConfig to construction. this.client = new DrillClient(); this.client.connect(config.getZookeeperConnectionString(), info); } } catch (OutOfMemoryException e) { throw new SQLException("Failure creating root allocator", e); } catch (RpcException e) { // (Include cause exception's text in wrapping exception's text so // it's more likely to get to user (e.g., via SQLLine), and use // toString() since getMessage() text doesn't always mention error:) throw new SQLException("Failure in connecting to Drill: " + e, e); } } /** * Throws AlreadyClosedSqlException <i>iff</i> this Connection is closed. * * @throws AlreadyClosedSqlException if Connection is closed */ private void throwIfClosed() throws AlreadyClosedSqlException { if ( isClosed() ) { throw new AlreadyClosedSqlException( "Connection is already closed." ); } } @Override public DrillConnectionConfig getConfig() { return config; } @Override protected Meta createMeta() { return new MetaImpl(this); } MetaImpl meta() { return (MetaImpl) meta; } BufferAllocator getAllocator() { return allocator; } @Override public DrillClient getClient() { return client; } @Override public void setAutoCommit( boolean autoCommit ) throws SQLException { throwIfClosed(); if ( ! autoCommit ) { throw new SQLFeatureNotSupportedException( "Can't turn off auto-committing; transactions are not supported. " + "(Drill is not transactional.)" ); } assert getAutoCommit() : "getAutoCommit() = " + getAutoCommit(); } @Override public void commit() throws SQLException { throwIfClosed(); if ( getAutoCommit() ) { throw new JdbcApiSqlException( "Can't call commit() in auto-commit mode." ); } else { // (Currently not reachable.) throw new SQLFeatureNotSupportedException( "Connection.commit() is not supported. (Drill is not transactional.)" ); } } @Override public void rollback() throws SQLException { throwIfClosed(); if ( getAutoCommit() ) { throw new JdbcApiSqlException( "Can't call rollback() in auto-commit mode." ); } else { // (Currently not reachable.) throw new SQLFeatureNotSupportedException( "Connection.rollback() is not supported. (Drill is not transactional.)" ); } } @Override public boolean isClosed() { try { return super.isClosed(); } catch ( SQLException e ) { // Currently can't happen, since AvaticaConnection.isClosed() never throws // SQLException. throw new DrillRuntimeException( "Unexpected exception from " + getClass().getSuperclass() + ".isClosed(): " + e, e ); } } @Override public Savepoint setSavepoint() throws SQLException { throwIfClosed(); throw new SQLFeatureNotSupportedException( "Savepoints are not supported. (Drill is not transactional.)" ); } @Override public Savepoint setSavepoint(String name) throws SQLException { throwIfClosed(); throw new SQLFeatureNotSupportedException( "Savepoints are not supported. (Drill is not transactional.)" ); } @Override public void rollback(Savepoint savepoint) throws SQLException { throwIfClosed(); throw new SQLFeatureNotSupportedException( "Savepoints are not supported. (Drill is not transactional.)" ); } @Override public void releaseSavepoint(Savepoint savepoint) throws SQLException { throwIfClosed(); throw new SQLFeatureNotSupportedException( "Savepoints are not supported. (Drill is not transactional.)" ); } private String isolationValueToString( final int level ) { switch ( level ) { case TRANSACTION_NONE: return "TRANSACTION_NONE"; case TRANSACTION_READ_UNCOMMITTED: return "TRANSACTION_READ_UNCOMMITTED"; case TRANSACTION_READ_COMMITTED: return "TRANSACTION_READ_COMMITTED"; case TRANSACTION_REPEATABLE_READ: return "TRANSACTION_REPEATABLE_READ"; case TRANSACTION_SERIALIZABLE: return "TRANSACTION_SERIALIZABLE"; default: return "<Unknown transaction isolation level value " + level + ">"; } } @Override public void setTransactionIsolation(int level) throws SQLException { throwIfClosed(); switch ( level ) { case TRANSACTION_NONE: // No-op. (Is already set in constructor, and we disallow changing it.) break; case TRANSACTION_READ_UNCOMMITTED: case TRANSACTION_READ_COMMITTED: case TRANSACTION_REPEATABLE_READ: case TRANSACTION_SERIALIZABLE: throw new SQLFeatureNotSupportedException( "Can't change transaction isolation level to Connection." + isolationValueToString( level ) + " (from Connection." + isolationValueToString( getTransactionIsolation() ) + ")." + " (Drill is not transactional.)" ); default: // Invalid value (or new one unknown to code). throw new JdbcApiSqlException( "Invalid transaction isolation level value " + level ); //break; } } @Override public void setNetworkTimeout( Executor executor, int milliseconds ) throws AlreadyClosedSqlException, JdbcApiSqlException, SQLFeatureNotSupportedException { throwIfClosed(); if ( null == executor ) { throw new InvalidParameterSqlException( "Invalid (null) \"executor\" parameter to setNetworkTimeout(...)" ); } else if ( milliseconds < 0 ) { throw new InvalidParameterSqlException( "Invalid (negative) \"milliseconds\" parameter to" + " setNetworkTimeout(...) (" + milliseconds + ")" ); } else { if ( 0 != milliseconds ) { throw new SQLFeatureNotSupportedException( "Setting network timeout is not supported." ); } } } @Override public int getNetworkTimeout() throws AlreadyClosedSqlException { throwIfClosed(); return 0; // (No timeout.) } @Override public DrillStatementImpl createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { throwIfClosed(); DrillStatementImpl statement = (DrillStatementImpl) super.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability); return statement; } @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { throwIfClosed(); try { DrillPrepareResult prepareResult = new DrillPrepareResult(sql); DrillPreparedStatementImpl statement = (DrillPreparedStatementImpl) factory.newPreparedStatement( this, prepareResult, resultSetType, resultSetConcurrency, resultSetHoldability); return statement; } catch (RuntimeException e) { throw Helper.INSTANCE.createException("Error while preparing statement [" + sql + "]", e); } catch (Exception e) { throw Helper.INSTANCE.createException("Error while preparing statement [" + sql + "]", e); } } @Override public TimeZone getTimeZone() { return config.getTimeZone(); } // Note: Using dynamic proxies would reduce the quantity (450?) of method // overrides by eliminating those that exist solely to check whether the // object is closed. It would also eliminate the need to throw non-compliant // RuntimeExceptions when Avatica's method declarations won't let us throw // proper SQLExceptions. (Check performance before applying to frequently // called ResultSet.) // No isWrapperFor(Class<?>) (it doesn't throw SQLException if already closed). // No unwrap(Class<T>) (it doesn't throw SQLException if already closed). @Override public AvaticaStatement createStatement() throws SQLException { throwIfClosed(); return super.createStatement(); } @Override public PreparedStatement prepareStatement(String sql) throws SQLException { throwIfClosed(); return super.prepareStatement(sql); } @Override public CallableStatement prepareCall(String sql) throws SQLException { throwIfClosed(); try { return super.prepareCall(sql); } catch (UnsupportedOperationException e) { throw new SQLFeatureNotSupportedException(e.getMessage(), e); } } @Override public String nativeSQL(String sql) throws SQLException { throwIfClosed(); try { return super.nativeSQL(sql); } catch (UnsupportedOperationException e) { throw new SQLFeatureNotSupportedException(e.getMessage(), e); } } @Override public boolean getAutoCommit() throws SQLException { throwIfClosed(); return super.getAutoCommit(); } // No close() (it doesn't throw SQLException if already closed). @Override public DatabaseMetaData getMetaData() throws SQLException { throwIfClosed(); return super.getMetaData(); } @Override public void setReadOnly(boolean readOnly) throws SQLException { throwIfClosed(); super.setReadOnly(readOnly); } @Override public boolean isReadOnly() throws SQLException { throwIfClosed(); return super.isReadOnly(); } @Override public void setCatalog(String catalog) throws SQLException { throwIfClosed(); super.setCatalog(catalog); } @Override public String getCatalog() { // Can't throw any SQLException because AvaticaConnection's getCatalog() is // missing "throws SQLException". try { throwIfClosed(); } catch (AlreadyClosedSqlException e) { throw new RuntimeException(e.getMessage(), e); } return super.getCatalog(); } @Override public int getTransactionIsolation() throws SQLException { throwIfClosed(); return super.getTransactionIsolation(); } @Override public SQLWarning getWarnings() throws SQLException { throwIfClosed(); return super.getWarnings(); } @Override public void clearWarnings() throws SQLException { throwIfClosed(); super.clearWarnings(); } @Override public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { throwIfClosed(); return super.createStatement(resultSetType, resultSetConcurrency); } @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { throwIfClosed(); return super.prepareStatement(sql, resultSetType, resultSetConcurrency); } @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { throwIfClosed(); try { return super.prepareCall(sql, resultSetType, resultSetConcurrency); } catch (UnsupportedOperationException e) { throw new SQLFeatureNotSupportedException(e.getMessage(), e); } } @Override public Map<String,Class<?>> getTypeMap() throws SQLException { throwIfClosed(); try { return super.getTypeMap(); } catch (UnsupportedOperationException e) { throw new SQLFeatureNotSupportedException(e.getMessage(), e); } } @Override public void setTypeMap(Map<String,Class<?>> map) throws SQLException { throwIfClosed(); try { super.setTypeMap(map); } catch (UnsupportedOperationException e) { throw new SQLFeatureNotSupportedException(e.getMessage(), e); } } @Override public void setHoldability(int holdability) throws SQLException { throwIfClosed(); super.setHoldability(holdability); } @Override public int getHoldability() throws SQLException { throwIfClosed(); return super.getHoldability(); } @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { throwIfClosed(); try { return super.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability); } catch (UnsupportedOperationException e) { throw new SQLFeatureNotSupportedException(e.getMessage(), e); } } @Override public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { throwIfClosed(); try { return super.prepareStatement(sql, autoGeneratedKeys); } catch (UnsupportedOperationException e) { throw new SQLFeatureNotSupportedException(e.getMessage(), e); } } @Override public PreparedStatement prepareStatement(String sql, int columnIndexes[]) throws SQLException { throwIfClosed(); try { return super.prepareStatement(sql, columnIndexes); } catch (UnsupportedOperationException e) { throw new SQLFeatureNotSupportedException(e.getMessage(), e); } } @Override public PreparedStatement prepareStatement(String sql, String columnNames[]) throws SQLException { throwIfClosed(); try { return super.prepareStatement(sql, columnNames); } catch (UnsupportedOperationException e) { throw new SQLFeatureNotSupportedException(e.getMessage(), e); } } @Override public Clob createClob() throws SQLException { throwIfClosed(); try { return super.createClob(); } catch (UnsupportedOperationException e) { throw new SQLFeatureNotSupportedException(e.getMessage(), e); } } @Override public Blob createBlob() throws SQLException { throwIfClosed(); try { return super.createBlob(); } catch (UnsupportedOperationException e) { throw new SQLFeatureNotSupportedException(e.getMessage(), e); } } @Override public NClob createNClob() throws SQLException { throwIfClosed(); try { return super.createNClob(); } catch (UnsupportedOperationException e) { throw new SQLFeatureNotSupportedException(e.getMessage(), e); } } @Override public SQLXML createSQLXML() throws SQLException { throwIfClosed(); try { return super.createSQLXML(); } catch (UnsupportedOperationException e) { throw new SQLFeatureNotSupportedException(e.getMessage(), e); } } @Override public boolean isValid(int timeout) throws SQLException { throwIfClosed(); try { return super.isValid(timeout); } catch (UnsupportedOperationException e) { throw new SQLFeatureNotSupportedException(e.getMessage(), e); } } @Override public void setClientInfo(String name, String value) throws SQLClientInfoException { try { throwIfClosed(); } catch (AlreadyClosedSqlException e) { throw new SQLClientInfoException(e.getMessage(), null, e); } try { super.setClientInfo(name, value); } catch (UnsupportedOperationException e) { SQLFeatureNotSupportedException intended = new SQLFeatureNotSupportedException(e.getMessage(), e); throw new SQLClientInfoException(e.getMessage(), null, intended); } } @Override public void setClientInfo(Properties properties) throws SQLClientInfoException { try { throwIfClosed(); } catch (AlreadyClosedSqlException e) { throw new SQLClientInfoException(e.getMessage(), null, e); } try { super.setClientInfo(properties); } catch (UnsupportedOperationException e) { SQLFeatureNotSupportedException intended = new SQLFeatureNotSupportedException(e.getMessage(), e); throw new SQLClientInfoException(e.getMessage(), null, intended); } } @Override public String getClientInfo(String name) throws SQLException { throwIfClosed(); try { return super.getClientInfo(name); } catch (UnsupportedOperationException e) { throw new SQLFeatureNotSupportedException(e.getMessage(), e); } } @Override public Properties getClientInfo() throws SQLException { throwIfClosed(); try { return super.getClientInfo(); } catch (UnsupportedOperationException e) { throw new SQLFeatureNotSupportedException(e.getMessage(), e); } } @Override public Array createArrayOf(String typeName, Object[] elements) throws SQLException { throwIfClosed(); try { return super.createArrayOf(typeName, elements); } catch (UnsupportedOperationException e) { throw new SQLFeatureNotSupportedException(e.getMessage(), e); } } @Override public Struct createStruct(String typeName, Object[] attributes) throws SQLException { throwIfClosed(); try { return super.createStruct(typeName, attributes); } catch (UnsupportedOperationException e) { throw new SQLFeatureNotSupportedException(e.getMessage(), e); } } @Override public void setSchema(String schema) throws SQLException { throwIfClosed(); super.setSchema(schema); } @Override public String getSchema() { // Can't throw any SQLException because AvaticaConnection's getCatalog() is // missing "throws SQLException". try { throwIfClosed(); } catch (AlreadyClosedSqlException e) { throw new RuntimeException(e.getMessage(), e); } return super.getSchema(); } @Override public void abort(Executor executor) throws SQLException { throwIfClosed(); try { super.abort(executor); } catch (UnsupportedOperationException e) { throw new SQLFeatureNotSupportedException(e.getMessage(), e); } } // do not make public UnregisteredDriver getDriver() { return driver; } // do not make public AvaticaFactory getFactory() { return factory; } private static void closeOrWarn(final AutoCloseable autoCloseable, final String message, final Logger logger) { if (autoCloseable == null) { return; } try { autoCloseable.close(); } catch(Exception e) { logger.warn(message, e); } } // TODO this should be an AutoCloseable, and this should be close() void cleanup() { // First close any open JDBC Statement objects, to close any open ResultSet // objects and release their buffers/vectors. openStatementsRegistry.close(); // TODO all of these should use DeferredException when it is available from DRILL-2245 closeOrWarn(client, "Exception while closing client.", logger); closeOrWarn(allocator, "Exception while closing allocator.", logger); if (bit != null) { bit.close(); } closeOrWarn(serviceSet, "Exception while closing service set.", logger); } // TODO(DRILL-xxxx): Eliminate this test-specific hack from production code. // If we're not going to have tests themselves explicitly handle making names // unique, then at least move this logic into a test base class, and have it // go through DrillConnection.getClient(). /** * Test only code to make JDBC tests run concurrently. If the property <i>drillJDBCUnitTests</i> is set to * <i>true</i> in connection properties: * - Update dfs_test.tmp workspace location with a temp directory. This temp is for exclusive use for test jvm. * - Update dfs.tmp workspace to immutable, so that test writer don't try to create views in dfs.tmp * @param pluginRegistry */ private static void makeTmpSchemaLocationsUnique(StoragePluginRegistry pluginRegistry, Properties props) { try { if (props != null && "true".equalsIgnoreCase(props.getProperty("drillJDBCUnitTests"))) { final String tmpDirPath = TestUtilities.createTempDir(); TestUtilities.updateDfsTestTmpSchemaLocation(pluginRegistry, tmpDirPath); TestUtilities.makeDfsTmpSchemaImmutable(pluginRegistry); } } catch(Throwable e) { // Reason for catching Throwable is to capture NoSuchMethodError etc which depend on certain classed to be // present in classpath which may not be available when just using the standalone JDBC. This is unlikely to // happen, but just a safeguard to avoid failing user applications. logger.warn("Failed to update tmp schema locations. This step is purely for testing purpose. " + "Shouldn't be seen in production code."); // Ignore the error and go with defaults } } }
package org.bouncycastle.math.ec.custom.sec; import java.math.BigInteger; import java.util.Random; import org.bouncycastle.math.ec.ECConstants; import org.bouncycastle.math.ec.ECCurve; import org.bouncycastle.math.ec.ECCurve.AbstractF2m; import org.bouncycastle.math.ec.ECFieldElement; import org.bouncycastle.math.ec.ECMultiplier; import org.bouncycastle.math.ec.ECPoint; import org.bouncycastle.math.ec.WTauNafMultiplier; import org.bouncycastle.util.encoders.Hex; public class SecT571K1Curve extends AbstractF2m { private static final int SecT571K1_DEFAULT_COORDS = COORD_LAMBDA_PROJECTIVE; protected SecT571K1Point infinity; public SecT571K1Curve() { super(571, 2, 5, 10); this.infinity = new SecT571K1Point(this, null, null); this.a = fromBigInteger(BigInteger.valueOf(0)); this.b = fromBigInteger(BigInteger.valueOf(1)); this.order = new BigInteger(1, Hex.decode("020000000000000000000000000000000000000000000000000000000000000000000000131850E1F19A63E4B391A8DB917F4138B630D84BE5D639381E91DEB45CFE778F637C1001")); this.cofactor = BigInteger.valueOf(4); this.coord = SecT571K1_DEFAULT_COORDS; } protected ECCurve cloneCurve() { return new SecT571K1Curve(); } public boolean supportsCoordinateSystem(int coord) { switch (coord) { case COORD_LAMBDA_PROJECTIVE: return true; default: return false; } } protected ECMultiplier createDefaultMultiplier() { return new WTauNafMultiplier(); } public int getFieldSize() { return 571; } public ECFieldElement fromBigInteger(BigInteger x) { return new SecT571FieldElement(x); } protected ECPoint createRawPoint(ECFieldElement x, ECFieldElement y, boolean withCompression) { return new SecT571K1Point(this, x, y, withCompression); } protected ECPoint createRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, boolean withCompression) { return new SecT571K1Point(this, x, y, zs, withCompression); } public ECPoint getInfinity() { return infinity; } public boolean isKoblitz() { return true; } /** * Decompresses a compressed point P = (xp, yp) (X9.62 s 4.2.2). * * @param yTilde * ~yp, an indication bit for the decompression of yp. * @param X1 * The field element xp. * @return the decompressed point. */ protected ECPoint decompressPoint(int yTilde, BigInteger X1) { ECFieldElement x = fromBigInteger(X1), y = null; if (x.isZero()) { y = b.sqrt(); } else { ECFieldElement beta = x.square().invert().multiply(b).add(a).add(x); ECFieldElement z = solveQuadraticEquation(beta); if (z != null) { if (z.testBitZero() != (yTilde == 1)) { z = z.addOne(); } switch (this.getCoordinateSystem()) { case COORD_LAMBDA_AFFINE: case COORD_LAMBDA_PROJECTIVE: { y = z.add(x); break; } default: { y = z.multiply(x); break; } } } } if (y == null) { throw new IllegalArgumentException("Invalid point compression"); } return this.createRawPoint(x, y, true); } /** * Solves a quadratic equation <code>z<sup>2</sup> + z = beta</code>(X9.62 * D.1.6) The other solution is <code>z + 1</code>. * * @param beta * The value to solve the quadratic equation for. * @return the solution for <code>z<sup>2</sup> + z = beta</code> or * <code>null</code> if no solution exists. */ private ECFieldElement solveQuadraticEquation(ECFieldElement beta) { if (beta.isZero()) { return beta; } ECFieldElement zeroElement = fromBigInteger(ECConstants.ZERO); ECFieldElement z = null; ECFieldElement gamma = null; Random rand = new Random(); do { ECFieldElement t = fromBigInteger(new BigInteger(571, rand)); z = zeroElement; ECFieldElement w = beta; for (int i = 1; i < 571; i++) { ECFieldElement w2 = w.square(); z = z.square().add(w2.multiply(t)); w = w2.add(beta); } if (!w.isZero()) { return null; } gamma = z.square().add(z); } while (gamma.isZero()); return z; } public int getM() { return 571; } public boolean isTrinomial() { return false; } public int getK1() { return 2; } public int getK2() { return 5; } public int getK3() { return 10; } }
/** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.masterdb.security.hibernate.swap; import com.opengamma.financial.security.swap.FloatingRateType; import com.opengamma.financial.security.swap.InterpolationMethod; import com.opengamma.financial.security.swap.VarianceSwapType; import com.opengamma.masterdb.security.hibernate.BusinessDayConventionBean; import com.opengamma.masterdb.security.hibernate.DayCountBean; import com.opengamma.masterdb.security.hibernate.ExternalIdBean; import com.opengamma.masterdb.security.hibernate.FrequencyBean; /** * A Hibernate bean representation of * {@link com.opengamma.financial.security.swap.SwapLeg}. */ public class SwapLegBean { // No identifier as this will be part of a SwapSecurityBean private SwapLegType _swapLegType; private DayCountBean _dayCount; private FrequencyBean _frequency; private ExternalIdBean _region; private BusinessDayConventionBean _businessDayConvention; private NotionalBean _notional; private Double _rate; private Double _spread; private ExternalIdBean _rateIdentifier; private boolean _eom; private FloatingRateType _floatingRateType; private Integer _settlementDays; private FrequencyBean _offsetFixing; private Double _gearing; private Double _strike; private VarianceSwapType _varianceSwapType; private ExternalIdBean _underlyingId; private FrequencyBean _monitoringFrequency; private Double _annualizationFactor; private Integer _conventionalIndexationLag; private Integer _actualIndexationLag; private InterpolationMethod _indexInterpolationMethod; /** * Gets the swapLegType. * @return the swapLegType */ public SwapLegType getSwapLegType() { return _swapLegType; } /** * Sets the swapLegType. * @param swapLegType the swapLegType */ public void setSwapLegType(final SwapLegType swapLegType) { _swapLegType = swapLegType; } /** * Gets the dayCount. * @return the dayCount */ public DayCountBean getDayCount() { return _dayCount; } /** * Sets the dayCount. * @param dayCount the dayCount */ public void setDayCount(final DayCountBean dayCount) { _dayCount = dayCount; } /** * Gets the frequency. * @return the frequency */ public FrequencyBean getFrequency() { return _frequency; } /** * Sets the frequency. * @param frequency the frequency */ public void setFrequency(final FrequencyBean frequency) { _frequency = frequency; } /** * Gets the region. * @return the region */ public ExternalIdBean getRegion() { return _region; } /** * Sets the region. * @param region the region */ public void setRegion(final ExternalIdBean region) { _region = region; } /** * Gets the businessDayConvention. * @return the businessDayConvention */ public BusinessDayConventionBean getBusinessDayConvention() { return _businessDayConvention; } /** * Sets the businessDayConvention. * @param businessDayConvention the businessDayConvention */ public void setBusinessDayConvention(final BusinessDayConventionBean businessDayConvention) { _businessDayConvention = businessDayConvention; } /** * Gets the notional. * @return the notional */ public NotionalBean getNotional() { return _notional; } /** * Sets the notional. * @param notional the notional */ public void setNotional(final NotionalBean notional) { _notional = notional; } /** * Gets the rate. * @return the rate */ public Double getRate() { return _rate; } /** * Sets the rate. * @param rate the rate */ public void setRate(final Double rate) { _rate = rate; } /** * Gets the spread. * @return the spread */ public Double getSpread() { return _spread; } /** * Sets the spread. * @param spread the spread */ public void setSpread(final Double spread) { _spread = spread; } /** * Gets the rateIdentifier. * @return the rateIdentifier */ public ExternalIdBean getRateIdentifier() { return _rateIdentifier; } /** * Sets the rateIdentifier. * @param rateIdentifier the rateIdentifier */ public void setRateIdentifier(final ExternalIdBean rateIdentifier) { _rateIdentifier = rateIdentifier; } /** * Gets the eom. * @return the eom */ public boolean isEom() { return _eom; } /** * Sets the eom. * @param eom the eom */ public void setEom(final boolean eom) { _eom = eom; } /** * Gets the floatingRateType. * @return the floatingRateType */ public FloatingRateType getFloatingRateType() { return _floatingRateType; } /** * Sets the floatingRateType. * @param floatingRateType the floatingRateType */ public void setFloatingRateType(final FloatingRateType floatingRateType) { _floatingRateType = floatingRateType; } /** * Gets the settlementDays. * @return the settlementDays */ public Integer getSettlementDays() { return _settlementDays; } /** * Sets the settlementDays. * @param settlementDays the settlementDays */ public void setSettlementDays(final Integer settlementDays) { _settlementDays = settlementDays; } /** * Gets the offsetFixing. * @return the offsetFixing */ public FrequencyBean getOffsetFixing() { return _offsetFixing; } /** * Sets the offsetFixing. * @param offsetFixing the offsetFixing */ public void setOffsetFixing(final FrequencyBean offsetFixing) { _offsetFixing = offsetFixing; } /** * Gets the gearing. * @return the gearing */ public Double getGearing() { return _gearing; } /** * Sets the gearing. * @param gearing the gearing */ public void setGearing(final Double gearing) { _gearing = gearing; } /** * Gets the strike. For fixed variance swap legs. * @return The strike */ public Double getStrike() { return _strike; } /** * Sets the strike. For fixed variance swap legs. * @param strike The strike */ public void setStrike(final Double strike) { _strike = strike; } /** * Gets the variance swap type. For fixed variance swap legs. * @return The variance swap type */ public VarianceSwapType getVarianceSwapType() { return _varianceSwapType; } /** * Sets the variance swap type. For fixed variance swap legs. * @param varianceSwapType The variance swap type */ public void setVarianceSwapType(final VarianceSwapType varianceSwapType) { _varianceSwapType = varianceSwapType; } /** * Gets the underlying ID. For floating variance swap legs. * @return The underlying ID */ public ExternalIdBean getUnderlyingId() { return _underlyingId; } /** * Sets the underlying ID. For floating variance swap legs. * @param underlyingId The underlying ID */ public void setUnderlyingId(final ExternalIdBean underlyingId) { _underlyingId = underlyingId; } /** * Gets the monitoring frequency. For floating variance swap legs. * @return The monitoring frequency */ public FrequencyBean getMonitoringFrequency() { return _monitoringFrequency; } /** * Gets the monitoring frequency. For floating variance swap legs. * @param monitoringFrequency The monitoring frequency */ public void setMonitoringFrequency(final FrequencyBean monitoringFrequency) { _monitoringFrequency = monitoringFrequency; } /** * Gets the annualization factor. For floating variance swap legs. * @return The annualization factor */ public Double getAnnualizationFactor() { return _annualizationFactor; } /** * Sets the annualization factor. For floating variance swap legs. * @param annualizationFactor The annualization factor */ public void setAnnualizationFactor(final Double annualizationFactor) { _annualizationFactor = annualizationFactor; } /** * Gets the inflation leg conventional indexation lag. For inflation swap legs. * @return lag The conventional indexation lag. */ public Integer getConventionalIndexationLag() { return _conventionalIndexationLag; } /** * Gets the conventional indexation lag. For inflation swap legs. * @param conventionalIndexationLag The conventional indexation lag. */ public void setConventionalIndexationLag(final Integer conventionalIndexationLag) { _conventionalIndexationLag = conventionalIndexationLag; } /** * Gets the actual indexation lag. For inflation swap legs. * @return lag The actual indexation lag. */ public Integer getActualIndexationLag() { return _actualIndexationLag; } /** * Gets the actual indexation lag. For inflation swap legs. * @param actualIndexationLag The actual indexation lag. */ public void setActualIndexationLag(final Integer actualIndexationLag) { _actualIndexationLag = actualIndexationLag; } /** * Gets the inflation leg interpolation method. For inflation swap legs. * @return The inflation leg interpolation method. */ public InterpolationMethod getIndexInterpolationMethod() { return _indexInterpolationMethod; } /** * Sets the inflation leg interpolation method. For inflation swap legs. * @param indexInterpolationMethod The inflation leg interpolation method. */ public void setIndexInterpolationMethod(final InterpolationMethod indexInterpolationMethod) { _indexInterpolationMethod = indexInterpolationMethod; } }
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.python.psi.resolve; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.fileTypes.ExtensionFileNameMatcher; import com.intellij.openapi.fileTypes.FileNameMatcher; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.roots.FileIndexFacade; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiInvalidElementAccessException; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.QualifiedName; import com.intellij.util.containers.HashSet; import com.jetbrains.python.PyNames; import com.jetbrains.python.PythonFileType; import com.jetbrains.python.psi.*; import com.jetbrains.python.psi.impl.*; import com.jetbrains.python.psi.types.PyModuleType; import com.jetbrains.python.psi.types.PyType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import static com.jetbrains.python.psi.FutureFeature.ABSOLUTE_IMPORT; /** * @author dcheryasov */ public class ResolveImportUtil { private ResolveImportUtil() { } private static final ThreadLocal<Set<String>> ourBeingImported = new ThreadLocal<Set<String>>() { @Override protected Set<String> initialValue() { return new HashSet<String>(); } }; public static boolean isAbsoluteImportEnabledFor(PsiElement foothold) { if (foothold != null) { PsiFile file = foothold.getContainingFile(); if (file instanceof PyFile) { final PyFile pyFile = (PyFile)file; if (pyFile.getLanguageLevel().isPy3K()) { return true; } return pyFile.hasImportFromFuture(ABSOLUTE_IMPORT); } } // if the relevant import is below the foothold, it is either legal or we've detected the offending statement already return false; } /** * Finds a directory that many levels above a given file, making sure that every level has an __init__.py. * * @param base file that works as a reference. * @param depth must be positive, 1 means the dir that contains base, 2 is one dir above, etc. * @return found directory, or null. */ @Nullable public static PsiDirectory stepBackFrom(PsiFile base, int depth) { if (depth == 0) { return base.getContainingDirectory(); } PsiDirectory result; if (base != null) { base = base.getOriginalFile(); // just to make sure result = base.getContainingDirectory(); int count = 1; while (result != null && PyUtil.isPackage(result, base)) { if (count >= depth) return result; result = result.getParentDirectory(); count += 1; } } return null; } @Nullable public static PsiElement resolveImportElement(PyImportElement importElement, @NotNull final QualifiedName qName) { List<RatedResolveResult> targets; final PyStatement importStatement = importElement.getContainingImportStatement(); if (importStatement instanceof PyFromImportStatement) { targets = resolveNameInFromImport((PyFromImportStatement)importStatement, qName); } else { // "import foo" targets = resolveNameInImportStatement(importElement, qName); } final List<RatedResolveResult> resultList = RatedResolveResult.sorted(targets); return resultList.size() > 0 ? resultList.get(0).getElement() : null; } public static List<RatedResolveResult> resolveNameInImportStatement(PyImportElement importElement, @NotNull QualifiedName qName) { final PsiFile file = importElement.getContainingFile().getOriginalFile(); boolean absoluteImportEnabled = isAbsoluteImportEnabledFor(importElement); final List<PsiElement> modules = resolveModule(qName, file, absoluteImportEnabled, 0); return rateResults(modules); } public static List<RatedResolveResult> resolveNameInFromImport(PyFromImportStatement importStatement, @NotNull QualifiedName qName) { PsiFile file = importStatement.getContainingFile().getOriginalFile(); String name = qName.getComponents().get(0); final List<PsiElement> candidates = importStatement.resolveImportSourceCandidates(); List<PsiElement> resultList = new ArrayList<PsiElement>(); for (PsiElement candidate : candidates) { if (!candidate.isValid()) { throw new PsiInvalidElementAccessException(candidate, "Got an invalid candidate from resolveImportSourceCandidates(): " + candidate.getClass()); } if (candidate instanceof PsiDirectory) { candidate = PyUtil.getPackageElement((PsiDirectory)candidate, importStatement); } PsiElement result = resolveChild(candidate, name, file, false, true); if (result != null) { if (!result.isValid()) { throw new PsiInvalidElementAccessException(result, "Got an invalid candidate from resolveChild(): " + result.getClass()); } resultList.add(result); } } if (!resultList.isEmpty()) { return rateResults(resultList); } return Collections.emptyList(); } @NotNull public static List<PsiElement> resolveFromImportStatementSource(@NotNull PyFromImportStatement fromImportStatement, @Nullable QualifiedName qName) { final boolean absoluteImportEnabled = isAbsoluteImportEnabledFor(fromImportStatement); final PsiFile file = fromImportStatement.getContainingFile(); return resolveModule(qName, file, absoluteImportEnabled, fromImportStatement.getRelativeLevel()); } /** * Resolves a module reference in a general case. * * * @param qualifiedName qualified name of the module reference to resolve * @param sourceFile where that reference resides; serves as PSI foothold to determine module, project, etc. * @param importIsAbsolute if false, try old python 2.x's "relative first, absolute next" approach. * @param relativeLevel if > 0, step back from sourceFile and resolve from there (even if importIsAbsolute is false!). * @return list of possible candidates */ @NotNull public static List<PsiElement> resolveModule(@Nullable QualifiedName qualifiedName, @Nullable PsiFile sourceFile, boolean importIsAbsolute, int relativeLevel) { if (qualifiedName == null || sourceFile == null) { return Collections.emptyList(); } final String marker = qualifiedName + "#" + Integer.toString(relativeLevel); final Set<String> beingImported = ourBeingImported.get(); if (beingImported.contains(marker)) { return Collections.emptyList(); // break endless loop in import } try { beingImported.add(marker); final QualifiedNameResolver visitor = new QualifiedNameResolverImpl(qualifiedName).fromElement(sourceFile); if (relativeLevel > 0) { // "from ...module import" visitor.withRelative(relativeLevel).withoutRoots(); } else { // "from module import" if (!importIsAbsolute) { visitor.withRelative(0); } } List<PsiElement> results = visitor.resultsAsList(); if (results.isEmpty() && relativeLevel == 0 && !importIsAbsolute) { results = resolveRelativeImportAsAbsolute(sourceFile, qualifiedName); } return results; } finally { beingImported.remove(marker); } } /** * Try to resolve relative import as absolute in roots, not in its parent directory. * * This may be useful for resolving to child skeleton modules located in other directories. * * @param foothold foothold file. * @param qualifiedName relative import name. * @return list of resolved elements. */ @NotNull private static List<PsiElement> resolveRelativeImportAsAbsolute(@NotNull PsiFile foothold, @NotNull QualifiedName qualifiedName) { final VirtualFile virtualFile = foothold.getVirtualFile(); if (virtualFile == null) return Collections.emptyList(); final boolean inSource = FileIndexFacade.getInstance(foothold.getProject()).isInContent(virtualFile); if (inSource) return Collections.emptyList(); final PsiDirectory containingDirectory = foothold.getContainingDirectory(); if (containingDirectory != null) { final QualifiedName containingPath = QualifiedNameFinder.findCanonicalImportPath(containingDirectory, null); if (containingPath != null && containingPath.getComponentCount() > 0) { final QualifiedName absolutePath = containingPath.append(qualifiedName.toString()); final QualifiedNameResolver absoluteVisitor = new QualifiedNameResolverImpl(absolutePath).fromElement(foothold); return absoluteVisitor.resultsAsList(); } } return Collections.emptyList(); } @Nullable public static PsiElement resolveModuleInRoots(@NotNull QualifiedName moduleQualifiedName, @Nullable PsiElement foothold) { if (foothold == null) return null; QualifiedNameResolver visitor = new QualifiedNameResolverImpl(moduleQualifiedName).fromElement(foothold); return visitor.firstResult(); } @Nullable static PythonPathCache getPathCache(PsiElement foothold) { PythonPathCache cache = null; final Module module = ModuleUtilCore.findModuleForPsiElement(foothold); if (module != null) { cache = PythonModulePathCache.getInstance(module); } else { final Sdk sdk = PyBuiltinCache.findSdkForFile(foothold.getContainingFile()); if (sdk != null) { cache = PythonSdkPathCache.getInstance(foothold.getProject(), sdk); } } return cache; } /** * Tries to find referencedName under the parent element. * * @param parent element under which to look for referenced name; if null, null is returned. * @param referencedName which name to look for. * @param containingFile where we're in. * @param fileOnly if true, considers only a PsiFile child as a valid result; non-file hits are ignored. * @param checkForPackage if true, directories are returned only if they contain __init__.py * @return the element the referencedName resolves to, or null. */ @Nullable public static PsiElement resolveChild(@Nullable final PsiElement parent, @NotNull final String referencedName, @Nullable final PsiFile containingFile, boolean fileOnly, boolean checkForPackage) { if (parent == null) { return null; } else if (parent instanceof PyFile) { return resolveInPackageModule((PyFile)parent, referencedName, containingFile, fileOnly, checkForPackage); } else if (parent instanceof PsiDirectory) { return resolveInPackageDirectory(parent, referencedName, containingFile, fileOnly, checkForPackage); } else { return resolveMemberFromReferenceTypeProviders(parent, referencedName); } } @Nullable private static PsiElement resolveInPackageModule(@NotNull PyFile parent, @NotNull String referencedName, @Nullable PsiFile containingFile, boolean fileOnly, boolean checkForPackage) { final PsiElement moduleMember = resolveModuleMember(parent, referencedName); final PsiElement resolved = !fileOnly || PyUtil.instanceOf(moduleMember, PsiFile.class, PsiDirectory.class) ? moduleMember : null; if (resolved != null && !preferResolveInDirectoryOverModule(resolved)) { return resolved; } final PsiElement resolvedInDirectory = resolveInPackageDirectory(parent, referencedName, containingFile, fileOnly, checkForPackage); if (resolvedInDirectory != null) { return resolvedInDirectory; } return resolved; } private static boolean preferResolveInDirectoryOverModule(@NotNull PsiElement resolved) { return PsiTreeUtil.getStubOrPsiParentOfType(resolved, PyExceptPart.class) != null || PyUtil.instanceOf(resolved, PsiFile.class, PsiDirectory.class) || // XXX: Workaround for PY-9439 isDunderAll(resolved); } @Nullable private static PsiElement resolveModuleMember(@NotNull PyFile file, @NotNull String referencedName) { final PyModuleType moduleType = new PyModuleType(file); final PyResolveContext resolveContext = PyResolveContext.defaultContext(); final List<? extends RatedResolveResult> results = moduleType.resolveMember(referencedName, null, AccessDirection.READ, resolveContext); return results != null && !results.isEmpty() ? results.get(0).getElement() : null; } @Nullable private static PsiElement resolveInPackageDirectory(@Nullable PsiElement parent, @NotNull String referencedName, @Nullable PsiFile containingFile, boolean fileOnly, boolean checkForPackage) { final PsiElement parentDir = PyUtil.turnInitIntoDir(parent); if (parentDir instanceof PsiDirectory) { final PsiElement resolved = resolveInDirectory(referencedName, containingFile, (PsiDirectory)parentDir, fileOnly, checkForPackage); if (resolved != null) { return resolved; } if (parent instanceof PsiFile) { return resolveForeignImports((PsiFile)parent, referencedName); } } return null; } @Nullable private static PsiElement resolveForeignImports(@NotNull PsiFile foothold, @NotNull String referencedName) { return new QualifiedNameResolverImpl(referencedName).fromElement(foothold).withoutRoots().firstResult(); } @Nullable private static PsiElement resolveMemberFromReferenceTypeProviders(@NotNull PsiElement parent, @NotNull String referencedName) { final PyResolveContext resolveContext = PyResolveContext.defaultContext(); PyType refType = PyReferenceExpressionImpl.getReferenceTypeFromProviders(parent, resolveContext.getTypeEvalContext(), null); if (refType != null) { final List<? extends RatedResolveResult> result = refType.resolveMember(referencedName, null, AccessDirection.READ, resolveContext); if (result != null && !result.isEmpty()) { return result.get(0).getElement(); } } return null; } private static boolean isDunderAll(@NotNull PsiElement element) { return (element instanceof PyElement) && PyNames.ALL.equals(((PyElement)element).getName()); } @Nullable private static PsiElement resolveInDirectory(final String referencedName, @Nullable final PsiFile containingFile, final PsiDirectory dir, boolean isFileOnly, boolean checkForPackage) { if (referencedName == null) return null; final PsiDirectory subdir = dir.findSubdirectory(referencedName); if (subdir != null && (!checkForPackage || PyUtil.isPackage(subdir, containingFile))) { return subdir; } final PsiFile module = findPyFileInDir(dir, referencedName); if (module != null) return module; if (!isFileOnly) { // not a subdir, not a file; could be a name in parent/__init__.py final PsiFile initPy = dir.findFile(PyNames.INIT_DOT_PY); if (initPy == containingFile) return null; // don't dive into the file we're in if (initPy instanceof PyFile) { return ((PyFile)initPy).getElementNamed(referencedName); } } return null; } @Nullable private static PsiFile findPyFileInDir(PsiDirectory dir, String referencedName) { PsiFile file = dir.findFile(referencedName + PyNames.DOT_PY); if (file == null) { final List<FileNameMatcher> associations = FileTypeManager.getInstance().getAssociations(PythonFileType.INSTANCE); for (FileNameMatcher association : associations) { if (association instanceof ExtensionFileNameMatcher) { file = dir.findFile(referencedName + "." + ((ExtensionFileNameMatcher)association).getExtension()); if (file != null) break; } } } if (file != null && FileUtil.getNameWithoutExtension(file.getName()).equals(referencedName)) { return file; } return null; } public static ResolveResultList rateResults(List<? extends PsiElement> targets) { ResolveResultList ret = new ResolveResultList(); for (PsiElement target : targets) { if (target instanceof PsiDirectory) { target = PyUtil.getPackageElement((PsiDirectory)target, null); } if (target != null) { int rate = RatedResolveResult.RATE_HIGH; if (target instanceof PyFile) { for (PyResolveResultRater rater : Extensions.getExtensions(PyResolveResultRater.EP_NAME)) { rate += rater.getImportElementRate(target); } } else if (isDunderAll(target)) { rate = RatedResolveResult.RATE_NORMAL; } ret.poke(target, rate); } } return ret; } /** * @param element what we test (identifier, reference, import element, etc) * @return the how the element relates to an enclosing import statement, if any * @see PointInImport */ @NotNull public static PointInImport getPointInImport(@NotNull PsiElement element) { final PsiElement parent = PsiTreeUtil.getNonStrictParentOfType(element, PyImportElement.class, PyFromImportStatement.class); if (parent instanceof PyFromImportStatement) { return PointInImport.AS_MODULE; // from foo ... } if (parent instanceof PyImportElement) { final PsiElement statement = parent.getParent(); if (statement instanceof PyImportStatement) { return PointInImport.AS_MODULE; // import foo,... } else if (statement instanceof PyFromImportStatement) { return PointInImport.AS_NAME; } } return PointInImport.NONE; } }
/* * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.xdebugger.impl; import com.intellij.execution.ExecutionException; import com.intellij.execution.Executor; import com.intellij.execution.executors.DefaultDebugExecutor; import com.intellij.execution.process.ProcessHandler; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.execution.runners.ProgramRunner; import com.intellij.execution.ui.ExecutionConsole; import com.intellij.execution.ui.RunContentDescriptor; import com.intellij.execution.ui.RunContentManagerImpl; import com.intellij.execution.ui.RunContentWithExecutorListener; import com.intellij.openapi.Disposable; import com.intellij.openapi.components.*; import com.intellij.openapi.editor.markup.GutterIconRenderer; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.FileEditorManagerAdapter; import com.intellij.openapi.fileEditor.FileEditorManagerListener; import com.intellij.openapi.project.Project; import com.intellij.openapi.startup.StartupManager; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.impl.http.HttpVirtualFile; import com.intellij.util.SmartList; import com.intellij.util.messages.MessageBus; import com.intellij.util.xmlb.annotations.Property; import com.intellij.xdebugger.*; import com.intellij.xdebugger.breakpoints.XBreakpoint; import com.intellij.xdebugger.breakpoints.XBreakpointAdapter; import com.intellij.xdebugger.breakpoints.XLineBreakpoint; import com.intellij.xdebugger.impl.breakpoints.XBreakpointBase; import com.intellij.xdebugger.impl.breakpoints.XBreakpointManagerImpl; import com.intellij.xdebugger.impl.ui.ExecutionPointHighlighter; import com.intellij.xdebugger.impl.ui.XDebugSessionData; import com.intellij.xdebugger.impl.ui.XDebugSessionTab; import gnu.trove.THashMap; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.*; /** * @author nik */ @State( name = XDebuggerManagerImpl.COMPONENT_NAME, storages = {@Storage( file = StoragePathMacros.WORKSPACE_FILE)}) public class XDebuggerManagerImpl extends XDebuggerManager implements ProjectComponent, PersistentStateComponent<XDebuggerManagerImpl.XDebuggerState> { @NonNls public static final String COMPONENT_NAME = "XDebuggerManager"; private final Project myProject; private final XBreakpointManagerImpl myBreakpointManager; private final Map<RunContentDescriptor, XDebugSessionData> mySessionData; private final Map<RunContentDescriptor, XDebugSessionTab> mySessionTabs; private final Map<ProcessHandler, XDebugSessionImpl> mySessions; private final ExecutionPointHighlighter myExecutionPointHighlighter; private XDebugSessionImpl myActiveSession; public XDebuggerManagerImpl(final Project project, final StartupManager startupManager, MessageBus messageBus) { myProject = project; myBreakpointManager = new XBreakpointManagerImpl(project, this, startupManager); mySessionData = new THashMap<RunContentDescriptor, XDebugSessionData>(); mySessionTabs = new THashMap<RunContentDescriptor, XDebugSessionTab>(); mySessions = new LinkedHashMap<ProcessHandler, XDebugSessionImpl>(); myExecutionPointHighlighter = new ExecutionPointHighlighter(project); messageBus.connect().subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, new FileEditorManagerAdapter() { @Override public void fileOpened(@NotNull final FileEditorManager source, @NotNull final VirtualFile file) { if (file instanceof HttpVirtualFile && file.equals(myExecutionPointHighlighter.getCurrentFile())) { myExecutionPointHighlighter.update(); } } }); myBreakpointManager.addBreakpointListener(new XBreakpointAdapter<XBreakpoint<?>>() { @Override public void breakpointChanged(@NotNull XBreakpoint<?> breakpoint) { if (!(breakpoint instanceof XLineBreakpoint)) { final XDebugSessionImpl session = getCurrentSession(); if (session != null && breakpoint.equals(session.getActiveNonLineBreakpoint())) { final XBreakpointBase breakpointBase = (XBreakpointBase)breakpoint; breakpointBase.clearIcon(); myExecutionPointHighlighter.updateGutterIcon(breakpointBase.createGutterIconRenderer()); } } } }); messageBus.connect().subscribe(RunContentManagerImpl.RUN_CONTENT_TOPIC, new RunContentWithExecutorListener() { @Override public void contentSelected(RunContentDescriptor descriptor, @NotNull Executor executor) { if (executor.equals(DefaultDebugExecutor.getDebugExecutorInstance())) { final XDebugSessionImpl session = mySessions.get(descriptor.getProcessHandler()); if (session != null) { session.activateSession(); } else { setActiveSession(null, null, false, null); } } } @Override public void contentRemoved(RunContentDescriptor descriptor, @NotNull Executor executor) { if (executor.equals(DefaultDebugExecutor.getDebugExecutorInstance())) { mySessions.remove(descriptor.getProcessHandler()); mySessionData.remove(descriptor); XDebugSessionTab tab = mySessionTabs.remove(descriptor); if (tab != null) { Disposer.dispose(tab); } } } }); } @Override @NotNull public XBreakpointManagerImpl getBreakpointManager() { return myBreakpointManager; } public Project getProject() { return myProject; } @Override public void projectOpened() { } @Override public void projectClosed() { } @NotNull @Override public String getComponentName() { return COMPONENT_NAME; } @Override public void initComponent() { } @Override public void disposeComponent() { } @Override @NotNull public XDebugSession startSession(@NotNull final ProgramRunner runner, @NotNull final ExecutionEnvironment env, @Nullable final RunContentDescriptor contentToReuse, @NotNull final XDebugProcessStarter processStarter) throws ExecutionException { return startSession(contentToReuse, processStarter, new XDebugSessionImpl(env, runner, this)); } @Override @NotNull public XDebugSession startSessionAndShowTab(@NotNull String sessionName, @Nullable RunContentDescriptor contentToReuse, @NotNull XDebugProcessStarter starter) throws ExecutionException { return startSessionAndShowTab(sessionName, contentToReuse, false, starter); } @NotNull @Override public XDebugSession startSessionAndShowTab(@NotNull String sessionName, @Nullable RunContentDescriptor contentToReuse, boolean showToolWindowOnSuspendOnly, @NotNull XDebugProcessStarter starter) throws ExecutionException { return startSessionAndShowTab(sessionName, null, contentToReuse, showToolWindowOnSuspendOnly, starter); } @NotNull @Override public XDebugSession startSessionAndShowTab(@NotNull String sessionName, final Icon icon, @Nullable RunContentDescriptor contentToReuse, boolean showToolWindowOnSuspendOnly, @NotNull XDebugProcessStarter starter) throws ExecutionException { XDebugSessionImpl session = startSession(contentToReuse, starter, new XDebugSessionImpl(null, null, this, sessionName, icon, showToolWindowOnSuspendOnly)); if (!showToolWindowOnSuspendOnly) { session.showSessionTab(); } ProcessHandler handler = session.getDebugProcess().getProcessHandler(); handler.startNotify(); return session; } private XDebugSessionImpl startSession(final RunContentDescriptor contentToReuse, final XDebugProcessStarter processStarter, final XDebugSessionImpl session) throws ExecutionException { XDebugProcess process = processStarter.start(session); XDebugSessionData oldSessionData = contentToReuse != null ? mySessionData.get(contentToReuse) : null; if (oldSessionData == null) { oldSessionData = new XDebugSessionData(); } session.init(process, oldSessionData); mySessions.put(session.getDebugProcess().getProcessHandler(), session); return session; } public void removeSession(@NotNull final XDebugSessionImpl session) { XDebugSessionTab sessionTab = session.getSessionTab(); mySessions.remove(session.getDebugProcess().getProcessHandler()); if (sessionTab != null) { final RunContentDescriptor descriptor = sessionTab.getRunContentDescriptor(); mySessionData.put(descriptor, session.getSessionData()); mySessionTabs.put(descriptor, sessionTab); // in test-mode RunContentWithExecutorListener.contentRemoved events are not sent (see RunContentManagerImpl.showRunContent) // so we make sure the mySessions and mySessionData are cleared correctly when session is disposed Disposer.register(sessionTab, new Disposable() { @Override public void dispose() { mySessionData.remove(descriptor); mySessionTabs.remove(descriptor); mySessions.remove(session.getDebugProcess().getProcessHandler()); } }); } if (myActiveSession == session) { myActiveSession = null; onActiveSessionChanged(); } } public void setActiveSession(@Nullable XDebugSessionImpl session, @Nullable XSourcePosition position, boolean useSelection, final @Nullable GutterIconRenderer gutterIconRenderer) { boolean sessionChanged = myActiveSession != session; myActiveSession = session; updateExecutionPoint(position, useSelection, gutterIconRenderer); if (sessionChanged) { onActiveSessionChanged(); } } public void updateExecutionPoint(XSourcePosition position, boolean useSelection, @Nullable GutterIconRenderer gutterIconRenderer) { if (position != null) { myExecutionPointHighlighter.show(position, useSelection, gutterIconRenderer); } else { myExecutionPointHighlighter.hide(); } } private void onActiveSessionChanged() { myBreakpointManager.getLineBreakpointManager().queueAllBreakpointsUpdate(); } @Override @NotNull public XDebugSession[] getDebugSessions() { final Collection<XDebugSessionImpl> sessions = mySessions.values(); return sessions.toArray(new XDebugSessionImpl[sessions.size()]); } @Override @Nullable public XDebugSession getDebugSession(@NotNull ExecutionConsole executionConsole) { for (final XDebugSessionImpl debuggerSession : mySessions.values()) { XDebugSessionTab sessionTab = debuggerSession.getSessionTab(); if (sessionTab != null) { RunContentDescriptor contentDescriptor = sessionTab.getRunContentDescriptor(); if (contentDescriptor != null && executionConsole == contentDescriptor.getExecutionConsole()) { return debuggerSession; } } } return null; } @NotNull @Override public <T extends XDebugProcess> List<? extends T> getDebugProcesses(Class<T> processClass) { List<T> list = null; for (XDebugSessionImpl session : mySessions.values()) { final XDebugProcess process = session.getDebugProcess(); if (processClass.isInstance(process)) { if (list == null) { list = new SmartList<T>(); } list.add(processClass.cast(process)); } } return list == null ? Collections.<T>emptyList() : list; } @Override @Nullable public XDebugSessionImpl getCurrentSession() { return myActiveSession; } @Override public XDebuggerState getState() { return new XDebuggerState(myBreakpointManager.getState()); } @Override public void loadState(final XDebuggerState state) { myBreakpointManager.loadState(state.myBreakpointManagerState); } public void showExecutionPosition() { myExecutionPointHighlighter.navigateTo(); } @SuppressWarnings("UnusedDeclaration") public static class XDebuggerState { private XBreakpointManagerImpl.BreakpointManagerState myBreakpointManagerState; public XDebuggerState() { } public XDebuggerState(final XBreakpointManagerImpl.BreakpointManagerState breakpointManagerState) { myBreakpointManagerState = breakpointManagerState; } @Property(surroundWithTag = false) public XBreakpointManagerImpl.BreakpointManagerState getBreakpointManagerState() { return myBreakpointManagerState; } public void setBreakpointManagerState(final XBreakpointManagerImpl.BreakpointManagerState breakpointManagerState) { myBreakpointManagerState = breakpointManagerState; } } }
/** Copyright 2008 University of Rochester 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.ur.ir; import java.util.StringTokenizer; /** * Helps with fixing any search string for lucene. * * @author Nathan Sarr * */ public class SearchHelper { public static int MIN_STRING_WILD_CARD_ADD = 4; /** * Prepares a string for searching - this removes problamatic characters. * * @param value - value to test * @param wildCardTearms - after string is fixed will append * at the end of each term * @return */ public static String prepareMainSearchString(String value, boolean wildCardTerms) { int count = count(value, "\""); // unbalanced quotes or no quotes if( count == 0 || ((count % 2) != 0) ) { String newVal = fixMainSearchStringSegment(value, wildCardTerms); //make sure search has more than Min String wild card if user using star if( stringHasEndingStar(newVal) && newVal.length() < MIN_STRING_WILD_CARD_ADD ) { if( newVal.length() > 1 ) { newVal = newVal.substring(0, newVal.length() -1 ); } else { newVal = ""; } } return newVal; } else { return fixOnlyNonQuoted(value, wildCardTerms); } } /** * Fixes a main search string segment. * * @param value * @return */ private static String fixMainSearchStringSegment(String value, boolean wildCardTerms) { String newValue = value; newValue = fixWildCardCharacters(newValue, '*'); newValue = fixWildCardCharacters(newValue, '?'); // this must be the first one checked newValue = escapeSpecialCharacters(newValue, "\\"); newValue = escapeSpecialCharacters(newValue, "+"); newValue = escapeSpecialCharacters(newValue, "("); newValue = escapeSpecialCharacters(newValue, ")"); newValue = escapeSpecialCharacters(newValue, "{"); newValue = escapeSpecialCharacters(newValue, "}"); newValue = escapeSpecialCharacters(newValue, "["); newValue = escapeSpecialCharacters(newValue, "]"); newValue = escapeSpecialCharacters(newValue, "^"); newValue = escapeSpecialCharacters(newValue, ":"); newValue = escapeSpecialCharacters(newValue, "-"); newValue = escapeSpecialCharacters(newValue, "&&"); newValue = escapeSpecialCharacters(newValue, "||"); newValue = escapeSpecialCharacters(newValue, "!"); newValue = escapeSpecialCharacters(newValue, "~"); newValue = escapeSpecialCharacters(newValue, "\""); //remove beginning and ending spaces newValue = newValue.trim(); // single term wild card, no spaces in the term and not already wild card if( wildCardTerms && !newValue.contains(".")) { // split values on white space String[] values = newValue.split("\\s"); // the string is a series of string values if( values.length > 0 ) { String tempValue = ""; for(String v : values) { // cannot have " before wild card don't need to add another * // if one already exists // do not apply * to any string less than 3 characters - otherwise two many clauses exception if( v.lastIndexOf('"') != (v.length() -1) && !stringHasEndingStar(v) && !containsSpecialCharacter(v) && v.length() >= MIN_STRING_WILD_CARD_ADD ) { tempValue = tempValue + " " + v + "*"; } else { tempValue = tempValue + " " + v; } } newValue = tempValue.trim(); } // single string value else if( newValue.length() > 0 && !stringHasEndingStar(newValue) && !containsSpecialCharacter(newValue) ) { if( newValue.length() >= MIN_STRING_WILD_CARD_ADD ) { newValue = newValue + "*"; } } } return newValue; } /** * Determine if the string has an ending * wild card value. * * @param value - value to check * @return - true if the string has an ending star */ private static boolean stringHasEndingStar(String value) { return value.lastIndexOf('*') == (value.length() -1 ); } /** * Determines if the string contains a special character. * * @param value - value to check * @return */ private static boolean containsSpecialCharacter(String value) { return value.contains("?") || value.contains("\\") || value.contains("+") || value.contains("(") || value.contains(")") || value.contains("{") || value.contains("}") || value.contains("[") || value.contains("]") || value.contains("^") || value.contains(":") || value.contains("&&") || value.contains("||") || value.contains("!") || value.contains("~") || value.contains("/") || value.contains("-"); } /** * This only fixes non quoted text * @param value * @param wildCardTerms * @return */ private static String fixOnlyNonQuoted(String value, boolean wildCardTerms ) { final String quotes = "\""; String newValue = ""; int beginIndex = 0; int toIndex = 0; // get the indexes of the quotes beginIndex = value.indexOf(quotes, beginIndex); if( beginIndex == -1) { newValue = value; } while( beginIndex != -1) { // get the end quote position toIndex = value.indexOf(quotes, beginIndex + 1); // set the newValue to this newValue = newValue + value.substring(beginIndex, toIndex + 1); // not at end of string get segment to fix if( toIndex != (value.length() -1)) { // get the next begin index (next start quotes) beginIndex = value.indexOf(quotes, toIndex + 1); String subString = ""; if( beginIndex == -1) { subString = value.substring(toIndex + 1, value.length()); } else { subString = value.substring(toIndex + 1, beginIndex); } String fixedValue = fixMainSearchStringSegment(subString, wildCardTerms); if( (subString.length() > 1)) { if( subString.charAt(0) == ' ' ) { fixedValue = " " + fixedValue; } if( subString.charAt(subString.length() - 1) == ' ' ) { fixedValue = fixedValue + " "; } } newValue = newValue + fixedValue; } else { beginIndex = -1; } } return newValue; } /** * Count the number of times a character appears * * @param value * @return number of times a character appears in the string */ public static int count(String value, String valueToCount) { int count = 0; int fromIndex = 0; fromIndex = value.indexOf(valueToCount,fromIndex ); while( fromIndex != -1) { fromIndex = value.indexOf(valueToCount,fromIndex + 1); count = count + 1; } return count; } /** * Prepares a string for searching - this removes problematic characters only including * escaping quotes. If quotes need to be applied they should be applied following the * call to this method. * * @param value * @return */ public static String prepareFacetSearchString(String value, boolean wildCardTerms) { return fixMainSearchStringSegment(value, wildCardTerms); } /** * Fix wild card characters like * and ? * * @param str - string to deal with * @param wildcard - wild card character */ private static String fixWildCardCharacters(String str, char wildcard) { if( !str.contains(wildcard + "")) { return str; } // determine if the * is final character int lastIndex = str.lastIndexOf(" " + wildcard); if(lastIndex == (str.length() - 2)) { str = str.substring(0, str.length() - 1); } // remove any leading star within the string // for example "this is *a test" int index = str.indexOf(" " + wildcard); while( index != -1) { str = str.substring(0, index + 1) + str.substring(index+2, str.length()-1); index = str.indexOf(" " + wildcard); } // remove beginning * if(str.indexOf(wildcard) == 0) { str = str.substring(1); } return str; } /** * Escape the special characters * * @param str - sting that has special characters, the characters that are special * @param theChars * @return the string cleaned up */ private static String escapeSpecialCharacters(String str, String theChars ) { if( !str.contains(theChars)) { return str; } String finalString = ""; //escapce all other instances of the character StringTokenizer tokenizer = new StringTokenizer(str, theChars, true); while( tokenizer.hasMoreElements()) { String token = tokenizer.nextToken(); if( token.equals(theChars)) { finalString = finalString + "\\" + theChars; } else { finalString = finalString + token ; } } return finalString; } public static void main(String[] args) { String value = "\"P-Selectivity\" Immunity, and"; System.out.println(SearchHelper.prepareMainSearchString(value, true)); } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: CChatMsg.proto package com.thanple.gs.common.nio.protocol; public final class _CChatMsg { private _CChatMsg() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { } public interface CChatMsgOrBuilder extends // @@protoc_insertion_point(interface_extends:CChatMsg) com.google.protobuf.MessageOrBuilder { /** * <code>required string msg = 1;</code> */ boolean hasMsg(); /** * <code>required string msg = 1;</code> */ java.lang.String getMsg(); /** * <code>required string msg = 1;</code> */ com.google.protobuf.ByteString getMsgBytes(); } /** * Protobuf type {@code CChatMsg} */ public static final class CChatMsg extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:CChatMsg) CChatMsgOrBuilder { // Use CChatMsg.newBuilder() to construct. private CChatMsg(com.google.protobuf.GeneratedMessage.Builder<?> builder) { super(builder); this.unknownFields = builder.getUnknownFields(); } private CChatMsg(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private static final CChatMsg defaultInstance; public static CChatMsg getDefaultInstance() { return defaultInstance; } public CChatMsg getDefaultInstanceForType() { return defaultInstance; } private final com.google.protobuf.UnknownFieldSet unknownFields; @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private CChatMsg( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 10: { com.google.protobuf.ByteString bs = input.readBytes(); bitField0_ |= 0x00000001; msg_ = bs; break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.thanple.gs.common.nio.protocol._CChatMsg.internal_static_CChatMsg_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.thanple.gs.common.nio.protocol._CChatMsg.internal_static_CChatMsg_fieldAccessorTable .ensureFieldAccessorsInitialized( com.thanple.gs.common.nio.protocol._CChatMsg.CChatMsg.class, com.thanple.gs.common.nio.protocol._CChatMsg.CChatMsg.Builder.class); } public static com.google.protobuf.Parser<CChatMsg> PARSER = new com.google.protobuf.AbstractParser<CChatMsg>() { public CChatMsg parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new CChatMsg(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser<CChatMsg> getParserForType() { return PARSER; } private int bitField0_; public static final int MSG_FIELD_NUMBER = 1; private java.lang.Object msg_; /** * <code>required string msg = 1;</code> */ public boolean hasMsg() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required string msg = 1;</code> */ public java.lang.String getMsg() { java.lang.Object ref = msg_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { msg_ = s; } return s; } } /** * <code>required string msg = 1;</code> */ public com.google.protobuf.ByteString getMsgBytes() { java.lang.Object ref = msg_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); msg_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private void initFields() { msg_ = ""; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; if (!hasMsg()) { memoizedIsInitialized = 0; return false; } memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeBytes(1, getMsgBytes()); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(1, getMsgBytes()); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static com.thanple.gs.common.nio.protocol._CChatMsg.CChatMsg parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.thanple.gs.common.nio.protocol._CChatMsg.CChatMsg parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.thanple.gs.common.nio.protocol._CChatMsg.CChatMsg parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.thanple.gs.common.nio.protocol._CChatMsg.CChatMsg parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.thanple.gs.common.nio.protocol._CChatMsg.CChatMsg parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static com.thanple.gs.common.nio.protocol._CChatMsg.CChatMsg parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static com.thanple.gs.common.nio.protocol._CChatMsg.CChatMsg parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static com.thanple.gs.common.nio.protocol._CChatMsg.CChatMsg parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static com.thanple.gs.common.nio.protocol._CChatMsg.CChatMsg parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static com.thanple.gs.common.nio.protocol._CChatMsg.CChatMsg parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(com.thanple.gs.common.nio.protocol._CChatMsg.CChatMsg prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code CChatMsg} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:CChatMsg) com.thanple.gs.common.nio.protocol._CChatMsg.CChatMsgOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.thanple.gs.common.nio.protocol._CChatMsg.internal_static_CChatMsg_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.thanple.gs.common.nio.protocol._CChatMsg.internal_static_CChatMsg_fieldAccessorTable .ensureFieldAccessorsInitialized( com.thanple.gs.common.nio.protocol._CChatMsg.CChatMsg.class, com.thanple.gs.common.nio.protocol._CChatMsg.CChatMsg.Builder.class); } // Construct using com.thanple.gs.common.nio.protocol._CChatMsg.CChatMsg.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); msg_ = ""; bitField0_ = (bitField0_ & ~0x00000001); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.thanple.gs.common.nio.protocol._CChatMsg.internal_static_CChatMsg_descriptor; } public com.thanple.gs.common.nio.protocol._CChatMsg.CChatMsg getDefaultInstanceForType() { return com.thanple.gs.common.nio.protocol._CChatMsg.CChatMsg.getDefaultInstance(); } public com.thanple.gs.common.nio.protocol._CChatMsg.CChatMsg build() { com.thanple.gs.common.nio.protocol._CChatMsg.CChatMsg result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public com.thanple.gs.common.nio.protocol._CChatMsg.CChatMsg buildPartial() { com.thanple.gs.common.nio.protocol._CChatMsg.CChatMsg result = new com.thanple.gs.common.nio.protocol._CChatMsg.CChatMsg(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.msg_ = msg_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.thanple.gs.common.nio.protocol._CChatMsg.CChatMsg) { return mergeFrom((com.thanple.gs.common.nio.protocol._CChatMsg.CChatMsg)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.thanple.gs.common.nio.protocol._CChatMsg.CChatMsg other) { if (other == com.thanple.gs.common.nio.protocol._CChatMsg.CChatMsg.getDefaultInstance()) return this; if (other.hasMsg()) { bitField0_ |= 0x00000001; msg_ = other.msg_; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { if (!hasMsg()) { return false; } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.thanple.gs.common.nio.protocol._CChatMsg.CChatMsg parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.thanple.gs.common.nio.protocol._CChatMsg.CChatMsg) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.lang.Object msg_ = ""; /** * <code>required string msg = 1;</code> */ public boolean hasMsg() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required string msg = 1;</code> */ public java.lang.String getMsg() { java.lang.Object ref = msg_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { msg_ = s; } return s; } else { return (java.lang.String) ref; } } /** * <code>required string msg = 1;</code> */ public com.google.protobuf.ByteString getMsgBytes() { java.lang.Object ref = msg_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); msg_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>required string msg = 1;</code> */ public Builder setMsg( java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; msg_ = value; onChanged(); return this; } /** * <code>required string msg = 1;</code> */ public Builder clearMsg() { bitField0_ = (bitField0_ & ~0x00000001); msg_ = getDefaultInstance().getMsg(); onChanged(); return this; } /** * <code>required string msg = 1;</code> */ public Builder setMsgBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; msg_ = value; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:CChatMsg) } static { defaultInstance = new CChatMsg(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:CChatMsg) } private static final com.google.protobuf.Descriptors.Descriptor internal_static_CChatMsg_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_CChatMsg_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n\016CChatMsg.proto\"\027\n\010CChatMsg\022\013\n\003msg\030\001 \002(" + "\tB/\n\"com.thanple.gs.common.nio.protocolB" + "\t_CChatMsg" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; return null; } }; com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { }, assigner); internal_static_CChatMsg_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_CChatMsg_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_CChatMsg_descriptor, new java.lang.String[] { "Msg", }); } // @@protoc_insertion_point(outer_class_scope) }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.appium.java_client.ios.options; import io.appium.java_client.ios.options.app.SupportsAppInstallStrategyOption; import io.appium.java_client.ios.options.app.SupportsAppPushTimeoutOption; import io.appium.java_client.ios.options.app.SupportsBundleIdOption; import io.appium.java_client.ios.options.app.SupportsLocalizableStringsDirOption; import io.appium.java_client.ios.options.general.SupportsIncludeDeviceCapsToSessionInfoOption; import io.appium.java_client.ios.options.general.SupportsResetLocationServiceOption; import io.appium.java_client.ios.options.other.SupportsCommandTimeoutsOption; import io.appium.java_client.ios.options.other.SupportsLaunchWithIdbOption; import io.appium.java_client.ios.options.other.SupportsResetOnSessionStartOnlyOption; import io.appium.java_client.ios.options.other.SupportsShowIosLogOption; import io.appium.java_client.ios.options.other.SupportsUseJsonSourceOption; import io.appium.java_client.ios.options.simulator.SupportsCalendarAccessAuthorizedOption; import io.appium.java_client.ios.options.simulator.SupportsCalendarFormatOption; import io.appium.java_client.ios.options.simulator.SupportsConnectHardwareKeyboardOption; import io.appium.java_client.ios.options.simulator.SupportsCustomSslCertOption; import io.appium.java_client.ios.options.simulator.SupportsEnforceFreshSimulatorCreationOption; import io.appium.java_client.ios.options.simulator.SupportsForceSimulatorSoftwareKeyboardPresenceOption; import io.appium.java_client.ios.options.simulator.SupportsIosSimulatorLogsPredicateOption; import io.appium.java_client.ios.options.simulator.SupportsKeepKeyChainsOption; import io.appium.java_client.ios.options.simulator.SupportsKeychainsExcludePatternsOption; import io.appium.java_client.ios.options.simulator.SupportsPermissionsOption; import io.appium.java_client.ios.options.simulator.SupportsReduceMotionOption; import io.appium.java_client.ios.options.simulator.SupportsScaleFactorOption; import io.appium.java_client.ios.options.simulator.SupportsShutdownOtherSimulatorsOption; import io.appium.java_client.ios.options.simulator.SupportsSimulatorDevicesSetPathOption; import io.appium.java_client.ios.options.simulator.SupportsSimulatorPasteboardAutomaticSyncOption; import io.appium.java_client.ios.options.simulator.SupportsSimulatorStartupTimeoutOption; import io.appium.java_client.ios.options.simulator.SupportsSimulatorTracePointerOption; import io.appium.java_client.ios.options.simulator.SupportsSimulatorWindowCenterOption; import io.appium.java_client.ios.options.simulator.SupportsWebkitResponseTimeoutOption; import io.appium.java_client.ios.options.wda.SupportsAllowProvisioningDeviceRegistrationOption; import io.appium.java_client.ios.options.wda.SupportsAutoAcceptAlertsOption; import io.appium.java_client.ios.options.wda.SupportsAutoDismissAlertsOption; import io.appium.java_client.ios.options.wda.SupportsDerivedDataPathOption; import io.appium.java_client.ios.options.wda.SupportsDisableAutomaticScreenshotsOption; import io.appium.java_client.ios.options.wda.SupportsForceAppLaunchOption; import io.appium.java_client.ios.options.wda.SupportsKeychainOptions; import io.appium.java_client.ios.options.wda.SupportsMaxTypingFrequencyOption; import io.appium.java_client.ios.options.wda.SupportsMjpegServerPortOption; import io.appium.java_client.ios.options.wda.SupportsProcessArgumentsOption; import io.appium.java_client.ios.options.wda.SupportsResultBundlePathOption; import io.appium.java_client.ios.options.wda.SupportsScreenshotQualityOption; import io.appium.java_client.ios.options.wda.SupportsShouldTerminateAppOption; import io.appium.java_client.ios.options.wda.SupportsShouldUseSingletonTestManagerOption; import io.appium.java_client.ios.options.wda.SupportsShowXcodeLogOption; import io.appium.java_client.ios.options.wda.SupportsSimpleIsVisibleCheckOption; import io.appium.java_client.ios.options.wda.SupportsUpdatedWdaBundleIdOption; import io.appium.java_client.ios.options.wda.SupportsUseNativeCachingStrategyOption; import io.appium.java_client.ios.options.wda.SupportsUseNewWdaOption; import io.appium.java_client.ios.options.wda.SupportsUsePrebuiltWdaOption; import io.appium.java_client.ios.options.wda.SupportsUseSimpleBuildTestOption; import io.appium.java_client.ios.options.wda.SupportsUseXctestrunFileOption; import io.appium.java_client.ios.options.wda.SupportsWaitForIdleTimeoutOption; import io.appium.java_client.ios.options.wda.SupportsWaitForQuiescenceOption; import io.appium.java_client.ios.options.wda.SupportsWdaBaseUrlOption; import io.appium.java_client.ios.options.wda.SupportsWdaConnectionTimeoutOption; import io.appium.java_client.ios.options.wda.SupportsWdaEventloopIdleDelayOption; import io.appium.java_client.ios.options.wda.SupportsWdaLaunchTimeoutOption; import io.appium.java_client.ios.options.wda.SupportsWdaLocalPortOption; import io.appium.java_client.ios.options.wda.SupportsWdaStartupRetriesOption; import io.appium.java_client.ios.options.wda.SupportsWdaStartupRetryIntervalOption; import io.appium.java_client.ios.options.wda.SupportsWebDriverAgentUrlOption; import io.appium.java_client.ios.options.wda.SupportsXcodeCertificateOptions; import io.appium.java_client.ios.options.webview.SupportsAbsoluteWebLocationsOption; import io.appium.java_client.ios.options.webview.SupportsAdditionalWebviewBundleIdsOption; import io.appium.java_client.ios.options.webview.SupportsEnableAsyncExecuteFromHttpsOption; import io.appium.java_client.ios.options.webview.SupportsFullContextListOption; import io.appium.java_client.ios.options.webview.SupportsIncludeSafariInWebviewsOption; import io.appium.java_client.ios.options.webview.SupportsNativeWebTapOption; import io.appium.java_client.ios.options.webview.SupportsNativeWebTapStrictOption; import io.appium.java_client.ios.options.webview.SupportsSafariAllowPopupsOption; import io.appium.java_client.ios.options.webview.SupportsSafariGarbageCollectOption; import io.appium.java_client.ios.options.webview.SupportsSafariIgnoreFraudWarningOption; import io.appium.java_client.ios.options.webview.SupportsSafariIgnoreWebHostnamesOption; import io.appium.java_client.ios.options.webview.SupportsSafariInitialUrlOption; import io.appium.java_client.ios.options.webview.SupportsSafariLogAllCommunicationHexDumpOption; import io.appium.java_client.ios.options.webview.SupportsSafariLogAllCommunicationOption; import io.appium.java_client.ios.options.webview.SupportsSafariOpenLinksInBackgroundOption; import io.appium.java_client.ios.options.webview.SupportsSafariSocketChunkSizeOption; import io.appium.java_client.ios.options.webview.SupportsSafariWebInspectorMaxFrameLengthOption; import io.appium.java_client.ios.options.webview.SupportsWebviewConnectRetriesOption; import io.appium.java_client.ios.options.webview.SupportsWebviewConnectTimeoutOption; import io.appium.java_client.remote.AutomationName; import io.appium.java_client.remote.MobilePlatform; import io.appium.java_client.remote.options.BaseOptions; import io.appium.java_client.remote.options.SupportsAppOption; import io.appium.java_client.remote.options.SupportsAutoWebViewOption; import io.appium.java_client.remote.options.SupportsClearSystemFilesOption; import io.appium.java_client.remote.options.SupportsDeviceNameOption; import io.appium.java_client.remote.options.SupportsEnablePerformanceLoggingOption; import io.appium.java_client.remote.options.SupportsIsHeadlessOption; import io.appium.java_client.remote.options.SupportsLanguageOption; import io.appium.java_client.remote.options.SupportsLocaleOption; import io.appium.java_client.remote.options.SupportsOrientationOption; import io.appium.java_client.remote.options.SupportsOtherAppsOption; import io.appium.java_client.remote.options.SupportsSkipLogCaptureOption; import io.appium.java_client.remote.options.SupportsUdidOption; import org.openqa.selenium.Capabilities; import java.util.Map; /** * https://github.com/appium/appium-xcuitest-driver#capabilities */ public class XCUITestOptions extends BaseOptions<XCUITestOptions> implements // General options: https://github.com/appium/appium-xcuitest-driver#general SupportsDeviceNameOption<XCUITestOptions>, SupportsUdidOption<XCUITestOptions>, SupportsIncludeDeviceCapsToSessionInfoOption<XCUITestOptions>, SupportsResetLocationServiceOption<XCUITestOptions>, // Localization Options SupportsLocalizableStringsDirOption<XCUITestOptions>, SupportsLanguageOption<XCUITestOptions>, SupportsLocaleOption<XCUITestOptions>, // App Options: https://github.com/appium/appium-xcuitest-driver#app SupportsAppOption<XCUITestOptions>, SupportsBundleIdOption<XCUITestOptions>, SupportsOtherAppsOption<XCUITestOptions>, SupportsAppPushTimeoutOption<XCUITestOptions>, SupportsAppInstallStrategyOption<XCUITestOptions>, // WebDriverAgent options: https://github.com/appium/appium-xcuitest-driver#webdriveragent SupportsXcodeCertificateOptions<XCUITestOptions>, SupportsKeychainOptions<XCUITestOptions>, SupportsUpdatedWdaBundleIdOption<XCUITestOptions>, SupportsDerivedDataPathOption<XCUITestOptions>, SupportsWebDriverAgentUrlOption<XCUITestOptions>, SupportsUseNewWdaOption<XCUITestOptions>, SupportsWdaLaunchTimeoutOption<XCUITestOptions>, SupportsWdaConnectionTimeoutOption<XCUITestOptions>, SupportsWdaStartupRetriesOption<XCUITestOptions>, SupportsWdaStartupRetryIntervalOption<XCUITestOptions>, SupportsWdaLocalPortOption<XCUITestOptions>, SupportsWdaBaseUrlOption<XCUITestOptions>, SupportsShowXcodeLogOption<XCUITestOptions>, SupportsUsePrebuiltWdaOption<XCUITestOptions>, SupportsShouldUseSingletonTestManagerOption<XCUITestOptions>, SupportsWaitForIdleTimeoutOption<XCUITestOptions>, SupportsUseXctestrunFileOption<XCUITestOptions>, SupportsUseSimpleBuildTestOption<XCUITestOptions>, SupportsWdaEventloopIdleDelayOption<XCUITestOptions>, SupportsProcessArgumentsOption<XCUITestOptions>, SupportsAllowProvisioningDeviceRegistrationOption<XCUITestOptions>, SupportsResultBundlePathOption<XCUITestOptions>, SupportsMaxTypingFrequencyOption<XCUITestOptions>, SupportsSimpleIsVisibleCheckOption<XCUITestOptions>, SupportsWaitForQuiescenceOption<XCUITestOptions>, SupportsMjpegServerPortOption<XCUITestOptions>, SupportsScreenshotQualityOption<XCUITestOptions>, SupportsAutoAcceptAlertsOption<XCUITestOptions>, SupportsAutoDismissAlertsOption<XCUITestOptions>, SupportsDisableAutomaticScreenshotsOption<XCUITestOptions>, SupportsShouldTerminateAppOption<XCUITestOptions>, SupportsForceAppLaunchOption<XCUITestOptions>, SupportsUseNativeCachingStrategyOption<XCUITestOptions>, // Simulator options: https://github.com/appium/appium-xcuitest-driver#simulator SupportsOrientationOption<XCUITestOptions>, SupportsScaleFactorOption<XCUITestOptions>, SupportsConnectHardwareKeyboardOption<XCUITestOptions>, SupportsForceSimulatorSoftwareKeyboardPresenceOption<XCUITestOptions>, SupportsCalendarAccessAuthorizedOption<XCUITestOptions>, SupportsCalendarFormatOption<XCUITestOptions>, SupportsIsHeadlessOption<XCUITestOptions>, SupportsSimulatorWindowCenterOption<XCUITestOptions>, SupportsSimulatorStartupTimeoutOption<XCUITestOptions>, SupportsSimulatorTracePointerOption<XCUITestOptions>, SupportsShutdownOtherSimulatorsOption<XCUITestOptions>, SupportsEnforceFreshSimulatorCreationOption<XCUITestOptions>, SupportsKeepKeyChainsOption<XCUITestOptions>, SupportsKeychainsExcludePatternsOption<XCUITestOptions>, SupportsReduceMotionOption<XCUITestOptions>, SupportsPermissionsOption<XCUITestOptions>, SupportsIosSimulatorLogsPredicateOption<XCUITestOptions>, SupportsSimulatorPasteboardAutomaticSyncOption<XCUITestOptions>, SupportsSimulatorDevicesSetPathOption<XCUITestOptions>, SupportsCustomSslCertOption<XCUITestOptions>, // Web context options: https://github.com/appium/appium-xcuitest-driver#web-context SupportsAutoWebViewOption<XCUITestOptions>, SupportsAbsoluteWebLocationsOption<XCUITestOptions>, SupportsSafariGarbageCollectOption<XCUITestOptions>, SupportsIncludeSafariInWebviewsOption<XCUITestOptions>, SupportsSafariLogAllCommunicationOption<XCUITestOptions>, SupportsSafariLogAllCommunicationHexDumpOption<XCUITestOptions>, SupportsSafariSocketChunkSizeOption<XCUITestOptions>, SupportsSafariWebInspectorMaxFrameLengthOption<XCUITestOptions>, SupportsAdditionalWebviewBundleIdsOption<XCUITestOptions>, SupportsWebviewConnectTimeoutOption<XCUITestOptions>, SupportsSafariIgnoreWebHostnamesOption<XCUITestOptions>, SupportsNativeWebTapOption<XCUITestOptions>, SupportsNativeWebTapStrictOption<XCUITestOptions>, SupportsSafariInitialUrlOption<XCUITestOptions>, SupportsSafariAllowPopupsOption<XCUITestOptions>, SupportsSafariIgnoreFraudWarningOption<XCUITestOptions>, SupportsSafariOpenLinksInBackgroundOption<XCUITestOptions>, SupportsWebviewConnectRetriesOption<XCUITestOptions>, SupportsWebkitResponseTimeoutOption<XCUITestOptions>, SupportsEnableAsyncExecuteFromHttpsOption<XCUITestOptions>, SupportsFullContextListOption<XCUITestOptions>, SupportsEnablePerformanceLoggingOption<XCUITestOptions>, // Other options: https://github.com/appium/appium-xcuitest-driver#other SupportsResetOnSessionStartOnlyOption<XCUITestOptions>, SupportsCommandTimeoutsOption<XCUITestOptions>, SupportsUseJsonSourceOption<XCUITestOptions>, SupportsSkipLogCaptureOption<XCUITestOptions>, SupportsLaunchWithIdbOption<XCUITestOptions>, SupportsShowIosLogOption<XCUITestOptions>, SupportsClearSystemFilesOption<XCUITestOptions> { public XCUITestOptions() { setCommonOptions(); } public XCUITestOptions(Capabilities source) { super(source); setCommonOptions(); } public XCUITestOptions(Map<String, ?> source) { super(source); setCommonOptions(); } private void setCommonOptions() { setPlatformName(MobilePlatform.IOS); setAutomationName(AutomationName.IOS_XCUI_TEST); } }
package com.intellij.tasks.redmine; import com.google.gson.Gson; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.text.StringUtil; import com.intellij.tasks.Task; import com.intellij.tasks.impl.RequestFailedException; import com.intellij.tasks.impl.gson.TaskGsonUtil; import com.intellij.tasks.impl.httpclient.NewBaseRepositoryImpl; import com.intellij.tasks.redmine.model.RedmineIssue; import com.intellij.tasks.redmine.model.RedmineProject; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.xmlb.annotations.Tag; import com.intellij.util.xmlb.annotations.Transient; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.utils.URIBuilder; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.regex.Pattern; import static com.intellij.tasks.impl.httpclient.TaskResponseUtil.GsonSingleObjectDeserializer; import static com.intellij.tasks.redmine.model.RedmineResponseWrapper.*; /** * @author Mikhail Golubev * @author Dennis.Ushakov */ @Tag("Redmine") public class RedmineRepository extends NewBaseRepositoryImpl { private static final Gson GSON = TaskGsonUtil.createDefaultBuilder().create(); private static final Pattern ID_PATTERN = Pattern.compile("\\d+"); private static final Logger LOG = Logger.getInstance(RedmineRepository.class); public static final RedmineProject UNSPECIFIED_PROJECT = createUnspecifiedProject(); @NotNull private static RedmineProject createUnspecifiedProject() { final RedmineProject unspecified = new RedmineProject() { @NotNull @Override public String getName() { return "-- from all projects --"; } @NotNull @Override public String getIdentifier() { return getName(); } }; unspecified.setId(-1); return unspecified; } private String myAPIKey = ""; private RedmineProject myCurrentProject; private boolean myAssignedToMe = true; private List<RedmineProject> myProjects = null; /** * Serialization constructor */ @SuppressWarnings({"UnusedDeclaration"}) public RedmineRepository() { // empty } /** * Normal instantiation constructor */ public RedmineRepository(RedmineRepositoryType type) { super(type); setUseHttpAuthentication(true); } /** * Cloning constructor */ public RedmineRepository(RedmineRepository other) { super(other); setAPIKey(other.myAPIKey); setCurrentProject(other.getCurrentProject()); setAssignedToMe(other.isAssignedToMe()); } @Override public boolean equals(Object o) { if (!super.equals(o)) return false; if (!(o instanceof RedmineRepository)) return false; RedmineRepository that = (RedmineRepository)o; if (!Comparing.equal(getAPIKey(), that.getAPIKey())) return false; if (!Comparing.equal(getCurrentProject(), that.getCurrentProject())) return false; if (isAssignedToMe() != that.isAssignedToMe()) return false; return true; } @NotNull @Override public RedmineRepository clone() { return new RedmineRepository(this); } @Nullable @Override public CancellableConnection createCancellableConnection() { return new NewBaseRepositoryImpl.HttpTestConnection(new HttpGet()) { @Override protected void test() throws Exception { // Strangely, Redmine doesn't return 401 or 403 error codes, if client sent wrong credentials, and instead // merely returns empty array of issues with status code of 200. This means that we should attempt to fetch // something more specific than issues to test proper configuration, e.g. current user information at // /users/current.json. Unfortunately this endpoint may be unavailable on some old servers (see IDEA-122845) // and in this case we have to come back to requesting issues in this case to test anything at all. URIBuilder uriBuilder = createUriBuilderWithApiKey("users", "current.json"); myCurrentRequest.setURI(uriBuilder.build()); HttpClient client = getHttpClient(); HttpResponse httpResponse = client.execute(myCurrentRequest); StatusLine statusLine = httpResponse.getStatusLine(); if (statusLine != null && statusLine.getStatusCode() == HttpStatus.SC_NOT_FOUND) { // Check that projects can be downloaded via given URL and the latter is not project-specific myCurrentRequest = new HttpGet(getProjectsUrl(0, 1)); statusLine = client.execute(myCurrentRequest).getStatusLine(); if (statusLine != null && statusLine.getStatusCode() == HttpStatus.SC_OK) { myCurrentRequest = new HttpGet(getIssuesUrl(0, 1, true)); statusLine = client.execute(myCurrentRequest).getStatusLine(); } } if (statusLine != null && statusLine.getStatusCode() != HttpStatus.SC_OK) { throw RequestFailedException.forStatusCode(statusLine.getStatusCode(), statusLine.getReasonPhrase()); } } }; } @Override public Task[] getIssues(@Nullable String query, int offset, int limit, boolean withClosed) throws Exception { List<RedmineIssue> issues = fetchIssues(query, offset, limit, withClosed); List<Task> result = ContainerUtil.map(issues, issue -> new RedmineTask(this, issue)); if (query != null && ID_PATTERN.matcher(query).matches()) { LOG.debug("Query '" + query + "' looks like an issue ID. Requesting it explicitly from the server " + this); final Task found = findTask(query); if (found != null) { result = ContainerUtil.append(result, found); } } return result.toArray(Task.EMPTY_ARRAY); } public List<RedmineIssue> fetchIssues(String query, int offset, int limit, boolean withClosed) throws Exception { ensureProjectsDiscovered(); // Legacy API, can't find proper documentation //if (StringUtil.isNotEmpty(query)) { // builder.addParameter("fields[]", "subject").addParameter("operators[subject]", "~").addParameter("values[subject][]", query); //} HttpClient client = getHttpClient(); HttpGet method = new HttpGet(getIssuesUrl(offset, limit, withClosed)); IssuesWrapper wrapper = client.execute(method, new GsonSingleObjectDeserializer<>(GSON, IssuesWrapper.class)); return wrapper == null ? Collections.emptyList() : wrapper.getIssues(); } private URI getIssuesUrl(int offset, int limit, boolean withClosed) throws URISyntaxException { URIBuilder builder = createUriBuilderWithApiKey("issues.json") .addParameter("offset", String.valueOf(offset)) .addParameter("limit", String.valueOf(limit)) .addParameter("sort", "updated_on:desc") .addParameter("status_id", withClosed ? "*" : "open"); if (myAssignedToMe) { builder.addParameter("assigned_to_id", "me"); } // If project was not chosen, all available issues still fetched. Such behavior may seems strange to user. if (myCurrentProject != null && myCurrentProject != UNSPECIFIED_PROJECT) { builder.addParameter("project_id", String.valueOf(myCurrentProject.getId())); } return builder.build(); } public List<RedmineProject> fetchProjects() throws Exception { HttpClient client = getHttpClient(); // Download projects with pagination (IDEA-125056, IDEA-125157) List<RedmineProject> allProjects = new ArrayList<>(); int offset = 0; ProjectsWrapper wrapper; do { HttpGet method = new HttpGet(getProjectsUrl(offset, 50)); wrapper = client.execute(method, new GsonSingleObjectDeserializer<>(GSON, ProjectsWrapper.class)); offset += wrapper.getProjects().size(); allProjects.addAll(wrapper.getProjects()); } while (wrapper.getTotalCount() > allProjects.size() || wrapper.getProjects().isEmpty()); myProjects = allProjects; return Collections.unmodifiableList(myProjects); } @NotNull private URI getProjectsUrl(int offset, int limit) throws URISyntaxException { URIBuilder builder = createUriBuilderWithApiKey("projects.json"); builder.addParameter("offset", String.valueOf(offset)); builder.addParameter("limit", String.valueOf(limit)); return builder.build(); } @Nullable @Override public Task findTask(@NotNull String id) throws Exception { ensureProjectsDiscovered(); HttpGet method = new HttpGet(createUriBuilderWithApiKey("issues", id + ".json").build()); IssueWrapper wrapper = getHttpClient().execute(method, new GsonSingleObjectDeserializer<>(GSON, IssueWrapper.class, true)); if (wrapper == null) { return null; } return new RedmineTask(this, wrapper.getIssue()); } public String getAPIKey() { return myAPIKey; } public void setAPIKey(String APIKey) { myAPIKey = APIKey; } public boolean isAssignedToMe() { return myAssignedToMe; } public void setAssignedToMe(boolean assignedToMe) { this.myAssignedToMe = assignedToMe; } private boolean isUseApiKeyAuthentication() { return !isUseHttpAuthentication() && StringUtil.isNotEmpty(myAPIKey); } @NotNull private URIBuilder createUriBuilderWithApiKey(Object @NotNull ... pathParts) throws URISyntaxException { final URIBuilder builder = new URIBuilder(getRestApiUrl(pathParts)); if (isUseApiKeyAuthentication()) { builder.addParameter("key", myAPIKey); } return builder; } @Override public String getPresentableName() { String name = super.getPresentableName(); if (myCurrentProject != null && myCurrentProject != UNSPECIFIED_PROJECT) { name += "/projects/" + StringUtil.notNullize(myCurrentProject.getIdentifier(), String.valueOf(myCurrentProject.getId())); } return name; } @Override public boolean isConfigured() { if (!super.isConfigured()) return false; if (isUseHttpAuthentication()) { return StringUtil.isNotEmpty(myPassword) && StringUtil.isNotEmpty(myUsername); } return StringUtil.isNotEmpty(myAPIKey); } @Nullable @Override public String extractId(@NotNull String taskName) { return ID_PATTERN.matcher(taskName).matches() ? taskName : null; } @Override protected int getFeatures() { return super.getFeatures() & ~NATIVE_SEARCH | BASIC_HTTP_AUTHORIZATION; } @Nullable public RedmineProject getCurrentProject() { return myCurrentProject; } public void setCurrentProject(@Nullable RedmineProject project) { myCurrentProject = project != null && project.getId() == -1 ? UNSPECIFIED_PROJECT : project; } @NotNull public List<RedmineProject> getProjects() { try { ensureProjectsDiscovered(); } catch (Exception ignored) { return Collections.emptyList(); } return Collections.unmodifiableList(myProjects); } private void ensureProjectsDiscovered() throws Exception { if (myProjects == null) { fetchProjects(); } } @TestOnly @Transient public void setProjects(@NotNull List<RedmineProject> projects) { myProjects = projects; } }
/* * Copyright 2007-2008 Dave Griffith * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.groovy.codeInspection.utils; import com.intellij.psi.PsiElement; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.lang.psi.GrControlFlowOwner; import org.jetbrains.plugins.groovy.lang.psi.GroovyFile; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement; import org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor; import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrCondition; import org.jetbrains.plugins.groovy.lang.psi.api.statements.*; import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock; import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrCodeBlock; import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrOpenBlock; import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrBreakStatement; import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrContinueStatement; import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrReturnStatement; import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrThrowStatement; import org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrCaseSection; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod; import org.jetbrains.plugins.groovy.lang.psi.controlFlow.Instruction; import org.jetbrains.plugins.groovy.lang.psi.controlFlow.impl.ControlFlowBuilder; import org.jetbrains.plugins.groovy.lang.psi.controlFlow.impl.IfEndInstruction; import org.jetbrains.plugins.groovy.lang.psi.controlFlow.impl.MaybeReturnInstruction; import java.util.ArrayList; import java.util.Collections; import java.util.List; @SuppressWarnings({"OverlyComplexClass"}) public class ControlFlowUtils { private ControlFlowUtils() { super(); } public static boolean statementMayCompleteNormally( @Nullable GrStatement statement) { if (statement == null) { return true; } if (statement instanceof GrBreakStatement || statement instanceof GrContinueStatement || statement instanceof GrReturnStatement || statement instanceof GrThrowStatement) { return false; } else if (statement instanceof GrForStatement) { return forStatementMayReturnNormally((GrForStatement) statement); } else if (statement instanceof GrWhileStatement) { return whileStatementMayReturnNormally( (GrWhileStatement) statement); } else if (statement instanceof GrBlockStatement) { return blockMayCompleteNormally((GrBlockStatement) statement); } else if (statement instanceof GrSynchronizedStatement) { final GrSynchronizedStatement syncStatement = (GrSynchronizedStatement) statement; return openBlockMayCompleteNormally(syncStatement.getBody()); } else if (statement instanceof GrLabeledStatement) { return labeledStatementMayCompleteNormally( (GrLabeledStatement) statement); } else if (statement instanceof GrIfStatement) { return ifStatementMayReturnNormally((GrIfStatement) statement); } else if (statement instanceof GrTryCatchStatement) { return tryStatementMayReturnNormally((GrTryCatchStatement) statement); } else if (statement instanceof GrSwitchStatement) { return switchStatementMayReturnNormally( (GrSwitchStatement) statement); } else // other statement type { return true; } } private static boolean whileStatementMayReturnNormally( @NotNull GrWhileStatement loopStatement) { final GrCondition test = loopStatement.getCondition(); return !BoolUtils.isTrue(test) || statementIsBreakTarget(loopStatement); } private static boolean forStatementMayReturnNormally( @NotNull GrForStatement loopStatement) { return true; } private static boolean switchStatementMayReturnNormally( @NotNull GrSwitchStatement switchStatement) { if (statementIsBreakTarget(switchStatement)) { return true; } final GrCaseSection[] caseClauses = switchStatement.getCaseSections(); if (caseClauses.length == 0) { return true; } boolean hasDefaultCase = false; for (GrCaseSection clause : caseClauses) { if (clause.getCaseLabel().getText().equals("default")) { hasDefaultCase = true; } } if (!hasDefaultCase) { return true; } final GrCaseSection lastClause = caseClauses[caseClauses.length - 1]; final GrStatement[] statements = lastClause.getStatements(); if (statements.length == 0) { return true; } return statementMayCompleteNormally(statements[statements.length - 1]); } private static boolean tryStatementMayReturnNormally( @NotNull GrTryCatchStatement tryStatement) { final GrFinallyClause finallyBlock = tryStatement.getFinallyClause(); if (finallyBlock != null) { if (!openBlockMayCompleteNormally(finallyBlock.getBody())) { return false; } } final GrOpenBlock tryBlock = tryStatement.getTryBlock(); if (openBlockMayCompleteNormally(tryBlock)) { return true; } final GrCatchClause[] catchClauses = tryStatement.getCatchClauses(); if (catchClauses != null) { for (GrCatchClause catchClause : catchClauses) { if (openBlockMayCompleteNormally(catchClause.getBody())) { return true; } } } return false; } private static boolean ifStatementMayReturnNormally( @NotNull GrIfStatement ifStatement) { final GrStatement thenBranch = ifStatement.getThenBranch(); if (statementMayCompleteNormally(thenBranch)) { return true; } final GrStatement elseBranch = ifStatement.getElseBranch(); return elseBranch == null || statementMayCompleteNormally(elseBranch); } private static boolean labeledStatementMayCompleteNormally( @NotNull GrLabeledStatement labeledStatement) { final GrStatement statement = labeledStatement.getStatement(); return statementMayCompleteNormally(statement) || statementIsBreakTarget(statement); } public static boolean blockMayCompleteNormally( @Nullable GrBlockStatement block) { if (block == null) { return true; } final GrStatement[] statements = block.getBlock().getStatements(); for (final GrStatement statement : statements) { if (!statementMayCompleteNormally(statement)) { return false; } } return true; } public static boolean openBlockMayCompleteNormally( @Nullable GrOpenBlock block) { if (block == null) { return true; } final GrStatement[] statements = block.getStatements(); for (final GrStatement statement : statements) { if (!statementMayCompleteNormally(statement)) { return false; } } return true; } private static boolean statementIsBreakTarget( @NotNull GrStatement statement) { final BreakFinder breakFinder = new BreakFinder(statement); statement.accept(breakFinder); return breakFinder.breakFound(); } public static boolean statementContainsReturn( @NotNull GrStatement statement) { final ReturnFinder returnFinder = new ReturnFinder(); statement.accept(returnFinder); return returnFinder.returnFound(); } public static boolean statementIsContinueTarget( @NotNull GrStatement statement) { final ContinueFinder continueFinder = new ContinueFinder(statement); statement.accept(continueFinder); return continueFinder.continueFound(); } public static boolean isInLoop(@NotNull GroovyPsiElement element) { return isInForStatementBody(element) || isInWhileStatementBody(element); } public static boolean isInFinallyBlock(@NotNull GroovyPsiElement element) { final GrFinallyClause containingClause = PsiTreeUtil.getParentOfType(element, GrFinallyClause.class); if (containingClause == null) { return false; } final GrOpenBlock body = containingClause.getBody(); return PsiTreeUtil.isAncestor(body, element, true); } public static boolean isInCatchBlock(@NotNull GroovyPsiElement element) { final GrCatchClause containingClause = PsiTreeUtil.getParentOfType(element, GrCatchClause.class); if (containingClause == null) { return false; } final GrOpenBlock body = containingClause.getBody(); return PsiTreeUtil.isAncestor(body, element, true); } private static boolean isInWhileStatementBody(@NotNull GroovyPsiElement element) { final GrWhileStatement whileStatement = PsiTreeUtil.getParentOfType(element, GrWhileStatement.class); if (whileStatement == null) { return false; } final GrStatement body = whileStatement.getBody(); return PsiTreeUtil.isAncestor(body, element, true); } private static boolean isInForStatementBody(@NotNull GroovyPsiElement element) { final GrForStatement forStatement = PsiTreeUtil.getParentOfType(element, GrForStatement.class); if (forStatement == null) { return false; } final GrStatement body = forStatement.getBody(); return PsiTreeUtil.isAncestor(body, element, true); } public static GrStatement stripBraces(@NotNull GrStatement branch) { if (branch instanceof GrBlockStatement) { final GrBlockStatement block = (GrBlockStatement) branch; final GrStatement[] statements = block.getBlock().getStatements(); if (statements.length == 1) { return statements[0]; } else { return block; } } else { return branch; } } public static boolean statementCompletesWithStatement( @NotNull GrStatement containingStatement, @NotNull GrStatement statement) { GroovyPsiElement statementToCheck = statement; while (true) { if (statementToCheck.equals(containingStatement)) { return true; } final GroovyPsiElement container = getContainingStatement(statementToCheck); if (container == null) { return false; } if (container instanceof GrBlockStatement) { if (!statementIsLastInBlock((GrBlockStatement) container, (GrStatement) statementToCheck)) { return false; } } if (isLoop(container)) { return false; } statementToCheck = container; } } public static boolean blockCompletesWithStatement( @NotNull GrBlockStatement body, @NotNull GrStatement statement) { GrStatement statementToCheck = statement; while (true) { if (statementToCheck == null) { return false; } final GrStatement container = getContainingStatement(statementToCheck); if (container == null) { return false; } if (isLoop(container)) { return false; } if (container instanceof GrBlockStatement) { if (!statementIsLastInBlock((GrBlockStatement) container, statementToCheck)) { return false; } if (container.equals(body)) { return true; } statementToCheck = PsiTreeUtil.getParentOfType(container, GrStatement.class); } else { statementToCheck = container; } } } public static boolean openBlockCompletesWithStatement(@NotNull GrCodeBlock body, @NotNull GrStatement statement) { GroovyPsiElement elementToCheck = statement; while (true) { if (elementToCheck == null) return false; final GroovyPsiElement container = getContainingStatementOrBlock(elementToCheck); if (container == null) return false; if (isLoop(container)) return false; if (container instanceof GrCodeBlock) { if (elementToCheck instanceof GrStatement) { final GrCodeBlock codeBlock = (GrCodeBlock) container; if (!statementIsLastInCodeBlock(codeBlock, (GrStatement) elementToCheck)) { return false; } } if (container instanceof GrOpenBlock || container instanceof GrClosableBlock) { if (container.equals(body)) { return true; } elementToCheck = PsiTreeUtil.getParentOfType(container, GrStatement.class); } else { elementToCheck = container; } } else { elementToCheck = container; } } } public static boolean closureCompletesWithStatement( @NotNull GrClosableBlock body, @NotNull GrStatement statement) { GroovyPsiElement statementToCheck = statement; while (true) { if (!(statementToCheck instanceof GrExpression || statementToCheck instanceof GrReturnStatement)) { return false; } final GroovyPsiElement container = getContainingStatementOrBlock(statementToCheck); if (container == null) { return false; } if (isLoop(container)) { return false; } if (container instanceof GrCodeBlock) { if (!statementIsLastInCodeBlock((GrCodeBlock)container, (GrStatement)statementToCheck)) { return false; } if (container.equals(body)) { return true; } statementToCheck = PsiTreeUtil.getParentOfType(container, GrStatement.class); } else { statementToCheck = container; } } } private static boolean isLoop(@NotNull GroovyPsiElement element) { return element instanceof GrLoopStatement; } @Nullable private static GrStatement getContainingStatement( @NotNull GroovyPsiElement statement) { return PsiTreeUtil.getParentOfType(statement, GrStatement.class); } @Nullable private static GroovyPsiElement getContainingStatementOrBlock( @NotNull GroovyPsiElement statement) { return PsiTreeUtil.getParentOfType(statement, GrStatement.class, GrCodeBlock.class); } private static boolean statementIsLastInBlock(@NotNull GrBlockStatement block, @NotNull GrStatement statement) { final GrStatement[] statements = block.getBlock().getStatements(); for (int i = statements.length - 1; i >= 0; i--) { final GrStatement childStatement = statements[i]; if (statement.equals(childStatement)) { return true; } if (!(childStatement instanceof GrReturnStatement)) { return false; } } return false; } private static boolean statementIsLastInCodeBlock(@NotNull GrCodeBlock block, @NotNull GrStatement statement) { final GrStatement[] statements = block.getStatements(); for (int i = statements.length - 1; i >= 0; i--) { final GrStatement childStatement = statements[i]; if (statement.equals(childStatement)) { return true; } if (!(childStatement instanceof GrReturnStatement)) { return false; } } return false; } public static List<GrStatement> collectReturns(@Nullable PsiElement element) { return collectReturns(element, element instanceof GrCodeBlock); } public static List<GrStatement> collectReturns(@Nullable PsiElement element, final boolean allExitPoints) { if (element == null) return Collections.emptyList(); final Instruction[] flow; if (element instanceof GrCodeBlock) { flow = ((GrCodeBlock)element).getControlFlow(); } else { flow = new ControlFlowBuilder(element.getProject()).buildControlFlow((GroovyPsiElement)element); } boolean[] visited = new boolean[flow.length]; final List<GrStatement> res = new ArrayList<GrStatement>(); visitAllExitPointsInner(flow[flow.length - 1], flow[0], visited, new ExitPointVisitor() { @Override public boolean visitExitPoint(Instruction instruction, @Nullable GrExpression returnValue) { final PsiElement element = instruction.getElement(); if (element instanceof GrReturnStatement || (allExitPoints && instruction instanceof MaybeReturnInstruction)) { res.add((GrStatement)element); } return true; } }); return res; } @Nullable public static GrExpression extractReturnExpression(GrStatement returnStatement) { if (returnStatement instanceof GrReturnStatement) return ((GrReturnStatement)returnStatement).getReturnValue(); if (returnStatement instanceof GrExpression) return (GrExpression)returnStatement; return null; } private static class ReturnFinder extends GroovyRecursiveElementVisitor { private boolean m_found = false; public boolean returnFound() { return m_found; } public void visitReturnStatement( @NotNull GrReturnStatement returnStatement) { if (m_found) { return; } super.visitReturnStatement(returnStatement); m_found = true; } } private static class BreakFinder extends GroovyRecursiveElementVisitor { private boolean m_found = false; private final GrStatement m_target; private BreakFinder(@NotNull GrStatement target) { super(); m_target = target; } public boolean breakFound() { return m_found; } public void visitBreakStatement( @NotNull GrBreakStatement breakStatement) { if (m_found) { return; } super.visitBreakStatement(breakStatement); final GrStatement exitedStatement = breakStatement.findTargetStatement(); if (exitedStatement == null) { return; } if (PsiTreeUtil.isAncestor(exitedStatement, m_target, false)) { m_found = true; } } } private static class ContinueFinder extends GroovyRecursiveElementVisitor { private boolean m_found = false; private final GrStatement m_target; private ContinueFinder(@NotNull GrStatement target) { super(); m_target = target; } public boolean continueFound() { return m_found; } public void visitContinueStatement( @NotNull GrContinueStatement continueStatement) { if (m_found) { return; } super.visitContinueStatement(continueStatement); final GrStatement exitedStatement = continueStatement.findTargetStatement(); if (exitedStatement == null) { return; } if (PsiTreeUtil.isAncestor(exitedStatement, m_target, false)) { m_found = true; } } } public static boolean isInExitStatement(@NotNull GrExpression expression) { return isInReturnStatementArgument(expression) || isInThrowStatementArgument(expression); } private static boolean isInReturnStatementArgument( @NotNull GrExpression expression) { final GrReturnStatement returnStatement = PsiTreeUtil .getParentOfType(expression, GrReturnStatement.class); return returnStatement != null; } private static boolean isInThrowStatementArgument( @NotNull GrExpression expression) { final GrThrowStatement throwStatement = PsiTreeUtil .getParentOfType(expression, GrThrowStatement.class); return throwStatement != null; } public interface ExitPointVisitor { boolean visitExitPoint(Instruction instruction, @Nullable GrExpression returnValue); } public static void visitAllExitPoints(@Nullable GrCodeBlock block, ExitPointVisitor visitor) { if (block == null) return; final Instruction[] flow = block.getControlFlow(); boolean[] visited = new boolean[flow.length]; visitAllExitPointsInner(flow[flow.length - 1], flow[0], visited, visitor); } private static boolean visitAllExitPointsInner(Instruction last, Instruction first, boolean[] visited, ExitPointVisitor visitor) { if (first == last) return true; if (last instanceof MaybeReturnInstruction) { return visitor.visitExitPoint(last, (GrExpression)last.getElement()); } else if (last instanceof IfEndInstruction) { visited[last.num()] = true; for (Instruction instruction : last.allPred()) { if (!visitAllExitPointsInner(instruction, first, visited, visitor)) return false; } return true; } PsiElement element = last.getElement(); if (element != null) { if (element instanceof GrReturnStatement) { element = ((GrReturnStatement)element).getReturnValue(); } return visitor.visitExitPoint(last, element instanceof GrExpression ? (GrExpression)element : null); } visited[last.num()] = true; for (Instruction pred : last.allPred()) { if (!visited[pred.num()]) { if (!visitAllExitPointsInner(pred, first, visited, visitor)) return false; } } return true; } @Nullable public static GrControlFlowOwner findControlFlowOwner(PsiElement place) { while (place.getParent() != null) { place = place.getParent(); if (place instanceof GrClosableBlock) return (GrClosableBlock)place; if (place instanceof GrMethod) return ((GrMethod)place).getBlock(); if (place instanceof GroovyFile) return (GroovyFile)place; } return null; } }
package me.moodcat.backend.rooms; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.Collections; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; import java.util.stream.Stream; import me.moodcat.api.ProfanityChecker; import me.moodcat.api.models.ChatMessageModel; import me.moodcat.backend.BackendTest; import me.moodcat.backend.UnitOfWorkSchedulingService; import me.moodcat.backend.Vote; import me.moodcat.database.controllers.RoomDAO; import me.moodcat.database.controllers.SongDAO; import me.moodcat.database.controllers.UserDAO; import me.moodcat.database.entities.Room; import me.moodcat.database.entities.Song; import me.moodcat.database.entities.User; import me.moodcat.util.JukitoRunnerSupportingMockAnnotations; import me.moodcat.util.MockedUnitOfWorkSchedulingService; import org.hamcrest.Matchers; import org.jukito.UseModules; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.inject.AbstractModule; import com.google.inject.Inject; @RunWith(JukitoRunnerSupportingMockAnnotations.class) @UseModules(RoomInstanceTest.RoomInstanceTestModule.class) public class RoomInstanceTest extends BackendTest { private static UserDAO userDAO = Mockito.mock(UserDAO.class); private static RoomDAO roomDAO = Mockito.mock(RoomDAO.class); private static SongDAO songDAO = Mockito.mock(SongDAO.class); public static class RoomInstanceTestModule extends AbstractModule { @Override protected void configure() { install(new RoomBackendModule()); bind(SongDAO.class).toInstance(songDAO); bind(RoomDAO.class).toInstance(roomDAO); bind(UserDAO.class).toInstance(userDAO); bind(ProfanityChecker.class).toInstance(Mockito.mock(ProfanityChecker.class)); bind(UnitOfWorkSchedulingService.class).to(MockedUnitOfWorkSchedulingService.class); } } private RoomInstance instance; @Inject private RoomInstanceFactory roomInstanceFactory; @Inject private MockedUnitOfWorkSchedulingService unitOfWorkSchedulingService; private Song song; private Room room; private User user; @Before public void setUp() { song = createSong(1); room = createRoom(song); user = createUser(); when(roomDAO.findById(room.getId())).thenReturn(room); when(userDAO.findById(user.getId())).thenReturn(user); instance = roomInstanceFactory.create(room); } @After public void tearDown() { unitOfWorkSchedulingService.shutdownNow(); } @Test public void whenTooManyMessagesRemoveOneFromList() { for (int i = 0; i < RoomInstance.MAXIMAL_NUMBER_OF_CHAT_MESSAGES + 1; i++) { ChatMessageModel model = new ChatMessageModel(); model.setMessage(String.valueOf(i)); instance.sendMessage(model, createUser()); } assertThat(instance.getMessages(), Matchers.iterableWithSize(RoomInstance.MAXIMAL_NUMBER_OF_CHAT_MESSAGES)); } @Test(expected = IllegalArgumentException.class) public void whenOneUserSendsMessagesTooFastThrowsException() { ChatMessageModel model = new ChatMessageModel(); model.setMessage("Spam"); User user = mock(User.class); when(user.getId()).thenReturn(1337); for (int i = 0; i < 6; i++) { instance.sendMessage(model, user); } } @Test public void testReplayHistoryOnNoResults() { when(songDAO.findForDistance(room.getVaVector(), RoomInstance.NUMBER_OF_SELECTED_SONGS)) .thenReturn(Collections.emptyList()); assertThat(room.getPlayHistory(), Matchers.empty()); assertThat(room.getPlayQueue(), Matchers.empty()); assertEquals(song, room.getCurrentSong()); instance.playNext(); assertThat(room.getPlayHistory(), Matchers.empty()); assertThat(room.getPlayQueue(), Matchers.empty()); assertEquals(song, room.getCurrentSong()); } @Test public void testPlayNextSongFromResults() throws ExecutionException, InterruptedException { Song newSong = createSong(); stubFindForDistance(room, newSong); assertThat(room.getPlayHistory(), Matchers.empty()); assertThat(room.getPlayQueue(), Matchers.empty()); assertEquals(song, room.getCurrentSong()); instance.playNext().get(); instance.merge().get(); assertThat(room.getPlayHistory(), Matchers.contains(song)); assertThat(room.getPlayQueue(), Matchers.empty()); assertEquals(newSong, room.getCurrentSong()); } @Test public void testScheduleResults() throws ExecutionException, InterruptedException { Song newSong = createSong(2); Song newOtherSong = createSong(3); stubFindForDistance(room, newSong, newOtherSong); assertThat(room.getPlayHistory(), Matchers.empty()); assertThat(room.getPlayQueue(), Matchers.empty()); assertEquals(song, room.getCurrentSong()); instance.playNext().get(); instance.merge().get(); assertThat(room.getPlayHistory(), Matchers.contains(song)); assertThat(room.getPlayQueue(), Matchers.contains(newOtherSong)); assertEquals(newSong, room.getCurrentSong()); } @Test public void testLimitHistory() throws ExecutionException, InterruptedException { List<Song> history = ImmutableList.copyOf(Stream.generate(BackendTest::createSong) .limit(RoomInstance.NUMBER_OF_SELECTED_SONGS) .iterator()); room.setPlayHistory(history); Song newSong = createSong(); stubFindForDistance(room, newSong); assertThat(room.getPlayQueue(), Matchers.empty()); assertEquals(song, room.getCurrentSong()); instance.playNext().get(); instance.merge().get(); List<Song> expectedHistory = Stream .concat(history.stream().skip(1), Stream.of(song)) .collect(Collectors.toList()); assertEquals(expectedHistory, room.getPlayHistory()); assertThat(room.getPlayQueue(), Matchers.empty()); assertEquals(newSong, room.getCurrentSong()); } private void stubFindForDistance(Room room, Song... songs) { when(songDAO.findNewSongsFor(room)).thenReturn(Lists.newArrayList(songs)); } @Test public void testVote() { User user = Mockito.mock(User.class); instance.addVote(user, Vote.LIKE); } @Test(expected = IllegalArgumentException.class) public void testDuplicateVote() { User user = Mockito.mock(User.class); instance.addVote(user, Vote.LIKE); instance.addVote(user, Vote.DISLIKE); } }
package com.nvapp.mupdf; import java.io.File; import java.io.FileFilter; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import com.nvapp.comic.R; import android.app.AlertDialog; import android.app.ListActivity; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.res.Resources; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.FileObserver; import android.os.Handler; import android.view.View; import android.widget.ListView; enum Purpose { PickPDF, PickKeyFile } public class ChoosePDFActivity extends ListActivity { static public final String PICK_KEY_FILE = "com.artifex.mupdfdemo.PICK_KEY_FILE"; static private File mDirectory; static private Map<String, Integer> mPositions = new HashMap<String, Integer>(); private File mParent; private File [] mDirs; private File [] mFiles; private Handler mHandler; private Runnable mUpdateFiles; private ChoosePDFAdapter adapter; private Purpose mPurpose; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mPurpose = PICK_KEY_FILE.equals(getIntent().getAction()) ? Purpose.PickKeyFile : Purpose.PickPDF; String storageState = Environment.getExternalStorageState(); if (!Environment.MEDIA_MOUNTED.equals(storageState) && !Environment.MEDIA_MOUNTED_READ_ONLY.equals(storageState)) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.no_media_warning); builder.setMessage(R.string.no_media_hint); AlertDialog alert = builder.create(); alert.setButton(AlertDialog.BUTTON_POSITIVE,getString(R.string.dismiss), new OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }); alert.show(); return; } if (mDirectory == null) mDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); // Create a list adapter... adapter = new ChoosePDFAdapter(getLayoutInflater()); setListAdapter(adapter); // ...that is updated dynamically when files are scanned mHandler = new Handler(); mUpdateFiles = new Runnable() { public void run() { Resources res = getResources(); String appName = res.getString(R.string.app_name); String version = res.getString(R.string.version); String title = res.getString(R.string.picker_title_App_Ver_Dir); setTitle(String.format(title, appName, version, mDirectory)); mParent = mDirectory.getParentFile(); mDirs = mDirectory.listFiles(new FileFilter() { public boolean accept(File file) { return file.isDirectory(); } }); if (mDirs == null) mDirs = new File[0]; mFiles = mDirectory.listFiles(new FileFilter() { public boolean accept(File file) { if (file.isDirectory()) return false; String fname = file.getName().toLowerCase(); switch (mPurpose) { case PickPDF: if (fname.endsWith(".pdf")) return true; if (fname.endsWith(".xps")) return true; if (fname.endsWith(".cbz")) return true; if (fname.endsWith(".epub")) return true; if (fname.endsWith(".png")) return true; if (fname.endsWith(".jpe")) return true; if (fname.endsWith(".jpeg")) return true; if (fname.endsWith(".jpg")) return true; if (fname.endsWith(".jfif")) return true; if (fname.endsWith(".jfif-tbnl")) return true; if (fname.endsWith(".tif")) return true; if (fname.endsWith(".tiff")) return true; return false; case PickKeyFile: if (fname.endsWith(".pfx")) return true; return false; default: return false; } } }); if (mFiles == null) mFiles = new File[0]; Arrays.sort(mFiles, new Comparator<File>() { public int compare(File arg0, File arg1) { return arg0.getName().compareToIgnoreCase(arg1.getName()); } }); Arrays.sort(mDirs, new Comparator<File>() { public int compare(File arg0, File arg1) { return arg0.getName().compareToIgnoreCase(arg1.getName()); } }); adapter.clear(); if (mParent != null) adapter.add(new ChoosePDFItem(ChoosePDFItem.Type.PARENT, getString(R.string.parent_directory))); for (File f : mDirs) adapter.add(new ChoosePDFItem(ChoosePDFItem.Type.DIR, f.getName())); for (File f : mFiles) adapter.add(new ChoosePDFItem(ChoosePDFItem.Type.DOC, f.getName())); lastPosition(); } }; // Start initial file scan... mHandler.post(mUpdateFiles); // ...and observe the directory and scan files upon changes. FileObserver observer = new FileObserver(mDirectory.getPath(), FileObserver.CREATE | FileObserver.DELETE) { public void onEvent(int event, String path) { mHandler.post(mUpdateFiles); } }; observer.startWatching(); } private void lastPosition() { String p = mDirectory.getAbsolutePath(); if (mPositions.containsKey(p)) getListView().setSelection(mPositions.get(p)); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); mPositions.put(mDirectory.getAbsolutePath(), getListView().getFirstVisiblePosition()); if (position < (mParent == null ? 0 : 1)) { mDirectory = mParent; mHandler.post(mUpdateFiles); return; } position -= (mParent == null ? 0 : 1); if (position < mDirs.length) { mDirectory = mDirs[position]; mHandler.post(mUpdateFiles); return; } position -= mDirs.length; Uri uri = Uri.parse(mFiles[position].getAbsolutePath()); Intent intent = new Intent(this,MuPDFActivity.class); intent.setAction(Intent.ACTION_VIEW); intent.setData(uri); switch (mPurpose) { case PickPDF: // Start an activity to display the PDF file startActivity(intent); break; case PickKeyFile: // Return the uri to the caller setResult(RESULT_OK, intent); finish(); break; } } @Override protected void onPause() { super.onPause(); if (mDirectory != null) mPositions.put(mDirectory.getAbsolutePath(), getListView().getFirstVisiblePosition()); } }
package com.handmark.pulltorefresh.library.internal; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Typeface; import android.graphics.drawable.AnimationDrawable; import android.graphics.drawable.Drawable; import android.os.Build.VERSION; import android.text.TextUtils; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.animation.Interpolator; import android.view.animation.LinearInterpolator; import android.widget.FrameLayout; import android.widget.FrameLayout.LayoutParams; import android.widget.ImageView; import android.widget.TextView; import com.bettycc.fancypulltorefresh.RefreshingView; import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode; import com.handmark.pulltorefresh.library.PullToRefreshBase.Orientation; import com.handmark.pulltorefresh.library.R.id; import com.handmark.pulltorefresh.library.R.layout; import com.handmark.pulltorefresh.library.R.string; import com.handmark.pulltorefresh.library.R.styleable; @SuppressLint({"ViewConstructor"}) public abstract class LoadingLayout extends FrameLayout implements com.handmark.pulltorefresh.library.a { static final Interpolator a = new LinearInterpolator(); public final ImageView b; public final View c; protected final PullToRefreshBase.Mode d; protected final PullToRefreshBase.Orientation e; private final RefreshingView f; private FrameLayout g; private View h; private boolean i; private final TextView j; private final TextView k; private CharSequence l; private CharSequence m; private CharSequence n; public LoadingLayout(Context paramContext, PullToRefreshBase.Mode paramMode, PullToRefreshBase.Orientation paramOrientation, TypedArray paramTypedArray) { super(paramContext); this.d = paramMode; this.e = paramOrientation; boolean bool1 = paramTypedArray.getBoolean(R.styleable.PullToRefresh_ptrTabMode, false); FrameLayout.LayoutParams localLayoutParams; int i4; label227: Drawable localDrawable2; label307: Drawable localDrawable1; switch (d.a[paramOrientation.ordinal()]) { default: if (!bool1) break; LayoutInflater.from(paramContext).inflate(R.layout.pull_to_refresh_header_vertical_tab, this); this.g = ((FrameLayout)findViewById(R.id.fl_inner)); this.j = ((TextView)this.g.findViewById(R.id.pull_to_refresh_text)); this.h = this.g.findViewById(R.id.pull_to_refresh_progress); this.k = ((TextView)this.g.findViewById(R.id.pull_to_refresh_sub_text)); this.b = ((ImageView)this.g.findViewById(R.id.pull_to_refresh_image)); this.c = this.g.findViewById(R.id.pull_to_refresh_tick); this.f = ((RefreshingView)this.g.findViewById(R.id.refreshing_view)); localLayoutParams = (FrameLayout.LayoutParams)this.g.getLayoutParams(); switch (d.b[paramMode.ordinal()]) { default: if (paramOrientation == PullToRefreshBase.Orientation.VERTICAL) { i4 = 80; localLayoutParams.gravity = i4; this.l = paramContext.getString(R.string.pull_to_refresh_pull_label); this.m = paramContext.getString(R.string.pull_to_refresh_refreshing_label); this.n = paramContext.getString(R.string.pull_to_refresh_release_label); if (paramTypedArray.hasValue(R.styleable.PullToRefresh_ptrHeaderBackground)) { localDrawable2 = paramTypedArray.getDrawable(R.styleable.PullToRefresh_ptrHeaderBackground); if (localDrawable2 != null) { if (Build.VERSION.SDK_INT < 16) break label742; setBackground(localDrawable2); } } if (paramTypedArray.hasValue(R.styleable.PullToRefresh_ptrHeaderTextAppearance)) { TypedValue localTypedValue1 = new TypedValue(); paramTypedArray.getValue(R.styleable.PullToRefresh_ptrHeaderTextAppearance, localTypedValue1); int i2 = localTypedValue1.data; if (this.j != null) this.j.setTextAppearance(getContext(), i2); if (this.k != null) this.k.setTextAppearance(getContext(), i2); } if (paramTypedArray.hasValue(R.styleable.PullToRefresh_ptrSubHeaderTextAppearance)) { TypedValue localTypedValue2 = new TypedValue(); paramTypedArray.getValue(R.styleable.PullToRefresh_ptrSubHeaderTextAppearance, localTypedValue2); int i3 = localTypedValue2.data; if (this.k != null) this.k.setTextAppearance(getContext(), i3); } if (paramTypedArray.hasValue(R.styleable.PullToRefresh_ptrHeaderTextColor)) { ColorStateList localColorStateList2 = paramTypedArray.getColorStateList(R.styleable.PullToRefresh_ptrHeaderTextColor); if (localColorStateList2 != null) { if (this.j != null) this.j.setTextColor(localColorStateList2); if (this.k != null) this.k.setTextColor(localColorStateList2); } } if (paramTypedArray.hasValue(R.styleable.PullToRefresh_ptrHeaderSubTextColor)) { ColorStateList localColorStateList1 = paramTypedArray.getColorStateList(R.styleable.PullToRefresh_ptrHeaderSubTextColor); if ((localColorStateList1 != null) && (this.k != null)) this.k.setTextColor(localColorStateList1); } boolean bool2 = paramTypedArray.hasValue(R.styleable.PullToRefresh_ptrDrawable); localDrawable1 = null; if (bool2) localDrawable1 = paramTypedArray.getDrawable(R.styleable.PullToRefresh_ptrDrawable); switch (d.b[paramMode.ordinal()]) { default: if (paramTypedArray.hasValue(R.styleable.PullToRefresh_ptrDrawableStart)) localDrawable1 = paramTypedArray.getDrawable(R.styleable.PullToRefresh_ptrDrawableStart); case 1: } } case 1: } case 1: } while (true) { if (localDrawable1 == null) localDrawable1 = paramContext.getResources().getDrawable(e()); setLoadingDrawable(localDrawable1); k(); return; LayoutInflater.from(paramContext).inflate(R.layout.pull_to_refresh_header_horizontal, this); break; LayoutInflater.from(paramContext).inflate(R.layout.pull_to_refresh_header_vertical, this); break; if (paramOrientation == PullToRefreshBase.Orientation.VERTICAL); for (int i1 = 48; ; i1 = 3) { localLayoutParams.gravity = i1; this.l = paramContext.getString(R.string.pull_to_refresh_from_bottom_pull_label); this.m = paramContext.getString(R.string.pull_to_refresh_from_bottom_refreshing_label); this.n = paramContext.getString(R.string.pull_to_refresh_from_bottom_release_label); break; } i4 = 5; break label227; label742: setBackgroundDrawable(localDrawable2); break label307; if (!paramTypedArray.hasValue(R.styleable.PullToRefresh_ptrDrawableTop)) continue; com.arcsoft.hpay100.a.a.c("ptrDrawableTop", "ptrDrawableStart"); localDrawable1 = paramTypedArray.getDrawable(R.styleable.PullToRefresh_ptrDrawableTop); continue; if (paramTypedArray.hasValue(R.styleable.PullToRefresh_ptrDrawableEnd)) { localDrawable1 = paramTypedArray.getDrawable(R.styleable.PullToRefresh_ptrDrawableEnd); continue; } if (!paramTypedArray.hasValue(R.styleable.PullToRefresh_ptrDrawableBottom)) continue; com.arcsoft.hpay100.a.a.c("ptrDrawableBottom", "ptrDrawableEnd"); localDrawable1 = paramTypedArray.getDrawable(R.styleable.PullToRefresh_ptrDrawableBottom); } } protected abstract void a(); protected abstract void a(float paramFloat); protected abstract void a(Drawable paramDrawable); protected abstract void b(); public final void b(float paramFloat) { if (!this.i) a(paramFloat); } protected abstract void c(); protected abstract void d(); protected abstract int e(); public final int f() { switch (d.a[this.e.ordinal()]) { default: return this.g.getHeight(); case 1: } return this.g.getWidth(); } public final void g() { if (this.j.getVisibility() == 0) this.j.setVisibility(4); if (this.h.getVisibility() == 0) this.h.setVisibility(4); if (this.b.getVisibility() == 0) this.b.setVisibility(4); if (this.k.getVisibility() == 0) this.k.setVisibility(4); } public final void h() { if (this.j != null) this.j.setText(this.l); a(); } public final void i() { if (this.j != null) this.j.setText(this.m); if (this.i) ((AnimationDrawable)this.b.getDrawable()).start(); while (true) { if (this.k != null) this.k.setVisibility(8); return; b(); } } public final void j() { if (this.j != null) this.j.setText(this.n); c(); } public final void k() { if (this.j != null) this.j.setText(this.l); this.b.setVisibility(0); if (this.i) ((AnimationDrawable)this.b.getDrawable()).stop(); while (true) { if (this.k != null) { if (!TextUtils.isEmpty(this.k.getText())) break; this.k.setVisibility(8); } return; d(); } this.k.setVisibility(0); } public final void l() { if (4 == this.j.getVisibility()) this.j.setVisibility(0); if (4 == this.h.getVisibility()) this.h.setVisibility(0); if (4 == this.b.getVisibility()) this.b.setVisibility(0); if (4 == this.k.getVisibility()) this.k.setVisibility(0); } public final void m() { this.f.setVisibility(0); this.f.setVisibility(0); } public final void n() { this.f.setVisibility(4); this.f.setVisibility(8); } public final void setHeight(int paramInt) { getLayoutParams().height = paramInt; requestLayout(); } public void setLastUpdatedLabel(CharSequence paramCharSequence) { if (this.k != null) { if (!TextUtils.isEmpty(paramCharSequence)) break label24; this.k.setVisibility(8); } label24: do { return; this.k.setText(paramCharSequence); } while (8 != this.k.getVisibility()); this.k.setVisibility(0); } public final void setLoadingDrawable(Drawable paramDrawable) { this.b.setImageDrawable(paramDrawable); this.i = (paramDrawable instanceof AnimationDrawable); a(paramDrawable); } public void setPullLabel(CharSequence paramCharSequence) { this.l = paramCharSequence; } public void setRefreshingLabel(CharSequence paramCharSequence) { this.m = paramCharSequence; } public void setReleaseLabel(CharSequence paramCharSequence) { this.n = paramCharSequence; } public void setTextTypeface(Typeface paramTypeface) { this.j.setTypeface(paramTypeface); } public final void setWidth(int paramInt) { getLayoutParams().width = paramInt; requestLayout(); } } /* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar * Qualified Name: com.handmark.pulltorefresh.library.internal.LoadingLayout * JD-Core Version: 0.6.0 */
/* * Copyright 2011, The gwtquery team. * * 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.gwt.query.client.impl; import static com.google.gwt.query.client.GQuery.$; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.Node; import com.google.gwt.query.client.GQuery; import com.google.gwt.query.client.js.JsNamedArray; import com.google.gwt.query.client.js.JsUtils; import com.google.gwt.regexp.shared.RegExp; import com.google.gwt.user.client.DOM; /** * A helper class to get computed CSS styles for elements. */ public class DocumentStyleImpl { private static final RegExp cssNumberRegex = RegExp.compile( "^(fillOpacity|fontWeight|lineHeight|opacity|orphans|widows|zIndex|zoom)$", "i"); private static final RegExp sizeRegex = RegExp.compile("^(client|offset|)(width|height)$", "i"); /** * Returns the numeric value of a css property. * * The parameter force has a special meaning: * - When force is false, returns the value of the css property defined * in the set of style attributes. * - Otherwise it returns the real computed value. */ public double cur(Element elem, String prop, boolean force) { if (JsUtils.isWindow(elem)) { if ("width".equals(prop)) { return getContentDocument(elem).getClientWidth(); } if ("height".equals(prop)) { return getContentDocument(elem).getClientHeight(); } elem = GQuery.body; } if (force && sizeRegex.test(prop)) { // make curCSS below resolve width and height (issue #145) when force is true } else if (elem.getPropertyString(prop) != null && (elem.getStyle() == null || elem.getStyle().getProperty(prop) == null)) { // cases where elem.prop exists instead of elem.style.prop return elem.getPropertyDouble(prop); } String val = curCSS(elem, prop, force); if ("thick".equalsIgnoreCase(val)) { return 5; } else if ("medium".equalsIgnoreCase(val)) { return 3; } else if ("thin".equalsIgnoreCase(val)) { return 1; } if (!val.matches("^[\\d\\.]+.*$")) { val = curCSS(elem, prop, false); } val = val.trim().replaceAll("[^\\d\\.\\-]+.*$", ""); return val.isEmpty() ? 0 : Double.parseDouble(val); } /** * Return the string value of a css property of an element. * * The parameter force has a special meaning: * - When force is false, returns the value of the css property defined * in the set of style attributes. * - Otherwise it returns the real computed value. * * For instance if you do not define 'display=none' in the element style but in * the css stylesheet, it will return an empty string unless you pass the * parameter force=true. */ public String curCSS(Element elem, String name, boolean force) { if (elem == null) { return ""; } name = fixPropertyName(name); // value defined in the element style String ret = elem.getStyle().getProperty(name); if (force) { Element toDetach = null; if (JsUtils.isDetached(elem)) { // If the element is detached to the DOM we attach temporary to it toDetach = attachTemporary(elem); } if (sizeRegex.test(name)) { ret = getVisibleSize(elem, name) + "px"; } else if ("opacity".equalsIgnoreCase(name)) { ret = String.valueOf(getOpacity(elem)); } else { ret = getComputedStyle(elem, JsUtils.hyphenize(name), name, null); } // If the element was previously attached, detached it. if (toDetach != null) { toDetach.removeFromParent(); } } return ret == null ? "" : ret; } private Element attachTemporary(Element elem) { Element lastParent = $(elem).parents().last().get(0); if (lastParent == null) { // the element itself is detached lastParent = elem; } Document.get().getBody().appendChild(lastParent); return lastParent; } /** * Fix style property names. */ public String fixPropertyName(String name) { if ("float".equalsIgnoreCase(name)) { return "cssFloat"; } else if ("for".equalsIgnoreCase(name)) { return "htmlFor"; } return JsUtils.camelize(name); } public int getVisibleSize(Element e, String name) { int ret; if (!isVisible(e)) { // jquery returns the size of the element even when the element isn't visible String display = curCSS(e, "display", false); String position = curCSS(e, "position", false); String visibility = curCSS(e, "visibility", false); setStyleProperty(e, "display", "block"); setStyleProperty(e, "position", "absolute"); setStyleProperty(e, "visibility", "hidden"); ret = getSize(e, name); setStyleProperty(e, "display", display); setStyleProperty(e, "position", position); setStyleProperty(e, "visibility", visibility); } else { ret = getSize(e, name); } return ret; } // inline elements do not have width nor height unless we set it to inline-block private void fixInlineElement(Element e) { if (e.getClientHeight() == 0 && e.getClientWidth() == 0 && "inline".equals(curCSS(e, "display", true))) { setStyleProperty(e, "display", "inline-block"); setStyleProperty(e, "width", "auto"); setStyleProperty(e, "height", "auto"); } } private int getSize(Element e, String name) { int ret = 0; if ("width".equals(name)) { ret = getWidth(e); } else if ("height".equals(name)) { ret = getHeight(e); } else if ("clientWidth".equals(name)) { ret = e.getClientWidth(); } else if ("clientHeight".equals(name)) { ret = e.getClientHeight(); } else if ("offsetWidth".equals(name)) { ret = e.getOffsetWidth(); } else if ("offsetHeight".equals(name)) { ret = e.getOffsetHeight(); } return ret; } public int getHeight(Element e) { fixInlineElement(e); return (int) (e.getClientHeight() - num(curCSS(e, "paddingTop", true)) - num(curCSS(e, "paddingBottom", true))); } public double getOpacity(Element e) { String o = e.getStyle().getOpacity(); return JsUtils.truth(o) ? num(o) : 1; } public int getWidth(Element e) { fixInlineElement(e); return (int) (e.getClientWidth() - num(curCSS(e, "paddingLeft", true)) - num(curCSS(e, "paddingRight", true))); } /** * Return whether the element is visible. */ public boolean isVisible(Element e) { return SelectorEngine.filters.get("visible").f(e, 0); } public double num(String val) { val = val.trim().replaceAll("[^\\d\\.\\-]+.*$", ""); return JsUtils.truth(val) ? Double.parseDouble(val) : 0; } /** * Remove a style property from an element. */ public void removeStyleProperty(Element elem, String prop) { elem.getStyle().setProperty(prop, ""); } /** * Set the value of a style property of an element. */ public void setStyleProperty(Element e, String prop, String val) { if (e == null || prop == null) { return; } prop = fixPropertyName(prop); // put it in lower-case only when all letters are upper-case, to avoid // modifying already camelized properties if (prop.matches("^[A-Z]+$")) { prop = prop.toLowerCase(); } prop = JsUtils.camelize(prop); if (val == null || val.trim().length() == 0) { removeStyleProperty(e, prop); } else { if (val.matches("-?[\\d\\.]+") && !cssNumberRegex.test(prop)) { val += "px"; } e.getStyle().setProperty(prop, val); } } protected native String getComputedStyle(Element elem, String hyphenName, String camelName, String pseudo) /*-{ try { var cStyle = $doc.defaultView.getComputedStyle(elem, pseudo); return cStyle && cStyle.getPropertyValue ? cStyle.getPropertyValue(hyphenName) : null; } catch(e) {return null;} }-*/; protected static final JsNamedArray<String> elemdisplay = JsNamedArray.create(); /** * Returns the default display value for each html tag. */ public String defaultDisplay(String tagName) { String ret = elemdisplay.get(tagName); if (ret == null) { Element e = DOM.createElement(tagName); Document.get().getBody().appendChild(e); ret = curCSS(e, "display", false); e.removeFromParent(); if (ret == null || ret.matches("(|none)")) { ret = "block"; } elemdisplay.put(tagName, ret); } return ret; } public native Document getContentDocument(Node n) /*-{ var d = n.contentDocument || n.document || n.contentWindow.document; if (!d.body) [email protected]::emptyDocument(Lcom/google/gwt/dom/client/Document;)(d); return d; }-*/; public native void emptyDocument(Document d) /*-{ d.open(); d.write("<head/><body/>"); d.close(); }-*/; }
/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.connectors.v1.model; /** * Metadata of an entity field. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Connectors API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class Field extends com.google.api.client.json.GenericJson { /** * The following map contains fields that are not explicitly mentioned above,this give connectors * the flexibility to add new metadata fields. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.Map<String, java.lang.Object> additionalDetails; /** * The data type of the Field. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String dataType; /** * The following field specifies the default value of the Field provided by the external system if * a value is not provided. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Object defaultValue; /** * A brief description of the Field. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String description; /** * Name of the Field. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String field; /** * The following boolean field specifies if the current Field acts as a primary key or id if the * parent is of type entity. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean key; /** * Specifies whether a null value is allowed. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean nullable; /** * Specifies if the Field is readonly. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean readonly; /** * The following map contains fields that are not explicitly mentioned above,this give connectors * the flexibility to add new metadata fields. * @return value or {@code null} for none */ public java.util.Map<String, java.lang.Object> getAdditionalDetails() { return additionalDetails; } /** * The following map contains fields that are not explicitly mentioned above,this give connectors * the flexibility to add new metadata fields. * @param additionalDetails additionalDetails or {@code null} for none */ public Field setAdditionalDetails(java.util.Map<String, java.lang.Object> additionalDetails) { this.additionalDetails = additionalDetails; return this; } /** * The data type of the Field. * @return value or {@code null} for none */ public java.lang.String getDataType() { return dataType; } /** * The data type of the Field. * @param dataType dataType or {@code null} for none */ public Field setDataType(java.lang.String dataType) { this.dataType = dataType; return this; } /** * The following field specifies the default value of the Field provided by the external system if * a value is not provided. * @return value or {@code null} for none */ public java.lang.Object getDefaultValue() { return defaultValue; } /** * The following field specifies the default value of the Field provided by the external system if * a value is not provided. * @param defaultValue defaultValue or {@code null} for none */ public Field setDefaultValue(java.lang.Object defaultValue) { this.defaultValue = defaultValue; return this; } /** * A brief description of the Field. * @return value or {@code null} for none */ public java.lang.String getDescription() { return description; } /** * A brief description of the Field. * @param description description or {@code null} for none */ public Field setDescription(java.lang.String description) { this.description = description; return this; } /** * Name of the Field. * @return value or {@code null} for none */ public java.lang.String getField() { return field; } /** * Name of the Field. * @param field field or {@code null} for none */ public Field setField(java.lang.String field) { this.field = field; return this; } /** * The following boolean field specifies if the current Field acts as a primary key or id if the * parent is of type entity. * @return value or {@code null} for none */ public java.lang.Boolean getKey() { return key; } /** * The following boolean field specifies if the current Field acts as a primary key or id if the * parent is of type entity. * @param key key or {@code null} for none */ public Field setKey(java.lang.Boolean key) { this.key = key; return this; } /** * Specifies whether a null value is allowed. * @return value or {@code null} for none */ public java.lang.Boolean getNullable() { return nullable; } /** * Specifies whether a null value is allowed. * @param nullable nullable or {@code null} for none */ public Field setNullable(java.lang.Boolean nullable) { this.nullable = nullable; return this; } /** * Specifies if the Field is readonly. * @return value or {@code null} for none */ public java.lang.Boolean getReadonly() { return readonly; } /** * Specifies if the Field is readonly. * @param readonly readonly or {@code null} for none */ public Field setReadonly(java.lang.Boolean readonly) { this.readonly = readonly; return this; } @Override public Field set(String fieldName, Object value) { return (Field) super.set(fieldName, value); } @Override public Field clone() { return (Field) super.clone(); } }
package crowdsurf.android.brainmurphy.com.crowdsurf; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.graphics.drawable.Drawable; import android.location.Location; import android.os.AsyncTask; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesClient; import com.google.android.gms.location.LocationClient; import com.google.android.gms.maps.model.LatLng; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; //import static crowdsurf.android.brainmurphy.com.crowdsurf.CrowdSurfSQLiteHelper.COLUMN_ID; //import static crowdsurf.android.brainmurphy.com.crowdsurf.CrowdSurfSQLiteHelper.TABLE_QUESTIONS; public class MainActivity extends Activity implements GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener { private ListView questionList; private TextView searchBar; private ArrayAdapter<Question> questionsAdapter; private LatLng lastLocation; private LocationClient locationClient; @Override @SuppressWarnings("unchecked") protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button goButton = (Button) findViewById(R.id.goButton); goButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String questionText = searchBar.getText().toString(); redirectToCreatePage(questionText); } }); //get ListView// questionList = (ListView) findViewById(R.id.questionsListView); //setup adapter that will populate question_list_item.xml// questionsAdapter = new ArrayAdapter<Question>(this, R.layout.question_list_item){ @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = getLayoutInflater().inflate(R.layout.question_list_item, parent, false); } Question question = getItem(position); final String questionID = question.getID(); ((TextView)convertView.findViewById(R.id.questionTitle)).setText(question.getTitle()); LinearLayout clickable = (LinearLayout) convertView.findViewById(R.id.clickableLayout); clickable.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { redirectToAnswerPage(questionID); } }); ((TextView)convertView.findViewById(R.id.numAnswers)).setText( question.getAnswers() + question.getAnswers() == 1 ? " answer" : " answers"); ImageView acceptedAnswer = (ImageView) convertView.findViewById(R.id.acceptedAnswer); boolean accepted = question.getAccepted(); if (accepted) { Drawable checkmark = getResources().getDrawable(R.drawable.checkmark); acceptedAnswer.setImageDrawable(checkmark); } else { Drawable questionmark = getResources().getDrawable(R.drawable.questionmark); acceptedAnswer.setImageDrawable(questionmark); } ImageButton upvoteButton = (ImageButton) convertView.findViewById(R.id.upvote); Drawable uparrow = getResources().getDrawable(R.drawable.uparrow); upvoteButton.setImageDrawable(uparrow); upvoteButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { query(questionID, 1); } }); ImageButton downvoteButton = (ImageButton) convertView.findViewById(R.id.downvote); Drawable downarrow = getResources().getDrawable(R.drawable.downarrow); downvoteButton.setImageDrawable(downarrow); downvoteButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { query(questionID, -1); } }); return convertView; } }; questionList.setAdapter(questionsAdapter); searchBar = (TextView) findViewById(R.id.searchAutoCompleteTextView); searchBar.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { Log.d("OnTextChanged","started"); Log.d("OnTextChanged","charsequence: " + s.toString()); if (s == null || s.toString().trim().equals("")) { return; } ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("lat", Double.toString(lastLocation.latitude))); params.add(new BasicNameValuePair("long", Double.toString(lastLocation.longitude))); params.add(new BasicNameValuePair("search", s.toString())); new AsyncTask<ArrayList<NameValuePair>, Void, ArrayList<Question>>(){ @Override protected ArrayList<Question> doInBackground(ArrayList<NameValuePair>... params) { Log.d("OnTextChanged", "doInBackground"); ArrayList<Question> questions = null; try { JSONArray jsonArray = new JSONObject(Util.post(params[0], "questionlist")).getJSONArray("questions"); questions = new ArrayList<Question>(); for (int i = 0; i < jsonArray.length(); i++) { questions.add(new Question(jsonArray.getJSONObject(i))); } } catch (JSONException e) { e.printStackTrace(); } return questions; } @Override protected void onPostExecute(ArrayList<Question> questions) { super.onPostExecute(questions); questionsAdapter.clear(); questionsAdapter.addAll(questions); } }.execute(params); } @Override public void afterTextChanged(Editable s) { } }); locationClient = new LocationClient(this, this, this); } private void getFeed() { ArrayList<NameValuePair> location = new ArrayList<NameValuePair>(); Location loc = locationClient.getLastLocation(); location.add(new BasicNameValuePair("lat", Double.toString(loc.getLatitude()))); location.add(new BasicNameValuePair("long", Double.toString(loc.getLongitude()))); location.add(new BasicNameValuePair("search","")); lastLocation = new LatLng(loc.getLatitude(), loc.getLongitude()); questionsAdapter.clear(); //populate list asynchronously// new AsyncTask<ArrayList<NameValuePair>, Question, Void>() { @Override protected Void doInBackground(ArrayList<NameValuePair>... params) { try { JSONArray jsonArray = new JSONObject(Util.post(params[0], "questionlist")).getJSONArray("questions"); for (int i = 0; i < jsonArray.length(); i++) { publishProgress(new Question(jsonArray.getJSONObject(i))); } } catch (JSONException e) { e.printStackTrace(); } return null; } @Override protected void onProgressUpdate(Question... values) { questionsAdapter.add(values[0]); questionsAdapter.notifyDataSetChanged(); Log.d("getFeed", "progressUpdated"); } }.execute(location); } @Override protected void onStart() { super.onStart(); locationClient.connect(); } @Override protected void onStop() { super.onStop(); locationClient.disconnect(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.global, menu); return true; } @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. int id = item.getItemId(); // if (id == R.id.action_my_questions) { // startActivity(new Intent(this, MyQuestionsActivity.class)); // return true; // } return super.onOptionsItemSelected(item); } private void query(String questionID, int upOrDown) { // CrowdSurfSQLiteHelper sqLiteHelper = ((MyApplication)getApplication()).getSqLiteHelper(); // Cursor crsr = sqLiteHelper.getReadableDatabase().query(TABLE_QUESTIONS, // new String[]{COLUMN_ID}, COLUMN_ID + " = " + questionID, null, null, null, null); // //TODO ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("qOrA", "questions")); params.add(new BasicNameValuePair("ID", new Integer(questionID).toString())); params.add(new BasicNameValuePair("upOrDown", new Integer(upOrDown).toString())); Util.post(params, "upvote/downvote"); } private void redirectToCreatePage(String questionTitle) { Intent intent = new Intent(this, CreateActivity.class); intent.putExtra(CreateActivity.KEY_TITLE, questionTitle); startActivityIfNeeded(intent, 0); } private void redirectToAnswerPage(String questionID) { Intent intent = new Intent(this, QuestionActivity.class); Log.d("MainActivity", "question Id sent: " + questionID); intent.putExtra(QuestionActivity.KEY_ID, questionID); startActivity(intent); } @Override public void onConnected(Bundle bundle) { getFeed(); } @Override public void onDisconnected() { } @Override public void onConnectionFailed(ConnectionResult connectionResult) { } }
/** * 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.codehaus.groovy.antlr.treewalker; import java.util.List; import java.util.ArrayList; import org.codehaus.groovy.antlr.GroovySourceAST; import org.codehaus.groovy.antlr.AntlrASTProcessor; import org.codehaus.groovy.antlr.parser.GroovyTokenTypes; import antlr.collections.AST; /** * Helper Class for Antlr AST traversal and visitation. * * @author <a href="mailto:[email protected]">Jeremy Rayner</a> * @version $Revision$ */ public abstract class TraversalHelper implements AntlrASTProcessor { protected List<GroovySourceAST> unvisitedNodes; private final Visitor v; public TraversalHelper(Visitor visitor) { this.unvisitedNodes = new ArrayList<GroovySourceAST>(); this.v = visitor; } protected void setUp(GroovySourceAST ast) { v.setUp(); } protected void tearDown(GroovySourceAST ast) { v.tearDown(); } protected void push(GroovySourceAST ast) { v.push(ast); } protected GroovySourceAST pop() { return v.pop(); } protected void visitNode(GroovySourceAST ast, int n) { if (ast != null) { switch (ast.getType()) { case GroovyTokenTypes.ABSTRACT : v.visitAbstract(ast,n); break; case GroovyTokenTypes.ANNOTATION : v.visitAnnotation(ast,n); break; case GroovyTokenTypes.ANNOTATIONS : v.visitAnnotations(ast,n); break; case GroovyTokenTypes.ANNOTATION_ARRAY_INIT : v.visitAnnotationArrayInit(ast,n); break; // obsolete? case GroovyTokenTypes.ANNOTATION_DEF : v.visitAnnotationDef(ast,n); break; case GroovyTokenTypes.ANNOTATION_FIELD_DEF : v.visitAnnotationFieldDef(ast,n); break; case GroovyTokenTypes.ANNOTATION_MEMBER_VALUE_PAIR : v.visitAnnotationMemberValuePair(ast,n); break; case GroovyTokenTypes.ARRAY_DECLARATOR : v.visitArrayDeclarator(ast,n); break; case GroovyTokenTypes.ASSIGN : v.visitAssign(ast,n); break; case GroovyTokenTypes.AT : v.visitAt(ast,n); break; case GroovyTokenTypes.BAND : v.visitBand(ast,n); break; case GroovyTokenTypes.BAND_ASSIGN : v.visitBandAssign(ast,n); break; case GroovyTokenTypes.BIG_SUFFIX : v.visitBigSuffix(ast,n); break; case GroovyTokenTypes.BLOCK : v.visitBlock(ast,n); break; case GroovyTokenTypes.BNOT : v.visitBnot(ast,n); break; case GroovyTokenTypes.BOR : v.visitBor(ast,n); break; case GroovyTokenTypes.BOR_ASSIGN : v.visitBorAssign(ast,n); break; case GroovyTokenTypes.BSR : v.visitBsr(ast,n); break; case GroovyTokenTypes.BSR_ASSIGN : v.visitBsrAssign(ast,n); break; case GroovyTokenTypes.BXOR : v.visitBxor(ast,n); break; case GroovyTokenTypes.BXOR_ASSIGN : v.visitBxorAssign(ast,n); break; case GroovyTokenTypes.CASE_GROUP : v.visitCaseGroup(ast,n); break; case GroovyTokenTypes.CLASS_DEF : v.visitClassDef(ast,n); break; case GroovyTokenTypes.CLOSABLE_BLOCK : v.visitClosedBlock(ast,n); break; case GroovyTokenTypes.CLOSABLE_BLOCK_OP : v.visitClosureOp(ast,n); break; case GroovyTokenTypes.CLOSURE_LIST : v.visitClosureList(ast,n); break; case GroovyTokenTypes.COLON : v.visitColon(ast,n); break; case GroovyTokenTypes.COMMA : v.visitComma(ast,n); break; case GroovyTokenTypes.COMPARE_TO : v.visitCompareTo(ast,n); break; case GroovyTokenTypes.CTOR_CALL : v.visitCtorCall(ast,n); break; case GroovyTokenTypes.CTOR_IDENT : v.visitCtorIdent(ast,n); break; case GroovyTokenTypes.DEC : v.visitDec(ast,n); break; case GroovyTokenTypes.DIGIT : v.visitDigit(ast,n); break; case GroovyTokenTypes.DIV : v.visitDiv(ast,n); break; case GroovyTokenTypes.DIV_ASSIGN : v.visitDivAssign(ast,n); break; case GroovyTokenTypes.DOLLAR : v.visitDollar(ast,n); break; case GroovyTokenTypes.DOLLAR_REGEXP_CTOR_END : v.visitRegexpCtorEnd(ast,n); break; case GroovyTokenTypes.DOLLAR_REGEXP_LITERAL : v.visitRegexpLiteral(ast,n); break; case GroovyTokenTypes.DOLLAR_REGEXP_SYMBOL : v.visitRegexpSymbol(ast,n); break; case GroovyTokenTypes.DOT : v.visitDot(ast,n); break; case GroovyTokenTypes.DYNAMIC_MEMBER : v.visitDynamicMember(ast,n); break; case GroovyTokenTypes.ELIST : v.visitElist(ast,n); break; case GroovyTokenTypes.EMPTY_STAT : v.visitEmptyStat(ast,n); break; case GroovyTokenTypes.ENUM_CONSTANT_DEF : v.visitEnumConstantDef(ast,n); break; case GroovyTokenTypes.ENUM_DEF : v.visitEnumDef(ast,n); break; case GroovyTokenTypes.EOF : v.visitEof(ast,n); break; case GroovyTokenTypes.EQUAL : v.visitEqual(ast,n); break; case GroovyTokenTypes.ESC : v.visitEsc(ast,n); break; case GroovyTokenTypes.EXPONENT : v.visitExponent(ast,n); break; case GroovyTokenTypes.EXPR : v.visitExpr(ast,n); break; case GroovyTokenTypes.EXTENDS_CLAUSE : v.visitExtendsClause(ast,n); break; case GroovyTokenTypes.FINAL : v.visitFinal(ast,n); break; case GroovyTokenTypes.FLOAT_SUFFIX : v.visitFloatSuffix(ast,n); break; case GroovyTokenTypes.FOR_CONDITION : v.visitForCondition(ast,n); break; case GroovyTokenTypes.FOR_EACH_CLAUSE : v.visitForEachClause(ast,n); break; case GroovyTokenTypes.FOR_INIT : v.visitForInit(ast,n); break; case GroovyTokenTypes.FOR_IN_ITERABLE : v.visitForInIterable(ast,n); break; case GroovyTokenTypes.FOR_ITERATOR : v.visitForIterator(ast,n); break; case GroovyTokenTypes.GE : v.visitGe(ast,n); break; case GroovyTokenTypes.GT : v.visitGt(ast,n); break; case GroovyTokenTypes.HEX_DIGIT : v.visitHexDigit(ast,n); break; case GroovyTokenTypes.IDENT : v.visitIdent(ast,n); break; case GroovyTokenTypes.IMPLEMENTS_CLAUSE : v.visitImplementsClause(ast,n); break; case GroovyTokenTypes.IMPLICIT_PARAMETERS : v.visitImplicitParameters(ast,n); break; case GroovyTokenTypes.IMPORT : v.visitImport(ast,n); break; case GroovyTokenTypes.INC : v.visitInc(ast,n); break; case GroovyTokenTypes.INDEX_OP : v.visitIndexOp(ast,n); break; case GroovyTokenTypes.INSTANCE_INIT : v.visitInstanceInit(ast,n); break; case GroovyTokenTypes.INTERFACE_DEF : v.visitInterfaceDef(ast,n); break; case GroovyTokenTypes.LABELED_ARG : v.visitLabeledArg(ast,n); break; case GroovyTokenTypes.LABELED_STAT : v.visitLabeledStat(ast,n); break; case GroovyTokenTypes.LAND : v.visitLand(ast,n); break; case GroovyTokenTypes.LBRACK : v.visitLbrack(ast,n); break; case GroovyTokenTypes.LCURLY : v.visitLcurly(ast,n); break; case GroovyTokenTypes.LE : v.visitLe(ast,n); break; case GroovyTokenTypes.LETTER : v.visitLetter(ast,n); break; case GroovyTokenTypes.LIST_CONSTRUCTOR : v.visitListConstructor(ast,n); break; case GroovyTokenTypes.LITERAL_as : v.visitLiteralAs(ast,n); break; case GroovyTokenTypes.LITERAL_assert : v.visitLiteralAssert(ast,n); break; case GroovyTokenTypes.LITERAL_boolean : v.visitLiteralBoolean(ast,n); break; case GroovyTokenTypes.LITERAL_break : v.visitLiteralBreak(ast,n); break; case GroovyTokenTypes.LITERAL_byte : v.visitLiteralByte(ast,n); break; case GroovyTokenTypes.LITERAL_case : v.visitLiteralCase(ast,n); break; case GroovyTokenTypes.LITERAL_catch : v.visitLiteralCatch(ast,n); break; case GroovyTokenTypes.LITERAL_char : v.visitLiteralChar(ast,n); break; case GroovyTokenTypes.LITERAL_class : v.visitLiteralClass(ast,n); break; case GroovyTokenTypes.LITERAL_continue : v.visitLiteralContinue(ast,n); break; case GroovyTokenTypes.LITERAL_def : v.visitLiteralDef(ast,n); break; case GroovyTokenTypes.LITERAL_default : v.visitLiteralDefault(ast,n); break; case GroovyTokenTypes.LITERAL_double : v.visitLiteralDouble(ast,n); break; case GroovyTokenTypes.LITERAL_else : v.visitLiteralElse(ast,n); break; case GroovyTokenTypes.LITERAL_enum : v.visitLiteralEnum(ast,n); break; case GroovyTokenTypes.LITERAL_extends : v.visitLiteralExtends(ast,n); break; case GroovyTokenTypes.LITERAL_false : v.visitLiteralFalse(ast,n); break; case GroovyTokenTypes.LITERAL_finally : v.visitLiteralFinally(ast,n); break; case GroovyTokenTypes.LITERAL_float : v.visitLiteralFloat(ast,n); break; case GroovyTokenTypes.LITERAL_for : v.visitLiteralFor(ast,n); break; case GroovyTokenTypes.LITERAL_if : v.visitLiteralIf(ast,n); break; case GroovyTokenTypes.LITERAL_implements : v.visitLiteralImplements(ast,n); break; case GroovyTokenTypes.LITERAL_import : v.visitLiteralImport(ast,n); break; case GroovyTokenTypes.LITERAL_in : v.visitLiteralIn(ast,n); break; case GroovyTokenTypes.LITERAL_instanceof : v.visitLiteralInstanceof(ast,n); break; case GroovyTokenTypes.LITERAL_int : v.visitLiteralInt(ast,n); break; case GroovyTokenTypes.LITERAL_interface : v.visitLiteralInterface(ast,n); break; case GroovyTokenTypes.LITERAL_long : v.visitLiteralLong(ast,n); break; case GroovyTokenTypes.LITERAL_native : v.visitLiteralNative(ast,n); break; case GroovyTokenTypes.LITERAL_new : v.visitLiteralNew(ast,n); break; case GroovyTokenTypes.LITERAL_null : v.visitLiteralNull(ast,n); break; case GroovyTokenTypes.LITERAL_package : v.visitLiteralPackage(ast,n); break; case GroovyTokenTypes.LITERAL_private : v.visitLiteralPrivate(ast,n); break; case GroovyTokenTypes.LITERAL_protected : v.visitLiteralProtected(ast,n); break; case GroovyTokenTypes.LITERAL_public : v.visitLiteralPublic(ast,n); break; case GroovyTokenTypes.LITERAL_return : v.visitLiteralReturn(ast,n); break; case GroovyTokenTypes.LITERAL_short : v.visitLiteralShort(ast,n); break; case GroovyTokenTypes.LITERAL_static : v.visitLiteralStatic(ast,n); break; case GroovyTokenTypes.LITERAL_super : v.visitLiteralSuper(ast,n); break; case GroovyTokenTypes.LITERAL_switch : v.visitLiteralSwitch(ast,n); break; case GroovyTokenTypes.LITERAL_synchronized : v.visitLiteralSynchronized(ast,n); break; case GroovyTokenTypes.LITERAL_this : v.visitLiteralThis(ast,n); break; case GroovyTokenTypes.LITERAL_threadsafe : v.visitLiteralThreadsafe(ast,n); break; case GroovyTokenTypes.LITERAL_throw : v.visitLiteralThrow(ast,n); break; case GroovyTokenTypes.LITERAL_throws : v.visitLiteralThrows(ast,n); break; case GroovyTokenTypes.LITERAL_transient : v.visitLiteralTransient(ast,n); break; case GroovyTokenTypes.LITERAL_true : v.visitLiteralTrue(ast,n); break; case GroovyTokenTypes.LITERAL_try : v.visitLiteralTry(ast,n); break; case GroovyTokenTypes.LITERAL_void : v.visitLiteralVoid(ast,n); break; case GroovyTokenTypes.LITERAL_volatile : v.visitLiteralVolatile(ast,n); break; case GroovyTokenTypes.LITERAL_while : v.visitLiteralWhile(ast,n); break; case GroovyTokenTypes.LNOT : v.visitLnot(ast,n); break; case GroovyTokenTypes.LOR : v.visitLor(ast,n); break; case GroovyTokenTypes.LPAREN : v.visitLparen(ast,n); break; case GroovyTokenTypes.LT : v.visitLt(ast,n); break; case GroovyTokenTypes.MAP_CONSTRUCTOR : v.visitMapConstructor(ast,n); break; case GroovyTokenTypes.MEMBER_POINTER : v.visitMemberPointer(ast,n); break; case GroovyTokenTypes.METHOD_CALL : v.visitMethodCall(ast,n); break; case GroovyTokenTypes.METHOD_DEF : v.visitMethodDef(ast,n); break; case GroovyTokenTypes.MINUS : v.visitMinus(ast,n); break; case GroovyTokenTypes.MINUS_ASSIGN : v.visitMinusAssign(ast,n); break; case GroovyTokenTypes.ML_COMMENT : v.visitMlComment(ast,n); break; case GroovyTokenTypes.MOD : v.visitMod(ast,n); break; case GroovyTokenTypes.MODIFIERS : v.visitModifiers(ast,n); break; case GroovyTokenTypes.MOD_ASSIGN : v.visitModAssign(ast,n); break; case GroovyTokenTypes.NLS : v.visitNls(ast,n); break; case GroovyTokenTypes.NOT_EQUAL : v.visitNotEqual(ast,n); break; case GroovyTokenTypes.NULL_TREE_LOOKAHEAD : v.visitNullTreeLookahead(ast,n); break; case GroovyTokenTypes.MULTICATCH : v.visitMultiCatch(ast,n); break; case GroovyTokenTypes.MULTICATCH_TYPES : v.visitMultiCatchTypes(ast,n); break; case GroovyTokenTypes.NUM_BIG_DECIMAL : v.visitNumBigDecimal(ast,n); break; case GroovyTokenTypes.NUM_BIG_INT : v.visitNumBigInt(ast,n); break; case GroovyTokenTypes.NUM_DOUBLE : v.visitNumDouble(ast,n); break; case GroovyTokenTypes.NUM_FLOAT : v.visitNumFloat(ast,n); break; case GroovyTokenTypes.NUM_INT : v.visitNumInt(ast,n); break; case GroovyTokenTypes.NUM_LONG : v.visitNumLong(ast,n); break; case GroovyTokenTypes.OBJBLOCK : v.visitObjblock(ast,n); break; case GroovyTokenTypes.ONE_NL : v.visitOneNl(ast,n); break; case GroovyTokenTypes.OPTIONAL_DOT : v.visitOptionalDot(ast,n); break; case GroovyTokenTypes.PACKAGE_DEF : v.visitPackageDef(ast,n); break; case GroovyTokenTypes.PARAMETERS : v.visitParameters(ast,n); break; case GroovyTokenTypes.PARAMETER_DEF : v.visitParameterDef(ast,n); break; case GroovyTokenTypes.PLUS : v.visitPlus(ast,n); break; case GroovyTokenTypes.PLUS_ASSIGN : v.visitPlusAssign(ast,n); break; case GroovyTokenTypes.POST_DEC : v.visitPostDec(ast,n); break; case GroovyTokenTypes.POST_INC : v.visitPostInc(ast,n); break; case GroovyTokenTypes.QUESTION : v.visitQuestion(ast,n); break; case GroovyTokenTypes.RANGE_EXCLUSIVE : v.visitRangeExclusive(ast,n); break; case GroovyTokenTypes.RANGE_INCLUSIVE : v.visitRangeInclusive(ast,n); break; case GroovyTokenTypes.RBRACK : v.visitRbrack(ast,n); break; case GroovyTokenTypes.RCURLY : v.visitRcurly(ast,n); break; case GroovyTokenTypes.REGEXP_CTOR_END : v.visitRegexpCtorEnd(ast,n); break; case GroovyTokenTypes.REGEXP_LITERAL : v.visitRegexpLiteral(ast,n); break; case GroovyTokenTypes.REGEXP_SYMBOL : v.visitRegexpSymbol(ast,n); break; case GroovyTokenTypes.REGEX_FIND : v.visitRegexFind(ast,n); break; case GroovyTokenTypes.REGEX_MATCH : v.visitRegexMatch(ast,n); break; case GroovyTokenTypes.RPAREN : v.visitRparen(ast,n); break; case GroovyTokenTypes.SELECT_SLOT : v.visitSelectSlot(ast,n); break; case GroovyTokenTypes.SEMI : v.visitSemi(ast,n); break; case GroovyTokenTypes.SH_COMMENT : v.visitShComment(ast,n); break; case GroovyTokenTypes.SL : v.visitSl(ast,n); break; case GroovyTokenTypes.SLIST : v.visitSlist(ast,n); break; case GroovyTokenTypes.SL_ASSIGN : v.visitSlAssign(ast,n); break; case GroovyTokenTypes.SL_COMMENT : v.visitSlComment(ast,n); break; case GroovyTokenTypes.SPREAD_ARG : v.visitSpreadArg(ast,n); break; case GroovyTokenTypes.SPREAD_DOT : v.visitSpreadDot(ast,n); break; case GroovyTokenTypes.SPREAD_MAP_ARG : v.visitSpreadMapArg(ast,n); break; case GroovyTokenTypes.SR : v.visitSr(ast,n); break; case GroovyTokenTypes.SR_ASSIGN : v.visitSrAssign(ast,n); break; case GroovyTokenTypes.STAR : v.visitStar(ast,n); break; case GroovyTokenTypes.STAR_ASSIGN : v.visitStarAssign(ast,n); break; case GroovyTokenTypes.STAR_STAR : v.visitStarStar(ast,n); break; case GroovyTokenTypes.STAR_STAR_ASSIGN : v.visitStarStarAssign(ast,n); break; case GroovyTokenTypes.STATIC_IMPORT : v.visitStaticImport(ast,n); break; case GroovyTokenTypes.STATIC_INIT : v.visitStaticInit(ast,n); break; case GroovyTokenTypes.STRICTFP : v.visitStrictfp(ast,n); break; case GroovyTokenTypes.STRING_CH : v.visitStringCh(ast,n); break; case GroovyTokenTypes.STRING_CONSTRUCTOR : v.visitStringConstructor(ast,n); break; case GroovyTokenTypes.STRING_CTOR_END : v.visitStringCtorEnd(ast,n); break; case GroovyTokenTypes.STRING_CTOR_MIDDLE : v.visitStringCtorMiddle(ast,n); break; case GroovyTokenTypes.STRING_CTOR_START : v.visitStringCtorStart(ast,n); break; case GroovyTokenTypes.STRING_LITERAL : v.visitStringLiteral(ast,n); break; case GroovyTokenTypes.STRING_NL : v.visitStringNl(ast,n); break; case GroovyTokenTypes.SUPER_CTOR_CALL : v.visitSuperCtorCall(ast,n); break; case GroovyTokenTypes.TRAIT_DEF : v.visitTraitDef(ast,n); break; case GroovyTokenTypes.TRIPLE_DOT : v.visitTripleDot(ast,n); break; case GroovyTokenTypes.TYPE : v.visitType(ast,n); break; case GroovyTokenTypes.TYPECAST : v.visitTypecast(ast,n); break; case GroovyTokenTypes.TYPE_ARGUMENT : v.visitTypeArgument(ast,n); break; case GroovyTokenTypes.TYPE_ARGUMENTS : v.visitTypeArguments(ast,n); break; case GroovyTokenTypes.TYPE_LOWER_BOUNDS : v.visitTypeLowerBounds(ast,n); break; case GroovyTokenTypes.TYPE_PARAMETER : v.visitTypeParameter(ast,n); break; case GroovyTokenTypes.TYPE_PARAMETERS : v.visitTypeParameters(ast,n); break; case GroovyTokenTypes.TYPE_UPPER_BOUNDS : v.visitTypeUpperBounds(ast,n); break; case GroovyTokenTypes.UNARY_MINUS : v.visitUnaryMinus(ast,n); break; case GroovyTokenTypes.UNARY_PLUS : v.visitUnaryPlus(ast,n); break; case GroovyTokenTypes.UNUSED_CONST : v.visitUnusedConst(ast,n); break; case GroovyTokenTypes.UNUSED_DO : v.visitUnusedDo(ast,n); break; case GroovyTokenTypes.UNUSED_GOTO : v.visitUnusedGoto(ast,n); break; case GroovyTokenTypes.VARIABLE_DEF : v.visitVariableDef(ast,n); break; case GroovyTokenTypes.VARIABLE_PARAMETER_DEF : v.visitVariableParameterDef(ast,n); break; case GroovyTokenTypes.VOCAB : v.visitVocab(ast,n); break; case GroovyTokenTypes.WILDCARD_TYPE : v.visitWildcardType(ast,n); break; case GroovyTokenTypes.WS : v.visitWs(ast,n); break; default : v.visitDefault(ast,n); break; } } else { // the supplied AST was null v.visitDefault(null,n); } } protected abstract void accept(GroovySourceAST currentNode); protected void accept_v_FirstChildsFirstChild_v_Child2_Child3_v_Child4_v___v_LastChild(GroovySourceAST t) { openingVisit(t); GroovySourceAST expr2 = t.childAt(0); skip(expr2); accept(expr2.childAt(0)); closingVisit(t); GroovySourceAST sibling = (GroovySourceAST) expr2.getNextSibling(); boolean firstSList = true; while (sibling != null) { if (!firstSList) { subsequentVisit(t); } firstSList = false; accept(sibling); sibling = (GroovySourceAST) sibling.getNextSibling(); } } protected void accept_v_FirstChildsFirstChild_v_RestOfTheChildren(GroovySourceAST t) { openingVisit(t); GroovySourceAST expr = t.childAt(0); skip(expr); accept(expr.childAt(0)); closingVisit(t); acceptSiblings(expr); } protected void accept_FirstChild_v_SecondChild(GroovySourceAST t) { accept(t.childAt(0)); subsequentVisit(t); accept(t.childAt(1)); } protected void accept_FirstChild_v_SecondChild_v(GroovySourceAST t) { accept(t.childAt(0)); openingVisit(t); accept(t.childAt(1)); closingVisit(t); } protected void accept_SecondChild_v_ThirdChild_v(GroovySourceAST t) { accept(t.childAt(1)); openingVisit(t); accept(t.childAt(2)); closingVisit(t); } protected void accept_FirstChild_v_SecondChildsChildren_v(GroovySourceAST t) { accept(t.childAt(0)); openingVisit(t); GroovySourceAST secondChild = t.childAt(1); if (secondChild != null) { acceptChildren(secondChild); } closingVisit(t); } protected void accept_v_FirstChild_SecondChild_v_ThirdChild_v(GroovySourceAST t) { openingVisit(t); accept(t.childAt(0)); accept(t.childAt(1)); subsequentVisit(t); accept(t.childAt(2)); closingVisit(t); } protected void accept_FirstChild_v_SecondChild_v_ThirdChild_v(GroovySourceAST t) { accept(t.childAt(0)); openingVisit(t); accept(t.childAt(1)); subsequentVisit(t); accept(t.childAt(2)); closingVisit(t); } protected void accept_FirstSecondAndThirdChild_v_v_ForthChild(GroovySourceAST t) { GroovySourceAST child1 = (GroovySourceAST) t.getFirstChild(); if (child1 != null) { accept(child1); GroovySourceAST child2 = (GroovySourceAST) child1.getNextSibling(); if (child2 != null) { accept(child2); GroovySourceAST child3 = (GroovySourceAST) child2.getNextSibling(); if (child3 != null) { accept(child3); openingVisit(t); GroovySourceAST child4 = (GroovySourceAST) child3.getNextSibling(); if (child4 != null) { subsequentVisit(t); accept(child4); } } } } } protected void accept_v_FirstChild_2ndv_SecondChild_v___LastChild_v(GroovySourceAST t) { openingVisit(t); GroovySourceAST child = (GroovySourceAST) t.getFirstChild(); if (child != null) { accept(child); GroovySourceAST sibling = (GroovySourceAST) child.getNextSibling(); if (sibling != null) { secondVisit(t); accept(sibling); sibling = (GroovySourceAST) sibling.getNextSibling(); while (sibling != null) { subsequentVisit(t); accept(sibling); sibling = (GroovySourceAST) sibling.getNextSibling(); } } } closingVisit(t); } protected void accept_v_FirstChild_v_SecondChild_v___LastChild_v(GroovySourceAST t) { openingVisit(t); GroovySourceAST child = (GroovySourceAST) t.getFirstChild(); if (child != null) { accept(child); GroovySourceAST sibling = (GroovySourceAST) child.getNextSibling(); while (sibling != null) { subsequentVisit(t); accept(sibling); sibling = (GroovySourceAST) sibling.getNextSibling(); } } closingVisit(t); } protected void accept_v_FirstChild_v(GroovySourceAST t) { openingVisit(t); accept(t.childAt(0)); closingVisit(t); } protected void accept_v_Siblings_v(GroovySourceAST t) { openingVisit(t); acceptSiblings(t); closingVisit(t); } protected void accept_v_AllChildren_v_Siblings(GroovySourceAST t) { openingVisit(t); acceptChildren(t); closingVisit(t); acceptSiblings(t); } protected void accept_v_AllChildren_v(GroovySourceAST t) { openingVisit(t); acceptChildren(t); closingVisit(t); } protected void accept_FirstChild_v_RestOfTheChildren(GroovySourceAST t) { accept(t.childAt(0)); openingVisit(t); closingVisit(t); acceptSiblings(t.childAt(0)); } protected void accept_FirstChild_v_RestOfTheChildren_v_LastChild(GroovySourceAST t) { int count = 0; accept(t.childAt(0)); count++; openingVisit(t); if (t.childAt(0) != null) { GroovySourceAST sibling = (GroovySourceAST) t.childAt(0).getNextSibling(); while (sibling != null) { if (count == t.getNumberOfChildren() - 1) { closingVisit(t); } accept(sibling); count++; sibling = (GroovySourceAST) sibling.getNextSibling(); } } } protected void accept_FirstChild_v_RestOfTheChildren_v(GroovySourceAST t) { accept(t.childAt(0)); openingVisit(t); acceptSiblings(t.childAt(0)); closingVisit(t); } protected void accept_v_FirstChild_v_RestOfTheChildren(GroovySourceAST t) { accept_v_FirstChild_v(t); acceptSiblings(t.childAt(0)); } protected void accept_v_FirstChild_v_RestOfTheChildren_v(GroovySourceAST t) { openingVisit(t); accept(t.childAt(0)); subsequentVisit(t); acceptSiblings(t.childAt(0)); closingVisit(t); } protected void acceptSiblings(GroovySourceAST t) { if (t != null) { GroovySourceAST sibling = (GroovySourceAST) t.getNextSibling(); while (sibling != null) { accept(sibling); sibling = (GroovySourceAST) sibling.getNextSibling(); } } } protected void acceptChildren(GroovySourceAST t) { if (t != null) { GroovySourceAST child = (GroovySourceAST) t.getFirstChild(); if (child != null) { accept(child); acceptSiblings(child); } } } protected void skip(GroovySourceAST expr) { unvisitedNodes.remove(expr); } protected void openingVisit(GroovySourceAST t) { unvisitedNodes.remove(t); int n = Visitor.OPENING_VISIT; visitNode(t, n); } protected void secondVisit(GroovySourceAST t) { int n = Visitor.SECOND_VISIT; visitNode(t, n); } protected void subsequentVisit(GroovySourceAST t) { int n = Visitor.SUBSEQUENT_VISIT; visitNode(t, n); } protected void closingVisit(GroovySourceAST t) { int n = Visitor.CLOSING_VISIT; visitNode(t, n); } public AST process(AST t) { GroovySourceAST node = (GroovySourceAST) t; // process each node in turn setUp(node); accept(node); acceptSiblings(node); tearDown(node); return null; } }
package io.katharsis.resource.internal; import static net.javacrumbs.jsonunit.fluent.JsonFluentAssert.assertThatJson; import java.io.IOException; import java.util.Arrays; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; import com.fasterxml.jackson.databind.ObjectWriter; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.node.ObjectNode; import io.katharsis.core.internal.jackson.JsonApiModuleBuilder; import io.katharsis.core.internal.resource.AnnotationResourceInformationBuilder; import io.katharsis.errorhandling.ErrorData; import io.katharsis.legacy.locator.SampleJsonServiceLocator; import io.katharsis.legacy.registry.ResourceRegistryBuilder; import io.katharsis.module.ModuleRegistry; import io.katharsis.resource.Document; import io.katharsis.resource.Relationship; import io.katharsis.resource.Resource; import io.katharsis.resource.ResourceIdentifier; import io.katharsis.resource.information.ResourceFieldNameTransformer; import io.katharsis.resource.information.ResourceInformationBuilder; import io.katharsis.resource.registry.ConstantServiceUrlProvider; import io.katharsis.resource.registry.ResourceRegistry; import io.katharsis.resource.registry.ResourceRegistryBuilderTest; import io.katharsis.resource.registry.ResourceRegistryTest; import io.katharsis.utils.Nullable; public class DocumentSerializerTest { private ObjectMapper objectMapper; private ObjectReader reader; private ObjectWriter writer; @Before public void setup() { ResourceInformationBuilder resourceInformationBuilder = new AnnotationResourceInformationBuilder(new ResourceFieldNameTransformer()); ResourceRegistryBuilder registryBuilder = new ResourceRegistryBuilder(new SampleJsonServiceLocator(), resourceInformationBuilder); ResourceRegistry resourceRegistry = registryBuilder.build(ResourceRegistryBuilderTest.TEST_MODELS_PACKAGE, new ModuleRegistry(), new ConstantServiceUrlProvider(ResourceRegistryTest.TEST_MODELS_URL)); objectMapper = new ObjectMapper(); objectMapper.registerModule(new JsonApiModuleBuilder().build(resourceRegistry, false)); objectMapper.enable(SerializationFeature.INDENT_OUTPUT); reader = objectMapper.reader().forType(Document.class); writer = objectMapper.writer(); } @Test public void testSingleResource() throws JsonProcessingException, IOException { Document doc = new Document(); Resource resource = new Resource(); resource.setId("2"); resource.setType("tasks"); resource.setAttribute("name", objectMapper.readTree("\"sample task\"")); doc.setData(Nullable.of((Object)resource)); String json = writer.writeValueAsString(doc); StringBuilder expected = new StringBuilder(); expected.append("{"); expected.append("\"data\" : {"); expected.append(" \"id\" : \"2\","); expected.append(" \"type\" : \"tasks\","); expected.append(" \"attributes\" : {"); expected.append(" \"name\" : \"sample task\""); expected.append(" }"); expected.append(" }"); expected.append("}"); expected.append("}"); assertThatJson(json).describedAs(expected.toString()); Document readDoc = reader.readValue(json); Assert.assertEquals(doc, readDoc); } @Test public void testInformation() throws JsonProcessingException, IOException { Document doc = new Document(); doc.setMeta((ObjectNode) objectMapper.readTree("{\"metaName\" : \"metaValue\"}")); doc.setLinks((ObjectNode) objectMapper.readTree("{\"linkName\" : \"linkValue\"}")); String json = writer.writeValueAsString(doc); StringBuilder expected = new StringBuilder(); expected.append("{"); expected.append(" 'meta' : {'metaName' = 'metaValue'},"); expected.append(" 'links' : {'linkName' = 'linkValue'}"); expected.append("}"); assertThatJson(json).describedAs(expected.toString().replace('\'', '\"')); Document readDoc = reader.readValue(json); Assert.assertEquals(doc, readDoc); } @Test public void testErrors() throws JsonProcessingException, IOException { Document doc = new Document(); ErrorData error = ErrorData.builder().setCode("test").build(); doc.setErrors(Arrays.asList(error)); String json = writer.writeValueAsString(doc); StringBuilder expected = new StringBuilder(); expected.append("{"); expected.append(" 'errors' : ["); expected.append(" '{"); expected.append(" 'code' = 'test'"); expected.append(" '}"); expected.append(" ]"); expected.append("}"); assertThatJson(json).describedAs(expected.toString().replace('\'', '\"')); Document readDoc = reader.readValue(json); Assert.assertEquals(doc, readDoc); } @Test public void testSingleValuedRelationship() throws JsonProcessingException, IOException { Document doc = new Document(); Resource resource = new Resource(); resource.setId("2"); resource.setType("tasks"); Relationship relationship = new Relationship(); relationship.setData(Nullable.of((Object) new ResourceIdentifier("3", "projects"))); relationship.setMeta((ObjectNode) objectMapper.readTree("{\"metaName\" : \"metaValue\"}")); relationship.setLinks((ObjectNode) objectMapper.readTree("{\"linkName\" : \"linkValue\"}")); resource.getRelationships().put("project", relationship); doc.setData(Nullable.of((Object)resource)); String json = writer.writeValueAsString(doc); StringBuilder expected = new StringBuilder(); expected.append("{"); expected.append("'data' : {"); expected.append(" 'id' : '2',"); expected.append(" 'type' : 'tasks',"); expected.append(" 'relationships' : {"); expected.append(" 'project' : {"); expected.append(" 'data' : {'id' = '3', 'type' = 'projects'},"); expected.append(" 'meta' : {'metaName' = 'metaValue'},"); expected.append(" 'links' : {'linkName' = 'linkValue'}"); expected.append(" }"); expected.append(" }"); expected.append("}"); expected.append("}"); assertThatJson(json).describedAs(expected.toString().replace('\'', '\"')); Document readDoc = reader.readValue(json); Relationship readRelationship = readDoc.getSingleData().get().getRelationships().get("project"); Assert.assertEquals(relationship, readRelationship); Assert.assertEquals(doc, readDoc); } @Test public void testNoRelationshipData() throws JsonProcessingException, IOException { Document doc = new Document(); Resource resource = new Resource(); resource.setId("2"); resource.setType("tasks"); Relationship relationship = new Relationship(); relationship.setMeta((ObjectNode) objectMapper.readTree("{\"metaName\" : \"metaValue\"}")); relationship.setLinks((ObjectNode) objectMapper.readTree("{\"linkName\" : \"linkValue\"}")); resource.getRelationships().put("project", relationship); doc.setData(Nullable.of((Object)resource)); String json = writer.writeValueAsString(doc); StringBuilder expected = new StringBuilder(); expected.append("{"); expected.append("'data' : {"); expected.append(" 'id' : '2',"); expected.append(" 'type' : 'tasks',"); expected.append(" 'relationships' : {"); expected.append(" 'project' : {"); expected.append(" 'meta' : {'metaName' = 'metaValue'},"); expected.append(" 'links' : {'linkName' = 'linkValue'}"); expected.append(" }"); expected.append(" }"); expected.append("}"); expected.append("}"); assertThatJson(json).describedAs(expected.toString().replace('\'', '\"')); Document readDoc = reader.readValue(json); Relationship readRelationship = readDoc.getSingleData().get().getRelationships().get("project"); Assert.assertEquals(relationship, readRelationship); Assert.assertEquals(doc, readDoc); } @Test public void testNullRelationshipData() throws JsonProcessingException, IOException { Document doc = new Document(); Resource resource = new Resource(); resource.setId("2"); resource.setType("tasks"); Relationship relationship = new Relationship(); relationship.setData(Nullable.of(null)); relationship.setMeta((ObjectNode) objectMapper.readTree("{\"metaName\" : \"metaValue\"}")); relationship.setLinks((ObjectNode) objectMapper.readTree("{\"linkName\" : \"linkValue\"}")); resource.getRelationships().put("project", relationship); doc.setData(Nullable.of((Object)resource)); String json = writer.writeValueAsString(doc); StringBuilder expected = new StringBuilder(); expected.append("{"); expected.append("'data' : {"); expected.append(" 'id' : '2',"); expected.append(" 'type' : 'tasks',"); expected.append(" 'relationships' : {"); expected.append(" 'project' : {"); expected.append(" 'meta' : {'metaName' = 'metaValue'},"); expected.append(" 'links' : {'linkName' = 'linkValue'}"); expected.append(" }"); expected.append(" }"); expected.append("}"); expected.append("}"); assertThatJson(json).describedAs(expected.toString().replace('\'', '\"')); Document readDoc = reader.readValue(json); Relationship readRelationship = readDoc.getSingleData().get().getRelationships().get("project"); Assert.assertEquals(relationship, readRelationship); Assert.assertEquals(doc, readDoc); } @Test public void testMultiValuedRelationship() throws JsonProcessingException, IOException { Relationship relationship = new Relationship(); relationship.setData(Nullable.of((Object) Arrays.asList(new ResourceIdentifier("3", "projects"), new ResourceIdentifier("4", "projects")))); relationship.setMeta((ObjectNode) objectMapper.readTree("{\"metaName\" : \"metaValue\"}")); relationship.setLinks((ObjectNode) objectMapper.readTree("{\"linkName\" : \"linkValue\"}")); String json = writer.writeValueAsString(relationship); StringBuilder expected = new StringBuilder(); expected.append("{"); expected.append(" 'project' : ["); expected.append(" {"); expected.append(" 'data' : [{'id' = '3', 'type' = 'projects'}, {'id' = '4', 'type' = 'projects'}],"); expected.append(" 'meta' : {'metaName' = 'metaValue'},"); expected.append(" 'links' : {'linkName' = 'linkValue'}"); expected.append(" }"); expected.append(" ]"); expected.append("}"); assertThatJson(json).describedAs(expected.toString().replace('\'', '\"')); Relationship readRelationship = objectMapper.reader().forType(Relationship.class).readValue(json); Assert.assertEquals(relationship, readRelationship); } @Test public void testMultipleResources() throws JsonProcessingException, IOException { Document doc = new Document(); Resource resource1 = new Resource(); resource1.setId("1"); resource1.setType("tasks"); resource1.setAttribute("name", objectMapper.readTree("\"sample task11\"")); Resource resource2 = new Resource(); resource2.setId("2"); resource2.setType("tasks"); resource2.setAttribute("name", objectMapper.readTree("\"sample task2\"")); doc.setData(Nullable.of((Object)Arrays.asList(resource1, resource2))); String json = writer.writeValueAsString(doc); StringBuilder expected = new StringBuilder(); expected.append("{"); expected.append("\"data\" : ["); expected.append(" {"); expected.append(" \"id\" : \"1\","); expected.append(" \"type\" : \"tasks\","); expected.append(" \"attributes\" : {"); expected.append(" \"name\" : \"sample task1\""); expected.append(" }"); expected.append(" }"); expected.append(" }"); expected.append(" {"); expected.append(" \"id\" : \"2\","); expected.append(" \"type\" : \"tasks\","); expected.append(" \"attributes\" : {"); expected.append(" \"name\" : \"sample task2\""); expected.append(" }"); expected.append(" }"); expected.append(" }"); expected.append(" ]"); expected.append("}"); assertThatJson(json).describedAs(expected.toString()); Document readDoc = reader.readValue(json); Assert.assertEquals(doc, readDoc); } @Test public void testIncludes() throws JsonProcessingException, IOException { Document doc = new Document(); Resource resource1 = new Resource(); resource1.setId("1"); resource1.setType("tasks"); resource1.setAttribute("name", objectMapper.readTree("\"sample task11\"")); Resource resource2 = new Resource(); resource2.setId("2"); resource2.setType("tasks"); resource2.setAttribute("name", objectMapper.readTree("\"sample task2\"")); doc.setIncluded(Arrays.asList(resource1, resource2)); String json = writer.writeValueAsString(doc); StringBuilder expected = new StringBuilder(); expected.append("{"); expected.append("\"includes\" : ["); expected.append(" {"); expected.append(" \"id\" : \"1\","); expected.append(" \"type\" : \"tasks\","); expected.append(" \"attributes\" : {"); expected.append(" \"name\" : \"sample task1\""); expected.append(" }"); expected.append(" }"); expected.append(" }"); expected.append(" {"); expected.append(" \"id\" : \"2\","); expected.append(" \"type\" : \"tasks\","); expected.append(" \"attributes\" : {"); expected.append(" \"name\" : \"sample task2\""); expected.append(" }"); expected.append(" }"); expected.append(" }"); expected.append(" ]"); expected.append("}"); assertThatJson(json).describedAs(expected.toString()); Document readDoc = reader.readValue(json); Assert.assertEquals(doc, readDoc); } }
/* * Copyright (c) 2011 The Broad Institute * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.broadinstitute.sting.gatk.walkers.variantrecalibration; import org.broadinstitute.sting.commandline.Argument; import org.broadinstitute.sting.commandline.Input; import org.broadinstitute.sting.commandline.Output; import org.broadinstitute.sting.commandline.RodBinding; import org.broadinstitute.sting.gatk.contexts.AlignmentContext; import org.broadinstitute.sting.gatk.contexts.ReferenceContext; import org.broadinstitute.sting.gatk.refdata.RefMetaDataTracker; import org.broadinstitute.sting.gatk.walkers.PartitionBy; import org.broadinstitute.sting.gatk.walkers.PartitionType; import org.broadinstitute.sting.gatk.walkers.RodWalker; import org.broadinstitute.sting.utils.SampleUtils; import org.broadinstitute.sting.utils.codecs.vcf.*; import org.broadinstitute.sting.utils.collections.NestedHashMap; import org.broadinstitute.sting.utils.exceptions.UserException; import org.broadinstitute.sting.utils.text.XReadLines; import org.broadinstitute.sting.utils.variantcontext.VariantContext; import org.broadinstitute.sting.utils.variantcontext.VariantContextBuilder; import java.io.File; import java.io.FileNotFoundException; import java.util.*; /** * Applies cuts to the input vcf file (by adding filter lines) to achieve the desired novel truth sensitivity levels which were specified during VariantRecalibration * * <p> * Using the tranche file generated by the previous step the ApplyRecalibration walker looks at each variant's VQSLOD value * and decides which tranche it falls in. Variants in tranches that fall below the specified truth sensitivity filter level * have their filter field annotated with its tranche level. This will result in a call set that simultaneously is filtered * to the desired level but also has the information necessary to pull out more variants for a higher sensitivity but a * slightly lower quality level. * * <p> * See <a href="http://www.broadinstitute.org/gsa/wiki/index.php/Variant_quality_score_recalibration">the GATK wiki for a tutorial and example recalibration accuracy plots.</a> * * <h2>Input</h2> * <p> * The input raw variants to be recalibrated. * <p> * The recalibration table file in CSV format that was generated by the VariantRecalibrator walker. * <p> * The tranches file that was generated by the VariantRecalibrator walker. * * <h2>Output</h2> * <p> * A recalibrated VCF file in which each variant is annotated with its VQSLOD and filtered if the score is below the desired quality level. * * <h2>Examples</h2> * <pre> * java -Xmx3g -jar GenomeAnalysisTK.jar \ * -T ApplyRecalibration \ * -R reference/human_g1k_v37.fasta \ * -input NA12878.HiSeq.WGS.bwa.cleaned.raw.subset.b37.vcf \ * --ts_filter_level 99.0 \ * -tranchesFile path/to/output.tranches \ * -recalFile path/to/output.recal \ * -o path/to/output.recalibrated.filtered.vcf * </pre> * */ @PartitionBy(PartitionType.NONE) public class ApplyRecalibration extends RodWalker<Integer, Integer> { ///////////////////////////// // Inputs ///////////////////////////// /** * These calls should be unfiltered and annotated with the error covariates that are intended to use for modeling. */ @Input(fullName="input", shortName = "input", doc="The raw input variants to be recalibrated", required=true) public List<RodBinding<VariantContext>> input; @Input(fullName="recal_file", shortName="recalFile", doc="The input recal file used by ApplyRecalibration", required=true) private File RECAL_FILE; @Input(fullName="tranches_file", shortName="tranchesFile", doc="The input tranches file describing where to cut the data", required=true) private File TRANCHES_FILE; ///////////////////////////// // Outputs ///////////////////////////// @Output( doc="The output filtered and recalibrated VCF file in which each variant is annotated with its VQSLOD value", required=true) private VCFWriter vcfWriter = null; ///////////////////////////// // Command Line Arguments ///////////////////////////// @Argument(fullName="ts_filter_level", shortName="ts_filter_level", doc="The truth sensitivity level at which to start filtering", required=false) private double TS_FILTER_LEVEL = 99.0; @Argument(fullName="ignore_filter", shortName="ignoreFilter", doc="If specified the variant recalibrator will use variants even if the specified filter name is marked in the input VCF file", required=false) private String[] IGNORE_INPUT_FILTERS = null; @Argument(fullName = "mode", shortName = "mode", doc = "Recalibration mode to employ: 1.) SNP for recalibrating only SNPs (emitting indels untouched in the output VCF); 2.) INDEL for indels; and 3.) BOTH for recalibrating both SNPs and indels simultaneously.", required = false) public VariantRecalibratorArgumentCollection.Mode MODE = VariantRecalibratorArgumentCollection.Mode.SNP; ///////////////////////////// // Private Member Variables ///////////////////////////// final private List<Tranche> tranches = new ArrayList<Tranche>(); final private Set<String> inputNames = new HashSet<String>(); final private NestedHashMap lodMap = new NestedHashMap(); final private NestedHashMap annotationMap = new NestedHashMap(); final private Set<String> ignoreInputFilterSet = new TreeSet<String>(); //--------------------------------------------------------------------------------------------------------------- // // initialize // //--------------------------------------------------------------------------------------------------------------- public void initialize() { for ( final Tranche t : Tranche.readTranches(TRANCHES_FILE) ) { if ( t.ts >= TS_FILTER_LEVEL ) { tranches.add(t); } logger.info(String.format("Read tranche " + t)); } Collections.reverse(tranches); // this algorithm wants the tranches ordered from best (lowest truth sensitivity) to worst (highest truth sensitivity) for( final RodBinding rod : input ) { inputNames.add( rod.getName() ); } if( IGNORE_INPUT_FILTERS != null ) { ignoreInputFilterSet.addAll( Arrays.asList(IGNORE_INPUT_FILTERS) ); } // setup the header fields final Set<VCFHeaderLine> hInfo = new HashSet<VCFHeaderLine>(); hInfo.addAll(VCFUtils.getHeaderFields(getToolkit(), inputNames)); hInfo.add(new VCFInfoHeaderLine(VariantRecalibrator.VQS_LOD_KEY, 1, VCFHeaderLineType.Float, "Log odds ratio of being a true variant versus being false under the trained gaussian mixture model")); hInfo.add(new VCFInfoHeaderLine(VariantRecalibrator.CULPRIT_KEY, 1, VCFHeaderLineType.String, "The annotation which was the worst performing in the Gaussian mixture model, likely the reason why the variant was filtered out")); final TreeSet<String> samples = new TreeSet<String>(); samples.addAll(SampleUtils.getUniqueSamplesFromRods(getToolkit(), inputNames)); if( tranches.size() >= 2 ) { for( int iii = 0; iii < tranches.size() - 1; iii++ ) { final Tranche t = tranches.get(iii); hInfo.add(new VCFFilterHeaderLine(t.name, String.format("Truth sensitivity tranche level at VSQ Lod: " + t.minVQSLod + " <= x < " + tranches.get(iii+1).minVQSLod))); } } if( tranches.size() >= 1 ) { hInfo.add(new VCFFilterHeaderLine(tranches.get(0).name + "+", String.format("Truth sensitivity tranche level at VQS Lod < " + tranches.get(0).minVQSLod))); } else { throw new UserException("No tranches were found in the file or were above the truth sensitivity filter level " + TS_FILTER_LEVEL); } logger.info("Keeping all variants in tranche " + tranches.get(tranches.size()-1)); final VCFHeader vcfHeader = new VCFHeader(hInfo, samples); vcfWriter.writeHeader(vcfHeader); try { logger.info("Reading in recalibration table..."); for ( final String line : new XReadLines( RECAL_FILE ) ) { final String[] vals = line.split(","); lodMap.put( Double.parseDouble(vals[3]), vals[0], Integer.parseInt(vals[1]), Integer.parseInt(vals[2]) ); // value comes before the keys annotationMap.put( vals[4], vals[0], Integer.parseInt(vals[1]), Integer.parseInt(vals[2]) ); // value comes before the keys } } catch ( FileNotFoundException e ) { throw new UserException.CouldNotReadInputFile(RECAL_FILE, e); } catch ( Exception e ) { throw new UserException.MalformedFile(RECAL_FILE, "Could not parse LOD and annotation information in input recal file. File is somehow malformed."); } } //--------------------------------------------------------------------------------------------------------------- // // map // //--------------------------------------------------------------------------------------------------------------- public Integer map( RefMetaDataTracker tracker, ReferenceContext ref, AlignmentContext context ) { if( tracker == null ) { // For some reason RodWalkers get map calls with null trackers return 1; } for( VariantContext vc : tracker.getValues(input, context.getLocation()) ) { if( vc != null ) { if( VariantRecalibrator.checkRecalibrationMode( vc, MODE ) && (vc.isNotFiltered() || ignoreInputFilterSet.containsAll(vc.getFilters())) ) { VariantContextBuilder builder = new VariantContextBuilder(vc); String filterString = null; final Double lod = (Double) lodMap.get( vc.getChr(), vc.getStart(), vc.getEnd() ); final String worstAnnotation = (String) annotationMap.get( vc.getChr(), vc.getStart(), vc.getEnd() ); if( lod == null ) { throw new UserException("Encountered input variant which isn't found in the input recal file. Please make sure VariantRecalibrator and ApplyRecalibration were run on the same set of input variants. First seen at: " + vc ); } // Annotate the new record with its VQSLOD and the worst performing annotation builder.attribute(VariantRecalibrator.VQS_LOD_KEY, String.format("%.4f", lod)); builder.attribute(VariantRecalibrator.CULPRIT_KEY, worstAnnotation); for( int i = tranches.size() - 1; i >= 0; i-- ) { final Tranche tranche = tranches.get(i); if( lod >= tranche.minVQSLod ) { if( i == tranches.size() - 1 ) { filterString = VCFConstants.PASSES_FILTERS_v4; } else { filterString = tranche.name; } break; } } if( filterString == null ) { filterString = tranches.get(0).name+"+"; } if( !filterString.equals(VCFConstants.PASSES_FILTERS_v4) ) { builder.filters(filterString); } vcfWriter.add( builder.make() ); } else { // valid VC but not compatible with this mode, so just emit the variant untouched vcfWriter.add( vc ); } } } return 1; // This value isn't used for anything } //--------------------------------------------------------------------------------------------------------------- // // reduce // //--------------------------------------------------------------------------------------------------------------- public Integer reduceInit() { return 1; // This value isn't used for anything } public Integer reduce( final Integer mapValue, final Integer reduceSum ) { return 1; // This value isn't used for anything } public void onTraversalDone( final Integer reduceSum ) { } }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2012.06.29 at 10:15:17 AM BST // package org.w3._1999.xhtml; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElements; import javax.xml.bind.annotation.XmlID; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;choice> * &lt;choice maxOccurs="unbounded"> * &lt;group ref="{http://www.w3.org/1999/xhtml}block"/> * &lt;element ref="{http://www.w3.org/1999/xhtml}form"/> * &lt;group ref="{http://www.w3.org/1999/xhtml}misc"/> * &lt;/choice> * &lt;element ref="{http://www.w3.org/1999/xhtml}area" maxOccurs="unbounded"/> * &lt;/choice> * &lt;attGroup ref="{http://www.w3.org/1999/xhtml}i18n"/> * &lt;attGroup ref="{http://www.w3.org/1999/xhtml}events"/> * &lt;attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}ID" /> * &lt;attribute name="class" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" /> * &lt;attribute name="style" type="{http://www.w3.org/1999/xhtml}StyleSheet" /> * &lt;attribute name="title" type="{http://www.w3.org/1999/xhtml}Text" /> * &lt;attribute name="name" type="{http://www.w3.org/2001/XMLSchema}NMTOKEN" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "pOrH1OrH2", "area" }) @XmlRootElement(name = "map") public class Map { @XmlElements({ @XmlElement(name = "fieldset", type = Fieldset.class), @XmlElement(name = "h4", type = H4 .class), @XmlElement(name = "div", type = Div.class), @XmlElement(name = "dl", type = Dl.class), @XmlElement(name = "ul", type = Ul.class), @XmlElement(name = "script", type = Script.class), @XmlElement(name = "h3", type = H3 .class), @XmlElement(name = "hr", type = Hr.class), @XmlElement(name = "noscript", type = Noscript.class), @XmlElement(name = "address", type = Address.class), @XmlElement(name = "ins", type = Ins.class), @XmlElement(name = "blockquote", type = Blockquote.class), @XmlElement(name = "h2", type = H2 .class), @XmlElement(name = "h5", type = H5 .class), @XmlElement(name = "h6", type = H6 .class), @XmlElement(name = "del", type = Del.class), @XmlElement(name = "ol", type = Ol.class), @XmlElement(name = "pre", type = Pre.class), @XmlElement(name = "form", type = Form.class), @XmlElement(name = "h1", type = H1 .class), @XmlElement(name = "table", type = Table.class), @XmlElement(name = "p", type = P.class) }) protected List<java.lang.Object> pOrH1OrH2; protected List<Area> area; @XmlAttribute(required = true) @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID @XmlSchemaType(name = "ID") protected String id; @XmlAttribute(name = "class") @XmlSchemaType(name = "anySimpleType") protected String clazz; @XmlAttribute protected String style; @XmlAttribute protected String title; @XmlAttribute @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "NMTOKEN") protected String name; @XmlAttribute(name = "lang") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) protected String langCode; @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") protected String lang; @XmlAttribute @XmlJavaTypeAdapter(CollapsedStringAdapter.class) protected String dir; @XmlAttribute protected String onclick; @XmlAttribute protected String ondblclick; @XmlAttribute protected String onmousedown; @XmlAttribute protected String onmouseup; @XmlAttribute protected String onmouseover; @XmlAttribute protected String onmousemove; @XmlAttribute protected String onmouseout; @XmlAttribute protected String onkeypress; @XmlAttribute protected String onkeydown; @XmlAttribute protected String onkeyup; /** * Gets the value of the pOrH1OrH2 property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the pOrH1OrH2 property. * * <p> * For example, to add a new item, do as follows: * <pre> * getPOrH1OrH2().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Fieldset } * {@link H4 } * {@link Div } * {@link Dl } * {@link Ul } * {@link Script } * {@link H3 } * {@link Hr } * {@link Noscript } * {@link Address } * {@link Ins } * {@link Blockquote } * {@link H2 } * {@link H5 } * {@link H6 } * {@link Del } * {@link Ol } * {@link Pre } * {@link Form } * {@link H1 } * {@link Table } * {@link P } * * */ public List<java.lang.Object> getPOrH1OrH2() { if (pOrH1OrH2 == null) { pOrH1OrH2 = new ArrayList<java.lang.Object>(); } return this.pOrH1OrH2; } /** * Gets the value of the area property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the area property. * * <p> * For example, to add a new item, do as follows: * <pre> * getArea().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Area } * * */ public List<Area> getArea() { if (area == null) { area = new ArrayList<Area>(); } return this.area; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the clazz property. * * @return * possible object is * {@link String } * */ public String getClazz() { return clazz; } /** * Sets the value of the clazz property. * * @param value * allowed object is * {@link String } * */ public void setClazz(String value) { this.clazz = value; } /** * Gets the value of the style property. * * @return * possible object is * {@link String } * */ public String getStyle() { return style; } /** * Sets the value of the style property. * * @param value * allowed object is * {@link String } * */ public void setStyle(String value) { this.style = value; } /** * Gets the value of the title property. * * @return * possible object is * {@link String } * */ public String getTitle() { return title; } /** * Sets the value of the title property. * * @param value * allowed object is * {@link String } * */ public void setTitle(String value) { this.title = value; } /** * Gets the value of the name property. * * @return * possible object is * {@link String } * */ public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } /** * Gets the value of the langCode property. * * @return * possible object is * {@link String } * */ public String getLangCode() { return langCode; } /** * Sets the value of the langCode property. * * @param value * allowed object is * {@link String } * */ public void setLangCode(String value) { this.langCode = value; } /** * Gets the value of the lang property. * * @return * possible object is * {@link String } * */ public String getLang() { return lang; } /** * Sets the value of the lang property. * * @param value * allowed object is * {@link String } * */ public void setLang(String value) { this.lang = value; } /** * Gets the value of the dir property. * * @return * possible object is * {@link String } * */ public String getDir() { return dir; } /** * Sets the value of the dir property. * * @param value * allowed object is * {@link String } * */ public void setDir(String value) { this.dir = value; } /** * Gets the value of the onclick property. * * @return * possible object is * {@link String } * */ public String getOnclick() { return onclick; } /** * Sets the value of the onclick property. * * @param value * allowed object is * {@link String } * */ public void setOnclick(String value) { this.onclick = value; } /** * Gets the value of the ondblclick property. * * @return * possible object is * {@link String } * */ public String getOndblclick() { return ondblclick; } /** * Sets the value of the ondblclick property. * * @param value * allowed object is * {@link String } * */ public void setOndblclick(String value) { this.ondblclick = value; } /** * Gets the value of the onmousedown property. * * @return * possible object is * {@link String } * */ public String getOnmousedown() { return onmousedown; } /** * Sets the value of the onmousedown property. * * @param value * allowed object is * {@link String } * */ public void setOnmousedown(String value) { this.onmousedown = value; } /** * Gets the value of the onmouseup property. * * @return * possible object is * {@link String } * */ public String getOnmouseup() { return onmouseup; } /** * Sets the value of the onmouseup property. * * @param value * allowed object is * {@link String } * */ public void setOnmouseup(String value) { this.onmouseup = value; } /** * Gets the value of the onmouseover property. * * @return * possible object is * {@link String } * */ public String getOnmouseover() { return onmouseover; } /** * Sets the value of the onmouseover property. * * @param value * allowed object is * {@link String } * */ public void setOnmouseover(String value) { this.onmouseover = value; } /** * Gets the value of the onmousemove property. * * @return * possible object is * {@link String } * */ public String getOnmousemove() { return onmousemove; } /** * Sets the value of the onmousemove property. * * @param value * allowed object is * {@link String } * */ public void setOnmousemove(String value) { this.onmousemove = value; } /** * Gets the value of the onmouseout property. * * @return * possible object is * {@link String } * */ public String getOnmouseout() { return onmouseout; } /** * Sets the value of the onmouseout property. * * @param value * allowed object is * {@link String } * */ public void setOnmouseout(String value) { this.onmouseout = value; } /** * Gets the value of the onkeypress property. * * @return * possible object is * {@link String } * */ public String getOnkeypress() { return onkeypress; } /** * Sets the value of the onkeypress property. * * @param value * allowed object is * {@link String } * */ public void setOnkeypress(String value) { this.onkeypress = value; } /** * Gets the value of the onkeydown property. * * @return * possible object is * {@link String } * */ public String getOnkeydown() { return onkeydown; } /** * Sets the value of the onkeydown property. * * @param value * allowed object is * {@link String } * */ public void setOnkeydown(String value) { this.onkeydown = value; } /** * Gets the value of the onkeyup property. * * @return * possible object is * {@link String } * */ public String getOnkeyup() { return onkeyup; } /** * Sets the value of the onkeyup property. * * @param value * allowed object is * {@link String } * */ public void setOnkeyup(String value) { this.onkeyup = value; } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v9/services/keyword_plan_service.proto package com.google.ads.googleads.v9.services; /** * <pre> * A keyword historical metrics. * </pre> * * Protobuf type {@code google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics} */ public final class KeywordPlanKeywordHistoricalMetrics extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics) KeywordPlanKeywordHistoricalMetricsOrBuilder { private static final long serialVersionUID = 0L; // Use KeywordPlanKeywordHistoricalMetrics.newBuilder() to construct. private KeywordPlanKeywordHistoricalMetrics(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private KeywordPlanKeywordHistoricalMetrics() { searchQuery_ = ""; closeVariants_ = com.google.protobuf.LazyStringArrayList.EMPTY; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new KeywordPlanKeywordHistoricalMetrics(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private KeywordPlanKeywordHistoricalMetrics( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 18: { com.google.ads.googleads.v9.common.KeywordPlanHistoricalMetrics.Builder subBuilder = null; if (keywordMetrics_ != null) { subBuilder = keywordMetrics_.toBuilder(); } keywordMetrics_ = input.readMessage(com.google.ads.googleads.v9.common.KeywordPlanHistoricalMetrics.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(keywordMetrics_); keywordMetrics_ = subBuilder.buildPartial(); } break; } case 26: { java.lang.String s = input.readStringRequireUtf8(); if (!((mutable_bitField0_ & 0x00000002) != 0)) { closeVariants_ = new com.google.protobuf.LazyStringArrayList(); mutable_bitField0_ |= 0x00000002; } closeVariants_.add(s); break; } case 34: { java.lang.String s = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; searchQuery_ = s; break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000002) != 0)) { closeVariants_ = closeVariants_.getUnmodifiableView(); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v9.services.KeywordPlanServiceProto.internal_static_google_ads_googleads_v9_services_KeywordPlanKeywordHistoricalMetrics_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v9.services.KeywordPlanServiceProto.internal_static_google_ads_googleads_v9_services_KeywordPlanKeywordHistoricalMetrics_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics.class, com.google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics.Builder.class); } private int bitField0_; public static final int SEARCH_QUERY_FIELD_NUMBER = 4; private volatile java.lang.Object searchQuery_; /** * <pre> * The text of the query associated with one or more ad_group_keywords in the * plan. * Note that we de-dupe your keywords list, eliminating close variants before * returning the plan's keywords as text. For example, if your plan originally * contained the keywords 'car' and 'cars', the returned search query will * only contain 'cars'. * Starting V5, the list of de-duped queries will be included in * close_variants field. * </pre> * * <code>optional string search_query = 4;</code> * @return Whether the searchQuery field is set. */ @java.lang.Override public boolean hasSearchQuery() { return ((bitField0_ & 0x00000001) != 0); } /** * <pre> * The text of the query associated with one or more ad_group_keywords in the * plan. * Note that we de-dupe your keywords list, eliminating close variants before * returning the plan's keywords as text. For example, if your plan originally * contained the keywords 'car' and 'cars', the returned search query will * only contain 'cars'. * Starting V5, the list of de-duped queries will be included in * close_variants field. * </pre> * * <code>optional string search_query = 4;</code> * @return The searchQuery. */ @java.lang.Override public java.lang.String getSearchQuery() { java.lang.Object ref = searchQuery_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); searchQuery_ = s; return s; } } /** * <pre> * The text of the query associated with one or more ad_group_keywords in the * plan. * Note that we de-dupe your keywords list, eliminating close variants before * returning the plan's keywords as text. For example, if your plan originally * contained the keywords 'car' and 'cars', the returned search query will * only contain 'cars'. * Starting V5, the list of de-duped queries will be included in * close_variants field. * </pre> * * <code>optional string search_query = 4;</code> * @return The bytes for searchQuery. */ @java.lang.Override public com.google.protobuf.ByteString getSearchQueryBytes() { java.lang.Object ref = searchQuery_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); searchQuery_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int CLOSE_VARIANTS_FIELD_NUMBER = 3; private com.google.protobuf.LazyStringList closeVariants_; /** * <pre> * The list of close variant queries for search_query whose search results * are combined into the search_query. * </pre> * * <code>repeated string close_variants = 3;</code> * @return A list containing the closeVariants. */ public com.google.protobuf.ProtocolStringList getCloseVariantsList() { return closeVariants_; } /** * <pre> * The list of close variant queries for search_query whose search results * are combined into the search_query. * </pre> * * <code>repeated string close_variants = 3;</code> * @return The count of closeVariants. */ public int getCloseVariantsCount() { return closeVariants_.size(); } /** * <pre> * The list of close variant queries for search_query whose search results * are combined into the search_query. * </pre> * * <code>repeated string close_variants = 3;</code> * @param index The index of the element to return. * @return The closeVariants at the given index. */ public java.lang.String getCloseVariants(int index) { return closeVariants_.get(index); } /** * <pre> * The list of close variant queries for search_query whose search results * are combined into the search_query. * </pre> * * <code>repeated string close_variants = 3;</code> * @param index The index of the value to return. * @return The bytes of the closeVariants at the given index. */ public com.google.protobuf.ByteString getCloseVariantsBytes(int index) { return closeVariants_.getByteString(index); } public static final int KEYWORD_METRICS_FIELD_NUMBER = 2; private com.google.ads.googleads.v9.common.KeywordPlanHistoricalMetrics keywordMetrics_; /** * <pre> * The historical metrics for the query associated with one or more * ad_group_keywords in the plan. * </pre> * * <code>.google.ads.googleads.v9.common.KeywordPlanHistoricalMetrics keyword_metrics = 2;</code> * @return Whether the keywordMetrics field is set. */ @java.lang.Override public boolean hasKeywordMetrics() { return keywordMetrics_ != null; } /** * <pre> * The historical metrics for the query associated with one or more * ad_group_keywords in the plan. * </pre> * * <code>.google.ads.googleads.v9.common.KeywordPlanHistoricalMetrics keyword_metrics = 2;</code> * @return The keywordMetrics. */ @java.lang.Override public com.google.ads.googleads.v9.common.KeywordPlanHistoricalMetrics getKeywordMetrics() { return keywordMetrics_ == null ? com.google.ads.googleads.v9.common.KeywordPlanHistoricalMetrics.getDefaultInstance() : keywordMetrics_; } /** * <pre> * The historical metrics for the query associated with one or more * ad_group_keywords in the plan. * </pre> * * <code>.google.ads.googleads.v9.common.KeywordPlanHistoricalMetrics keyword_metrics = 2;</code> */ @java.lang.Override public com.google.ads.googleads.v9.common.KeywordPlanHistoricalMetricsOrBuilder getKeywordMetricsOrBuilder() { return getKeywordMetrics(); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (keywordMetrics_ != null) { output.writeMessage(2, getKeywordMetrics()); } for (int i = 0; i < closeVariants_.size(); i++) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, closeVariants_.getRaw(i)); } if (((bitField0_ & 0x00000001) != 0)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 4, searchQuery_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (keywordMetrics_ != null) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(2, getKeywordMetrics()); } { int dataSize = 0; for (int i = 0; i < closeVariants_.size(); i++) { dataSize += computeStringSizeNoTag(closeVariants_.getRaw(i)); } size += dataSize; size += 1 * getCloseVariantsList().size(); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, searchQuery_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics)) { return super.equals(obj); } com.google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics other = (com.google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics) obj; if (hasSearchQuery() != other.hasSearchQuery()) return false; if (hasSearchQuery()) { if (!getSearchQuery() .equals(other.getSearchQuery())) return false; } if (!getCloseVariantsList() .equals(other.getCloseVariantsList())) return false; if (hasKeywordMetrics() != other.hasKeywordMetrics()) return false; if (hasKeywordMetrics()) { if (!getKeywordMetrics() .equals(other.getKeywordMetrics())) return false; } if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasSearchQuery()) { hash = (37 * hash) + SEARCH_QUERY_FIELD_NUMBER; hash = (53 * hash) + getSearchQuery().hashCode(); } if (getCloseVariantsCount() > 0) { hash = (37 * hash) + CLOSE_VARIANTS_FIELD_NUMBER; hash = (53 * hash) + getCloseVariantsList().hashCode(); } if (hasKeywordMetrics()) { hash = (37 * hash) + KEYWORD_METRICS_FIELD_NUMBER; hash = (53 * hash) + getKeywordMetrics().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * A keyword historical metrics. * </pre> * * Protobuf type {@code google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics) com.google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetricsOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v9.services.KeywordPlanServiceProto.internal_static_google_ads_googleads_v9_services_KeywordPlanKeywordHistoricalMetrics_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v9.services.KeywordPlanServiceProto.internal_static_google_ads_googleads_v9_services_KeywordPlanKeywordHistoricalMetrics_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics.class, com.google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics.Builder.class); } // Construct using com.google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); searchQuery_ = ""; bitField0_ = (bitField0_ & ~0x00000001); closeVariants_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000002); if (keywordMetricsBuilder_ == null) { keywordMetrics_ = null; } else { keywordMetrics_ = null; keywordMetricsBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v9.services.KeywordPlanServiceProto.internal_static_google_ads_googleads_v9_services_KeywordPlanKeywordHistoricalMetrics_descriptor; } @java.lang.Override public com.google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics getDefaultInstanceForType() { return com.google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics build() { com.google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics buildPartial() { com.google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics result = new com.google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { to_bitField0_ |= 0x00000001; } result.searchQuery_ = searchQuery_; if (((bitField0_ & 0x00000002) != 0)) { closeVariants_ = closeVariants_.getUnmodifiableView(); bitField0_ = (bitField0_ & ~0x00000002); } result.closeVariants_ = closeVariants_; if (keywordMetricsBuilder_ == null) { result.keywordMetrics_ = keywordMetrics_; } else { result.keywordMetrics_ = keywordMetricsBuilder_.build(); } result.bitField0_ = to_bitField0_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics) { return mergeFrom((com.google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics other) { if (other == com.google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics.getDefaultInstance()) return this; if (other.hasSearchQuery()) { bitField0_ |= 0x00000001; searchQuery_ = other.searchQuery_; onChanged(); } if (!other.closeVariants_.isEmpty()) { if (closeVariants_.isEmpty()) { closeVariants_ = other.closeVariants_; bitField0_ = (bitField0_ & ~0x00000002); } else { ensureCloseVariantsIsMutable(); closeVariants_.addAll(other.closeVariants_); } onChanged(); } if (other.hasKeywordMetrics()) { mergeKeywordMetrics(other.getKeywordMetrics()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.lang.Object searchQuery_ = ""; /** * <pre> * The text of the query associated with one or more ad_group_keywords in the * plan. * Note that we de-dupe your keywords list, eliminating close variants before * returning the plan's keywords as text. For example, if your plan originally * contained the keywords 'car' and 'cars', the returned search query will * only contain 'cars'. * Starting V5, the list of de-duped queries will be included in * close_variants field. * </pre> * * <code>optional string search_query = 4;</code> * @return Whether the searchQuery field is set. */ public boolean hasSearchQuery() { return ((bitField0_ & 0x00000001) != 0); } /** * <pre> * The text of the query associated with one or more ad_group_keywords in the * plan. * Note that we de-dupe your keywords list, eliminating close variants before * returning the plan's keywords as text. For example, if your plan originally * contained the keywords 'car' and 'cars', the returned search query will * only contain 'cars'. * Starting V5, the list of de-duped queries will be included in * close_variants field. * </pre> * * <code>optional string search_query = 4;</code> * @return The searchQuery. */ public java.lang.String getSearchQuery() { java.lang.Object ref = searchQuery_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); searchQuery_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * The text of the query associated with one or more ad_group_keywords in the * plan. * Note that we de-dupe your keywords list, eliminating close variants before * returning the plan's keywords as text. For example, if your plan originally * contained the keywords 'car' and 'cars', the returned search query will * only contain 'cars'. * Starting V5, the list of de-duped queries will be included in * close_variants field. * </pre> * * <code>optional string search_query = 4;</code> * @return The bytes for searchQuery. */ public com.google.protobuf.ByteString getSearchQueryBytes() { java.lang.Object ref = searchQuery_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); searchQuery_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * The text of the query associated with one or more ad_group_keywords in the * plan. * Note that we de-dupe your keywords list, eliminating close variants before * returning the plan's keywords as text. For example, if your plan originally * contained the keywords 'car' and 'cars', the returned search query will * only contain 'cars'. * Starting V5, the list of de-duped queries will be included in * close_variants field. * </pre> * * <code>optional string search_query = 4;</code> * @param value The searchQuery to set. * @return This builder for chaining. */ public Builder setSearchQuery( java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; searchQuery_ = value; onChanged(); return this; } /** * <pre> * The text of the query associated with one or more ad_group_keywords in the * plan. * Note that we de-dupe your keywords list, eliminating close variants before * returning the plan's keywords as text. For example, if your plan originally * contained the keywords 'car' and 'cars', the returned search query will * only contain 'cars'. * Starting V5, the list of de-duped queries will be included in * close_variants field. * </pre> * * <code>optional string search_query = 4;</code> * @return This builder for chaining. */ public Builder clearSearchQuery() { bitField0_ = (bitField0_ & ~0x00000001); searchQuery_ = getDefaultInstance().getSearchQuery(); onChanged(); return this; } /** * <pre> * The text of the query associated with one or more ad_group_keywords in the * plan. * Note that we de-dupe your keywords list, eliminating close variants before * returning the plan's keywords as text. For example, if your plan originally * contained the keywords 'car' and 'cars', the returned search query will * only contain 'cars'. * Starting V5, the list of de-duped queries will be included in * close_variants field. * </pre> * * <code>optional string search_query = 4;</code> * @param value The bytes for searchQuery to set. * @return This builder for chaining. */ public Builder setSearchQueryBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); bitField0_ |= 0x00000001; searchQuery_ = value; onChanged(); return this; } private com.google.protobuf.LazyStringList closeVariants_ = com.google.protobuf.LazyStringArrayList.EMPTY; private void ensureCloseVariantsIsMutable() { if (!((bitField0_ & 0x00000002) != 0)) { closeVariants_ = new com.google.protobuf.LazyStringArrayList(closeVariants_); bitField0_ |= 0x00000002; } } /** * <pre> * The list of close variant queries for search_query whose search results * are combined into the search_query. * </pre> * * <code>repeated string close_variants = 3;</code> * @return A list containing the closeVariants. */ public com.google.protobuf.ProtocolStringList getCloseVariantsList() { return closeVariants_.getUnmodifiableView(); } /** * <pre> * The list of close variant queries for search_query whose search results * are combined into the search_query. * </pre> * * <code>repeated string close_variants = 3;</code> * @return The count of closeVariants. */ public int getCloseVariantsCount() { return closeVariants_.size(); } /** * <pre> * The list of close variant queries for search_query whose search results * are combined into the search_query. * </pre> * * <code>repeated string close_variants = 3;</code> * @param index The index of the element to return. * @return The closeVariants at the given index. */ public java.lang.String getCloseVariants(int index) { return closeVariants_.get(index); } /** * <pre> * The list of close variant queries for search_query whose search results * are combined into the search_query. * </pre> * * <code>repeated string close_variants = 3;</code> * @param index The index of the value to return. * @return The bytes of the closeVariants at the given index. */ public com.google.protobuf.ByteString getCloseVariantsBytes(int index) { return closeVariants_.getByteString(index); } /** * <pre> * The list of close variant queries for search_query whose search results * are combined into the search_query. * </pre> * * <code>repeated string close_variants = 3;</code> * @param index The index to set the value at. * @param value The closeVariants to set. * @return This builder for chaining. */ public Builder setCloseVariants( int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureCloseVariantsIsMutable(); closeVariants_.set(index, value); onChanged(); return this; } /** * <pre> * The list of close variant queries for search_query whose search results * are combined into the search_query. * </pre> * * <code>repeated string close_variants = 3;</code> * @param value The closeVariants to add. * @return This builder for chaining. */ public Builder addCloseVariants( java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureCloseVariantsIsMutable(); closeVariants_.add(value); onChanged(); return this; } /** * <pre> * The list of close variant queries for search_query whose search results * are combined into the search_query. * </pre> * * <code>repeated string close_variants = 3;</code> * @param values The closeVariants to add. * @return This builder for chaining. */ public Builder addAllCloseVariants( java.lang.Iterable<java.lang.String> values) { ensureCloseVariantsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, closeVariants_); onChanged(); return this; } /** * <pre> * The list of close variant queries for search_query whose search results * are combined into the search_query. * </pre> * * <code>repeated string close_variants = 3;</code> * @return This builder for chaining. */ public Builder clearCloseVariants() { closeVariants_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * <pre> * The list of close variant queries for search_query whose search results * are combined into the search_query. * </pre> * * <code>repeated string close_variants = 3;</code> * @param value The bytes of the closeVariants to add. * @return This builder for chaining. */ public Builder addCloseVariantsBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensureCloseVariantsIsMutable(); closeVariants_.add(value); onChanged(); return this; } private com.google.ads.googleads.v9.common.KeywordPlanHistoricalMetrics keywordMetrics_; private com.google.protobuf.SingleFieldBuilderV3< com.google.ads.googleads.v9.common.KeywordPlanHistoricalMetrics, com.google.ads.googleads.v9.common.KeywordPlanHistoricalMetrics.Builder, com.google.ads.googleads.v9.common.KeywordPlanHistoricalMetricsOrBuilder> keywordMetricsBuilder_; /** * <pre> * The historical metrics for the query associated with one or more * ad_group_keywords in the plan. * </pre> * * <code>.google.ads.googleads.v9.common.KeywordPlanHistoricalMetrics keyword_metrics = 2;</code> * @return Whether the keywordMetrics field is set. */ public boolean hasKeywordMetrics() { return keywordMetricsBuilder_ != null || keywordMetrics_ != null; } /** * <pre> * The historical metrics for the query associated with one or more * ad_group_keywords in the plan. * </pre> * * <code>.google.ads.googleads.v9.common.KeywordPlanHistoricalMetrics keyword_metrics = 2;</code> * @return The keywordMetrics. */ public com.google.ads.googleads.v9.common.KeywordPlanHistoricalMetrics getKeywordMetrics() { if (keywordMetricsBuilder_ == null) { return keywordMetrics_ == null ? com.google.ads.googleads.v9.common.KeywordPlanHistoricalMetrics.getDefaultInstance() : keywordMetrics_; } else { return keywordMetricsBuilder_.getMessage(); } } /** * <pre> * The historical metrics for the query associated with one or more * ad_group_keywords in the plan. * </pre> * * <code>.google.ads.googleads.v9.common.KeywordPlanHistoricalMetrics keyword_metrics = 2;</code> */ public Builder setKeywordMetrics(com.google.ads.googleads.v9.common.KeywordPlanHistoricalMetrics value) { if (keywordMetricsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } keywordMetrics_ = value; onChanged(); } else { keywordMetricsBuilder_.setMessage(value); } return this; } /** * <pre> * The historical metrics for the query associated with one or more * ad_group_keywords in the plan. * </pre> * * <code>.google.ads.googleads.v9.common.KeywordPlanHistoricalMetrics keyword_metrics = 2;</code> */ public Builder setKeywordMetrics( com.google.ads.googleads.v9.common.KeywordPlanHistoricalMetrics.Builder builderForValue) { if (keywordMetricsBuilder_ == null) { keywordMetrics_ = builderForValue.build(); onChanged(); } else { keywordMetricsBuilder_.setMessage(builderForValue.build()); } return this; } /** * <pre> * The historical metrics for the query associated with one or more * ad_group_keywords in the plan. * </pre> * * <code>.google.ads.googleads.v9.common.KeywordPlanHistoricalMetrics keyword_metrics = 2;</code> */ public Builder mergeKeywordMetrics(com.google.ads.googleads.v9.common.KeywordPlanHistoricalMetrics value) { if (keywordMetricsBuilder_ == null) { if (keywordMetrics_ != null) { keywordMetrics_ = com.google.ads.googleads.v9.common.KeywordPlanHistoricalMetrics.newBuilder(keywordMetrics_).mergeFrom(value).buildPartial(); } else { keywordMetrics_ = value; } onChanged(); } else { keywordMetricsBuilder_.mergeFrom(value); } return this; } /** * <pre> * The historical metrics for the query associated with one or more * ad_group_keywords in the plan. * </pre> * * <code>.google.ads.googleads.v9.common.KeywordPlanHistoricalMetrics keyword_metrics = 2;</code> */ public Builder clearKeywordMetrics() { if (keywordMetricsBuilder_ == null) { keywordMetrics_ = null; onChanged(); } else { keywordMetrics_ = null; keywordMetricsBuilder_ = null; } return this; } /** * <pre> * The historical metrics for the query associated with one or more * ad_group_keywords in the plan. * </pre> * * <code>.google.ads.googleads.v9.common.KeywordPlanHistoricalMetrics keyword_metrics = 2;</code> */ public com.google.ads.googleads.v9.common.KeywordPlanHistoricalMetrics.Builder getKeywordMetricsBuilder() { onChanged(); return getKeywordMetricsFieldBuilder().getBuilder(); } /** * <pre> * The historical metrics for the query associated with one or more * ad_group_keywords in the plan. * </pre> * * <code>.google.ads.googleads.v9.common.KeywordPlanHistoricalMetrics keyword_metrics = 2;</code> */ public com.google.ads.googleads.v9.common.KeywordPlanHistoricalMetricsOrBuilder getKeywordMetricsOrBuilder() { if (keywordMetricsBuilder_ != null) { return keywordMetricsBuilder_.getMessageOrBuilder(); } else { return keywordMetrics_ == null ? com.google.ads.googleads.v9.common.KeywordPlanHistoricalMetrics.getDefaultInstance() : keywordMetrics_; } } /** * <pre> * The historical metrics for the query associated with one or more * ad_group_keywords in the plan. * </pre> * * <code>.google.ads.googleads.v9.common.KeywordPlanHistoricalMetrics keyword_metrics = 2;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.ads.googleads.v9.common.KeywordPlanHistoricalMetrics, com.google.ads.googleads.v9.common.KeywordPlanHistoricalMetrics.Builder, com.google.ads.googleads.v9.common.KeywordPlanHistoricalMetricsOrBuilder> getKeywordMetricsFieldBuilder() { if (keywordMetricsBuilder_ == null) { keywordMetricsBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.ads.googleads.v9.common.KeywordPlanHistoricalMetrics, com.google.ads.googleads.v9.common.KeywordPlanHistoricalMetrics.Builder, com.google.ads.googleads.v9.common.KeywordPlanHistoricalMetricsOrBuilder>( getKeywordMetrics(), getParentForChildren(), isClean()); keywordMetrics_ = null; } return keywordMetricsBuilder_; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics) private static final com.google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics(); } public static com.google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<KeywordPlanKeywordHistoricalMetrics> PARSER = new com.google.protobuf.AbstractParser<KeywordPlanKeywordHistoricalMetrics>() { @java.lang.Override public KeywordPlanKeywordHistoricalMetrics parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new KeywordPlanKeywordHistoricalMetrics(input, extensionRegistry); } }; public static com.google.protobuf.Parser<KeywordPlanKeywordHistoricalMetrics> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<KeywordPlanKeywordHistoricalMetrics> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v9.services.KeywordPlanKeywordHistoricalMetrics getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
/* * Copyright (c) 2004-2014, KNOPFLERFISH project * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * - Neither the name of the KNOPFLERFISH project nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.knopflerfish.bundle.framework_test; import java.io.PrintStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Dictionary; import java.util.Hashtable; import junit.framework.TestSuite; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleException; import org.osgi.framework.ServiceReference; public class NativeCodeTestSuite extends TestSuite { BundleContext bc; Bundle buN; String test_url_base; PrintStream out = System.out; public NativeCodeTestSuite(BundleContext bc) { super ("NativeCodeTestSuite"); this.bc = bc; test_url_base = "bundle://" + bc.getBundle().getBundleId() + "/"; addTest(new Setup()); // addTest(new Frame0135a()); addTest(new Frame0137a()); addTest(new Frame0138a()); addTest(new Frame0139a()); addTest(new Cleanup()); } // Also install all possible listeners public class Setup extends FWTestCase { public String getDescription() { return "This does some error handling tests of bundles with native code"; } public void runTest() throws Throwable { out.println("### framework test bundle :SETUP:PASS"); } } class Cleanup extends FWTestCase { public void runTest() throws Throwable { Bundle[] bundles = new Bundle[] { buN , }; for(int i = 0; i < bundles.length; i++) { try { bundles[i].uninstall(); } catch (Exception ignored) { } } buN = null; } } // 27. Install testbundle N (with native code ) // and call its test method, which should return Hello world // The name of the test bundle .jar file to load is made from // a concatenation of the strings // bundleN-<processor>-<osname>[-<osversion>][-<language>]_test.jar class Frame0135a extends FWTestCase { public void runTest() throws Throwable { Dictionary opts = new Hashtable(); String processor = (String) opts.get("processor"); String osname = (String) opts.get("osname"); String osversion = (String) opts.get("osversion"); String language = (String) opts.get("language"); // at present only the processor and osname are used StringBuffer b1 = new StringBuffer(test_url_base+"bundleN-"+ processor + "-" + osname); // if (osversion != null) { b1.append("-"+osversion); } if (language != null) { b1.append("-"+language); } b1.append("_test_all-1.0.0.jar"); String jarName = b1.toString(); // out.println("NATIVE " + jarName); // out.flush(); boolean teststatus = true; try { buN = Util.installBundle (bc, jarName); buN.start(); } catch (BundleException bex) { out.println("framework test bundle "+ bex +" :FRAME135:FAIL"); Throwable tx = bex.getNestedException(); if (tx != null) { out.println("framework test bundle, nested exception "+ tx +" :FRAME135:FAIL"); } teststatus = false; } catch (SecurityException sec) { out.println("framework test bundle "+ sec +" :FRAME135A:FAIL"); teststatus = false; } if (teststatus == true) { // Get the service reference and a service from the native bundle ServiceReference srnative = bc.getServiceReference("org.knopflerfish.service.nativetest.NativeTest"); if (srnative != null) { @SuppressWarnings("unchecked") Object o = bc.getService(srnative); if (o != null) { // now for some reflection exercises String expectedString = "Hello world"; String nativeString = null; Method m; Class<? extends Object> c; Class parameters[]; // out.println("servref = "+ sr); // out.println("object = "+ obj1); Object[] arguments = new Object[0]; parameters = new Class[0]; c = o.getClass(); try { m = c.getMethod("getString", parameters); nativeString = (String) m.invoke(o, arguments); if (!expectedString.equals(nativeString)) { out.println("Frame test native bundle method failed, expected: " + expectedString + " got: " + nativeString + ":FRAME135A:FAIL"); teststatus = false; } } catch (IllegalAccessException ia) { out.println("Frame test IllegaleAccessException" + ia + ":FRAME135A:FAIL"); teststatus = false; } catch (InvocationTargetException ita) { out.println("Frame test InvocationTargetException" + ita); out.println("Frame test nested InvocationTargetException" + ita.getTargetException() + ":FRAME135A:FAIL"); teststatus = false; } catch (NoSuchMethodException nme) { out.println("Frame test NoSuchMethodException" + nme + ":FRAME135A:FAIL"); teststatus = false; } } else { out.println("framework test bundle, failed to get service for org.knopflerfish.service.nativetest.NativeTest :FRAME135A:FAIL"); teststatus = false; } } else { out.println("framework test bundle, failed to get service reference for org.knopflerfish.service.nativetest.NativeTest :FRAME135A:FAIL"); teststatus = false; } } if (teststatus == true && buN.getState() == Bundle.ACTIVE) { out.println("### framework test bundle :FRAME135A:PASS"); } else { out.println("### framework test bundle :FRAME135A:FAIL"); } } } // Install testbundle N1 & N2 (with faulty native code headers) // class Frame0137a extends FWTestCase { public void runTest() throws Throwable { try { buN = Util.installBundle (bc, "bundleN1_test-1.0.0.jar"); buN.start(); fail("framework faulty native test bundle N1 should not resolve :FRAME137:FAIL"); } catch (BundleException bex) { // Expected bundle exception } catch (Exception e) { e.printStackTrace(); fail("framework test bundle N1, unexpected "+ e +" :FRAME137A:FAIL"); } try { buN = Util.installBundle (bc, "bundleN2_test-1.0.0.jar"); buN.start(); fail("framework faulty native test bundle N2 should not resolve :FRAME137:FAIL"); } catch (BundleException bex) { // Expected bundle exception } catch (Exception e) { e.printStackTrace(); fail("framework test bundle N2, unexpected "+ e +" :FRAME137A:FAIL"); } out.println("### framework test bundle :FRAME137A:PASS"); } } // Install testbundle N3 and fragments N4+N5 and check that only N5 fragment is attached. // class Frame0138a extends FWTestCase { public void runTest() throws Throwable { Bundle buN4 = null; Bundle buN5 = null; try { buN = Util.installBundle (bc, "bundleN3_test-1.0.0.jar"); buN4 = Util.installBundle (bc, "bundleN4_test-1.0.0.jar"); buN5 = Util.installBundle (bc, "bundleN5_test-1.0.0.jar"); buN.start(); assertEquals("Unmatched fragment not resolved", Bundle.INSTALLED, buN4.getState()); assertEquals("Matched fragment resolved", Bundle.RESOLVED, buN5.getState()); } catch (Exception e) { e.printStackTrace(); fail("framework test bundle N3, unexpected "+ e +" :FRAME138A:FAIL"); } finally { if (buN4 != null) { buN4.uninstall(); } if (buN5 != null) { buN5.uninstall(); } } out.println("### framework test bundle :FRAME138A:PASS"); } } // Install testbundle N3 with arm processor and match with arm_le framework // class Frame0139a extends FWTestCase { public void runTest() throws Throwable { try { buN = Util.installBundle (bc, "bundleN3_test-1.0.0.jar"); buN.start(); } catch (Exception e) { e.printStackTrace(); fail("framework test bundle N3, unexpected "+ e +" :FRAME139A:FAIL"); } out.println("### framework test bundle :FRAME139A:PASS"); } } }
/* * Copyright (C) 2013 salesforce.com, 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.auraframework.integration.test.http; import org.apache.http.HttpHeaders; import org.auraframework.def.ApplicationDef; import org.auraframework.def.DefDescriptor; import org.auraframework.def.SVGDef; import org.auraframework.http.AuraResourceRewriteFilter; import org.auraframework.http.AuraResourceServlet; import org.auraframework.service.CachingService; import org.auraframework.service.ContextService; import org.auraframework.service.DefinitionService; import org.auraframework.system.AuraContext; import org.auraframework.system.AuraContext.Mode; import org.auraframework.system.SourceListener; import org.auraframework.test.util.AuraTestCase; import org.auraframework.test.util.DummyHttpServletRequest; import org.auraframework.test.util.DummyHttpServletResponse; import org.auraframework.util.test.annotation.ThreadHostileTest; import org.auraframework.util.test.annotation.UnAdaptableTest; import org.junit.Ignore; import org.junit.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockHttpSession; import javax.inject.Inject; import javax.servlet.http.HttpServletResponse; import java.util.List; /** * Simple (non-integration) test case for {@link AuraResourceServlet}, most useful for exercising hard-to-reach error * conditions. I would like this test to be in the "aura" module (vice "aura-impl"), but the configuration there isn't * friendly to getting a context service, and I think changing that may impact other tests, so I'm leaving it at least * for now. */ public class AuraResourceServletTest extends AuraTestCase { @Inject DefinitionService definitionService; @Inject ContextService contextService; @Inject CachingService cachingService; public static class SimulatedErrorException extends RuntimeException { private static final long serialVersionUID = 411181168049748986L; } private AuraResourceServlet getAuraResourceServlet() throws Exception { AuraResourceServlet servlet = new AuraResourceServlet(); applicationContext.getAutowireCapableBeanFactory().autowireBean(servlet); return servlet; } private String getKey(String uid, DefDescriptor<?> descriptor, String key) { return String.format("%s@%s@%s", uid, descriptor.getQualifiedName().toLowerCase(), key); } /** * Verify cache of SVG definitions is cleared on source change in DEV mode. */ @UnAdaptableTest("W-2929438") @Test @Ignore("The cache is sometimes wrong here") @ThreadHostileTest("depends on cache state") public void testSvgCacheClearedOnSourceChange() throws Exception { DefDescriptor<ApplicationDef> appDesc = definitionService.getDefDescriptor("appCache:withpreload", ApplicationDef.class); AuraContext context = contextService .startContext(Mode.DEV, AuraContext.Format.SVG, AuraContext.Authentication.AUTHENTICATED, appDesc); DefDescriptor<SVGDef> svgDesc = definitionService.getDefinition(appDesc).getSVGDefDescriptor(); final String uid = definitionService.getUid(null, svgDesc); context.addLoaded(appDesc, uid); DummyHttpServletRequest request = new DummyHttpServletRequest("resources.svg") { @Override public long getDateHeader(String name) { return -1; } }; request.setQueryParam(AuraResourceRewriteFilter.TYPE_PARAM, "svg"); HttpServletResponse response = new DummyHttpServletResponse(); AuraResourceServlet servlet = getAuraResourceServlet(); servlet.doGet(request, response); final String key = "SVG:" + context.getClient().getType() + "$" + uid; // Verify something was actually added to cache String svgCache = cachingService.getStringsCache().getIfPresent(getKey(uid, svgDesc, key)); assertNotNull("Nothing added to SVG cache", svgCache); // Now force a source change event and verify cache is emptied fileMonitor.onSourceChanged(SourceListener.SourceMonitorEvent.CHANGED, null); svgCache = cachingService.getStringsCache().getIfPresent(getKey(uid, svgDesc, key)); assertNull("SVG cache not cleared after source change event", svgCache); } /** * Verify SVG requests return a correct etag. */ @Test public void testSvgCacheUsesEtag() throws Exception { DefDescriptor<ApplicationDef> appDesc = definitionService.getDefDescriptor("markup://appCache:withpreload", ApplicationDef.class); AuraContext context = contextService.startContext( Mode.PROD, AuraContext.Format.SVG, AuraContext.Authentication.AUTHENTICATED, appDesc); DefDescriptor<SVGDef> svgDesc = definitionService.getDefinition(appDesc).getSVGDefDescriptor(); String etag = "\"" + definitionService.getDefinition(svgDesc).getOwnHash() + "\""; String uid = definitionService.getUid(null, svgDesc); context.addLoaded(appDesc, uid); MockHttpServletRequest mockRequest = new MockHttpServletRequest(null, "resources.svg"); mockRequest.setAttribute(AuraResourceServlet.ORIG_REQUEST_URI, "resources.svg"); mockRequest.addParameter(AuraResourceRewriteFilter.TYPE_PARAM, "svg"); //If referer is empty we assume the image is not viewed from within a webpage mockRequest.addHeader(HttpHeaders.REFERER, "ANotNullString"); mockRequest.setSession(new MockHttpSession()); MockHttpServletResponse mockResponse = new MockHttpServletResponse(); AuraResourceServlet servlet = getAuraResourceServlet(); servlet.doGet(mockRequest, mockResponse); List<String> headers = mockResponse.getHeaders(HttpHeaders.ETAG); assertTrue("Failed to find expected value in header: " + headers, headers.contains(etag)); // For etag to work properly, we need to "disable" the browser from caching it permanently. headers = mockResponse.getHeaders(HttpHeaders.CACHE_CONTROL); assertTrue("Failed to find expected value in header: " + headers, headers.contains("private,must-revalidate,max-age=0")); // If referer is not null, the image should be sent as a embedded image. // IE not an attachment. headers = mockResponse.getHeaders("Content-Disposition"); assertTrue(headers.isEmpty()); } /** * Verify SVG servlet returns 304 if etag's match. */ @Test public void testSvgReturns304() throws Exception { DefDescriptor<ApplicationDef> appDesc = definitionService.getDefDescriptor("markup://appCache:withpreload", ApplicationDef.class); AuraContext context = contextService.startContext( Mode.PROD, AuraContext.Format.SVG, AuraContext.Authentication.AUTHENTICATED, appDesc); //First we will go to the server with no etag. This will give us the etag to use for next step MockHttpServletRequest mockRequest = new MockHttpServletRequest(null, "resources.svg"); mockRequest.setSession(new MockHttpSession()); mockRequest.setAttribute(AuraResourceServlet.ORIG_REQUEST_URI, "resources.svg"); //If referer is empty we assume the image is not viewed from within a webpage mockRequest.addHeader(HttpHeaders.REFERER, "ANotNullString"); mockRequest.addParameter(AuraResourceRewriteFilter.TYPE_PARAM, "svg"); MockHttpServletResponse mockResponse = new MockHttpServletResponse(); AuraResourceServlet servlet = getAuraResourceServlet(); servlet.doGet(mockRequest, mockResponse); assertEquals(200, mockResponse.getStatus()); String etag = mockResponse.getHeader(HttpHeaders.ETAG); DefDescriptor<SVGDef> svgDesc = definitionService.getDefinition(appDesc).getSVGDefDescriptor(); String uid = definitionService.getUid(null, svgDesc); context.addLoaded(appDesc, uid); //Now that we have the etag from the first request, we will query with that etag mockRequest = new MockHttpServletRequest(null, "resources.svg"); mockRequest.setSession(new MockHttpSession()); mockRequest.setAttribute(AuraResourceServlet.ORIG_REQUEST_URI, "resources.svg"); mockRequest.addHeader(HttpHeaders.IF_NONE_MATCH, etag); //If referer is empty we assume the image is not viewed from within a webpage mockRequest.addHeader(HttpHeaders.REFERER, "ANotNullString"); mockRequest.addParameter(AuraResourceRewriteFilter.TYPE_PARAM, "svg"); servlet.doGet(mockRequest, mockResponse); assertEquals(304, mockResponse.getStatus()); } /** * Verify SVG servlet returns Content-Disposition = attachment; filename=resources.svg if referer header is null * This is to prevent any scripts hidden in the SVG from running on the local domain */ @Test public void testSvgNoReferer() throws Exception { DefDescriptor<ApplicationDef> appDesc = definitionService.getDefDescriptor("markup://appCache:withpreload", ApplicationDef.class); AuraContext context = contextService.startContext( Mode.PROD, AuraContext.Format.SVG, AuraContext.Authentication.AUTHENTICATED, appDesc); DefDescriptor<SVGDef> svgDesc = definitionService.getDefinition(appDesc).getSVGDefDescriptor(); String uid = definitionService.getUid(null, svgDesc); context.addLoaded(appDesc, uid); MockHttpServletRequest mockRequest = new MockHttpServletRequest(null, "resources.svg"); mockRequest.setAttribute(AuraResourceServlet.ORIG_REQUEST_URI, "resources.svg"); mockRequest.addParameter(AuraResourceRewriteFilter.TYPE_PARAM, "svg"); mockRequest.setSession(new MockHttpSession()); MockHttpServletResponse mockResponse = new MockHttpServletResponse(); AuraResourceServlet servlet = getAuraResourceServlet(); servlet.doGet(mockRequest, mockResponse); List<String> headers = mockResponse.getHeaders("Content-Disposition"); assertFalse("Failed to find any header for Content-Disposition", headers.isEmpty()); assertTrue(headers.contains("attachment; filename=resources.svg")); } }
/* * Copyright 2000-2013 Vaadin Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.vaadin.netbeans.customizer; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.util.Calendar; import java.util.Date; import java.util.prefs.Preferences; import org.openide.util.NbPreferences; /** * @author denis */ public final class VaadinConfiguration { public static final String JETTY = "jetty"; // NOI18N public static final String CODE_COMPLETION = "add-on-cc"; // NOI18N public static final String STATISTICS = "statistics"; // NOI18N public static final String TIMEOUT = "timeout"; // NOI18N public static final String CONFIRM_FREE_ADD_ON = "confirmFreeAddOn"; // NOI18N public static final String VERSIONS_STRATEGY = "versions-strategy"; // NOI18N public static final String INDEX_STRATEGY = "index-strategy"; // NOI18N public static final String REST_STRATEGY = "rest-strategy"; // NOI18N private static final String LAST_VERSIONS_UPDATE = "last-versions"; // NOI18N private static final String LAST_INDEX_UPDATE = "last-index"; // NOI18N private static final String LAST_REST_UPDATE = "last-rest"; // NOI18N private static final String PREFIX_LENGTH = "prefix"; // NOI18N private static final VaadinConfiguration INSTANCE = new VaadinConfiguration(); private VaadinConfiguration() { mySupport = new PropertyChangeSupport(this); } public static VaadinConfiguration getInstance() { return INSTANCE; } public int getCCPrefixLength() { int prefix; synchronized (getPreferences()) { prefix = getPreferences().getInt(PREFIX_LENGTH, 3); } return prefix >= 2 ? prefix : 2; } public void setCCPrefixLength( int minLength ) { int length; synchronized (getPreferences()) { length = getCCPrefixLength(); getPreferences().putInt(PREFIX_LENGTH, minLength); } fireEvent(PREFIX_LENGTH, length, minLength); } public void enableJetty( boolean enable ) { boolean jettyEnabled; synchronized (getPreferences()) { jettyEnabled = isJettyEnabled(); getPreferences().putBoolean(JETTY, enable); } fireEvent(JETTY, jettyEnabled, enable); } public boolean isJettyEnabled() { synchronized (getPreferences()) { return getPreferences().getBoolean(JETTY, true); } } public void enableAddonCodeCompletion( boolean enable ) { boolean isEnabled; synchronized (getPreferences()) { isEnabled = isAddonCodeCompletionEnabled(); getPreferences().putBoolean(CODE_COMPLETION, enable); } fireEvent(CODE_COMPLETION, isEnabled, enable); } public boolean isAddonCodeCompletionEnabled() { synchronized (getPreferences()) { return getPreferences().getBoolean(CODE_COMPLETION, true); } } public void enableStatistics( boolean enable ) { boolean isEnabled; synchronized (getPreferences()) { isEnabled = isStatisticsEnabled(); getPreferences().putBoolean(STATISTICS, enable); } fireEvent(STATISTICS, isEnabled, enable); } public boolean isStatisticsEnabled() { synchronized (getPreferences()) { return getPreferences().getBoolean(STATISTICS, true); } } public void setTimeout( int timeout ) { int previous; synchronized (getPreferences()) { previous = getTimeout(); getPreferences().putInt(TIMEOUT, timeout); } fireEvent(TIMEOUT, previous, timeout); } public int getTimeout() { synchronized (getPreferences()) { return getPreferences().getInt(TIMEOUT, 20); } } public boolean freeAddonRequiresConfirmation() { synchronized (getPreferences()) { return getPreferences().getBoolean(CONFIRM_FREE_ADD_ON, true); } } public void setFreeAddonRequiresConfirmation( boolean askConfirmation ) { boolean freeConfirmation; synchronized (getPreferences()) { freeConfirmation = freeAddonRequiresConfirmation(); getPreferences().putBoolean(CONFIRM_FREE_ADD_ON, askConfirmation); } fireEvent(CONFIRM_FREE_ADD_ON, freeConfirmation, askConfirmation); } public void setVersionRequestStrategy( RemoteDataAccessStrategy versionStrategy ) { RemoteDataAccessStrategy strategy; synchronized (getPreferences()) { strategy = getVersionRequestStrategy(); getPreferences().put(VERSIONS_STRATEGY, versionStrategy.getCode()); } fireEvent(VERSIONS_STRATEGY, strategy, versionStrategy); } public RemoteDataAccessStrategy getVersionRequestStrategy() { String code; synchronized (getPreferences()) { code = getPreferences().get(VERSIONS_STRATEGY, RemoteDataAccessStrategy.PER_IDE_RUN.getCode()); } return RemoteDataAccessStrategy.forString(code); } public void setIndexRequestStrategy( RemoteDataAccessStrategy indexStrategy ) { RemoteDataAccessStrategy strategy; synchronized (getPreferences()) { strategy = getIndexRequestStrategy(); getPreferences().put(INDEX_STRATEGY, indexStrategy.getCode()); } fireEvent(INDEX_STRATEGY, strategy, indexStrategy); } public RemoteDataAccessStrategy getIndexRequestStrategy() { String code; synchronized (getPreferences()) { code = getPreferences().get(INDEX_STRATEGY, RemoteDataAccessStrategy.PER_IDE_RUN.getCode()); } return RemoteDataAccessStrategy.forString(code); } public void setDirectoryRequestStrategy( RemoteDataAccessStrategy directoryStrategy ) { RemoteDataAccessStrategy strategy; synchronized (getPreferences()) { strategy = getDirectoryRequestStrategy(); getPreferences().put(REST_STRATEGY, directoryStrategy.getCode()); } fireEvent(REST_STRATEGY, strategy, directoryStrategy); } public RemoteDataAccessStrategy getDirectoryRequestStrategy() { String code; synchronized (getPreferences()) { code = getPreferences().get(REST_STRATEGY, RemoteDataAccessStrategy.PER_IDE_RUN.getCode()); } return RemoteDataAccessStrategy.forString(code); } public Date getLastVersionsUpdate() { return getLastUpdate(LAST_VERSIONS_UPDATE); } public Date getLastIndexUpdate() { return getLastUpdate(LAST_INDEX_UPDATE); } public Date getLastDirectoryUpdate() { return getLastUpdate(LAST_REST_UPDATE); } public void setLastDirectoryUpdate( Date date ) { setLastUpdate(LAST_REST_UPDATE, date); } public void setLastIndexUpdate( Date date ) { setLastUpdate(LAST_INDEX_UPDATE, date); } public void setLastVersionUpdate( Date date ) { setLastUpdate(LAST_VERSIONS_UPDATE, date); } public static boolean requiresUpdate( RemoteDataAccessStrategy strategy, Date date ) { boolean requiresUpdate = false; Calendar calendar = Calendar.getInstance(); switch (strategy) { case PER_DAY: calendar.add(Calendar.DAY_OF_YEAR, -1); requiresUpdate = date.before(calendar.getTime()); break; case PER_WEEK: calendar.add(Calendar.WEEK_OF_YEAR, -1); requiresUpdate = date.before(calendar.getTime()); break; case PER_MONTH: calendar.add(Calendar.MONTH, -1); requiresUpdate = date.before(calendar.getTime()); break; default: break; } return requiresUpdate; } private Date getLastUpdate( String property ) { synchronized (getPreferences()) { long lastUpdate = getPreferences().getLong(property, -1); if (lastUpdate == -1) { return null; } Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(lastUpdate); return calendar.getTime(); } } private void setLastUpdate( String property, Date date ) { synchronized (getPreferences()) { if (date == null) { getPreferences().putLong(property, -1); } else { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); getPreferences().putLong(property, calendar.getTimeInMillis()); } } } public void addPropertyChangeListener( PropertyChangeListener listener ) { mySupport.addPropertyChangeListener(listener); } public void removePropertyChangeListener( PropertyChangeListener listener ) { mySupport.removePropertyChangeListener(listener); } private void fireEvent( String property, Object oldValue, Object newValue ) { mySupport.firePropertyChange(property, oldValue, newValue); } private Preferences getPreferences() { return NbPreferences.forModule(VaadinConfiguration.class); } private PropertyChangeSupport mySupport; }
package sourcecoded.quantum.item; import baubles.api.BaubleType; import baubles.api.IBauble; import net.minecraft.block.Block; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.inventory.IInventory; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipe; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.ChatComponentText; import net.minecraft.world.World; import net.minecraftforge.common.IExtendedEntityProperties; import sourcecoded.core.crafting.ICraftableItem; import sourcecoded.quantum.api.discovery.DiscoveryManager; import sourcecoded.quantum.api.translation.LocalizationUtils; import sourcecoded.quantum.api.vacuum.VacuumRegistry; import sourcecoded.quantum.crafting.vacuum.VacuumEnchantDeception; import sourcecoded.quantum.crafting.vacuum.VacuumEnchantRange; import sourcecoded.quantum.crafting.vacuum.VacuumMagnet; import sourcecoded.quantum.discovery.QADiscoveries; import sourcecoded.quantum.enchantment.EnchantmentDeception; import sourcecoded.quantum.entity.EntityItemMagnet; import sourcecoded.quantum.entity.properties.PropertiesItem; import sourcecoded.quantum.registry.QAEnchant; import java.util.ArrayList; import java.util.List; public class ItemRiftMagnet extends ItemQuantum implements IBauble, ICraftableItem { public ItemRiftMagnet() { this.setUnlocalizedName("itemRiftMagnet"); this.setTextureName("tools/magnet"); this.setHasSubtypes(true); } public boolean hasEffect(ItemStack stack, int pass) { return this.getDamage(stack) == 1; } public boolean hasCustomEntity(ItemStack stack) { return true; } public Entity createEntity(World world, Entity location, ItemStack itemstack) { return new EntityItemMagnet(world, location, itemstack); } public int getItemEnchantability() { return 22; } public boolean isItemTool(ItemStack par1ItemStack) { return true; } public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) { if (player.isSneaking()) { if (this.getDamage(stack) == 0) this.setDamage(stack, 1); else this.setDamage(stack, 0); } if (!world.isRemote) DiscoveryManager.unlockItem(QADiscoveries.Item.MAGNETISM.get().getKey(), player, false); return stack; } public boolean onItemUseFirst(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) { checkCompound(stack); TileEntity tile = world.getTileEntity(x, y, z); if (tile != null && tile instanceof IInventory) { ArrayList<ItemStack> stacks = new ArrayList<ItemStack>(); IInventory inv = (IInventory) tile; for (int i = 0; i < inv.getSizeInventory(); i++) { ItemStack c = inv.getStackInSlot(i); if (c != null) stacks.add(c); } boolean whitelist = player.isSneaking(); ArrayList<String> messages = new ArrayList<String>(); NBTTagList list = (NBTTagList) stack.stackTagCompound.getTag("blacklist"); if (list == null) list = new NBTTagList(); for (ItemStack cs : stacks) { boolean inTag = false; for (int i = 0; i < list.tagCount(); i++) { NBTTagCompound compound = list.getCompoundTagAt(i); if (compound.getString("id").equals(cs.getUnlocalizedName()) && compound.getInteger("dmg") == cs.getItemDamage()) { inTag = true; } } if (!inTag && !whitelist) { NBTTagCompound compound = new NBTTagCompound(); compound.setString("id", cs.getUnlocalizedName()); compound.setInteger("dmg", cs.getItemDamage()); messages.add(LocalizationUtils.translateLocalWithColours("qa.items.itemRiftMagnet.add", "Added Item To Blacklist: ") + " " + cs.getDisplayName() + " @ " + cs.getItemDamage()); list.appendTag(compound); } } stack.stackTagCompound.setTag("blacklist", list); for (String s : messages) { player.addChatComponentMessage(new ChatComponentText(s)); } return !world.isRemote && !whitelist; } return false; } public boolean onItemUse(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) { checkCompound(stack); TileEntity tile = world.getTileEntity(x, y, z); Block block = world.getBlock(x, y, z); if (block == Blocks.cauldron) { if (!world.isRemote) if (world.getBlockMetadata(x, y, z) > 0) { stack.stackTagCompound.removeTag("blacklist"); world.setBlockMetadataWithNotify(x, y, z, world.getBlockMetadata(x, y, z) - 1, 2); player.addChatComponentMessage(new ChatComponentText(LocalizationUtils.translateLocalWithColours("qa.items.itemRiftMagnet.clear", "Cleared the Blacklist!"))); } return world.isRemote; } if (tile != null && tile instanceof IInventory) { ArrayList<ItemStack> stacks = new ArrayList<ItemStack>(); IInventory inv = (IInventory) tile; for (int i = 0; i < inv.getSizeInventory(); i++) { ItemStack c = inv.getStackInSlot(i); if (c != null) stacks.add(c); } boolean whitelist = player.isSneaking(); ArrayList<String> messages = new ArrayList<String>(); NBTTagList list = (NBTTagList) stack.stackTagCompound.getTag("blacklist"); if (list == null) list = new NBTTagList(); for (ItemStack cs : stacks) { boolean inTag = false; for (int i = 0; i < list.tagCount(); i++) { NBTTagCompound compound = list.getCompoundTagAt(i); if (compound.getString("id").equals(cs.getUnlocalizedName()) && compound.getInteger("dmg") == cs.getItemDamage()) { if (whitelist) { list.removeTag(i); messages.add(LocalizationUtils.translateLocalWithColours("qa.items.itemRiftMagnet.remove", "Removed Item From Blacklist: ") + " " + cs.getDisplayName() + " @ " + cs.getItemDamage()); } inTag = true; } } } stack.stackTagCompound.setTag("blacklist", list); for (String s : messages) { player.addChatComponentMessage(new ChatComponentText(s)); } return world.isRemote; } return false; } public void checkCompound(ItemStack stack) { if (stack.stackTagCompound == null) stack.stackTagCompound = new NBTTagCompound(); } @SuppressWarnings("unchecked") public void onUpdate(ItemStack stack, World world, Entity p, int slot, boolean held) { checkCompound(stack); if (this.getDamage(stack) == 1 && !world.isRemote) { int rangeX = 8; int rangeY = 4; int ench = EnchantmentHelper.getEnchantmentLevel(QAEnchant.RANGE.get().effectId, stack); if (ench > 0) { rangeX += ench * 2; rangeY += ench; } List<EntityItem> items = world.getEntitiesWithinAABB(EntityItem.class, AxisAlignedBB.getBoundingBox(p.posX - rangeX, p.posY - rangeY, p.posZ - rangeY, p.posX + rangeX, p.posY + rangeY, p.posZ + rangeX)); itemLoop: for (EntityItem item : items) { IExtendedEntityProperties properties = item.getExtendedProperties("tossData"); if (properties != null) { PropertiesItem prop = (PropertiesItem) properties; if (p.getUniqueID().toString().equals(prop.tosser) && item.age <= 300) return; } NBTTagList list = (NBTTagList) stack.stackTagCompound.getTag("blacklist"); if (list != null) for (int i = 0; i < list.tagCount(); i++) { int dmg = list.getCompoundTagAt(i).getInteger("dmg"); String nm = list.getCompoundTagAt(i).getString("id"); if (item.getEntityItem().getUnlocalizedName().equals(nm) && item.getEntityItem().getItemDamage() == dmg) continue itemLoop; } item.delayBeforeCanPickup = 0; item.setPosition(p.posX, p.posY, p.posZ); } } } public void addInformation(ItemStack itemStack, EntityPlayer player, List list, boolean idk) { String formatted = "qa.items.itemRiftMagnet.lore.range"; String newForm = LocalizationUtils.translateLocalWithColours(formatted, formatted); int rangeX = 8; int rangeY = 4; int ench = EnchantmentHelper.getEnchantmentLevel(QAEnchant.RANGE.get().effectId, itemStack); if (ench > 0) { rangeX += ench * 2; rangeY += ench; } list.add(String.format(newForm, rangeX, rangeY)); } @Override public BaubleType getBaubleType(ItemStack itemstack) { return BaubleType.AMULET; } @Override public void onWornTick(ItemStack itemstack, EntityLivingBase player) { onUpdate(itemstack, player.worldObj, player, 0, false); } @Override public void onEquipped(ItemStack itemstack, EntityLivingBase player) { } @Override public void onUnequipped(ItemStack itemstack, EntityLivingBase player) { } @Override public boolean canEquip(ItemStack itemstack, EntityLivingBase player) { return true; } @Override public boolean canUnequip(ItemStack itemstack, EntityLivingBase player) { return true; } @Override public IRecipe[] getRecipes(Item item) { VacuumRegistry.addRecipe(new VacuumMagnet()); VacuumEnchantRange.registerAll(); VacuumEnchantDeception.registerAll(); return new IRecipe[0]; } }
/* * 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.presto.raptor.storage; import com.facebook.presto.memory.context.AggregatedMemoryContext; import com.facebook.presto.orc.FileOrcDataSource; import com.facebook.presto.orc.OrcDataSource; import com.facebook.presto.orc.OrcPredicate; import com.facebook.presto.orc.OrcReader; import com.facebook.presto.orc.OrcRecordReader; import com.facebook.presto.orc.TupleDomainOrcPredicate; import com.facebook.presto.orc.TupleDomainOrcPredicate.ColumnReference; import com.facebook.presto.orc.metadata.OrcType; import com.facebook.presto.raptor.RaptorColumnHandle; import com.facebook.presto.raptor.RaptorConnectorId; import com.facebook.presto.raptor.backup.BackupManager; import com.facebook.presto.raptor.backup.BackupStore; import com.facebook.presto.raptor.metadata.ColumnInfo; import com.facebook.presto.raptor.metadata.ColumnStats; import com.facebook.presto.raptor.metadata.ShardDelta; import com.facebook.presto.raptor.metadata.ShardInfo; import com.facebook.presto.raptor.metadata.ShardRecorder; import com.facebook.presto.raptor.storage.OrcFileRewriter.OrcFileInfo; import com.facebook.presto.spi.ConnectorPageSource; import com.facebook.presto.spi.NodeManager; import com.facebook.presto.spi.Page; import com.facebook.presto.spi.PrestoException; import com.facebook.presto.spi.predicate.TupleDomain; import com.facebook.presto.spi.type.DecimalType; import com.facebook.presto.spi.type.NamedTypeSignature; import com.facebook.presto.spi.type.RowFieldName; import com.facebook.presto.spi.type.StandardTypes; import com.facebook.presto.spi.type.Type; import com.facebook.presto.spi.type.TypeManager; import com.facebook.presto.spi.type.TypeSignature; import com.facebook.presto.spi.type.TypeSignatureParameter; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import io.airlift.json.JsonCodec; import io.airlift.slice.Slice; import io.airlift.slice.Slices; import io.airlift.slice.XxHash64; import io.airlift.units.DataSize; import io.airlift.units.Duration; import javax.annotation.PreDestroy; import javax.inject.Inject; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.util.ArrayList; import java.util.BitSet; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.OptionalInt; import java.util.OptionalLong; import java.util.Set; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import static com.facebook.presto.memory.context.AggregatedMemoryContext.newSimpleAggregatedMemoryContext; import static com.facebook.presto.orc.OrcEncoding.ORC; import static com.facebook.presto.orc.OrcReader.INITIAL_BATCH_SIZE; import static com.facebook.presto.raptor.RaptorColumnHandle.isBucketNumberColumn; import static com.facebook.presto.raptor.RaptorColumnHandle.isHiddenColumn; import static com.facebook.presto.raptor.RaptorColumnHandle.isShardRowIdColumn; import static com.facebook.presto.raptor.RaptorColumnHandle.isShardUuidColumn; import static com.facebook.presto.raptor.RaptorErrorCode.RAPTOR_ERROR; import static com.facebook.presto.raptor.RaptorErrorCode.RAPTOR_LOCAL_DISK_FULL; import static com.facebook.presto.raptor.RaptorErrorCode.RAPTOR_RECOVERY_ERROR; import static com.facebook.presto.raptor.RaptorErrorCode.RAPTOR_RECOVERY_TIMEOUT; import static com.facebook.presto.raptor.storage.OrcPageSource.BUCKET_NUMBER_COLUMN; import static com.facebook.presto.raptor.storage.OrcPageSource.NULL_COLUMN; import static com.facebook.presto.raptor.storage.OrcPageSource.ROWID_COLUMN; import static com.facebook.presto.raptor.storage.OrcPageSource.SHARD_UUID_COLUMN; import static com.facebook.presto.raptor.storage.ShardStats.computeColumnStats; import static com.facebook.presto.spi.type.BigintType.BIGINT; import static com.facebook.presto.spi.type.BooleanType.BOOLEAN; import static com.facebook.presto.spi.type.CharType.createCharType; import static com.facebook.presto.spi.type.DoubleType.DOUBLE; import static com.facebook.presto.spi.type.VarbinaryType.VARBINARY; import static com.facebook.presto.spi.type.VarcharType.createUnboundedVarcharType; import static com.facebook.presto.spi.type.VarcharType.createVarcharType; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Throwables.throwIfInstanceOf; import static io.airlift.concurrent.MoreFutures.allAsList; import static io.airlift.concurrent.MoreFutures.getFutureValue; import static io.airlift.concurrent.Threads.daemonThreadsNamed; import static io.airlift.json.JsonCodec.jsonCodec; import static io.airlift.units.DataSize.Unit.PETABYTE; import static java.lang.Math.min; import static java.nio.file.StandardCopyOption.ATOMIC_MOVE; import static java.util.Objects.requireNonNull; import static java.util.concurrent.CompletableFuture.completedFuture; import static java.util.concurrent.CompletableFuture.supplyAsync; import static java.util.concurrent.Executors.newCachedThreadPool; import static java.util.concurrent.Executors.newFixedThreadPool; import static java.util.stream.Collectors.toList; import static org.joda.time.DateTimeZone.UTC; public class OrcStorageManager implements StorageManager { private static final JsonCodec<ShardDelta> SHARD_DELTA_CODEC = jsonCodec(ShardDelta.class); private static final long MAX_ROWS = 1_000_000_000; // TODO: do not limit the max size of blocks to read for now; enable the limit when the Hive connector is ready private static final DataSize HUGE_MAX_READ_BLOCK_SIZE = new DataSize(1, PETABYTE); private static final JsonCodec<OrcFileMetadata> METADATA_CODEC = jsonCodec(OrcFileMetadata.class); private final String nodeId; private final StorageService storageService; private final Optional<BackupStore> backupStore; private final ReaderAttributes defaultReaderAttributes; private final BackupManager backupManager; private final ShardRecoveryManager recoveryManager; private final ShardRecorder shardRecorder; private final Duration recoveryTimeout; private final long maxShardRows; private final DataSize maxShardSize; private final DataSize minAvailableSpace; private final TypeManager typeManager; private final ExecutorService deletionExecutor; private final ExecutorService commitExecutor; @Inject public OrcStorageManager( NodeManager nodeManager, StorageService storageService, Optional<BackupStore> backupStore, ReaderAttributes readerAttributes, StorageManagerConfig config, RaptorConnectorId connectorId, BackupManager backgroundBackupManager, ShardRecoveryManager recoveryManager, ShardRecorder shardRecorder, TypeManager typeManager) { this(nodeManager.getCurrentNode().getNodeIdentifier(), storageService, backupStore, readerAttributes, backgroundBackupManager, recoveryManager, shardRecorder, typeManager, connectorId.toString(), config.getDeletionThreads(), config.getShardRecoveryTimeout(), config.getMaxShardRows(), config.getMaxShardSize(), config.getMinAvailableSpace()); } public OrcStorageManager( String nodeId, StorageService storageService, Optional<BackupStore> backupStore, ReaderAttributes readerAttributes, BackupManager backgroundBackupManager, ShardRecoveryManager recoveryManager, ShardRecorder shardRecorder, TypeManager typeManager, String connectorId, int deletionThreads, Duration shardRecoveryTimeout, long maxShardRows, DataSize maxShardSize, DataSize minAvailableSpace) { this.nodeId = requireNonNull(nodeId, "nodeId is null"); this.storageService = requireNonNull(storageService, "storageService is null"); this.backupStore = requireNonNull(backupStore, "backupStore is null"); this.defaultReaderAttributes = requireNonNull(readerAttributes, "readerAttributes is null"); backupManager = requireNonNull(backgroundBackupManager, "backgroundBackupManager is null"); this.recoveryManager = requireNonNull(recoveryManager, "recoveryManager is null"); this.recoveryTimeout = requireNonNull(shardRecoveryTimeout, "shardRecoveryTimeout is null"); checkArgument(maxShardRows > 0, "maxShardRows must be > 0"); this.maxShardRows = min(maxShardRows, MAX_ROWS); this.maxShardSize = requireNonNull(maxShardSize, "maxShardSize is null"); this.minAvailableSpace = requireNonNull(minAvailableSpace, "minAvailableSpace is null"); this.shardRecorder = requireNonNull(shardRecorder, "shardRecorder is null"); this.typeManager = requireNonNull(typeManager, "typeManager is null"); this.deletionExecutor = newFixedThreadPool(deletionThreads, daemonThreadsNamed("raptor-delete-" + connectorId + "-%s")); this.commitExecutor = newCachedThreadPool(daemonThreadsNamed("raptor-commit-" + connectorId + "-%s")); } @PreDestroy public void shutdown() { deletionExecutor.shutdownNow(); commitExecutor.shutdown(); } @Override public ConnectorPageSource getPageSource( UUID shardUuid, OptionalInt bucketNumber, List<Long> columnIds, List<Type> columnTypes, TupleDomain<RaptorColumnHandle> effectivePredicate, ReaderAttributes readerAttributes, OptionalLong transactionId) { OrcDataSource dataSource = openShard(shardUuid, readerAttributes); AggregatedMemoryContext systemMemoryUsage = newSimpleAggregatedMemoryContext(); try { OrcReader reader = new OrcReader(dataSource, ORC, readerAttributes.getMaxMergeDistance(), readerAttributes.getMaxReadSize(), readerAttributes.getTinyStripeThreshold(), HUGE_MAX_READ_BLOCK_SIZE); Map<Long, Integer> indexMap = columnIdIndex(reader.getColumnNames()); ImmutableMap.Builder<Integer, Type> includedColumns = ImmutableMap.builder(); ImmutableList.Builder<Integer> columnIndexes = ImmutableList.builder(); for (int i = 0; i < columnIds.size(); i++) { long columnId = columnIds.get(i); if (isHiddenColumn(columnId)) { columnIndexes.add(toSpecialIndex(columnId)); continue; } Integer index = indexMap.get(columnId); if (index == null) { columnIndexes.add(NULL_COLUMN); } else { columnIndexes.add(index); includedColumns.put(index, columnTypes.get(i)); } } OrcPredicate predicate = getPredicate(effectivePredicate, indexMap); OrcRecordReader recordReader = reader.createRecordReader(includedColumns.build(), predicate, UTC, systemMemoryUsage, INITIAL_BATCH_SIZE); Optional<ShardRewriter> shardRewriter = Optional.empty(); if (transactionId.isPresent()) { shardRewriter = Optional.of(createShardRewriter(transactionId.getAsLong(), bucketNumber, shardUuid)); } return new OrcPageSource(shardRewriter, recordReader, dataSource, columnIds, columnTypes, columnIndexes.build(), shardUuid, bucketNumber, systemMemoryUsage); } catch (IOException | RuntimeException e) { closeQuietly(dataSource); throw new PrestoException(RAPTOR_ERROR, "Failed to create page source for shard " + shardUuid, e); } catch (Throwable t) { closeQuietly(dataSource); throw t; } } private static int toSpecialIndex(long columnId) { if (isShardRowIdColumn(columnId)) { return ROWID_COLUMN; } if (isShardUuidColumn(columnId)) { return SHARD_UUID_COLUMN; } if (isBucketNumberColumn(columnId)) { return BUCKET_NUMBER_COLUMN; } throw new PrestoException(RAPTOR_ERROR, "Invalid column ID: " + columnId); } @Override public StoragePageSink createStoragePageSink(long transactionId, OptionalInt bucketNumber, List<Long> columnIds, List<Type> columnTypes, boolean checkSpace) { if (checkSpace && storageService.getAvailableBytes() < minAvailableSpace.toBytes()) { throw new PrestoException(RAPTOR_LOCAL_DISK_FULL, "Local disk is full on node " + nodeId); } return new OrcStoragePageSink(transactionId, columnIds, columnTypes, bucketNumber); } private ShardRewriter createShardRewriter(long transactionId, OptionalInt bucketNumber, UUID shardUuid) { return rowsToDelete -> { if (rowsToDelete.isEmpty()) { return completedFuture(ImmutableList.of()); } return supplyAsync(() -> rewriteShard(transactionId, bucketNumber, shardUuid, rowsToDelete), deletionExecutor); }; } private void writeShard(UUID shardUuid) { if (backupStore.isPresent() && !backupStore.get().shardExists(shardUuid)) { throw new PrestoException(RAPTOR_ERROR, "Backup does not exist after write"); } File stagingFile = storageService.getStagingFile(shardUuid); File storageFile = storageService.getStorageFile(shardUuid); storageService.createParents(storageFile); try { Files.move(stagingFile.toPath(), storageFile.toPath(), ATOMIC_MOVE); } catch (IOException e) { throw new PrestoException(RAPTOR_ERROR, "Failed to move shard file", e); } } @VisibleForTesting OrcDataSource openShard(UUID shardUuid, ReaderAttributes readerAttributes) { File file = storageService.getStorageFile(shardUuid).getAbsoluteFile(); if (!file.exists() && backupStore.isPresent()) { try { Future<?> future = recoveryManager.recoverShard(shardUuid); future.get(recoveryTimeout.toMillis(), TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } catch (ExecutionException e) { if (e.getCause() != null) { throwIfInstanceOf(e.getCause(), PrestoException.class); } throw new PrestoException(RAPTOR_RECOVERY_ERROR, "Error recovering shard " + shardUuid, e.getCause()); } catch (TimeoutException e) { throw new PrestoException(RAPTOR_RECOVERY_TIMEOUT, "Shard is being recovered from backup. Please retry in a few minutes: " + shardUuid); } } try { return fileOrcDataSource(readerAttributes, file); } catch (IOException e) { throw new PrestoException(RAPTOR_ERROR, "Failed to open shard file: " + file, e); } } private static FileOrcDataSource fileOrcDataSource(ReaderAttributes readerAttributes, File file) throws FileNotFoundException { return new FileOrcDataSource(file, readerAttributes.getMaxMergeDistance(), readerAttributes.getMaxReadSize(), readerAttributes.getStreamBufferSize(), readerAttributes.isLazyReadSmallRanges()); } private ShardInfo createShardInfo(UUID shardUuid, OptionalInt bucketNumber, File file, Set<String> nodes, long rowCount, long uncompressedSize) { return new ShardInfo(shardUuid, bucketNumber, nodes, computeShardStats(file), rowCount, file.length(), uncompressedSize, xxhash64(file)); } private List<ColumnStats> computeShardStats(File file) { try (OrcDataSource dataSource = fileOrcDataSource(defaultReaderAttributes, file)) { OrcReader reader = new OrcReader(dataSource, ORC, defaultReaderAttributes.getMaxMergeDistance(), defaultReaderAttributes.getMaxReadSize(), defaultReaderAttributes.getTinyStripeThreshold(), HUGE_MAX_READ_BLOCK_SIZE); ImmutableList.Builder<ColumnStats> list = ImmutableList.builder(); for (ColumnInfo info : getColumnInfo(reader)) { computeColumnStats(reader, info.getColumnId(), info.getType()).ifPresent(list::add); } return list.build(); } catch (IOException e) { throw new PrestoException(RAPTOR_ERROR, "Failed to read file: " + file, e); } } @VisibleForTesting Collection<Slice> rewriteShard(long transactionId, OptionalInt bucketNumber, UUID shardUuid, BitSet rowsToDelete) { if (rowsToDelete.isEmpty()) { return ImmutableList.of(); } UUID newShardUuid = UUID.randomUUID(); File input = storageService.getStorageFile(shardUuid); File output = storageService.getStagingFile(newShardUuid); OrcFileInfo info = rewriteFile(input, output, rowsToDelete); long rowCount = info.getRowCount(); if (rowCount == 0) { return shardDelta(shardUuid, Optional.empty()); } shardRecorder.recordCreatedShard(transactionId, newShardUuid); // submit for backup and wait until it finishes getFutureValue(backupManager.submit(newShardUuid, output)); Set<String> nodes = ImmutableSet.of(nodeId); long uncompressedSize = info.getUncompressedSize(); ShardInfo shard = createShardInfo(newShardUuid, bucketNumber, output, nodes, rowCount, uncompressedSize); writeShard(newShardUuid); return shardDelta(shardUuid, Optional.of(shard)); } private static Collection<Slice> shardDelta(UUID oldShardUuid, Optional<ShardInfo> shardInfo) { List<ShardInfo> newShards = shardInfo.map(ImmutableList::of).orElse(ImmutableList.of()); ShardDelta delta = new ShardDelta(ImmutableList.of(oldShardUuid), newShards); return ImmutableList.of(Slices.wrappedBuffer(SHARD_DELTA_CODEC.toJsonBytes(delta))); } private static OrcFileInfo rewriteFile(File input, File output, BitSet rowsToDelete) { try { return OrcFileRewriter.rewrite(input, output, rowsToDelete); } catch (IOException e) { throw new PrestoException(RAPTOR_ERROR, "Failed to rewrite shard file: " + input, e); } } private List<ColumnInfo> getColumnInfo(OrcReader reader) { Optional<OrcFileMetadata> metadata = getOrcFileMetadata(reader); if (metadata.isPresent()) { return getColumnInfoFromOrcUserMetadata(metadata.get()); } // support for legacy files without metadata return getColumnInfoFromOrcColumnTypes(reader.getColumnNames(), reader.getFooter().getTypes()); } private List<ColumnInfo> getColumnInfoFromOrcColumnTypes(List<String> orcColumnNames, List<OrcType> orcColumnTypes) { Type rowType = getType(orcColumnTypes, 0); if (orcColumnNames.size() != rowType.getTypeParameters().size()) { throw new PrestoException(RAPTOR_ERROR, "Column names and types do not match"); } ImmutableList.Builder<ColumnInfo> list = ImmutableList.builder(); for (int i = 0; i < orcColumnNames.size(); i++) { list.add(new ColumnInfo(Long.parseLong(orcColumnNames.get(i)), rowType.getTypeParameters().get(i))); } return list.build(); } static long xxhash64(File file) { try (InputStream in = new FileInputStream(file)) { return XxHash64.hash(in); } catch (IOException e) { throw new PrestoException(RAPTOR_ERROR, "Failed to read file: " + file, e); } } private static Optional<OrcFileMetadata> getOrcFileMetadata(OrcReader reader) { return Optional.ofNullable(reader.getFooter().getUserMetadata().get(OrcFileMetadata.KEY)) .map(slice -> METADATA_CODEC.fromJson(slice.getBytes())); } private List<ColumnInfo> getColumnInfoFromOrcUserMetadata(OrcFileMetadata orcFileMetadata) { return orcFileMetadata.getColumnTypes().entrySet() .stream() .sorted(Map.Entry.comparingByKey()) .map(entry -> new ColumnInfo(entry.getKey(), typeManager.getType(entry.getValue()))) .collect(toList()); } private Type getType(List<OrcType> types, int index) { OrcType type = types.get(index); switch (type.getOrcTypeKind()) { case BOOLEAN: return BOOLEAN; case LONG: return BIGINT; case DOUBLE: return DOUBLE; case STRING: return createUnboundedVarcharType(); case VARCHAR: return createVarcharType(type.getLength().get()); case CHAR: return createCharType(type.getLength().get()); case BINARY: return VARBINARY; case DECIMAL: return DecimalType.createDecimalType(type.getPrecision().get(), type.getScale().get()); case LIST: TypeSignature elementType = getType(types, type.getFieldTypeIndex(0)).getTypeSignature(); return typeManager.getParameterizedType(StandardTypes.ARRAY, ImmutableList.of(TypeSignatureParameter.of(elementType))); case MAP: TypeSignature keyType = getType(types, type.getFieldTypeIndex(0)).getTypeSignature(); TypeSignature valueType = getType(types, type.getFieldTypeIndex(1)).getTypeSignature(); return typeManager.getParameterizedType(StandardTypes.MAP, ImmutableList.of(TypeSignatureParameter.of(keyType), TypeSignatureParameter.of(valueType))); case STRUCT: List<String> fieldNames = type.getFieldNames(); ImmutableList.Builder<TypeSignatureParameter> fieldTypes = ImmutableList.builder(); for (int i = 0; i < type.getFieldCount(); i++) { fieldTypes.add(TypeSignatureParameter.of(new NamedTypeSignature( Optional.of(new RowFieldName(fieldNames.get(i), false)), getType(types, type.getFieldTypeIndex(i)).getTypeSignature()))); } return typeManager.getParameterizedType(StandardTypes.ROW, fieldTypes.build()); } throw new PrestoException(RAPTOR_ERROR, "Unhandled ORC type: " + type); } private static OrcPredicate getPredicate(TupleDomain<RaptorColumnHandle> effectivePredicate, Map<Long, Integer> indexMap) { ImmutableList.Builder<ColumnReference<RaptorColumnHandle>> columns = ImmutableList.builder(); for (RaptorColumnHandle column : effectivePredicate.getDomains().get().keySet()) { Integer index = indexMap.get(column.getColumnId()); if (index != null) { columns.add(new ColumnReference<>(column, index, column.getColumnType())); } } return new TupleDomainOrcPredicate<>(effectivePredicate, columns.build(), false); } private static Map<Long, Integer> columnIdIndex(List<String> columnNames) { ImmutableMap.Builder<Long, Integer> map = ImmutableMap.builder(); for (int i = 0; i < columnNames.size(); i++) { map.put(Long.valueOf(columnNames.get(i)), i); } return map.build(); } private class OrcStoragePageSink implements StoragePageSink { private final long transactionId; private final List<Long> columnIds; private final List<Type> columnTypes; private final OptionalInt bucketNumber; private final List<File> stagingFiles = new ArrayList<>(); private final List<ShardInfo> shards = new ArrayList<>(); private final List<CompletableFuture<?>> futures = new ArrayList<>(); private boolean committed; private OrcFileWriter writer; private UUID shardUuid; public OrcStoragePageSink(long transactionId, List<Long> columnIds, List<Type> columnTypes, OptionalInt bucketNumber) { this.transactionId = transactionId; this.columnIds = ImmutableList.copyOf(requireNonNull(columnIds, "columnIds is null")); this.columnTypes = ImmutableList.copyOf(requireNonNull(columnTypes, "columnTypes is null")); this.bucketNumber = requireNonNull(bucketNumber, "bucketNumber is null"); } @Override public void appendPages(List<Page> pages) { createWriterIfNecessary(); writer.appendPages(pages); } @Override public void appendPages(List<Page> inputPages, int[] pageIndexes, int[] positionIndexes) { createWriterIfNecessary(); writer.appendPages(inputPages, pageIndexes, positionIndexes); } @Override public void appendRow(Row row) { createWriterIfNecessary(); writer.appendRow(row); } @Override public boolean isFull() { if (writer == null) { return false; } return (writer.getRowCount() >= maxShardRows) || (writer.getUncompressedSize() >= maxShardSize.toBytes()); } @Override public void flush() { if (writer != null) { writer.close(); shardRecorder.recordCreatedShard(transactionId, shardUuid); File stagingFile = storageService.getStagingFile(shardUuid); futures.add(backupManager.submit(shardUuid, stagingFile)); Set<String> nodes = ImmutableSet.of(nodeId); long rowCount = writer.getRowCount(); long uncompressedSize = writer.getUncompressedSize(); shards.add(createShardInfo(shardUuid, bucketNumber, stagingFile, nodes, rowCount, uncompressedSize)); writer = null; shardUuid = null; } } @Override public CompletableFuture<List<ShardInfo>> commit() { checkState(!committed, "already committed"); committed = true; flush(); return allAsList(futures).thenApplyAsync(ignored -> { for (ShardInfo shard : shards) { writeShard(shard.getShardUuid()); } return ImmutableList.copyOf(shards); }, commitExecutor); } @SuppressWarnings("ResultOfMethodCallIgnored") @Override public void rollback() { try { if (writer != null) { writer.close(); writer = null; } } finally { for (File file : stagingFiles) { file.delete(); } // cancel incomplete backup jobs futures.forEach(future -> future.cancel(true)); // delete completed backup shards backupStore.ifPresent(backupStore -> { for (ShardInfo shard : shards) { backupStore.deleteShard(shard.getShardUuid()); } }); } } private void createWriterIfNecessary() { if (writer == null) { shardUuid = UUID.randomUUID(); File stagingFile = storageService.getStagingFile(shardUuid); storageService.createParents(stagingFile); stagingFiles.add(stagingFile); writer = new OrcFileWriter(columnIds, columnTypes, stagingFile); } } } private static void closeQuietly(Closeable closeable) { try { closeable.close(); } catch (IOException ignored) { } } }
package fr.jmini.asciidoctorj.testcases; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.asciidoctor.OptionsBuilder; import org.asciidoctor.ast.Block; import org.asciidoctor.ast.Document; public class ImageImagesdirTestCase implements AdocTestCase { public static final String ASCIIDOC = "" + ":imagesdir: imgs\n" + "\n" + "image::sunset.jpg[]\n" + "\n" + "image::../cover.png[]\n" + "\n" + "image::http://asciidoctor.org/images/sunset.jpg[]\n" + "\n" + "image::https://upload.wikimedia.org/wikipedia/commons/a/af/Tux.png[]\n" + "\n" + "image::ftp://site.com/sunset.jpg[]\n" + "\n" + "image::file:///C:/absolute/cover.png[]\n" + "\n" + "image::file:///absolute/cover.png[]\n" + "\n" + "image::/absolute/sunset2.jpg[]\n" + "\n" + ""; @Override public String getAdocInput() { return ASCIIDOC; } @Override public Map<String, Object> getInputOptions() { return OptionsBuilder.options() .asMap(); } // tag::expected-html[] public static final String EXPECTED_HTML = "" + "<div class=\"imageblock\">\n" + "<div class=\"content\">\n" + "<img src=\"imgs/sunset.jpg\" alt=\"sunset\" />\n" + "</div>\n" + "</div>\n" + "<div class=\"imageblock\">\n" + "<div class=\"content\">\n" + "<img src=\"cover.png\" alt=\"cover\" />\n" + "</div>\n" + "</div>\n" + "<div class=\"imageblock\">\n" + "<div class=\"content\">\n" + "<img src=\"http://asciidoctor.org/images/sunset.jpg\" alt=\"sunset\" />\n" + "</div>\n" + "</div>\n" + "<div class=\"imageblock\">\n" + "<div class=\"content\">\n" + "<img src=\"https://upload.wikimedia.org/wikipedia/commons/a/af/Tux.png\" alt=\"Tux\" />\n" + "</div>\n" + "</div>\n" + "<div class=\"imageblock\">\n" + "<div class=\"content\">\n" + "<img src=\"ftp://site.com/sunset.jpg\" alt=\"sunset\" />\n" + "</div>\n" + "</div>\n" + "<div class=\"imageblock\">\n" + "<div class=\"content\">\n" + "<img src=\"file:///C:/absolute/cover.png\" alt=\"cover\" />\n" + "</div>\n" + "</div>\n" + "<div class=\"imageblock\">\n" + "<div class=\"content\">\n" + "<img src=\"file:///absolute/cover.png\" alt=\"cover\" />\n" + "</div>\n" + "</div>\n" + "<div class=\"imageblock\">\n" + "<div class=\"content\">\n" + "<img src=\"/absolute/sunset2.jpg\" alt=\"sunset2\" />\n" + "</div>\n" + "</div>"; // end::expected-html[] @Override public String getHtmlOutput() { return EXPECTED_HTML; } @Override // tag::assert-code[] public void checkAst(Document astDocument) { Document document1 = astDocument; assertThat(document1.getId()).isNull(); assertThat(document1.getNodeName()).isEqualTo("document"); assertThat(document1.getParent()).isNull(); assertThat(document1.getContext()).isEqualTo("document"); assertThat(document1.getDocument()).isSameAs(document1); assertThat(document1.isInline()).isFalse(); assertThat(document1.isBlock()).isTrue(); assertThat(document1.getAttributes()).containsEntry("doctype", "article") .containsEntry("example-caption", "Example") .containsEntry("figure-caption", "Figure") .containsEntry("filetype", "html") .containsEntry("imagesdir", "imgs") .containsEntry("notitle", "") .containsEntry("prewrap", "") .containsEntry("table-caption", "Table"); assertThat(document1.getRoles()).isNullOrEmpty(); assertThat(document1.isReftext()).isFalse(); assertThat(document1.getReftext()).isNull(); assertThat(document1.getCaption()).isNull(); assertThat(document1.getTitle()).isNull(); assertThat(document1.getStyle()).isNull(); assertThat(document1.getLevel()).isEqualTo(0); assertThat(document1.getContentModel()).isEqualTo("compound"); assertThat(document1.getSourceLocation()).isNull(); assertThat(document1.getSubstitutions()).isNullOrEmpty(); assertThat(document1.getBlocks()).hasSize(8); Block block1 = (Block) document1.getBlocks() .get(0); assertThat(block1.getId()).isNull(); assertThat(block1.getNodeName()).isEqualTo("image"); assertThat(block1.getParent()).isSameAs(document1); assertThat(block1.getContext()).isEqualTo("image"); assertThat(block1.getDocument()).isSameAs(document1); assertThat(block1.isInline()).isFalse(); assertThat(block1.isBlock()).isTrue(); assertThat(block1.getAttributes()).containsEntry("alt", "sunset") .containsEntry("default-alt", "sunset") .containsEntry("target", "sunset.jpg"); assertThat(block1.getRoles()).isNullOrEmpty(); assertThat(block1.isReftext()).isFalse(); assertThat(block1.getReftext()).isNull(); assertThat(block1.getCaption()).isNull(); assertThat(block1.getTitle()).isNull(); assertThat(block1.getStyle()).isNull(); assertThat(block1.getLevel()).isEqualTo(0); assertThat(block1.getContentModel()).isEqualTo("empty"); assertThat(block1.getSourceLocation()).isNull(); assertThat(block1.getSubstitutions()).isNullOrEmpty(); assertThat(block1.getBlocks()).isNullOrEmpty(); assertThat(block1.getLines()).isNullOrEmpty(); assertThat(block1.getSource()).isEqualTo(""); Block block2 = (Block) document1.getBlocks() .get(1); assertThat(block2.getId()).isNull(); assertThat(block2.getNodeName()).isEqualTo("image"); assertThat(block2.getParent()).isSameAs(document1); assertThat(block2.getContext()).isEqualTo("image"); assertThat(block2.getDocument()).isSameAs(document1); assertThat(block2.isInline()).isFalse(); assertThat(block2.isBlock()).isTrue(); assertThat(block2.getAttributes()).containsEntry("alt", "cover") .containsEntry("default-alt", "cover") .containsEntry("target", "../cover.png"); assertThat(block2.getRoles()).isNullOrEmpty(); assertThat(block2.isReftext()).isFalse(); assertThat(block2.getReftext()).isNull(); assertThat(block2.getCaption()).isNull(); assertThat(block2.getTitle()).isNull(); assertThat(block2.getStyle()).isNull(); assertThat(block2.getLevel()).isEqualTo(0); assertThat(block2.getContentModel()).isEqualTo("empty"); assertThat(block2.getSourceLocation()).isNull(); assertThat(block2.getSubstitutions()).isNullOrEmpty(); assertThat(block2.getBlocks()).isNullOrEmpty(); assertThat(block2.getLines()).isNullOrEmpty(); assertThat(block2.getSource()).isEqualTo(""); Block block3 = (Block) document1.getBlocks() .get(2); assertThat(block3.getId()).isNull(); assertThat(block3.getNodeName()).isEqualTo("image"); assertThat(block3.getParent()).isSameAs(document1); assertThat(block3.getContext()).isEqualTo("image"); assertThat(block3.getDocument()).isSameAs(document1); assertThat(block3.isInline()).isFalse(); assertThat(block3.isBlock()).isTrue(); assertThat(block3.getAttributes()).containsEntry("alt", "sunset") .containsEntry("default-alt", "sunset") .containsEntry("target", "http://asciidoctor.org/images/sunset.jpg"); assertThat(block3.getRoles()).isNullOrEmpty(); assertThat(block3.isReftext()).isFalse(); assertThat(block3.getReftext()).isNull(); assertThat(block3.getCaption()).isNull(); assertThat(block3.getTitle()).isNull(); assertThat(block3.getStyle()).isNull(); assertThat(block3.getLevel()).isEqualTo(0); assertThat(block3.getContentModel()).isEqualTo("empty"); assertThat(block3.getSourceLocation()).isNull(); assertThat(block3.getSubstitutions()).isNullOrEmpty(); assertThat(block3.getBlocks()).isNullOrEmpty(); assertThat(block3.getLines()).isNullOrEmpty(); assertThat(block3.getSource()).isEqualTo(""); Block block4 = (Block) document1.getBlocks() .get(3); assertThat(block4.getId()).isNull(); assertThat(block4.getNodeName()).isEqualTo("image"); assertThat(block4.getParent()).isSameAs(document1); assertThat(block4.getContext()).isEqualTo("image"); assertThat(block4.getDocument()).isSameAs(document1); assertThat(block4.isInline()).isFalse(); assertThat(block4.isBlock()).isTrue(); assertThat(block4.getAttributes()).containsEntry("alt", "Tux") .containsEntry("default-alt", "Tux") .containsEntry("target", "https://upload.wikimedia.org/wikipedia/commons/a/af/Tux.png"); assertThat(block4.getRoles()).isNullOrEmpty(); assertThat(block4.isReftext()).isFalse(); assertThat(block4.getReftext()).isNull(); assertThat(block4.getCaption()).isNull(); assertThat(block4.getTitle()).isNull(); assertThat(block4.getStyle()).isNull(); assertThat(block4.getLevel()).isEqualTo(0); assertThat(block4.getContentModel()).isEqualTo("empty"); assertThat(block4.getSourceLocation()).isNull(); assertThat(block4.getSubstitutions()).isNullOrEmpty(); assertThat(block4.getBlocks()).isNullOrEmpty(); assertThat(block4.getLines()).isNullOrEmpty(); assertThat(block4.getSource()).isEqualTo(""); Block block5 = (Block) document1.getBlocks() .get(4); assertThat(block5.getId()).isNull(); assertThat(block5.getNodeName()).isEqualTo("image"); assertThat(block5.getParent()).isSameAs(document1); assertThat(block5.getContext()).isEqualTo("image"); assertThat(block5.getDocument()).isSameAs(document1); assertThat(block5.isInline()).isFalse(); assertThat(block5.isBlock()).isTrue(); assertThat(block5.getAttributes()).containsEntry("alt", "sunset") .containsEntry("default-alt", "sunset") .containsEntry("target", "ftp://site.com/sunset.jpg"); assertThat(block5.getRoles()).isNullOrEmpty(); assertThat(block5.isReftext()).isFalse(); assertThat(block5.getReftext()).isNull(); assertThat(block5.getCaption()).isNull(); assertThat(block5.getTitle()).isNull(); assertThat(block5.getStyle()).isNull(); assertThat(block5.getLevel()).isEqualTo(0); assertThat(block5.getContentModel()).isEqualTo("empty"); assertThat(block5.getSourceLocation()).isNull(); assertThat(block5.getSubstitutions()).isNullOrEmpty(); assertThat(block5.getBlocks()).isNullOrEmpty(); assertThat(block5.getLines()).isNullOrEmpty(); assertThat(block5.getSource()).isEqualTo(""); Block block6 = (Block) document1.getBlocks() .get(5); assertThat(block6.getId()).isNull(); assertThat(block6.getNodeName()).isEqualTo("image"); assertThat(block6.getParent()).isSameAs(document1); assertThat(block6.getContext()).isEqualTo("image"); assertThat(block6.getDocument()).isSameAs(document1); assertThat(block6.isInline()).isFalse(); assertThat(block6.isBlock()).isTrue(); assertThat(block6.getAttributes()).containsEntry("alt", "cover") .containsEntry("default-alt", "cover") .containsEntry("target", "file:///C:/absolute/cover.png"); assertThat(block6.getRoles()).isNullOrEmpty(); assertThat(block6.isReftext()).isFalse(); assertThat(block6.getReftext()).isNull(); assertThat(block6.getCaption()).isNull(); assertThat(block6.getTitle()).isNull(); assertThat(block6.getStyle()).isNull(); assertThat(block6.getLevel()).isEqualTo(0); assertThat(block6.getContentModel()).isEqualTo("empty"); assertThat(block6.getSourceLocation()).isNull(); assertThat(block6.getSubstitutions()).isNullOrEmpty(); assertThat(block6.getBlocks()).isNullOrEmpty(); assertThat(block6.getLines()).isNullOrEmpty(); assertThat(block6.getSource()).isEqualTo(""); Block block7 = (Block) document1.getBlocks() .get(6); assertThat(block7.getId()).isNull(); assertThat(block7.getNodeName()).isEqualTo("image"); assertThat(block7.getParent()).isSameAs(document1); assertThat(block7.getContext()).isEqualTo("image"); assertThat(block7.getDocument()).isSameAs(document1); assertThat(block7.isInline()).isFalse(); assertThat(block7.isBlock()).isTrue(); assertThat(block7.getAttributes()).containsEntry("alt", "cover") .containsEntry("default-alt", "cover") .containsEntry("target", "file:///absolute/cover.png"); assertThat(block7.getRoles()).isNullOrEmpty(); assertThat(block7.isReftext()).isFalse(); assertThat(block7.getReftext()).isNull(); assertThat(block7.getCaption()).isNull(); assertThat(block7.getTitle()).isNull(); assertThat(block7.getStyle()).isNull(); assertThat(block7.getLevel()).isEqualTo(0); assertThat(block7.getContentModel()).isEqualTo("empty"); assertThat(block7.getSourceLocation()).isNull(); assertThat(block7.getSubstitutions()).isNullOrEmpty(); assertThat(block7.getBlocks()).isNullOrEmpty(); assertThat(block7.getLines()).isNullOrEmpty(); assertThat(block7.getSource()).isEqualTo(""); Block block8 = (Block) document1.getBlocks() .get(7); assertThat(block8.getId()).isNull(); assertThat(block8.getNodeName()).isEqualTo("image"); assertThat(block8.getParent()).isSameAs(document1); assertThat(block8.getContext()).isEqualTo("image"); assertThat(block8.getDocument()).isSameAs(document1); assertThat(block8.isInline()).isFalse(); assertThat(block8.isBlock()).isTrue(); assertThat(block8.getAttributes()).containsEntry("alt", "sunset2") .containsEntry("default-alt", "sunset2") .containsEntry("target", "/absolute/sunset2.jpg"); assertThat(block8.getRoles()).isNullOrEmpty(); assertThat(block8.isReftext()).isFalse(); assertThat(block8.getReftext()).isNull(); assertThat(block8.getCaption()).isNull(); assertThat(block8.getTitle()).isNull(); assertThat(block8.getStyle()).isNull(); assertThat(block8.getLevel()).isEqualTo(0); assertThat(block8.getContentModel()).isEqualTo("empty"); assertThat(block8.getSourceLocation()).isNull(); assertThat(block8.getSubstitutions()).isNullOrEmpty(); assertThat(block8.getBlocks()).isNullOrEmpty(); assertThat(block8.getLines()).isNullOrEmpty(); assertThat(block8.getSource()).isEqualTo(""); assertThat(document1.getStructuredDoctitle()).isNull(); assertThat(document1.getDoctitle()).isNull(); assertThat(document1.getOptions()).containsEntry("header_footer", false); } // end::assert-code[] @Override // tag::mock-code[] public Document createMock() { Document mockDocument1 = mock(Document.class); when(mockDocument1.getId()).thenReturn(null); when(mockDocument1.getNodeName()).thenReturn("document"); when(mockDocument1.getParent()).thenReturn(null); when(mockDocument1.getContext()).thenReturn("document"); when(mockDocument1.getDocument()).thenReturn(mockDocument1); when(mockDocument1.isInline()).thenReturn(false); when(mockDocument1.isBlock()).thenReturn(true); Map<String, Object> map1 = new HashMap<>(); map1.put("doctype", "article"); map1.put("example-caption", "Example"); map1.put("figure-caption", "Figure"); map1.put("filetype", "html"); map1.put("imagesdir", "imgs"); map1.put("notitle", ""); map1.put("prewrap", ""); map1.put("table-caption", "Table"); when(mockDocument1.getAttributes()).thenReturn(map1); when(mockDocument1.getRoles()).thenReturn(Collections.emptyList()); when(mockDocument1.isReftext()).thenReturn(false); when(mockDocument1.getReftext()).thenReturn(null); when(mockDocument1.getCaption()).thenReturn(null); when(mockDocument1.getTitle()).thenReturn(null); when(mockDocument1.getStyle()).thenReturn(null); when(mockDocument1.getLevel()).thenReturn(0); when(mockDocument1.getContentModel()).thenReturn("compound"); when(mockDocument1.getSourceLocation()).thenReturn(null); when(mockDocument1.getSubstitutions()).thenReturn(Collections.emptyList()); Block mockBlock1 = mock(Block.class); when(mockBlock1.getId()).thenReturn(null); when(mockBlock1.getNodeName()).thenReturn("image"); when(mockBlock1.getParent()).thenReturn(mockDocument1); when(mockBlock1.getContext()).thenReturn("image"); when(mockBlock1.getDocument()).thenReturn(mockDocument1); when(mockBlock1.isInline()).thenReturn(false); when(mockBlock1.isBlock()).thenReturn(true); Map<String, Object> map2 = new HashMap<>(); map2.put("alt", "sunset"); map2.put("default-alt", "sunset"); map2.put("target", "sunset.jpg"); when(mockBlock1.getAttributes()).thenReturn(map2); when(mockBlock1.getRoles()).thenReturn(Collections.emptyList()); when(mockBlock1.isReftext()).thenReturn(false); when(mockBlock1.getReftext()).thenReturn(null); when(mockBlock1.getCaption()).thenReturn(null); when(mockBlock1.getTitle()).thenReturn(null); when(mockBlock1.getStyle()).thenReturn(null); when(mockBlock1.getLevel()).thenReturn(0); when(mockBlock1.getContentModel()).thenReturn("empty"); when(mockBlock1.getSourceLocation()).thenReturn(null); when(mockBlock1.getSubstitutions()).thenReturn(Collections.emptyList()); when(mockBlock1.getBlocks()).thenReturn(Collections.emptyList()); when(mockBlock1.getLines()).thenReturn(Collections.emptyList()); when(mockBlock1.getSource()).thenReturn(""); Block mockBlock2 = mock(Block.class); when(mockBlock2.getId()).thenReturn(null); when(mockBlock2.getNodeName()).thenReturn("image"); when(mockBlock2.getParent()).thenReturn(mockDocument1); when(mockBlock2.getContext()).thenReturn("image"); when(mockBlock2.getDocument()).thenReturn(mockDocument1); when(mockBlock2.isInline()).thenReturn(false); when(mockBlock2.isBlock()).thenReturn(true); Map<String, Object> map3 = new HashMap<>(); map3.put("alt", "cover"); map3.put("default-alt", "cover"); map3.put("target", "../cover.png"); when(mockBlock2.getAttributes()).thenReturn(map3); when(mockBlock2.getRoles()).thenReturn(Collections.emptyList()); when(mockBlock2.isReftext()).thenReturn(false); when(mockBlock2.getReftext()).thenReturn(null); when(mockBlock2.getCaption()).thenReturn(null); when(mockBlock2.getTitle()).thenReturn(null); when(mockBlock2.getStyle()).thenReturn(null); when(mockBlock2.getLevel()).thenReturn(0); when(mockBlock2.getContentModel()).thenReturn("empty"); when(mockBlock2.getSourceLocation()).thenReturn(null); when(mockBlock2.getSubstitutions()).thenReturn(Collections.emptyList()); when(mockBlock2.getBlocks()).thenReturn(Collections.emptyList()); when(mockBlock2.getLines()).thenReturn(Collections.emptyList()); when(mockBlock2.getSource()).thenReturn(""); Block mockBlock3 = mock(Block.class); when(mockBlock3.getId()).thenReturn(null); when(mockBlock3.getNodeName()).thenReturn("image"); when(mockBlock3.getParent()).thenReturn(mockDocument1); when(mockBlock3.getContext()).thenReturn("image"); when(mockBlock3.getDocument()).thenReturn(mockDocument1); when(mockBlock3.isInline()).thenReturn(false); when(mockBlock3.isBlock()).thenReturn(true); Map<String, Object> map4 = new HashMap<>(); map4.put("alt", "sunset"); map4.put("default-alt", "sunset"); map4.put("target", "http://asciidoctor.org/images/sunset.jpg"); when(mockBlock3.getAttributes()).thenReturn(map4); when(mockBlock3.getRoles()).thenReturn(Collections.emptyList()); when(mockBlock3.isReftext()).thenReturn(false); when(mockBlock3.getReftext()).thenReturn(null); when(mockBlock3.getCaption()).thenReturn(null); when(mockBlock3.getTitle()).thenReturn(null); when(mockBlock3.getStyle()).thenReturn(null); when(mockBlock3.getLevel()).thenReturn(0); when(mockBlock3.getContentModel()).thenReturn("empty"); when(mockBlock3.getSourceLocation()).thenReturn(null); when(mockBlock3.getSubstitutions()).thenReturn(Collections.emptyList()); when(mockBlock3.getBlocks()).thenReturn(Collections.emptyList()); when(mockBlock3.getLines()).thenReturn(Collections.emptyList()); when(mockBlock3.getSource()).thenReturn(""); Block mockBlock4 = mock(Block.class); when(mockBlock4.getId()).thenReturn(null); when(mockBlock4.getNodeName()).thenReturn("image"); when(mockBlock4.getParent()).thenReturn(mockDocument1); when(mockBlock4.getContext()).thenReturn("image"); when(mockBlock4.getDocument()).thenReturn(mockDocument1); when(mockBlock4.isInline()).thenReturn(false); when(mockBlock4.isBlock()).thenReturn(true); Map<String, Object> map5 = new HashMap<>(); map5.put("alt", "Tux"); map5.put("default-alt", "Tux"); map5.put("target", "https://upload.wikimedia.org/wikipedia/commons/a/af/Tux.png"); when(mockBlock4.getAttributes()).thenReturn(map5); when(mockBlock4.getRoles()).thenReturn(Collections.emptyList()); when(mockBlock4.isReftext()).thenReturn(false); when(mockBlock4.getReftext()).thenReturn(null); when(mockBlock4.getCaption()).thenReturn(null); when(mockBlock4.getTitle()).thenReturn(null); when(mockBlock4.getStyle()).thenReturn(null); when(mockBlock4.getLevel()).thenReturn(0); when(mockBlock4.getContentModel()).thenReturn("empty"); when(mockBlock4.getSourceLocation()).thenReturn(null); when(mockBlock4.getSubstitutions()).thenReturn(Collections.emptyList()); when(mockBlock4.getBlocks()).thenReturn(Collections.emptyList()); when(mockBlock4.getLines()).thenReturn(Collections.emptyList()); when(mockBlock4.getSource()).thenReturn(""); Block mockBlock5 = mock(Block.class); when(mockBlock5.getId()).thenReturn(null); when(mockBlock5.getNodeName()).thenReturn("image"); when(mockBlock5.getParent()).thenReturn(mockDocument1); when(mockBlock5.getContext()).thenReturn("image"); when(mockBlock5.getDocument()).thenReturn(mockDocument1); when(mockBlock5.isInline()).thenReturn(false); when(mockBlock5.isBlock()).thenReturn(true); Map<String, Object> map6 = new HashMap<>(); map6.put("alt", "sunset"); map6.put("default-alt", "sunset"); map6.put("target", "ftp://site.com/sunset.jpg"); when(mockBlock5.getAttributes()).thenReturn(map6); when(mockBlock5.getRoles()).thenReturn(Collections.emptyList()); when(mockBlock5.isReftext()).thenReturn(false); when(mockBlock5.getReftext()).thenReturn(null); when(mockBlock5.getCaption()).thenReturn(null); when(mockBlock5.getTitle()).thenReturn(null); when(mockBlock5.getStyle()).thenReturn(null); when(mockBlock5.getLevel()).thenReturn(0); when(mockBlock5.getContentModel()).thenReturn("empty"); when(mockBlock5.getSourceLocation()).thenReturn(null); when(mockBlock5.getSubstitutions()).thenReturn(Collections.emptyList()); when(mockBlock5.getBlocks()).thenReturn(Collections.emptyList()); when(mockBlock5.getLines()).thenReturn(Collections.emptyList()); when(mockBlock5.getSource()).thenReturn(""); Block mockBlock6 = mock(Block.class); when(mockBlock6.getId()).thenReturn(null); when(mockBlock6.getNodeName()).thenReturn("image"); when(mockBlock6.getParent()).thenReturn(mockDocument1); when(mockBlock6.getContext()).thenReturn("image"); when(mockBlock6.getDocument()).thenReturn(mockDocument1); when(mockBlock6.isInline()).thenReturn(false); when(mockBlock6.isBlock()).thenReturn(true); Map<String, Object> map7 = new HashMap<>(); map7.put("alt", "cover"); map7.put("default-alt", "cover"); map7.put("target", "file:///C:/absolute/cover.png"); when(mockBlock6.getAttributes()).thenReturn(map7); when(mockBlock6.getRoles()).thenReturn(Collections.emptyList()); when(mockBlock6.isReftext()).thenReturn(false); when(mockBlock6.getReftext()).thenReturn(null); when(mockBlock6.getCaption()).thenReturn(null); when(mockBlock6.getTitle()).thenReturn(null); when(mockBlock6.getStyle()).thenReturn(null); when(mockBlock6.getLevel()).thenReturn(0); when(mockBlock6.getContentModel()).thenReturn("empty"); when(mockBlock6.getSourceLocation()).thenReturn(null); when(mockBlock6.getSubstitutions()).thenReturn(Collections.emptyList()); when(mockBlock6.getBlocks()).thenReturn(Collections.emptyList()); when(mockBlock6.getLines()).thenReturn(Collections.emptyList()); when(mockBlock6.getSource()).thenReturn(""); Block mockBlock7 = mock(Block.class); when(mockBlock7.getId()).thenReturn(null); when(mockBlock7.getNodeName()).thenReturn("image"); when(mockBlock7.getParent()).thenReturn(mockDocument1); when(mockBlock7.getContext()).thenReturn("image"); when(mockBlock7.getDocument()).thenReturn(mockDocument1); when(mockBlock7.isInline()).thenReturn(false); when(mockBlock7.isBlock()).thenReturn(true); Map<String, Object> map8 = new HashMap<>(); map8.put("alt", "cover"); map8.put("default-alt", "cover"); map8.put("target", "file:///absolute/cover.png"); when(mockBlock7.getAttributes()).thenReturn(map8); when(mockBlock7.getRoles()).thenReturn(Collections.emptyList()); when(mockBlock7.isReftext()).thenReturn(false); when(mockBlock7.getReftext()).thenReturn(null); when(mockBlock7.getCaption()).thenReturn(null); when(mockBlock7.getTitle()).thenReturn(null); when(mockBlock7.getStyle()).thenReturn(null); when(mockBlock7.getLevel()).thenReturn(0); when(mockBlock7.getContentModel()).thenReturn("empty"); when(mockBlock7.getSourceLocation()).thenReturn(null); when(mockBlock7.getSubstitutions()).thenReturn(Collections.emptyList()); when(mockBlock7.getBlocks()).thenReturn(Collections.emptyList()); when(mockBlock7.getLines()).thenReturn(Collections.emptyList()); when(mockBlock7.getSource()).thenReturn(""); Block mockBlock8 = mock(Block.class); when(mockBlock8.getId()).thenReturn(null); when(mockBlock8.getNodeName()).thenReturn("image"); when(mockBlock8.getParent()).thenReturn(mockDocument1); when(mockBlock8.getContext()).thenReturn("image"); when(mockBlock8.getDocument()).thenReturn(mockDocument1); when(mockBlock8.isInline()).thenReturn(false); when(mockBlock8.isBlock()).thenReturn(true); Map<String, Object> map9 = new HashMap<>(); map9.put("alt", "sunset2"); map9.put("default-alt", "sunset2"); map9.put("target", "/absolute/sunset2.jpg"); when(mockBlock8.getAttributes()).thenReturn(map9); when(mockBlock8.getRoles()).thenReturn(Collections.emptyList()); when(mockBlock8.isReftext()).thenReturn(false); when(mockBlock8.getReftext()).thenReturn(null); when(mockBlock8.getCaption()).thenReturn(null); when(mockBlock8.getTitle()).thenReturn(null); when(mockBlock8.getStyle()).thenReturn(null); when(mockBlock8.getLevel()).thenReturn(0); when(mockBlock8.getContentModel()).thenReturn("empty"); when(mockBlock8.getSourceLocation()).thenReturn(null); when(mockBlock8.getSubstitutions()).thenReturn(Collections.emptyList()); when(mockBlock8.getBlocks()).thenReturn(Collections.emptyList()); when(mockBlock8.getLines()).thenReturn(Collections.emptyList()); when(mockBlock8.getSource()).thenReturn(""); when(mockDocument1.getBlocks()).thenReturn(Arrays.asList(mockBlock1, mockBlock2, mockBlock3, mockBlock4, mockBlock5, mockBlock6, mockBlock7, mockBlock8)); when(mockDocument1.getStructuredDoctitle()).thenReturn(null); when(mockDocument1.getDoctitle()).thenReturn(null); Map<Object, Object> map10 = new HashMap<>(); map10.put("attributes", "{}"); map10.put("header_footer", false); when(mockDocument1.getOptions()).thenReturn(map10); return mockDocument1; } // end::mock-code[] }
/** * JBoss, Home of Professional Open Source. * Copyright 2014-2020 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.pnc.rest.api.endpoints; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import org.jboss.pnc.dto.Build; import org.jboss.pnc.dto.ProductMilestone; import org.jboss.pnc.dto.ProductMilestoneCloseResult; import org.jboss.pnc.dto.requests.validation.VersionValidationRequest; import org.jboss.pnc.dto.response.ErrorResponse; import org.jboss.pnc.dto.response.Page; import org.jboss.pnc.dto.response.ValidationResponse; import org.jboss.pnc.processor.annotation.Client; import org.jboss.pnc.rest.annotation.RespondWithStatus; import org.jboss.pnc.rest.api.parameters.BuildsFilterParameters; import org.jboss.pnc.rest.api.parameters.PageParameters; import org.jboss.pnc.rest.api.parameters.ProductMilestoneCloseParameters; import org.jboss.pnc.rest.api.swagger.response.SwaggerPages.BuildPage; import org.jboss.pnc.rest.api.swagger.response.SwaggerPages.ProductMilestoneCloseResultPage; import javax.validation.Valid; import javax.validation.constraints.NotNull; import javax.ws.rs.BeanParam; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.PATCH; import javax.ws.rs.POST; import javax.ws.rs.PUT; 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; import static org.jboss.pnc.rest.configuration.SwaggerConstants.ACCEPTED_CODE; import static org.jboss.pnc.rest.configuration.SwaggerConstants.ACCEPTED_DESCRIPTION; import static org.jboss.pnc.rest.configuration.SwaggerConstants.CONFLICTED_CODE; import static org.jboss.pnc.rest.configuration.SwaggerConstants.CONFLICTED_DESCRIPTION; import static org.jboss.pnc.rest.configuration.SwaggerConstants.ENTITY_CREATED_CODE; import static org.jboss.pnc.rest.configuration.SwaggerConstants.ENTITY_CREATED_DESCRIPTION; import static org.jboss.pnc.rest.configuration.SwaggerConstants.ENTITY_UPDATED_CODE; import static org.jboss.pnc.rest.configuration.SwaggerConstants.ENTITY_UPDATED_DESCRIPTION; import static org.jboss.pnc.rest.configuration.SwaggerConstants.INVALID_CODE; import static org.jboss.pnc.rest.configuration.SwaggerConstants.INVALID_DESCRIPTION; import static org.jboss.pnc.rest.configuration.SwaggerConstants.NOT_FOUND_CODE; import static org.jboss.pnc.rest.configuration.SwaggerConstants.NOT_FOUND_DESCRIPTION; import static org.jboss.pnc.rest.configuration.SwaggerConstants.SERVER_ERROR_CODE; import static org.jboss.pnc.rest.configuration.SwaggerConstants.SERVER_ERROR_DESCRIPTION; import static org.jboss.pnc.rest.configuration.SwaggerConstants.SUCCESS_CODE; import static org.jboss.pnc.rest.configuration.SwaggerConstants.SUCCESS_DESCRIPTION; @Tag(name = "Product Milestones") @Path("/product-milestones") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Client public interface ProductMilestoneEndpoint { static final String PM_ID = "ID of the product milestone"; static final String CREATE_NEW_DESC = "Creates a new product milestone."; /** * {@value CREATE_NEW_DESC} * * @param productMilestone * @return */ @Operation( summary = CREATE_NEW_DESC, responses = { @ApiResponse( responseCode = ENTITY_CREATED_CODE, description = ENTITY_CREATED_DESCRIPTION, content = @Content(schema = @Schema(implementation = ProductMilestone.class))), @ApiResponse( responseCode = INVALID_CODE, description = INVALID_DESCRIPTION, content = @Content(schema = @Schema(implementation = ErrorResponse.class))), @ApiResponse( responseCode = CONFLICTED_CODE, description = CONFLICTED_DESCRIPTION, content = @Content(schema = @Schema(implementation = ErrorResponse.class))), @ApiResponse( responseCode = SERVER_ERROR_CODE, description = SERVER_ERROR_DESCRIPTION, content = @Content(schema = @Schema(implementation = ErrorResponse.class))) }) @POST @RespondWithStatus(Response.Status.CREATED) ProductMilestone createNew(@NotNull ProductMilestone productMilestone); static final String GET_SPECIFIC_DESC = "Gets a specific product milestone."; /** * {@value GET_SPECIFIC_DESC} * * @param id {@value PM_ID} * @return */ @Operation( summary = GET_SPECIFIC_DESC, responses = { @ApiResponse( responseCode = SUCCESS_CODE, description = SUCCESS_DESCRIPTION, content = @Content(schema = @Schema(implementation = ProductMilestone.class))), @ApiResponse(responseCode = NOT_FOUND_CODE, description = NOT_FOUND_DESCRIPTION), @ApiResponse( responseCode = SERVER_ERROR_CODE, description = SERVER_ERROR_DESCRIPTION, content = @Content(schema = @Schema(implementation = ErrorResponse.class))) }) @GET @Path("/{id}") @Consumes(MediaType.APPLICATION_JSON_PATCH_JSON) // workaround for PATCH support ProductMilestone getSpecific(@Parameter(description = PM_ID) @PathParam("id") String id); static final String UPDATE_DESC = "Updates an existing product milestone."; /** * {@value UPDATE_DESC} * * @param id {@value PM_ID} * @param productMilestone */ @Operation( summary = UPDATE_DESC, responses = { @ApiResponse(responseCode = ENTITY_UPDATED_CODE, description = ENTITY_UPDATED_DESCRIPTION), @ApiResponse( responseCode = INVALID_CODE, description = INVALID_DESCRIPTION, content = @Content(schema = @Schema(implementation = ErrorResponse.class))), @ApiResponse( responseCode = CONFLICTED_CODE, description = CONFLICTED_DESCRIPTION, content = @Content(schema = @Schema(implementation = ErrorResponse.class))), @ApiResponse( responseCode = SERVER_ERROR_CODE, description = SERVER_ERROR_DESCRIPTION, content = @Content(schema = @Schema(implementation = ErrorResponse.class))) }) @PUT @Path("/{id}") void update(@Parameter(description = PM_ID) @PathParam("id") String id, @NotNull ProductMilestone productMilestone); static final String PATCH_SPECIFIC_DESC = "Patch an existing product milestone."; /** * {@value PATCH_SPECIFIC_DESC} * * @param id {@value PM_ID} * @param productMilestone * @return */ @Operation( summary = PATCH_SPECIFIC_DESC, responses = { @ApiResponse( responseCode = SUCCESS_CODE, description = SUCCESS_DESCRIPTION, content = @Content(schema = @Schema(implementation = ProductMilestone.class))), @ApiResponse( responseCode = INVALID_CODE, description = INVALID_DESCRIPTION, content = @Content(schema = @Schema(implementation = ErrorResponse.class))), @ApiResponse(responseCode = NOT_FOUND_CODE, description = NOT_FOUND_DESCRIPTION), @ApiResponse( responseCode = SERVER_ERROR_CODE, description = SERVER_ERROR_DESCRIPTION, content = @Content(schema = @Schema(implementation = ErrorResponse.class))) }) @PATCH @Path("/{id}") @Consumes(MediaType.APPLICATION_JSON_PATCH_JSON) ProductMilestone patchSpecific( @Parameter(description = PM_ID) @PathParam("id") String id, @NotNull ProductMilestone productMilestone); static final String GET_BUILDS_DESC = "Gets builds performed during a product milestone cycle."; /** * {@value GET_BUILDS_DESC} * * @param id {@value PM_ID} * @param pageParameters * @param buildsFilter * @return */ @Operation( summary = GET_BUILDS_DESC, responses = { @ApiResponse( responseCode = SUCCESS_CODE, description = SUCCESS_DESCRIPTION, content = @Content(schema = @Schema(implementation = BuildPage.class))), @ApiResponse( responseCode = INVALID_CODE, description = INVALID_DESCRIPTION, content = @Content(schema = @Schema(implementation = ErrorResponse.class))), @ApiResponse( responseCode = SERVER_ERROR_CODE, description = SERVER_ERROR_DESCRIPTION, content = @Content(schema = @Schema(implementation = ErrorResponse.class))) }) @GET @Path("/{id}/builds") Page<Build> getBuilds( @Parameter(description = PM_ID) @PathParam("id") String id, @Valid @BeanParam PageParameters pageParameters, @BeanParam BuildsFilterParameters buildsFilter); static final String CLOSE_MILESTONE_DESC = "Close a product milestone."; /** * {@value CLOSE_MILESTONE_DESC} * * @param id {@value PM_ID} * @param productMilestone * @return */ @Operation( summary = CLOSE_MILESTONE_DESC, responses = { @ApiResponse(responseCode = ACCEPTED_CODE, description = ACCEPTED_DESCRIPTION), @ApiResponse( responseCode = INVALID_CODE, description = INVALID_DESCRIPTION, content = @Content(schema = @Schema(implementation = ErrorResponse.class))), @ApiResponse( responseCode = CONFLICTED_CODE, description = CONFLICTED_DESCRIPTION, content = @Content(schema = @Schema(implementation = ErrorResponse.class))), @ApiResponse( responseCode = SERVER_ERROR_CODE, description = SERVER_ERROR_DESCRIPTION, content = @Content(schema = @Schema(implementation = ErrorResponse.class))) }) @POST @RespondWithStatus(Response.Status.ACCEPTED) @Path("/{id}/close") ProductMilestoneCloseResult closeMilestone( @Parameter(description = PM_ID) @PathParam("id") String id, ProductMilestone productMilestone); static final String CLOSE_MILESTONE_CANCEL_DESC = "Cancel product milestone close process."; /** * {@value CLOSE_MILESTONE_CANCEL_DESC} * * @param id {@value PM_ID} */ @Operation( summary = CLOSE_MILESTONE_CANCEL_DESC, responses = { @ApiResponse(responseCode = ACCEPTED_CODE, description = ACCEPTED_DESCRIPTION), @ApiResponse( responseCode = INVALID_CODE, description = INVALID_DESCRIPTION, content = @Content(schema = @Schema(implementation = ErrorResponse.class))), @ApiResponse( responseCode = SERVER_ERROR_CODE, description = SERVER_ERROR_DESCRIPTION, content = @Content(schema = @Schema(implementation = ErrorResponse.class))) }) @DELETE @RespondWithStatus(Response.Status.ACCEPTED) @Path("/{id}/close") void cancelMilestoneClose(@Parameter(description = PM_ID) @PathParam("id") String id); static final String GET_CLOSE_RESULTS = "Get milestone releases."; /** * {@value GET_CLOSE_RESULTS} * * @param id{@value PM_ID} * @param pageParams * @param filterParams * @return */ @Operation( summary = GET_CLOSE_RESULTS, responses = { @ApiResponse( responseCode = SUCCESS_CODE, description = SUCCESS_DESCRIPTION, content = @Content( schema = @Schema(implementation = ProductMilestoneCloseResultPage.class))), @ApiResponse( responseCode = INVALID_CODE, description = INVALID_DESCRIPTION, content = @Content(schema = @Schema(implementation = ErrorResponse.class))), @ApiResponse( responseCode = SERVER_ERROR_CODE, description = SERVER_ERROR_DESCRIPTION, content = @Content(schema = @Schema(implementation = ErrorResponse.class))) }) @GET @Path("/{id}/close-results") Page<ProductMilestoneCloseResult> getCloseResults( @Parameter(description = PM_ID) @PathParam("id") String id, @Valid @BeanParam PageParameters pageParams, @BeanParam ProductMilestoneCloseParameters filterParams); static final String VALIDATE_VERSION = "Validate product milestone version."; /** * {@value VALIDATE_VERSION} * * @param productMilestone * @return */ @Operation( summary = VALIDATE_VERSION, responses = { @ApiResponse( responseCode = SUCCESS_CODE, description = SUCCESS_DESCRIPTION, content = @Content(schema = @Schema(implementation = ValidationResponse.class))), @ApiResponse( responseCode = INVALID_CODE, description = INVALID_DESCRIPTION, content = @Content(schema = @Schema(implementation = ErrorResponse.class))), @ApiResponse( responseCode = SERVER_ERROR_CODE, description = SERVER_ERROR_DESCRIPTION, content = @Content(schema = @Schema(implementation = ErrorResponse.class))) }) @POST @Path("/validate-version") ValidationResponse validateVersion(@Valid VersionValidationRequest productMilestone); }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.codec.prefixtree; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import org.apache.hadoop.hbase.classification.InterfaceAudience; import org.apache.hadoop.hbase.codec.prefixtree.encode.other.LongEncoder; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.vint.UVIntTool; import org.apache.hadoop.hbase.util.vint.UVLongTool; /** * Information about the block. Stored at the beginning of the byte[]. Contains things * like minimum timestamp and width of FInts in the row tree. * * Most fields stored in VInts that get decoded on the first access of each new block. */ @InterfaceAudience.Private public class PrefixTreeBlockMeta { /******************* static fields ********************/ public static final int VERSION = 0; public static final int MAX_FAMILY_LENGTH = Byte.MAX_VALUE;// hard-coded in KeyValue public static final int NUM_LONGS = 2, NUM_INTS = 28, NUM_SHORTS = 0,//keyValueTypeWidth not persisted NUM_SINGLE_BYTES = 2, MAX_BYTES = Bytes.SIZEOF_LONG * NUM_LONGS + Bytes.SIZEOF_SHORT * NUM_SHORTS + Bytes.SIZEOF_INT * NUM_INTS + NUM_SINGLE_BYTES; /**************** transient fields *********************/ protected int arrayOffset; protected int bufferOffset; /**************** persisted fields **********************/ // PrefixTree version to allow future format modifications protected int version; protected int numMetaBytes; protected int numKeyValueBytes; protected boolean includesMvccVersion;//probably don't need this explicitly, but only 1 byte // split the byte[] into 6 sections for the different data types protected int numRowBytes; protected int numFamilyBytes; protected int numQualifierBytes; protected int numTimestampBytes; protected int numMvccVersionBytes; protected int numValueBytes; protected int numTagsBytes; // number of bytes in each section of fixed width FInts protected int nextNodeOffsetWidth; protected int familyOffsetWidth; protected int qualifierOffsetWidth; protected int timestampIndexWidth; protected int mvccVersionIndexWidth; protected int valueOffsetWidth; protected int valueLengthWidth; protected int tagsOffsetWidth; // used to pre-allocate structures for reading protected int rowTreeDepth; protected int maxRowLength; protected int maxQualifierLength; protected int maxTagsLength; // the timestamp from which the deltas are calculated protected long minTimestamp; protected int timestampDeltaWidth; protected long minMvccVersion; protected int mvccVersionDeltaWidth; protected boolean allSameType; protected byte allTypes; protected int numUniqueRows; protected int numUniqueFamilies; protected int numUniqueQualifiers; protected int numUniqueTags; /***************** constructors ********************/ public PrefixTreeBlockMeta() { } public PrefixTreeBlockMeta(InputStream is) throws IOException{ this.version = VERSION; this.arrayOffset = 0; this.bufferOffset = 0; readVariableBytesFromInputStream(is); } /** * @param buffer positioned at start of PtBlockMeta */ public PrefixTreeBlockMeta(ByteBuffer buffer) { initOnBlock(buffer); } public void initOnBlock(ByteBuffer buffer) { arrayOffset = buffer.arrayOffset(); bufferOffset = buffer.position(); readVariableBytesFromArray(buffer.array(), arrayOffset + bufferOffset); } /**************** operate on each field **********************/ public int calculateNumMetaBytes(){ int numBytes = 0; numBytes += UVIntTool.numBytes(version); numBytes += UVLongTool.numBytes(numMetaBytes); numBytes += UVIntTool.numBytes(numKeyValueBytes); ++numBytes;//os.write(getIncludesMvccVersion()); numBytes += UVIntTool.numBytes(numRowBytes); numBytes += UVIntTool.numBytes(numFamilyBytes); numBytes += UVIntTool.numBytes(numQualifierBytes); numBytes += UVIntTool.numBytes(numTagsBytes); numBytes += UVIntTool.numBytes(numTimestampBytes); numBytes += UVIntTool.numBytes(numMvccVersionBytes); numBytes += UVIntTool.numBytes(numValueBytes); numBytes += UVIntTool.numBytes(nextNodeOffsetWidth); numBytes += UVIntTool.numBytes(familyOffsetWidth); numBytes += UVIntTool.numBytes(qualifierOffsetWidth); numBytes += UVIntTool.numBytes(tagsOffsetWidth); numBytes += UVIntTool.numBytes(timestampIndexWidth); numBytes += UVIntTool.numBytes(mvccVersionIndexWidth); numBytes += UVIntTool.numBytes(valueOffsetWidth); numBytes += UVIntTool.numBytes(valueLengthWidth); numBytes += UVIntTool.numBytes(rowTreeDepth); numBytes += UVIntTool.numBytes(maxRowLength); numBytes += UVIntTool.numBytes(maxQualifierLength); numBytes += UVIntTool.numBytes(maxTagsLength); numBytes += UVLongTool.numBytes(minTimestamp); numBytes += UVIntTool.numBytes(timestampDeltaWidth); numBytes += UVLongTool.numBytes(minMvccVersion); numBytes += UVIntTool.numBytes(mvccVersionDeltaWidth); ++numBytes;//os.write(getAllSameTypeByte()); ++numBytes;//os.write(allTypes); numBytes += UVIntTool.numBytes(numUniqueRows); numBytes += UVIntTool.numBytes(numUniqueFamilies); numBytes += UVIntTool.numBytes(numUniqueQualifiers); numBytes += UVIntTool.numBytes(numUniqueTags); return numBytes; } public void writeVariableBytesToOutputStream(OutputStream os) throws IOException{ UVIntTool.writeBytes(version, os); UVIntTool.writeBytes(numMetaBytes, os); UVIntTool.writeBytes(numKeyValueBytes, os); os.write(getIncludesMvccVersionByte()); UVIntTool.writeBytes(numRowBytes, os); UVIntTool.writeBytes(numFamilyBytes, os); UVIntTool.writeBytes(numQualifierBytes, os); UVIntTool.writeBytes(numTagsBytes, os); UVIntTool.writeBytes(numTimestampBytes, os); UVIntTool.writeBytes(numMvccVersionBytes, os); UVIntTool.writeBytes(numValueBytes, os); UVIntTool.writeBytes(nextNodeOffsetWidth, os); UVIntTool.writeBytes(familyOffsetWidth, os); UVIntTool.writeBytes(qualifierOffsetWidth, os); UVIntTool.writeBytes(tagsOffsetWidth, os); UVIntTool.writeBytes(timestampIndexWidth, os); UVIntTool.writeBytes(mvccVersionIndexWidth, os); UVIntTool.writeBytes(valueOffsetWidth, os); UVIntTool.writeBytes(valueLengthWidth, os); UVIntTool.writeBytes(rowTreeDepth, os); UVIntTool.writeBytes(maxRowLength, os); UVIntTool.writeBytes(maxQualifierLength, os); UVIntTool.writeBytes(maxTagsLength, os); UVLongTool.writeBytes(minTimestamp, os); UVIntTool.writeBytes(timestampDeltaWidth, os); UVLongTool.writeBytes(minMvccVersion, os); UVIntTool.writeBytes(mvccVersionDeltaWidth, os); os.write(getAllSameTypeByte()); os.write(allTypes); UVIntTool.writeBytes(numUniqueRows, os); UVIntTool.writeBytes(numUniqueFamilies, os); UVIntTool.writeBytes(numUniqueQualifiers, os); UVIntTool.writeBytes(numUniqueTags, os); } public void readVariableBytesFromInputStream(InputStream is) throws IOException{ version = UVIntTool.getInt(is); numMetaBytes = UVIntTool.getInt(is); numKeyValueBytes = UVIntTool.getInt(is); setIncludesMvccVersion((byte) is.read()); numRowBytes = UVIntTool.getInt(is); numFamilyBytes = UVIntTool.getInt(is); numQualifierBytes = UVIntTool.getInt(is); numTagsBytes = UVIntTool.getInt(is); numTimestampBytes = UVIntTool.getInt(is); numMvccVersionBytes = UVIntTool.getInt(is); numValueBytes = UVIntTool.getInt(is); nextNodeOffsetWidth = UVIntTool.getInt(is); familyOffsetWidth = UVIntTool.getInt(is); qualifierOffsetWidth = UVIntTool.getInt(is); tagsOffsetWidth = UVIntTool.getInt(is); timestampIndexWidth = UVIntTool.getInt(is); mvccVersionIndexWidth = UVIntTool.getInt(is); valueOffsetWidth = UVIntTool.getInt(is); valueLengthWidth = UVIntTool.getInt(is); rowTreeDepth = UVIntTool.getInt(is); maxRowLength = UVIntTool.getInt(is); maxQualifierLength = UVIntTool.getInt(is); maxTagsLength = UVIntTool.getInt(is); minTimestamp = UVLongTool.getLong(is); timestampDeltaWidth = UVIntTool.getInt(is); minMvccVersion = UVLongTool.getLong(is); mvccVersionDeltaWidth = UVIntTool.getInt(is); setAllSameType((byte) is.read()); allTypes = (byte) is.read(); numUniqueRows = UVIntTool.getInt(is); numUniqueFamilies = UVIntTool.getInt(is); numUniqueQualifiers = UVIntTool.getInt(is); numUniqueTags = UVIntTool.getInt(is); } public void readVariableBytesFromArray(byte[] bytes, int offset) { int position = offset; version = UVIntTool.getInt(bytes, position); position += UVIntTool.numBytes(version); numMetaBytes = UVIntTool.getInt(bytes, position); position += UVIntTool.numBytes(numMetaBytes); numKeyValueBytes = UVIntTool.getInt(bytes, position); position += UVIntTool.numBytes(numKeyValueBytes); setIncludesMvccVersion(bytes[position]); ++position; numRowBytes = UVIntTool.getInt(bytes, position); position += UVIntTool.numBytes(numRowBytes); numFamilyBytes = UVIntTool.getInt(bytes, position); position += UVIntTool.numBytes(numFamilyBytes); numQualifierBytes = UVIntTool.getInt(bytes, position); position += UVIntTool.numBytes(numQualifierBytes); numTagsBytes = UVIntTool.getInt(bytes, position); position += UVIntTool.numBytes(numTagsBytes); numTimestampBytes = UVIntTool.getInt(bytes, position); position += UVIntTool.numBytes(numTimestampBytes); numMvccVersionBytes = UVIntTool.getInt(bytes, position); position += UVIntTool.numBytes(numMvccVersionBytes); numValueBytes = UVIntTool.getInt(bytes, position); position += UVIntTool.numBytes(numValueBytes); nextNodeOffsetWidth = UVIntTool.getInt(bytes, position); position += UVIntTool.numBytes(nextNodeOffsetWidth); familyOffsetWidth = UVIntTool.getInt(bytes, position); position += UVIntTool.numBytes(familyOffsetWidth); qualifierOffsetWidth = UVIntTool.getInt(bytes, position); position += UVIntTool.numBytes(qualifierOffsetWidth); tagsOffsetWidth = UVIntTool.getInt(bytes, position); position += UVIntTool.numBytes(tagsOffsetWidth); timestampIndexWidth = UVIntTool.getInt(bytes, position); position += UVIntTool.numBytes(timestampIndexWidth); mvccVersionIndexWidth = UVIntTool.getInt(bytes, position); position += UVIntTool.numBytes(mvccVersionIndexWidth); valueOffsetWidth = UVIntTool.getInt(bytes, position); position += UVIntTool.numBytes(valueOffsetWidth); valueLengthWidth = UVIntTool.getInt(bytes, position); position += UVIntTool.numBytes(valueLengthWidth); rowTreeDepth = UVIntTool.getInt(bytes, position); position += UVIntTool.numBytes(rowTreeDepth); maxRowLength = UVIntTool.getInt(bytes, position); position += UVIntTool.numBytes(maxRowLength); maxQualifierLength = UVIntTool.getInt(bytes, position); position += UVIntTool.numBytes(maxQualifierLength); maxTagsLength = UVIntTool.getInt(bytes, position); position += UVIntTool.numBytes(maxTagsLength); minTimestamp = UVLongTool.getLong(bytes, position); position += UVLongTool.numBytes(minTimestamp); timestampDeltaWidth = UVIntTool.getInt(bytes, position); position += UVIntTool.numBytes(timestampDeltaWidth); minMvccVersion = UVLongTool.getLong(bytes, position); position += UVLongTool.numBytes(minMvccVersion); mvccVersionDeltaWidth = UVIntTool.getInt(bytes, position); position += UVIntTool.numBytes(mvccVersionDeltaWidth); setAllSameType(bytes[position]); ++position; allTypes = bytes[position]; ++position; numUniqueRows = UVIntTool.getInt(bytes, position); position += UVIntTool.numBytes(numUniqueRows); numUniqueFamilies = UVIntTool.getInt(bytes, position); position += UVIntTool.numBytes(numUniqueFamilies); numUniqueQualifiers = UVIntTool.getInt(bytes, position); position += UVIntTool.numBytes(numUniqueQualifiers); numUniqueTags = UVIntTool.getInt(bytes, position); position += UVIntTool.numBytes(numUniqueTags); } //TODO method that can read directly from ByteBuffer instead of InputStream /*************** methods *************************/ public int getKeyValueTypeWidth() { return allSameType ? 0 : 1; } public byte getIncludesMvccVersionByte() { return includesMvccVersion ? (byte) 1 : (byte) 0; } public void setIncludesMvccVersion(byte includesMvccVersionByte) { includesMvccVersion = includesMvccVersionByte != 0; } public byte getAllSameTypeByte() { return allSameType ? (byte) 1 : (byte) 0; } public void setAllSameType(byte allSameTypeByte) { allSameType = allSameTypeByte != 0; } public boolean isAllSameTimestamp() { return timestampIndexWidth == 0; } public boolean isAllSameMvccVersion() { return mvccVersionIndexWidth == 0; } public void setTimestampFields(LongEncoder encoder){ this.minTimestamp = encoder.getMin(); this.timestampIndexWidth = encoder.getBytesPerIndex(); this.timestampDeltaWidth = encoder.getBytesPerDelta(); this.numTimestampBytes = encoder.getTotalCompressedBytes(); } public void setMvccVersionFields(LongEncoder encoder){ this.minMvccVersion = encoder.getMin(); this.mvccVersionIndexWidth = encoder.getBytesPerIndex(); this.mvccVersionDeltaWidth = encoder.getBytesPerDelta(); this.numMvccVersionBytes = encoder.getTotalCompressedBytes(); } /*************** Object methods *************************/ /** * Generated by Eclipse */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; PrefixTreeBlockMeta other = (PrefixTreeBlockMeta) obj; if (allSameType != other.allSameType) return false; if (allTypes != other.allTypes) return false; if (arrayOffset != other.arrayOffset) return false; if (bufferOffset != other.bufferOffset) return false; if (valueLengthWidth != other.valueLengthWidth) return false; if (valueOffsetWidth != other.valueOffsetWidth) return false; if (familyOffsetWidth != other.familyOffsetWidth) return false; if (includesMvccVersion != other.includesMvccVersion) return false; if (maxQualifierLength != other.maxQualifierLength) return false; if (maxTagsLength != other.maxTagsLength) return false; if (maxRowLength != other.maxRowLength) return false; if (mvccVersionDeltaWidth != other.mvccVersionDeltaWidth) return false; if (mvccVersionIndexWidth != other.mvccVersionIndexWidth) return false; if (minMvccVersion != other.minMvccVersion) return false; if (minTimestamp != other.minTimestamp) return false; if (nextNodeOffsetWidth != other.nextNodeOffsetWidth) return false; if (numValueBytes != other.numValueBytes) return false; if (numFamilyBytes != other.numFamilyBytes) return false; if (numMvccVersionBytes != other.numMvccVersionBytes) return false; if (numMetaBytes != other.numMetaBytes) return false; if (numQualifierBytes != other.numQualifierBytes) return false; if (numTagsBytes != other.numTagsBytes) return false; if (numRowBytes != other.numRowBytes) return false; if (numTimestampBytes != other.numTimestampBytes) return false; if (numUniqueFamilies != other.numUniqueFamilies) return false; if (numUniqueQualifiers != other.numUniqueQualifiers) return false; if (numUniqueTags != other.numUniqueTags) return false; if (numUniqueRows != other.numUniqueRows) return false; if (numKeyValueBytes != other.numKeyValueBytes) return false; if (qualifierOffsetWidth != other.qualifierOffsetWidth) return false; if(tagsOffsetWidth != other.tagsOffsetWidth) return false; if (rowTreeDepth != other.rowTreeDepth) return false; if (timestampDeltaWidth != other.timestampDeltaWidth) return false; if (timestampIndexWidth != other.timestampIndexWidth) return false; if (version != other.version) return false; return true; } /** * Generated by Eclipse */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (allSameType ? 1231 : 1237); result = prime * result + allTypes; result = prime * result + arrayOffset; result = prime * result + bufferOffset; result = prime * result + valueLengthWidth; result = prime * result + valueOffsetWidth; result = prime * result + familyOffsetWidth; result = prime * result + (includesMvccVersion ? 1231 : 1237); result = prime * result + maxQualifierLength; result = prime * result + maxTagsLength; result = prime * result + maxRowLength; result = prime * result + mvccVersionDeltaWidth; result = prime * result + mvccVersionIndexWidth; result = prime * result + (int) (minMvccVersion ^ (minMvccVersion >>> 32)); result = prime * result + (int) (minTimestamp ^ (minTimestamp >>> 32)); result = prime * result + nextNodeOffsetWidth; result = prime * result + numValueBytes; result = prime * result + numFamilyBytes; result = prime * result + numMvccVersionBytes; result = prime * result + numMetaBytes; result = prime * result + numQualifierBytes; result = prime * result + numTagsBytes; result = prime * result + numRowBytes; result = prime * result + numTimestampBytes; result = prime * result + numUniqueFamilies; result = prime * result + numUniqueQualifiers; result = prime * result + numUniqueTags; result = prime * result + numUniqueRows; result = prime * result + numKeyValueBytes; result = prime * result + qualifierOffsetWidth; result = prime * result + tagsOffsetWidth; result = prime * result + rowTreeDepth; result = prime * result + timestampDeltaWidth; result = prime * result + timestampIndexWidth; result = prime * result + version; return result; } /** * Generated by Eclipse */ @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("PtBlockMeta [arrayOffset="); builder.append(arrayOffset); builder.append(", bufferOffset="); builder.append(bufferOffset); builder.append(", version="); builder.append(version); builder.append(", numMetaBytes="); builder.append(numMetaBytes); builder.append(", numKeyValueBytes="); builder.append(numKeyValueBytes); builder.append(", includesMvccVersion="); builder.append(includesMvccVersion); builder.append(", numRowBytes="); builder.append(numRowBytes); builder.append(", numFamilyBytes="); builder.append(numFamilyBytes); builder.append(", numQualifierBytes="); builder.append(numQualifierBytes); builder.append(", numTimestampBytes="); builder.append(numTimestampBytes); builder.append(", numMvccVersionBytes="); builder.append(numMvccVersionBytes); builder.append(", numValueBytes="); builder.append(numValueBytes); builder.append(", numTagBytes="); builder.append(numTagsBytes); builder.append(", nextNodeOffsetWidth="); builder.append(nextNodeOffsetWidth); builder.append(", familyOffsetWidth="); builder.append(familyOffsetWidth); builder.append(", qualifierOffsetWidth="); builder.append(qualifierOffsetWidth); builder.append(", tagOffsetWidth="); builder.append(tagsOffsetWidth); builder.append(", timestampIndexWidth="); builder.append(timestampIndexWidth); builder.append(", mvccVersionIndexWidth="); builder.append(mvccVersionIndexWidth); builder.append(", valueOffsetWidth="); builder.append(valueOffsetWidth); builder.append(", valueLengthWidth="); builder.append(valueLengthWidth); builder.append(", rowTreeDepth="); builder.append(rowTreeDepth); builder.append(", maxRowLength="); builder.append(maxRowLength); builder.append(", maxQualifierLength="); builder.append(maxQualifierLength); builder.append(", maxTagLength="); builder.append(maxTagsLength); builder.append(", minTimestamp="); builder.append(minTimestamp); builder.append(", timestampDeltaWidth="); builder.append(timestampDeltaWidth); builder.append(", minMvccVersion="); builder.append(minMvccVersion); builder.append(", mvccVersionDeltaWidth="); builder.append(mvccVersionDeltaWidth); builder.append(", allSameType="); builder.append(allSameType); builder.append(", allTypes="); builder.append(allTypes); builder.append(", numUniqueRows="); builder.append(numUniqueRows); builder.append(", numUniqueFamilies="); builder.append(numUniqueFamilies); builder.append(", numUniqueQualifiers="); builder.append(numUniqueQualifiers); builder.append(", numUniqueTags="); builder.append(numUniqueTags); builder.append("]"); return builder.toString(); } /************** absolute getters *******************/ public int getAbsoluteMetaOffset() { return arrayOffset + bufferOffset; } public int getAbsoluteRowOffset() { return getAbsoluteMetaOffset() + numMetaBytes; } public int getAbsoluteFamilyOffset() { return getAbsoluteRowOffset() + numRowBytes; } public int getAbsoluteQualifierOffset() { return getAbsoluteFamilyOffset() + numFamilyBytes; } public int getAbsoluteTagsOffset() { return getAbsoluteQualifierOffset() + numQualifierBytes; } public int getAbsoluteTimestampOffset() { return getAbsoluteTagsOffset() + numTagsBytes; } public int getAbsoluteMvccVersionOffset() { return getAbsoluteTimestampOffset() + numTimestampBytes; } public int getAbsoluteValueOffset() { return getAbsoluteMvccVersionOffset() + numMvccVersionBytes; } /*************** get/set ***************************/ public int getTimestampDeltaWidth() { return timestampDeltaWidth; } public void setTimestampDeltaWidth(int timestampDeltaWidth) { this.timestampDeltaWidth = timestampDeltaWidth; } public int getValueOffsetWidth() { return valueOffsetWidth; } public int getTagsOffsetWidth() { return tagsOffsetWidth; } public void setValueOffsetWidth(int dataOffsetWidth) { this.valueOffsetWidth = dataOffsetWidth; } public void setTagsOffsetWidth(int dataOffsetWidth) { this.tagsOffsetWidth = dataOffsetWidth; } public int getValueLengthWidth() { return valueLengthWidth; } public void setValueLengthWidth(int dataLengthWidth) { this.valueLengthWidth = dataLengthWidth; } public int getMaxRowLength() { return maxRowLength; } public void setMaxRowLength(int maxRowLength) { this.maxRowLength = maxRowLength; } public long getMinTimestamp() { return minTimestamp; } public void setMinTimestamp(long minTimestamp) { this.minTimestamp = minTimestamp; } public byte getAllTypes() { return allTypes; } public void setAllTypes(byte allTypes) { this.allTypes = allTypes; } public boolean isAllSameType() { return allSameType; } public void setAllSameType(boolean allSameType) { this.allSameType = allSameType; } public int getNextNodeOffsetWidth() { return nextNodeOffsetWidth; } public void setNextNodeOffsetWidth(int nextNodeOffsetWidth) { this.nextNodeOffsetWidth = nextNodeOffsetWidth; } public int getNumRowBytes() { return numRowBytes; } public void setNumRowBytes(int numRowBytes) { this.numRowBytes = numRowBytes; } public int getNumTimestampBytes() { return numTimestampBytes; } public void setNumTimestampBytes(int numTimestampBytes) { this.numTimestampBytes = numTimestampBytes; } public int getNumValueBytes() { return numValueBytes; } public int getNumTagsBytes() { return numTagsBytes; } public void setNumTagsBytes(int numTagBytes){ this.numTagsBytes = numTagBytes; } public void setNumValueBytes(int numValueBytes) { this.numValueBytes = numValueBytes; } public int getNumMetaBytes() { return numMetaBytes; } public void setNumMetaBytes(int numMetaBytes) { this.numMetaBytes = numMetaBytes; } public int getArrayOffset() { return arrayOffset; } public void setArrayOffset(int arrayOffset) { this.arrayOffset = arrayOffset; } public int getBufferOffset() { return bufferOffset; } public void setBufferOffset(int bufferOffset) { this.bufferOffset = bufferOffset; } public int getNumKeyValueBytes() { return numKeyValueBytes; } public void setNumKeyValueBytes(int numKeyValueBytes) { this.numKeyValueBytes = numKeyValueBytes; } public int getRowTreeDepth() { return rowTreeDepth; } public void setRowTreeDepth(int rowTreeDepth) { this.rowTreeDepth = rowTreeDepth; } public int getNumMvccVersionBytes() { return numMvccVersionBytes; } public void setNumMvccVersionBytes(int numMvccVersionBytes) { this.numMvccVersionBytes = numMvccVersionBytes; } public int getMvccVersionDeltaWidth() { return mvccVersionDeltaWidth; } public void setMvccVersionDeltaWidth(int mvccVersionDeltaWidth) { this.mvccVersionDeltaWidth = mvccVersionDeltaWidth; } public long getMinMvccVersion() { return minMvccVersion; } public void setMinMvccVersion(long minMvccVersion) { this.minMvccVersion = minMvccVersion; } public int getNumFamilyBytes() { return numFamilyBytes; } public void setNumFamilyBytes(int numFamilyBytes) { this.numFamilyBytes = numFamilyBytes; } public int getFamilyOffsetWidth() { return familyOffsetWidth; } public void setFamilyOffsetWidth(int familyOffsetWidth) { this.familyOffsetWidth = familyOffsetWidth; } public int getNumUniqueRows() { return numUniqueRows; } public void setNumUniqueRows(int numUniqueRows) { this.numUniqueRows = numUniqueRows; } public int getNumUniqueFamilies() { return numUniqueFamilies; } public void setNumUniqueFamilies(int numUniqueFamilies) { this.numUniqueFamilies = numUniqueFamilies; } public int getNumUniqueQualifiers() { return numUniqueQualifiers; } public void setNumUniqueQualifiers(int numUniqueQualifiers) { this.numUniqueQualifiers = numUniqueQualifiers; } public void setNumUniqueTags(int numUniqueTags) { this.numUniqueTags = numUniqueTags; } public int getNumUniqueTags() { return numUniqueTags; } public int getNumQualifierBytes() { return numQualifierBytes; } public void setNumQualifierBytes(int numQualifierBytes) { this.numQualifierBytes = numQualifierBytes; } public int getQualifierOffsetWidth() { return qualifierOffsetWidth; } public void setQualifierOffsetWidth(int qualifierOffsetWidth) { this.qualifierOffsetWidth = qualifierOffsetWidth; } public int getMaxQualifierLength() { return maxQualifierLength; } // TODO : decide on some max value for this ? INTEGER_MAX? public void setMaxQualifierLength(int maxQualifierLength) { this.maxQualifierLength = maxQualifierLength; } public int getMaxTagsLength() { return this.maxTagsLength; } public void setMaxTagsLength(int maxTagLength) { this.maxTagsLength = maxTagLength; } public int getTimestampIndexWidth() { return timestampIndexWidth; } public void setTimestampIndexWidth(int timestampIndexWidth) { this.timestampIndexWidth = timestampIndexWidth; } public int getMvccVersionIndexWidth() { return mvccVersionIndexWidth; } public void setMvccVersionIndexWidth(int mvccVersionIndexWidth) { this.mvccVersionIndexWidth = mvccVersionIndexWidth; } public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public boolean isIncludesMvccVersion() { return includesMvccVersion; } public void setIncludesMvccVersion(boolean includesMvccVersion) { this.includesMvccVersion = includesMvccVersion; } }
package com.adarsh.apps.campusstore; import android.app.Activity; import android.app.AlertDialog; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageView; import android.widget.Spinner; import android.widget.Toast; import com.parse.GetCallback; import com.parse.ParseException; import com.parse.ParseFile; import com.parse.ParseObject; import com.parse.ParseQuery; import com.parse.ParseUser; import com.parse.SaveCallback; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; public class CreateActivity extends Activity { private static final int REQUEST_CODE = 1; private static final int CAMERA_PIC_REQUEST = 1337; private Bitmap bitmap; private ImageView imageView[]=new ImageView[3]; private Button save, capture,capture1,capture2,submit; private EditText et1,et2,et3; private Spinner spinner1; private ParseFile imagefile,imagefile1,imagefile2; private CheckBox neg; ItemInfo olditem=null; static String cat; int im=0; static final int REQUEST_TAKE_PHOTO = 1; String mCurrentPhotoPath; // private ItemInfo item; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_create); et1=(EditText)findViewById(R.id.editText4); et2=(EditText)findViewById(R.id.editText3); et3=(EditText)findViewById(R.id.editText5); // neg=(CheckBox)findViewById(R.id.checkBox); // imageView[0] = (ImageView) findViewById(R.id.imageView); // imageView[1] = (ImageView) findViewById(R.id.imageView1); // imageView[2] = (ImageView) findViewById(R.id.imageView2); save = (Button) findViewById(R.id.save); spinner1 = (Spinner) findViewById(R.id.spinner); spinner1.setOnItemSelectedListener(new OnCategorySelected()); spinner1.setPopupBackgroundDrawable(new ColorDrawable(Color.parseColor("#900707"))); Intent intent=getIntent(); if(intent.getExtras()!=null) { final String titletext = intent.getStringExtra("key"); final String desctext = intent.getStringExtra("key3"); final String pricetext=intent.getStringExtra("key4"); final String nametext=intent.getStringExtra("key2"); Log.d("test","Olditem found"); et1.setText(titletext); et2.setText(desctext); et3.setText(pricetext); /*imageView.setImageBitmap(CommonResources.bmp); olditem=new ItemInfo(intent.getStringExtra("noteId"),titletext,nametext,desctext,new BitmapDrawable(getResources(), CommonResources.bmp),pricetext,cat);*/ } /*save.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { { BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable(); Bitmap bitmap = drawable.getBitmap(); File sdCardDirectory = Environment.getExternalStorageDirectory(); File image = new File(sdCardDirectory, "test.png"); boolean success = false; // Encode the file as a PNG image. FileOutputStream outStream; try { outStream = new FileOutputStream(image); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream); /* 100 to keep full quality of the image */ /* outStream.flush(); outStream.close(); success = true; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if (success) { Toast.makeText(getApplicationContext(), "Image saved with success", Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(), "Error during image saving", Toast.LENGTH_LONG).show(); } } } });*/ capture = (Button) findViewById(R.id.capture); capture.setOnClickListener(new View.OnClickListener(){ @Override public void onClick (View v){ { im=1; dispatchTakePictureIntent(); } } }); // capture2 = (Button) findViewById(R.id.capture2); // capture2.setOnClickListener(new View.OnClickListener(){ // @Override // public void onClick (View v){ // { // im=3; // dispatchTakePictureIntent(); // } // } // }); // capture1 = (Button) findViewById(R.id.capture1); // capture1.setOnClickListener(new View.OnClickListener(){ // @Override // public void onClick (View v){ // { // im=2; // dispatchTakePictureIntent(); // } // } // }); submit = (Button) findViewById(R.id.submit); submit.setOnClickListener(new View.OnClickListener(){ @Override public void onClick (View v){ { BitmapDrawable drawable; drawable = (BitmapDrawable)imageView[0].getDrawable(); Bitmap bitmap = drawable.getBitmap(); ByteArrayOutputStream bs = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bs); byte[] byteArray = bs.toByteArray(); BitmapDrawable drawable1; drawable1 = (BitmapDrawable)imageView[1].getDrawable(); Bitmap bitmap1 = drawable1.getBitmap(); ByteArrayOutputStream bs1 = new ByteArrayOutputStream(); bitmap1.compress(Bitmap.CompressFormat.PNG, 50, bs1); byte[] byteArray1 = bs1.toByteArray(); BitmapDrawable drawable2; drawable2 = (BitmapDrawable)imageView[2].getDrawable(); Bitmap bitmap2 = drawable2.getBitmap(); ByteArrayOutputStream bs2 = new ByteArrayOutputStream(); bitmap2.compress(Bitmap.CompressFormat.PNG, 50, bs2); byte[] byteArray2 = bs2.toByteArray(); imagefile = new ParseFile("image.png", byteArray); imagefile1= new ParseFile("image1.png", byteArray1); imagefile2= new ParseFile("image2.png", byteArray); saveitem(); Intent i = new Intent(CreateActivity.this,MainActivity.class); i.putExtra("name1", et1.getText().toString()); i.putExtra("desc1", et2.getText().toString()); startActivity(i); } } }); } public void captureImage() { // Capture image from camera Intent intent = new Intent( android.provider.MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent, CAMERA_PIC_REQUEST); } public void pickImage() { // To pick a image from file system Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); intent.addCategory(Intent.CATEGORY_OPENABLE); startActivityForResult(intent, REQUEST_CODE); } /* @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK) { if (requestCode == REQUEST_CODE) { try { // We need to recycle unused bitmaps if (bitmap != null) { bitmap.recycle(); } InputStream stream = getContentResolver().openInputStream(data.getData()); bitmap = BitmapFactory.decodeStream(stream); stream.close(); imageView[im-1].setImageBitmap(bitmap); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else if (requestCode == CAMERA_PIC_REQUEST) { if (bitmap != null) { bitmap.recycle(); } bitmap = (Bitmap) data.getExtras().get("data"); if (data.getExtras().get("data") == null) Toast.makeText(getApplicationContext(), "No image returned", Toast.LENGTH_LONG).show(); else imageView[im-1].setImageBitmap(bitmap); } } super.onActivityResult(requestCode, resultCode, data); }*/ /* public void onClick(View v) { // TODO Auto-generated method stub if (v == save) { BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable(); Bitmap bitmap = drawable.getBitmap(); File sdCardDirectory = Environment.getExternalStorageDirectory(); File image = new File(sdCardDirectory, "test.png"); boolean success = false; // Encode the file as a PNG image. FileOutputStream outStream; try { outStream = new FileOutputStream(image); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream); /* 100 to keep full quality of the image */ /* outStream.flush(); outStream.close(); success = true; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if (success) { Toast.makeText(getApplicationContext(), "Image saved with success", Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(), "Error during image saving", Toast.LENGTH_LONG).show(); } } else if (v == capture) { captureImage(); } } */ @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_create, menu); return true; } @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. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } private void saveitem() { final String name = et1.getText().toString().trim(); final String desc = et2.getText().toString().trim(); final String price = et3.getText().toString().trim(); /*name=name.trim(); desc=desc.trim(); price=price.trim();*/ // If user doesn't enter a title or content, do nothing // If user enters title, but no content, save // If user enters content with no title, give warning // If user enters both title and content, save if (!name.isEmpty()) { if (olditem == null) { // Check if post is being created or edited // create new post //res = getResources(); final ParseObject post = new ParseObject("Items"); //ByteArrayOutputStream stream = new ByteArrayOutputStream(); //bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream); //byte[] data = stream.toByteArray(); //ParseFile file = new ParseFile("resume.txt", data); //file.saveInBackground(); //post.put("mediatype", data); final Drawable d = getResources().getDrawable(R.drawable.ic_launcher); post.put("name", name); post.put("description", desc); post.put("price", price); post.put("image", imagefile); post.put("image1", imagefile1); post.put("image2", imagefile2); post.put("postedby", ParseUser.getCurrentUser().getUsername()); if(cat.equals("Choose a Category"))cat="Others"; post.put("category",cat); setProgressBarIndeterminateVisibility(true); post.saveInBackground(new SaveCallback() { public void done(ParseException e) { setProgressBarIndeterminateVisibility(false); if (e == null) { // Saved successfully. if(cat==null) { cat = "Others"; } olditem=new ItemInfo(post.getObjectId(),name,ParseUser.getCurrentUser().getUsername(),desc,new BitmapDrawable(getResources(), CommonResources.bmp),new BitmapDrawable(getResources(), CommonResources.bmp1),new BitmapDrawable(getResources(), CommonResources.bmp2),price,cat); Toast.makeText(getApplicationContext(), "Updated", Toast.LENGTH_SHORT).show(); finish(); } else { // The save failed. Toast.makeText(getApplicationContext(), "Failed to Save", Toast.LENGTH_SHORT).show(); Log.d(getClass().getSimpleName(), "User update error: " + e); } } }); }else{ParseQuery<ParseObject> query = ParseQuery.getQuery("Items"); Log.d("test","Modifing Old item"+olditem.getId()); // Retrieve the object by id query.getInBackground(olditem.getId(), new GetCallback<ParseObject>() { public void done(ParseObject post, ParseException e) { if (e == null) { // Now let's update it with some new data. post.put("name", name); post.put("description", desc); post.put("price", price); post.put("image", imagefile); post.put("postedby", ParseUser.getCurrentUser().getUsername()); if(neg.isChecked()==true)post.put("negotiable","yes"); else post.put("negotiable","no"); setProgressBarIndeterminateVisibility(true); post.saveInBackground(new SaveCallback() { public void done(ParseException e) { setProgressBarIndeterminateVisibility(false); if (e == null) { //ItemInfo olditem = new ItemInfo(name, null, desc, null, price); Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_SHORT).show(); Log.d("test","Saved"); } else { // The save failed. Toast.makeText(getApplicationContext(), "Failed to Save", Toast.LENGTH_SHORT).show(); Log.d(getClass().getSimpleName(), "User update error: " + e); } } }); }else{Log.d("test","no item found");} } }); } } else if (name.isEmpty() && !desc.isEmpty()) { AlertDialog.Builder builder = new AlertDialog.Builder(CreateActivity.this); builder.setMessage("Missing name or description!") .setTitle(R.string.edit_error_title) .setPositiveButton(android.R.string.ok, null); AlertDialog dialog = builder.create(); dialog.show(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_TAKE_PHOTO && resultCode == Activity.RESULT_OK && data!=null) { Bundle extras = data.getExtras(); Bitmap imageBitmap = (Bitmap) extras.get("data"); imageView[im-1].setImageBitmap(imageBitmap); } } private File createImageFile() throws IOException { // Create an image file name String imageFileName = "test"+im; File storageDir = Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES); File image = File.createTempFile( imageFileName, /* prefix */ ".jpg", /* suffix */ storageDir /* directory */ ); // Save a file: path for use with ACTION_VIEW intents mCurrentPhotoPath = "file:" + image.getAbsolutePath(); return image; } private void dispatchTakePictureIntent() { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // Ensure that there's a camera activity to handle the intent if (takePictureIntent.resolveActivity(getPackageManager()) != null) { // Create the File where the photo should go File photoFile = null; try { photoFile = createImageFile(); } catch (IOException ex) { // Error occurred while creating the File Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_SHORT).show(); } // Continue only if the File was successfully created if (photoFile != null) { //takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photoFile)); startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO); } } } }
package rsc.publisher; import java.util.Objects; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import java.util.function.*; import org.reactivestreams.*; import rsc.documentation.FusionMode; import rsc.documentation.FusionSupport; import rsc.flow.*; import rsc.subscriber.SubscriptionHelper; import rsc.util.*; /** * Uses a resource, generated by a supplier for each individual Subscriber, * while streaming the values from a * Publisher derived from the same resource and makes sure the resource is released * if the sequence terminates or the Subscriber cancels. * <p> * <p> * Eager resource cleanup happens just before the source termination and exceptions * raised by the cleanup Consumer may override the terminal even. Non-eager * cleanup will drop any exception. * * @param <T> the value type streamed * @param <S> the resource type */ @FusionSupport(input = { FusionMode.NOT_APPLICABLE }, innerInput = { FusionMode.SYNC, FusionMode.ASYNC, FusionMode.CONDITIONAL }, output = { FusionMode.SYNC, FusionMode.ASYNC, FusionMode.CONDITIONAL } ) public final class PublisherUsing<T, S> extends Px<T> implements Receiver, Fuseable { final Callable<S> resourceSupplier; final Function<? super S, ? extends Publisher<? extends T>> sourceFactory; final Consumer<? super S> resourceCleanup; final boolean eager; public PublisherUsing(Callable<S> resourceSupplier, Function<? super S, ? extends Publisher<? extends T>> sourceFactory, Consumer<? super S> resourceCleanup, boolean eager) { this.resourceSupplier = Objects.requireNonNull(resourceSupplier, "resourceSupplier"); this.sourceFactory = Objects.requireNonNull(sourceFactory, "sourceFactory"); this.resourceCleanup = Objects.requireNonNull(resourceCleanup, "resourceCleanup"); this.eager = eager; } @Override public Object upstream() { return resourceSupplier; } @Override public void subscribe(Subscriber<? super T> s) { S resource; try { resource = resourceSupplier.call(); } catch (Throwable e) { ExceptionHelper.throwIfFatal(e); SubscriptionHelper.error(s, ExceptionHelper.unwrap(e)); return; } Publisher<? extends T> p; try { p = sourceFactory.apply(resource); } catch (Throwable e) { try { resourceCleanup.accept(resource); } catch (Throwable ex) { ExceptionHelper.throwIfFatal(ex); ex.addSuppressed(ExceptionHelper.unwrap(e)); e = ex; } SubscriptionHelper.error(s, ExceptionHelper.unwrap(e)); return; } if (p == null) { Throwable e = new NullPointerException("The sourceFactory returned a null value"); try { resourceCleanup.accept(resource); } catch (Throwable ex) { ExceptionHelper.throwIfFatal(ex); Throwable _ex = ExceptionHelper.unwrap(ex); _ex.addSuppressed(e); e = _ex; } SubscriptionHelper.error(s, e); return; } if (p instanceof Fuseable) { p.subscribe(new PublisherUsingFuseableSubscriber<>(s, resourceCleanup, resource, eager)); } else if (s instanceof ConditionalSubscriber) { p.subscribe(new PublisherUsingConditionalSubscriber<>((ConditionalSubscriber<? super T>)s, resourceCleanup, resource, eager)); } else { p.subscribe(new PublisherUsingSubscriber<>(s, resourceCleanup, resource, eager)); } } static final class PublisherUsingSubscriber<T, S> implements Subscriber<T>, QueueSubscription<T> { final Subscriber<? super T> actual; final Consumer<? super S> resourceCleanup; final S resource; final boolean eager; Subscription s; volatile int wip; @SuppressWarnings("rawtypes") static final AtomicIntegerFieldUpdater<PublisherUsingSubscriber> WIP = AtomicIntegerFieldUpdater.newUpdater(PublisherUsingSubscriber.class, "wip"); public PublisherUsingSubscriber(Subscriber<? super T> actual, Consumer<? super S> resourceCleanup, S resource, boolean eager) { this.actual = actual; this.resourceCleanup = resourceCleanup; this.resource = resource; this.eager = eager; } @Override public void request(long n) { s.request(n); } @Override public void cancel() { if (WIP.compareAndSet(this, 0, 1)) { s.cancel(); cleanup(); } } void cleanup() { try { resourceCleanup.accept(resource); } catch (Throwable e) { UnsignalledExceptions.onErrorDropped(e); } } @Override public void onSubscribe(Subscription s) { if (SubscriptionHelper.validate(this.s, s)) { this.s = s; actual.onSubscribe(this); } } @Override public void onNext(T t) { actual.onNext(t); } @Override public void onError(Throwable t) { if (eager && WIP.compareAndSet(this, 0, 1)) { try { resourceCleanup.accept(resource); } catch (Throwable e) { ExceptionHelper.throwIfFatal(e); Throwable _e = ExceptionHelper.unwrap(e); _e.addSuppressed(t); t = _e; } } actual.onError(t); if (!eager && WIP.compareAndSet(this, 0, 1)) { cleanup(); } } @Override public void onComplete() { if (eager && WIP.compareAndSet(this, 0, 1)) { try { resourceCleanup.accept(resource); } catch (Throwable e) { ExceptionHelper.throwIfFatal(e); actual.onError(ExceptionHelper.unwrap(e)); return; } } actual.onComplete(); if (!eager && WIP.compareAndSet(this, 0, 1)) { cleanup(); } } @Override public int requestFusion(int requestedMode) { return NONE; // always reject, upstream turned out to be non-fuseable after all } @Override public void clear() { // ignoring fusion methods } @Override public boolean isEmpty() { // ignoring fusion methods return wip != 0; } @Override public T poll() { return null; } @Override public int size() { return 0; } } static final class PublisherUsingFuseableSubscriber<T, S> implements Subscriber<T>, QueueSubscription<T> { final Subscriber<? super T> actual; final Consumer<? super S> resourceCleanup; final S resource; final boolean eager; QueueSubscription<T> s; volatile int wip; @SuppressWarnings("rawtypes") static final AtomicIntegerFieldUpdater<PublisherUsingFuseableSubscriber> WIP = AtomicIntegerFieldUpdater.newUpdater(PublisherUsingFuseableSubscriber.class, "wip"); int mode; public PublisherUsingFuseableSubscriber(Subscriber<? super T> actual, Consumer<? super S> resourceCleanup, S resource, boolean eager) { this.actual = actual; this.resourceCleanup = resourceCleanup; this.resource = resource; this.eager = eager; } @Override public void request(long n) { s.request(n); } @Override public void cancel() { if (WIP.compareAndSet(this, 0, 1)) { s.cancel(); cleanup(); } } void cleanup() { try { resourceCleanup.accept(resource); } catch (Throwable e) { UnsignalledExceptions.onErrorDropped(e); } } @SuppressWarnings("unchecked") @Override public void onSubscribe(Subscription s) { if (SubscriptionHelper.validate(this.s, s)) { this.s = (QueueSubscription<T>)s; actual.onSubscribe(this); } } @Override public void onNext(T t) { actual.onNext(t); } @Override public void onError(Throwable t) { if (eager && WIP.compareAndSet(this, 0, 1)) { try { resourceCleanup.accept(resource); } catch (Throwable e) { ExceptionHelper.throwIfFatal(e); Throwable _e = ExceptionHelper.unwrap(e); _e.addSuppressed(t); t = _e; } } actual.onError(t); if (!eager && WIP.compareAndSet(this, 0, 1)) { cleanup(); } } @Override public void onComplete() { if (eager && WIP.compareAndSet(this, 0, 1)) { try { resourceCleanup.accept(resource); } catch (Throwable e) { ExceptionHelper.throwIfFatal(e); actual.onError(ExceptionHelper.unwrap(e)); return; } } actual.onComplete(); if (!eager && WIP.compareAndSet(this, 0, 1)) { cleanup(); } } @Override public void clear() { s.clear(); } @Override public boolean isEmpty() { return s.isEmpty(); } @Override public T poll() { T v = s.poll(); if (v == null && mode == SYNC) { if (WIP.compareAndSet(this, 0, 1)) { resourceCleanup.accept(resource); } } return v; } @Override public int requestFusion(int requestedMode) { int m = s.requestFusion(requestedMode); mode = m; return m; } @Override public int size() { return s.size(); } } static final class PublisherUsingConditionalSubscriber<T, S> implements ConditionalSubscriber<T>, QueueSubscription<T> { final ConditionalSubscriber<? super T> actual; final Consumer<? super S> resourceCleanup; final S resource; final boolean eager; Subscription s; volatile int wip; @SuppressWarnings("rawtypes") static final AtomicIntegerFieldUpdater<PublisherUsingConditionalSubscriber> WIP = AtomicIntegerFieldUpdater.newUpdater(PublisherUsingConditionalSubscriber.class, "wip"); public PublisherUsingConditionalSubscriber(ConditionalSubscriber<? super T> actual, Consumer<? super S> resourceCleanup, S resource, boolean eager) { this.actual = actual; this.resourceCleanup = resourceCleanup; this.resource = resource; this.eager = eager; } @Override public void request(long n) { s.request(n); } @Override public void cancel() { if (WIP.compareAndSet(this, 0, 1)) { s.cancel(); cleanup(); } } void cleanup() { try { resourceCleanup.accept(resource); } catch (Throwable e) { UnsignalledExceptions.onErrorDropped(e); } } @Override public void onSubscribe(Subscription s) { if (SubscriptionHelper.validate(this.s, s)) { this.s = s; actual.onSubscribe(this); } } @Override public void onNext(T t) { actual.onNext(t); } @Override public boolean tryOnNext(T t) { return actual.tryOnNext(t); } @Override public void onError(Throwable t) { if (eager && WIP.compareAndSet(this, 0, 1)) { try { resourceCleanup.accept(resource); } catch (Throwable e) { ExceptionHelper.throwIfFatal(e); Throwable _e = ExceptionHelper.unwrap(e); _e.addSuppressed(t); t = _e; } } actual.onError(t); if (!eager && WIP.compareAndSet(this, 0, 1)) { cleanup(); } } @Override public void onComplete() { if (eager && WIP.compareAndSet(this, 0, 1)) { try { resourceCleanup.accept(resource); } catch (Throwable e) { ExceptionHelper.throwIfFatal(e); actual.onError(ExceptionHelper.unwrap(e)); return; } } actual.onComplete(); if (!eager && WIP.compareAndSet(this, 0, 1)) { cleanup(); } } @Override public int requestFusion(int requestedMode) { return NONE; // always reject, upstream turned out to be non-fuseable after all } @Override public void clear() { // ignoring fusion methods } @Override public boolean isEmpty() { // ignoring fusion methods return wip != 0; } @Override public T poll() { return null; } @Override public int size() { return 0; } } }
/* * 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.samoa.instances; import java.text.SimpleDateFormat; /** * Implementation of Instance. */ public class InstanceImpl implements MultiLabelInstance { /** * The weight. */ protected double weight; /** * The instance data. */ protected InstanceData instanceData; /** * The instance information. */ protected InstancesHeader instanceHeader; /** * Instantiates a new instance. * * @param inst * the inst */ public InstanceImpl(InstanceImpl inst) { this.weight = inst.weight; this.instanceData = inst.instanceData; this.instanceHeader = inst.instanceHeader; } //Dense /** * Instantiates a new instance. * * @param weight * the weight * @param res * the res */ public InstanceImpl(double weight, double[] res) { this.weight = weight; this.instanceData = new DenseInstanceData(res); } //Sparse /** * Instantiates a new instance. * * @param weight * the weight * @param attributeValues * the attribute values * @param indexValues * the index values * @param numberAttributes * the number attributes */ public InstanceImpl(double weight, double[] attributeValues, int[] indexValues, int numberAttributes) { this.weight = weight; this.instanceData = new SparseInstanceData(attributeValues, indexValues, numberAttributes); } /** * Instantiates a new instance. * * @param weight * the weight * @param instanceData * the instance data */ public InstanceImpl(double weight, InstanceData instanceData) { this.weight = weight; this.instanceData = instanceData; } /** * Instantiates a new instance. * * @param numAttributes * the num attributes */ public InstanceImpl(int numAttributes) { this.instanceData = new DenseInstanceData(new double[numAttributes]); //JD this.weight = 1; } /** * Weight. * * @return the double */ @Override public double weight() { return weight; } /** * Sets the weight. * * @param weight * the new weight */ @Override public void setWeight(double weight) { this.weight = weight; } /** * Attribute. * * @param instAttIndex * the inst att index * @return the attribute */ @Override public Attribute attribute(int instAttIndex) { return this.instanceHeader.attribute(instAttIndex); } public int indexOfAttribute(Attribute attribute) { return this.instanceHeader.indexOf(attribute); } /** * Delete attribute at. * * @param i * the i */ @Override public void deleteAttributeAt(int i) { this.instanceData.deleteAttributeAt(i); } /** * Insert attribute at. * * @param i * the i */ @Override public void insertAttributeAt(int i) { this.instanceData.insertAttributeAt(i); } /** * Num attributes. * * @return the int */ @Override public int numAttributes() { return this.instanceData.numAttributes(); } /** * Value. * * @param instAttIndex * the inst att index * @return the double */ @Override public double value(int instAttIndex) { return this.instanceData.value(instAttIndex); } /** * Checks if is missing. * * @param instAttIndex * the inst att index * @return true, if is missing */ @Override public boolean isMissing(int instAttIndex) { return this.instanceData.isMissing(instAttIndex); } /** * Num values. * * @return the int */ @Override public int numValues() { return this.instanceData.numValues(); } /** * Index. * * @param i * the i * @return the int */ @Override public int index(int i) { return this.instanceData.index(i); } /** * Value sparse. * * @param i * the i * @return the double */ @Override public double valueSparse(int i) { return this.instanceData.valueSparse(i); } /** * Checks if is missing sparse. * * @param p * the p * @return true, if is missing sparse */ @Override public boolean isMissingSparse(int p) { return this.instanceData.isMissingSparse(p); } /** * Value. * * @param attribute * the attribute * @return the double */ @Override public double value(Attribute attribute) { int index = this.instanceHeader.indexOf(attribute); return value(index); } /** * String value. * * @param i * the i * @return the string */ @Override public String stringValue(int i) { throw new UnsupportedOperationException("Not yet implemented"); } /** * To double array. * * @return the double[] */ @Override public double[] toDoubleArray() { return this.instanceData.toDoubleArray(); } /** * Sets the value. * * @param numAttribute * the num attribute * @param d * the d */ @Override public void setValue(int numAttribute, double d) { this.instanceData.setValue(numAttribute, d); } /** * Class value. * * @return the double */ @Override public double classValue() { return this.instanceData.value(classIndex()); } /** * Class index. * * @return the int */ @Override public int classIndex() { int classIndex = instanceHeader.classIndex(); // return ? classIndex : 0; if (classIndex == Integer.MAX_VALUE) if (this.instanceHeader.instanceInformation.range != null) classIndex = instanceHeader.instanceInformation.range.getStart(); else classIndex = 0; return classIndex; } /** * Num classes. * * @return the int */ @Override public int numClasses() { return this.instanceHeader.numClasses(); } /** * Class is missing. * * @return true, if successful */ @Override public boolean classIsMissing() { return this.instanceData.isMissing(classIndex()); } /** * Class attribute. * * @return the attribute */ @Override public Attribute classAttribute() { return this.instanceHeader.attribute(classIndex()); } /** * Sets the class value. * * @param d * the new class value */ @Override public void setClassValue(double d) { this.setValue(classIndex(), d); } /** * Copy. * * @return the instance */ @Override public Instance copy() { InstanceImpl inst = new InstanceImpl(this); return inst; } /** * Dataset. * * @return the instances */ @Override public Instances dataset() { return this.instanceHeader; } /** * Sets the dataset. * * @param dataset * the new dataset */ @Override public void setDataset(Instances dataset) { if (dataset instanceof InstancesHeader) { this.instanceHeader = (InstancesHeader) dataset; } else { this.instanceHeader = new InstancesHeader(dataset); } } /** * Adds the sparse values. * * @param indexValues * the index values * @param attributeValues * the attribute values * @param numberAttributes * the number attributes */ @Override public void addSparseValues(int[] indexValues, double[] attributeValues, int numberAttributes) { this.instanceData = new SparseInstanceData(attributeValues, indexValues, numberAttributes); //??? } /** * Text representation of a InstanceImpl. */ @Override public String toString() { StringBuilder str = new StringBuilder(); for (int attIndex = 0; attIndex < this.numAttributes(); attIndex++) { if (!this.isMissing(attIndex)) { if (this.attribute(attIndex).isNominal()) { int valueIndex = (int) this.value(attIndex); String stringValue = this.attribute(attIndex).value(valueIndex); str.append(stringValue).append(","); } else if (this.attribute(attIndex).isNumeric()) { str.append(this.value(attIndex)).append(","); } else if (this.attribute(attIndex).isDate()) { SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); str.append(dateFormatter.format(this.value(attIndex))).append(","); } } else { str.append("?,"); } } return str.toString(); } @Override public int numInputAttributes() { return this.instanceHeader.numInputAttributes(); } @Override public int numOutputAttributes() { return numberOutputTargets(); } @Override public int numberOutputTargets() { return this.instanceHeader.numOutputAttributes(); } @Override public double classValue(int instAttIndex) { return valueOutputAttribute(instAttIndex); } @Override public void setClassValue(int indexClass, double valueAttribute) { InstanceInformation instanceInformation = this.instanceHeader.getInstanceInformation(); this.instanceData.setValue(instanceInformation.outputAttributeIndex(indexClass), valueAttribute); } @Override public Attribute outputAttribute(int outputIndex) { InstanceInformation instanceInformation = this.instanceHeader.getInstanceInformation(); return instanceInformation.outputAttribute(outputIndex); } @Override public Attribute inputAttribute(int attributeIndex) { InstanceInformation instanceInformation = this.instanceHeader.getInstanceInformation(); return instanceInformation.inputAttribute(attributeIndex); } @Override public double valueInputAttribute(int attributeIndex) { InstanceInformation instanceInformation = this.instanceHeader.getInstanceInformation(); return this.instanceData.value(instanceInformation.inputAttributeIndex(attributeIndex)); } @Override public double valueOutputAttribute(int attributeIndex) { InstanceInformation instanceInformation = this.instanceHeader.getInstanceInformation(); return this.instanceData.value(instanceInformation.outputAttributeIndex(attributeIndex)); } @Override public void setMissing(int instAttIndex) { this.setValue(instAttIndex, Double.NaN); } @Override public void setMissing(Attribute attribute) { int index = this.instanceHeader.indexOf(attribute); this.setMissing(index); } @Override public boolean isMissing(Attribute attribute) { int index = this.instanceHeader.indexOf(attribute); return this.isMissing(index); } @Override public void setValue(Attribute attribute, double value) { int index = this.instanceHeader.indexOf(attribute); this.setValue(index, value); } }
package systemtests; import static seedu.address.logic.commands.CommandTestUtil.ADDRESS_DESC_AMY; import static seedu.address.logic.commands.CommandTestUtil.ADDRESS_DESC_BOB; import static seedu.address.logic.commands.CommandTestUtil.EMAIL_DESC_AMY; import static seedu.address.logic.commands.CommandTestUtil.EMAIL_DESC_BOB; import static seedu.address.logic.commands.CommandTestUtil.INVALID_ADDRESS_DESC; import static seedu.address.logic.commands.CommandTestUtil.INVALID_EMAIL_DESC; import static seedu.address.logic.commands.CommandTestUtil.INVALID_NAME_DESC; import static seedu.address.logic.commands.CommandTestUtil.INVALID_PHONE_DESC; import static seedu.address.logic.commands.CommandTestUtil.INVALID_TAG_DESC; import static seedu.address.logic.commands.CommandTestUtil.NAME_DESC_AMY; import static seedu.address.logic.commands.CommandTestUtil.NAME_DESC_BOB; import static seedu.address.logic.commands.CommandTestUtil.PHONE_DESC_AMY; import static seedu.address.logic.commands.CommandTestUtil.PHONE_DESC_BOB; import static seedu.address.logic.commands.CommandTestUtil.TAG_DESC_FRIEND; import static seedu.address.logic.commands.CommandTestUtil.TAG_DESC_HUSBAND; import static seedu.address.logic.commands.CommandTestUtil.VALID_ADDRESS_BOB; import static seedu.address.logic.commands.CommandTestUtil.VALID_EMAIL_BOB; import static seedu.address.logic.commands.CommandTestUtil.VALID_NAME_BOB; import static seedu.address.logic.commands.CommandTestUtil.VALID_PHONE_BOB; import static seedu.address.logic.commands.CommandTestUtil.VALID_TAG_FRIEND; import static seedu.address.logic.commands.CommandTestUtil.VALID_TAG_HUSBAND; import static seedu.address.logic.parser.CliSyntax.PREFIX_TAG; import static seedu.address.model.Model.PREDICATE_SHOW_ALL_PERSONS; import static seedu.address.testutil.TypicalIndexes.INDEX_FIRST_PERSON; import static seedu.address.testutil.TypicalPersons.AMY; import static seedu.address.testutil.TypicalPersons.BOB; import static seedu.address.testutil.TypicalPersons.KEYWORD_MATCHING_MEIER; import org.junit.Test; import seedu.address.commons.core.Messages; import seedu.address.commons.core.index.Index; import seedu.address.logic.commands.EditCommand; import seedu.address.logic.commands.RedoCommand; import seedu.address.logic.commands.UndoCommand; import seedu.address.model.Model; import seedu.address.model.person.Address; import seedu.address.model.person.Email; import seedu.address.model.person.Name; import seedu.address.model.person.Person; import seedu.address.model.person.Phone; import seedu.address.model.person.ReadOnlyPerson; import seedu.address.model.person.exceptions.DuplicatePersonException; import seedu.address.model.person.exceptions.PersonNotFoundException; import seedu.address.model.tag.Tag; import seedu.address.testutil.PersonBuilder; import seedu.address.testutil.PersonUtil; public class EditCommandSystemTest extends AddressBookSystemTest { @Test public void edit() throws Exception { Model model = getModel(); /* ----------------- Performing edit operation while an unfiltered list is being shown ---------------------- */ /* Case: edit all fields, command with leading spaces, trailing spaces and multiple spaces between each field * -> edited */ Index index = INDEX_FIRST_PERSON; String command = " " + EditCommand.COMMAND_WORD + " " + index.getOneBased() + " " + NAME_DESC_BOB + " " + PHONE_DESC_BOB + " " + EMAIL_DESC_BOB + " " + ADDRESS_DESC_BOB + " " + TAG_DESC_HUSBAND + " "; Person editedPerson = new PersonBuilder().withName(VALID_NAME_BOB).withPhone(VALID_PHONE_BOB) .withEmail(VALID_EMAIL_BOB).withAddress(VALID_ADDRESS_BOB).withTags(VALID_TAG_HUSBAND).build(); assertCommandSuccess(command, index, editedPerson); /* Case: undo editing the last person in the list -> last person restored */ command = UndoCommand.COMMAND_WORD; String expectedResultMessage = UndoCommand.MESSAGE_SUCCESS; assertCommandSuccess(command, model, expectedResultMessage); /* Case: redo editing the last person in the list -> last person edited again */ command = RedoCommand.COMMAND_WORD; expectedResultMessage = RedoCommand.MESSAGE_SUCCESS; model.updatePerson( getModel().getFilteredPersonList().get(INDEX_FIRST_PERSON.getZeroBased()), editedPerson); assertCommandSuccess(command, model, expectedResultMessage); /* Case: edit a person with new values same as existing values -> edited */ command = EditCommand.COMMAND_WORD + " " + index.getOneBased() + NAME_DESC_BOB + PHONE_DESC_BOB + EMAIL_DESC_BOB + ADDRESS_DESC_BOB + TAG_DESC_FRIEND + TAG_DESC_HUSBAND; assertCommandSuccess(command, index, BOB); /* Case: edit some fields -> edited */ index = INDEX_FIRST_PERSON; command = EditCommand.COMMAND_WORD + " " + index.getOneBased() + TAG_DESC_FRIEND; ReadOnlyPerson personToEdit = getModel().getFilteredPersonList().get(index.getZeroBased()); editedPerson = new PersonBuilder(personToEdit).withTags(VALID_TAG_FRIEND).build(); assertCommandSuccess(command, index, editedPerson); /* Case: clear tags -> cleared */ index = INDEX_FIRST_PERSON; command = EditCommand.COMMAND_WORD + " " + index.getOneBased() + " " + PREFIX_TAG.getPrefix(); editedPerson = new PersonBuilder(personToEdit).withTags().build(); assertCommandSuccess(command, index, editedPerson); /* ------------------ Performing edit operation while a filtered list is being shown ------------------------ */ /* Case: filtered person list, edit index within bounds of address book and person list -> edited */ showPersonsWithName(KEYWORD_MATCHING_MEIER); index = INDEX_FIRST_PERSON; assert index.getZeroBased() < getModel().getFilteredPersonList().size(); command = EditCommand.COMMAND_WORD + " " + index.getOneBased() + " " + NAME_DESC_BOB; personToEdit = getModel().getFilteredPersonList().get(index.getZeroBased()); editedPerson = new PersonBuilder(personToEdit).withName(VALID_NAME_BOB).build(); assertCommandSuccess(command, index, editedPerson); /* Case: filtered person list, edit index within bounds of address book but out of bounds of person list * -> rejected */ showPersonsWithName(KEYWORD_MATCHING_MEIER); int invalidIndex = getModel().getAddressBook().getPersonList().size(); assertCommandFailure(EditCommand.COMMAND_WORD + " " + invalidIndex + NAME_DESC_BOB, Messages.MESSAGE_INVALID_PERSON_DISPLAYED_INDEX); /* --------------------- Performing edit operation while a person card is selected -------------------------- */ /* Case: selects first card in the person list, edit a person -> edited, card selection remains unchanged but * browser url changes */ showAllPersons(); index = INDEX_FIRST_PERSON; selectPerson(index); command = EditCommand.COMMAND_WORD + " " + index.getOneBased() + NAME_DESC_AMY + PHONE_DESC_AMY + EMAIL_DESC_AMY + ADDRESS_DESC_AMY + TAG_DESC_FRIEND; // this can be misleading: card selection actually remains unchanged but the // browser's url is updated to reflect the new person's name assertCommandSuccess(command, index, AMY, index); /* --------------------------------- Performing invalid edit operation -------------------------------------- */ /* Case: invalid index (0) -> rejected */ assertCommandFailure(EditCommand.COMMAND_WORD + " 0" + NAME_DESC_BOB, String.format(Messages.MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE)); /* Case: invalid index (-1) -> rejected */ assertCommandFailure(EditCommand.COMMAND_WORD + " -1" + NAME_DESC_BOB, String.format(Messages.MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE)); /* Case: invalid index (size + 1) -> rejected */ invalidIndex = getModel().getFilteredPersonList().size() + 1; assertCommandFailure(EditCommand.COMMAND_WORD + " " + invalidIndex + NAME_DESC_BOB, Messages.MESSAGE_INVALID_PERSON_DISPLAYED_INDEX); /* Case: missing index -> rejected */ assertCommandFailure(EditCommand.COMMAND_WORD + NAME_DESC_BOB, String.format(Messages.MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE)); /* Case: missing all fields -> rejected */ assertCommandFailure(EditCommand.COMMAND_WORD + " " + INDEX_FIRST_PERSON.getOneBased(), EditCommand.MESSAGE_NOT_EDITED); /* Case: invalid name -> rejected */ assertCommandFailure(EditCommand.COMMAND_WORD + " " + INDEX_FIRST_PERSON.getOneBased() + INVALID_NAME_DESC, Name.MESSAGE_NAME_CONSTRAINTS); /* Case: invalid phone -> rejected */ assertCommandFailure(EditCommand.COMMAND_WORD + " " + INDEX_FIRST_PERSON.getOneBased() + INVALID_PHONE_DESC, Phone.MESSAGE_PHONE_CONSTRAINTS); /* Case: invalid email -> rejected */ assertCommandFailure(EditCommand.COMMAND_WORD + " " + INDEX_FIRST_PERSON.getOneBased() + INVALID_EMAIL_DESC, Email.MESSAGE_EMAIL_CONSTRAINTS); /* Case: invalid address -> rejected */ assertCommandFailure(EditCommand.COMMAND_WORD + " " + INDEX_FIRST_PERSON.getOneBased() + INVALID_ADDRESS_DESC, Address.MESSAGE_ADDRESS_CONSTRAINTS); /* Case: invalid tag -> rejected */ assertCommandFailure(EditCommand.COMMAND_WORD + " " + INDEX_FIRST_PERSON.getOneBased() + INVALID_TAG_DESC, Tag.MESSAGE_TAG_CONSTRAINTS); /* Case: edit a person with new values same as another person's values -> rejected */ executeCommand(PersonUtil.getAddCommand(BOB)); assert getModel().getAddressBook().getPersonList().contains(BOB); index = INDEX_FIRST_PERSON; assert !getModel().getFilteredPersonList().get(index.getZeroBased()).equals(BOB); command = EditCommand.COMMAND_WORD + " " + index.getOneBased() + NAME_DESC_BOB + PHONE_DESC_BOB + EMAIL_DESC_BOB + ADDRESS_DESC_BOB + TAG_DESC_FRIEND + TAG_DESC_HUSBAND; assertCommandFailure(command, EditCommand.MESSAGE_DUPLICATE_PERSON); /* Case: edit a person with new values same as another person's values but with different tags -> rejected */ command = EditCommand.COMMAND_WORD + " " + index.getOneBased() + NAME_DESC_BOB + PHONE_DESC_BOB + EMAIL_DESC_BOB + ADDRESS_DESC_BOB + TAG_DESC_HUSBAND; assertCommandFailure(command, EditCommand.MESSAGE_DUPLICATE_PERSON); } /** * Performs the same verification as {@code assertCommandSuccess(String, Index, ReadOnlyPerson, Index)} except that * the browser url and selected card remain unchanged. * @param toEdit the index of the current model's filtered list * @see EditCommandSystemTest#assertCommandSuccess(String, Index, ReadOnlyPerson, Index) */ private void assertCommandSuccess(String command, Index toEdit, ReadOnlyPerson editedPerson) { assertCommandSuccess(command, toEdit, editedPerson, null); } /** * Performs the same verification as {@code assertCommandSuccess(String, Model, String, Index)} and in addition,<br> * 1. Asserts that result display box displays the success message of executing {@code EditCommand}.<br> * 2. Asserts that the model related components are updated to reflect the person at index {@code toEdit} being * updated to values specified {@code editedPerson}.<br> * @param toEdit the index of the current model's filtered list. * @see EditCommandSystemTest#assertCommandSuccess(String, Model, String, Index) */ private void assertCommandSuccess(String command, Index toEdit, ReadOnlyPerson editedPerson, Index expectedSelectedCardIndex) { Model expectedModel = getModel(); try { expectedModel.updatePerson( expectedModel.getFilteredPersonList().get(toEdit.getZeroBased()), editedPerson); expectedModel.updateFilteredPersonList(PREDICATE_SHOW_ALL_PERSONS); } catch (DuplicatePersonException | PersonNotFoundException e) { throw new IllegalArgumentException( "editedPerson is a duplicate in expectedModel, or it isn't found in the model."); } assertCommandSuccess(command, expectedModel, String.format(EditCommand.MESSAGE_EDIT_PERSON_SUCCESS, editedPerson), expectedSelectedCardIndex); } /** * Performs the same verification as {@code assertCommandSuccess(String, Model, String, Index)} except that the * browser url and selected card remain unchanged. * @see EditCommandSystemTest#assertCommandSuccess(String, Model, String, Index) */ private void assertCommandSuccess(String command, Model expectedModel, String expectedResultMessage) { assertCommandSuccess(command, expectedModel, expectedResultMessage, null); } /** * Executes {@code command} and in addition,<br> * 1. Asserts that the command box displays an empty string.<br> * 2. Asserts that the result display box displays {@code expectedResultMessage}.<br> * 3. Asserts that the model related components equal to {@code expectedModel}.<br> * 4. Asserts that the browser url and selected card update accordingly depending on the card at * {@code expectedSelectedCardIndex}.<br> * 5. Asserts that the status bar's sync status changes.<br> * 6. Asserts that the command box has the default style class.<br> * Verifications 1 to 3 are performed by * {@code AddressBookSystemTest#assertApplicationDisplaysExpected(String, String, Model)}.<br> * @see AddressBookSystemTest#assertApplicationDisplaysExpected(String, String, Model) * @see AddressBookSystemTest#assertSelectedCardChanged(Index) */ private void assertCommandSuccess(String command, Model expectedModel, String expectedResultMessage, Index expectedSelectedCardIndex) { executeCommand(command); expectedModel.updateFilteredPersonList(PREDICATE_SHOW_ALL_PERSONS); assertApplicationDisplaysExpected("", expectedResultMessage, expectedModel); assertCommandBoxShowsDefaultStyle(); if (expectedSelectedCardIndex != null) { assertSelectedCardChanged(expectedSelectedCardIndex); } else { assertSelectedCardUnchanged(); } assertStatusBarUnchangedExceptSyncStatus(); } /** * Executes {@code command} and in addition,<br> * 1. Asserts that the command box displays {@code command}.<br> * 2. Asserts that result display box displays {@code expectedResultMessage}.<br> * 3. Asserts that the model related components equal to the current model.<br> * 4. Asserts that the browser url, selected card and status bar remain unchanged.<br> * 5. Asserts that the command box has the error style.<br> * Verifications 1 to 3 are performed by * {@code AddressBookSystemTest#assertApplicationDisplaysExpected(String, String, Model)}.<br> * @see AddressBookSystemTest#assertApplicationDisplaysExpected(String, String, Model) */ private void assertCommandFailure(String command, String expectedResultMessage) { Model expectedModel = getModel(); executeCommand(command); assertApplicationDisplaysExpected(command, expectedResultMessage, expectedModel); assertSelectedCardUnchanged(); assertCommandBoxShowsErrorStyle(); assertStatusBarUnchanged(); } }
package org.testcontainers.containers; import lombok.NonNull; import com.github.dockerjava.api.command.InspectContainerResponse; import org.jetbrains.annotations.NotNull; import org.rnorth.ducttape.ratelimits.RateLimiter; import org.rnorth.ducttape.ratelimits.RateLimiterBuilder; import org.rnorth.ducttape.unreliables.Unreliables; import org.testcontainers.containers.traits.LinkableContainer; import org.testcontainers.delegate.DatabaseDelegate; import org.testcontainers.ext.ScriptUtils; import org.testcontainers.jdbc.JdbcDatabaseDelegate; import org.testcontainers.utility.MountableFile; import java.sql.Connection; import java.sql.Driver; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; /** * Base class for containers that expose a JDBC connection * * @author richardnorth */ public abstract class JdbcDatabaseContainer<SELF extends JdbcDatabaseContainer<SELF>> extends GenericContainer<SELF> implements LinkableContainer { private static final Object DRIVER_LOAD_MUTEX = new Object(); private Driver driver; private String initScriptPath; protected Map<String, String> parameters = new HashMap<>(); private static final RateLimiter DB_CONNECT_RATE_LIMIT = RateLimiterBuilder.newBuilder() .withRate(10, TimeUnit.SECONDS) .withConstantThroughput() .build(); private int startupTimeoutSeconds = 120; private int connectTimeoutSeconds = 120; public JdbcDatabaseContainer(@NonNull final String dockerImageName) { super(dockerImageName); } public JdbcDatabaseContainer(@NonNull final Future<String> image) { super(image); } /** * @return the name of the actual JDBC driver to use */ public abstract String getDriverClassName(); /** * @return a JDBC URL that may be used to connect to the dockerized DB */ public abstract String getJdbcUrl(); /** * @return the database name */ public String getDatabaseName() { throw new UnsupportedOperationException(); } /** * @return the standard database username that should be used for connections */ public abstract String getUsername(); /** * @return the standard password that should be used for connections */ public abstract String getPassword(); /** * @return a test query string suitable for testing that this particular database type is alive */ protected abstract String getTestQueryString(); public SELF withUsername(String username) { throw new UnsupportedOperationException(); } public SELF withPassword(String password) { throw new UnsupportedOperationException(); } public SELF withDatabaseName(String dbName) { throw new UnsupportedOperationException(); } /** * Set startup time to allow, including image pull time, in seconds. * * @param startupTimeoutSeconds startup time to allow, including image pull time, in seconds * @return self */ public SELF withStartupTimeoutSeconds(int startupTimeoutSeconds) { this.startupTimeoutSeconds = startupTimeoutSeconds; return self(); } /** * Set time to allow for the database to start and establish an initial connection, in seconds. * * @param connectTimeoutSeconds time to allow for the database to start and establish an initial connection in seconds * @return self */ public SELF withConnectTimeoutSeconds(int connectTimeoutSeconds) { this.connectTimeoutSeconds = connectTimeoutSeconds; return self(); } public SELF withInitScript(String initScriptPath) { this.initScriptPath = initScriptPath; return self(); } @Override protected void waitUntilContainerStarted() { // Repeatedly try and open a connection to the DB and execute a test query logger().info("Waiting for database connection to become available at {} using query '{}'", getJdbcUrl(), getTestQueryString()); Unreliables.retryUntilSuccess(getStartupTimeoutSeconds(), TimeUnit.SECONDS, () -> { if (!isRunning()) { throw new ContainerLaunchException("Container failed to start"); } try (Connection connection = createConnection("")) { boolean success = connection.createStatement().execute(JdbcDatabaseContainer.this.getTestQueryString()); if (success) { logger().info("Obtained a connection to container ({})", JdbcDatabaseContainer.this.getJdbcUrl()); return null; } else { throw new SQLException("Failed to execute test query"); } } }); } @Override protected void containerIsStarted(InspectContainerResponse containerInfo) { runInitScriptIfRequired(); } /** * Obtain an instance of the correct JDBC driver for this particular database container type * * @return a JDBC Driver */ public Driver getJdbcDriverInstance() { synchronized (DRIVER_LOAD_MUTEX) { if (driver == null) { try { driver = (Driver) Class.forName(this.getDriverClassName()).newInstance(); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { throw new RuntimeException("Could not get Driver", e); } } } return driver; } /** * Creates a connection to the underlying containerized database instance. * * @param queryString query string parameters that should be appended to the JDBC connection URL. * The '?' character must be included * @return a Connection * @throws SQLException if there is a repeated failure to create the connection */ public Connection createConnection(String queryString) throws SQLException { final Properties info = new Properties(); info.put("user", this.getUsername()); info.put("password", this.getPassword()); final String url = constructUrlForConnection(queryString); final Driver jdbcDriverInstance = getJdbcDriverInstance(); try { return Unreliables.retryUntilSuccess(getConnectTimeoutSeconds(), TimeUnit.SECONDS, () -> DB_CONNECT_RATE_LIMIT.getWhenReady(() -> jdbcDriverInstance.connect(url, info))); } catch (Exception e) { throw new SQLException("Could not create new connection", e); } } /** * Template method for constructing the JDBC URL to be used for creating {@link Connection}s. * This should be overridden if the JDBC URL and query string concatenation or URL string * construction needs to be different to normal. * * @param queryString query string parameters that should be appended to the JDBC connection URL. * The '?' character must be included * @return a full JDBC URL including queryString */ protected String constructUrlForConnection(String queryString) { return getJdbcUrl() + queryString; } protected void optionallyMapResourceParameterAsVolume(@NotNull String paramName, @NotNull String pathNameInContainer, @NotNull String defaultResource) { String resourceName = parameters.getOrDefault(paramName, defaultResource); if (resourceName != null) { final MountableFile mountableFile = MountableFile.forClasspathResource(resourceName); withCopyFileToContainer(mountableFile, pathNameInContainer); } } /** * Load init script content and apply it to the database if initScriptPath is set */ protected void runInitScriptIfRequired() { if (initScriptPath != null) { ScriptUtils.runInitScript(getDatabaseDelegate(), initScriptPath); } } public void setParameters(Map<String, String> parameters) { this.parameters = parameters; } @SuppressWarnings("unused") public void addParameter(String paramName, String value) { this.parameters.put(paramName, value); } /** * @return startup time to allow, including image pull time, in seconds * @deprecated should not be overridden anymore, use {@link #withStartupTimeoutSeconds(int)} in constructor instead */ @Deprecated protected int getStartupTimeoutSeconds() { return startupTimeoutSeconds; } /** * @return time to allow for the database to start and establish an initial connection, in seconds * @deprecated should not be overridden anymore, use {@link #withConnectTimeoutSeconds(int)} in constructor instead */ @Deprecated protected int getConnectTimeoutSeconds() { return connectTimeoutSeconds; } protected DatabaseDelegate getDatabaseDelegate() { return new JdbcDatabaseDelegate(this, ""); } }
package tdg.reranking; import java.io.*; import java.util.*; import tdg.TDNode; import tdg.TDNodePair; import tdg.corpora.DepCorpus; import util.*; import util.file.FileUtil; public class DepKernelSubTrees { final public static float alfa = 1f; final public static float alfa2 = alfa*alfa; final public static boolean keepDaughterOrdering = false; final public static boolean printTable = true; TDNode currentNode; TDNode[] thisStructureArray; int currentLength; ArrayList<TDNode> treebank; public BitSet[] bestKS; public boolean[] ambiguityTracker; public int[] cardinalityTracker; int maxCardinalityIndex; float selfK; public DepKernelSubTrees(TDNode currentNode, ArrayList<TDNode> treebank) { this.currentNode = currentNode; this.treebank = treebank; currentLength = currentNode.length(); thisStructureArray = currentNode.getStructureArray(); bestKS = new BitSet[currentLength]; ambiguityTracker = new boolean[currentLength]; cardinalityTracker = new int [currentLength]; Arrays.fill(cardinalityTracker, -1); selfK = getK(currentNode, currentNode); //computeKernelSimilaity(); //computeCPP(); //computeBestKS(); //printBestKS(); } public void computeBestKS() { for(TDNode otherTree : treebank) { if (currentNode==otherTree) continue; getKS(otherTree); } } public int computeKernelPathSimilarity() { int K = 0; for(TDNode otherTree : treebank) { if (currentNode==otherTree) continue; K += getK(currentNode, otherTree); } return K; } public float computeKernelPathSimilarityNorm() { float K = 0; if (selfK==0) return 0; for(TDNode otherTree : treebank) { if (currentNode==otherTree) continue; float KcurrentOther = getK(currentNode, otherTree); float otherK = getK(otherTree, otherTree); if (otherK==0) continue; K += (float) KcurrentOther / Math.sqrt((selfK * otherK)); } return K; } public static BitSet[] bestKS(TDNode currentNode, ArrayList<TDNode> treebank) { DepKernelSubTrees DK = new DepKernelSubTrees(currentNode, treebank); DK.computeBestKS(); return DK.bestKS; } public void getKS(TDNode otherTree) { TDNode[] otherStructureArray = otherTree.getStructureArray(); int otherLength = otherStructureArray.length; BitSet[][] KStable = new BitSet[currentLength][otherLength]; for(TDNode nodeA : thisStructureArray) { for(TDNode nodeB : otherStructureArray) { getKS(nodeA, nodeB, KStable); } } } public void printBestKS() { for(TDNode nodeA : thisStructureArray) { System.out.println(TDNodeToString(nodeA, bestKS[nodeA.index])); } } public BitSet getKS(TDNode nodeA, TDNode nodeB, BitSet[][] KStable) { BitSet ks = KStable[nodeA.index][nodeB.index]; if (ks != null) return ks; ks = new BitSet(currentLength); if (nodeA.sameLexPosTag(nodeB)) { ks.set(nodeA.index); ArrayList<ArrayList<TDNode>> ump = uniqueMappingPairs(nodeA, nodeB); for(ArrayList<TDNode> pair : ump) { ks.or(getKS(pair.get(0), pair.get(1), KStable)); } } KStable[nodeA.index][nodeB.index] = ks; updateBestKS(nodeA, ks); return ks; } public void updateBestKS(TDNode node, BitSet ks) { int index = node.index; int cardinality = ks.cardinality(); if (cardinality > cardinalityTracker[index]) { cardinalityTracker[index] = cardinality; bestKS[index] = ks; ambiguityTracker[index] = false; } else if (cardinality == cardinalityTracker[index]) ambiguityTracker[index] = true; } public static String TDNodeToString(TDNode node, BitSet gst) { String result = "( "; result += node.lexPosTag() + " "; if (node.leftDaughters==null && node.rightDaughters==null) return result + ") "; if (node.leftDaughters!=null) { for(TDNode TDN : node.leftDaughters) { if (gst.get(TDN.index)) result += TDNodeToString(TDN, gst); } } result += "* "; if (node.rightDaughters!=null) { for(TDNode TDN : node.rightDaughters) { if (gst.get(TDN.index)) result += TDNodeToString(TDN, gst); } } result += ") "; return result; } public static ArrayList<ArrayList<TDNode>> uniqueMappingPairs(TDNode nodeA, TDNode nodeB) { ArrayList<ArrayList<TDNode>> pairs = new ArrayList<ArrayList<TDNode>>(); TDNode[][] nodeADaughters = new TDNode[][]{nodeA.leftDaughters, nodeA.rightDaughters}; TDNode[][] nodeBDaughters = new TDNode[][]{nodeB.leftDaughters, nodeB.rightDaughters}; for(int i=0; i<2; i++) { if(nodeADaughters[i] !=null && nodeBDaughters[i] != null) { int bIndex = 0; for(TDNode CA : nodeADaughters[i]) { for(int j=bIndex; j<nodeBDaughters[i].length; j++) { TDNode CB = nodeBDaughters[i][j]; if (CA.sameLexPosTag(CB)) { pairs.add(makePair(CA,CB)); bIndex = j; break; } } } } } return pairs; } public static ArrayList<TDNode> makePair(TDNode nodeA, TDNode nodeB) { ArrayList<TDNode> pair = new ArrayList<TDNode>(2); pair.add(nodeA); pair.add(nodeB); return pair; } public static float getK(TDNode thisTree, TDNode otherTree) { float K = 0; TDNode[] thisStructureArray = thisTree.getStructureArray(); TDNode[] otherStructureArray = otherTree.getStructureArray(); int thisSize = thisStructureArray.length; int otherSize = otherStructureArray.length; float[][] CDP = new float[thisSize][otherSize]; float[][] CPP = new float[thisSize][otherSize]; Utility.fillDoubleFloatArray(CDP, -1); Utility.fillDoubleFloatArray(CPP, -1); for(TDNode nodeA : thisStructureArray) { for(TDNode nodeB : otherStructureArray) { if (nodeA.sameLexPosTag(nodeB)) { K += 1 + getCPP(nodeA, nodeB, CDP, CPP); } } } /*String[] columnHeader = otherTree.getStructureLabelsArray(); String[] headHeader = thisTree.getStructureLabelsArray(); Utility.printFloatChart(CDP, columnHeader, headHeader); Utility.printFloatChart(CPP, columnHeader, headHeader);*/ return K; } public static float getCDP(TDNode A, TDNode B, float[][] CDP) { float cdp = CDP[A.index][B.index]; if (cdp != -1) return cdp; cdp = 0; if(A.sameLexPosTag(B)) { TDNode[][] ADaughters = A.daughters(); TDNode[][] BDaughters = B.daughters(); for(int i=0; i<2; i++) { if(ADaughters[i] !=null && BDaughters[i] != null) { for(TDNode CA : ADaughters[i]) { for(TDNode CB : BDaughters[i]) { if(CA.sameLexPosTag(CB)) { cdp += alfa + alfa*getCDP(CA, CB, CDP); } } } } } } CDP[A.index][B.index] = cdp; return cdp; } public static float getCPP(TDNode A, TDNode B, float[][] CDP, float[][] CPP) { float cpp = CPP[A.index][B.index]; if (cpp != -1) return cpp; cpp = getCDP(A, B, CDP); if (A.sameLexPosTag(B)) { ArrayList<ArrayList<TDNodePair>> pairs= n_airs(2, A.daughters(), B.daughters()); for(ArrayList<TDNodePair> p : pairs) { TDNodePair first = p.get(0); TDNodePair second = p.get(1); TDNode firstA = first.first; TDNode firstB = first.second; TDNode secondA = second.first; TDNode secondB = second.second; float CDPfirst = getCDP(firstA, firstB, CDP); float CDPsecond = getCDP(secondA, secondB, CDP); cpp += alfa2 + alfa * CDPfirst + alfa * CDPsecond + alfa2 * CDPfirst * CDPsecond; } } CPP[A.index][B.index] = cpp; return cpp; } public static float getCPS(TDNode A, TDNode B, float[][] CDP, float[][] CPS) { float cpp = CPS[A.index][B.index]; if (cpp != -1) return cpp; cpp = getCDP(A, B, CDP); if (A.sameLexPosTag(B)) { int maxN = Utility.max(new int[]{A.leftProle(), A.rightProle(), B.leftProle(), B.rightProle()}); ArrayList<ArrayList<TDNodePair>> nairs= new ArrayList<ArrayList<TDNodePair>>(); for(int n=2; n<maxN; n++) { nairs.addAll(n_airs(n, A.daughters(), B.daughters())); } for(ArrayList<TDNodePair> tuple : nairs) { TDNodePair first = tuple.get(0); TDNodePair second = tuple.get(1); TDNode firstA = first.first; TDNode firstB = first.second; TDNode secondA = second.first; TDNode secondB = second.second; float CDPfirst = getCDP(firstA, firstB, CDP); float CDPsecond = getCDP(secondA, secondB, CDP); cpp += 1 + CDPfirst + CDPsecond + (CDPfirst * CDPsecond); } } CPS[A.index][B.index] = cpp; return cpp; } public static ArrayList<ArrayList<TDNodePair>> n_airs(int n, TDNode[][] A, TDNode[][] B) { ArrayList<ArrayList<TDNodePair>> result = new ArrayList<ArrayList<TDNodePair>>(); result.addAll(n_airs(n, A[0], B[0])); result.addAll(n_airs(n, A[1], B[1])); int[][] splits = Utility.split(n); ArrayList<ArrayList<ArrayList<TDNodePair>>> leftSplits, rightSplits; leftSplits = new ArrayList<ArrayList<ArrayList<TDNodePair>>>(n-1); rightSplits = new ArrayList<ArrayList<ArrayList<TDNodePair>>>(n-1); for(int i=1; i<n; i++) { leftSplits.add(n_airs(i, A[0], B[0])); rightSplits.add(n_airs(i, A[1], B[1])); } for(int[] s : splits) { for(ArrayList<TDNodePair> leftPart : leftSplits.get(s[0]-1)) { for(ArrayList<TDNodePair> rightPart : rightSplits.get(s[1]-1)) { if (leftPart.isEmpty() || rightPart.isEmpty()) continue; ArrayList<TDNodePair> nair = new ArrayList<TDNodePair>(n); nair.addAll(leftPart); nair.addAll(rightPart); result.add(nair); } } } return result; } public static ArrayList<ArrayList<TDNodePair>> n_airs(int n, TDNode[] A, TDNode[] B) { ArrayList<ArrayList<TDNodePair>> result = new ArrayList<ArrayList<TDNodePair>>(); if(A==null || B==null || A.length<n || B.length<n) return result; int[][] Anairs = Utility.n_air(A.length, n); int[][] Bnairs = Utility.n_air(B.length, n); for(int[] a : Anairs) { for(int[] b : Bnairs) { ArrayList<TDNodePair> matchedNair = new ArrayList<TDNodePair>(n); boolean matched = true; for(int i=0; i<n; i++) { TDNode a_match = A[a[i]]; TDNode b_match = B[b[i]]; if (!a_match.sameLexPosTag(b_match)) { matched = false; break; } matchedNair.add(new TDNodePair(a_match, b_match)); } if (matched) result.add(matchedNair); } } return result; } public static void correlation_UAS_K(int index, int LL){ File trainFile = new File("/scratch/fsangati/CORPUS/WSJ/DEPWSJ/wsj-02-21.dep"); //File trainFile = new File("./tmp/twoDTrees.txt"); File tableFile = new File("./tmp/wsjN_correlation.txt"); PrintWriter out = FileUtil.getPrintWriter(tableFile); ArrayList<TDNode> treebank = DepCorpus.readTreebankFromFileYM(trainFile, LL); TDNode goldTree = treebank.get(index); treebank.remove(index); ArrayList<HashSet<TDNode>> UASspectrum = goldTree.collectVariationUASspectrumSameRoot(10); float goldK = 0; int mistakes = -1; int goldTreeLength = goldTree.length(); System.out.println(goldTree.toStringSentenceStructure()); for(HashSet<TDNode> bin : UASspectrum) { mistakes++; int UAS = goldTreeLength-mistakes; float UASscore = (float)UAS/goldTreeLength; for(TDNode t: bin) { DepKernelSubTrees DK = new DepKernelSubTrees(t, treebank); float Kscore_norm = DK.computeKernelPathSimilarityNorm(); if (mistakes==0) goldK = Kscore_norm; Kscore_norm = Kscore_norm / goldK; out.println(UASscore + "\t" + Kscore_norm); } } out.close(); } public static void total_correlation_UAS_K(){ //File trainFile = new File("/home/fsangati/CORPUS/WSJ/DEPWSJ/wsj-02-21.dep"); //File trainFile = new File("/scratch/fsangati/CORPUS/WSJ/DEPWSJ/wsj-02-21.dep"); //File trainFile = new File("/Users/fedya/CORPUS/WSJ/DEPWSJ/wsj-02-21.dep"); File trainFile = new File("./tmp/twoDTrees.txt"); //File tableFileExact = new File("/home/fsangati/Code/TreeGrammars/tmp/wsj10_UAS_K_correlation_exact.txt"); //File tableFileNoise = new File("/home/fsangati/Code/TreeGrammars/tmp/wsj10_UAS_K_correlation_noise.txt"); //File tableFile = new File("./tmp/wsj10_UAS_K_correlation.txt"); File tableFileExact = new File("./tmp/toy_correlation_exact.txt"); File tableFileNoise = new File("./tmp/toy_correlation_noise.txt"); File tmpFile = new File("./tmp/tmp.txt"); PrintWriter out_exact = FileUtil.getPrintWriter(tableFileExact); PrintWriter out_noise = FileUtil.getPrintWriter(tableFileNoise); PrintWriter out_tmp = FileUtil.getPrintWriter(tmpFile); ArrayList<TDNode> treebank = DepCorpus.readTreebankFromFileYM(trainFile, 20); int corpusSize = treebank.size(); float goldK = 0; for(ListIterator<TDNode> i = treebank.listIterator(); i.hasNext(); ) { System.out.println((i.previousIndex()+2) + "/" + corpusSize); TDNode goldTree = i.next(); i.remove(); int goldTreeLength = goldTree.length(); ArrayList<HashSet<TDNode>> UASspectrum = goldTree.collectVariationUASspectrumSameRoot(100); int mistakes = -1; for(HashSet<TDNode> bin : UASspectrum) { mistakes++; int UAS = goldTreeLength-mistakes; float UASscore = (float)UAS/goldTreeLength; for(TDNode t: bin) { DepKernelSubTrees DK = new DepKernelSubTrees(t, treebank); float Kscore_norm = DK.computeKernelPathSimilarityNorm(); if (mistakes==0) goldK = Kscore_norm; Kscore_norm = Kscore_norm / goldK; out_noise.println(Utility.randomNoise(UASscore, 0.01f) + "\t" + Utility.randomNoise(Kscore_norm, 0.0001f)); out_exact.println(UASscore + "\t" + Kscore_norm); } } i.add(goldTree); } out_exact.close(); out_noise.close(); out_tmp.close(); } public static void main(String[] args) { /*File toyFile = new File("./tmp/twoDTrees.txt"); ArrayList<TDNode> treebank = Corpus.readTreebankFromFile(toyFile); TDNode TDN = treebank.get(1); System.out.println(TDN); System.out.println(DepKernels.getK(TDN, TDN));*/ correlation_UAS_K(50, 10); //total_correlation_UAS_K(); } }
// $Id: TinyDBQuery.java,v 1.29 2003/10/07 21:46:07 idgay Exp $ /* tab:4 * "Copyright (c) 2000-2003 The Regents of the University of California. * All rights reserved. * * Permission to use, copy, modify, and distribute this software and its * documentation for any purpose, without fee, and without written agreement is * hereby granted, provided that the above copyright notice, the following * two paragraphs and the author appear in all copies of this software. * * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS." * * Copyright (c) 2002-2003 Intel Corporation * All rights reserved. * * This file is distributed under the terms in the attached INTEL-LICENSE * file. If you do not find these files, copies can be found by writing to * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, * 94704. Attention: Intel License Inquiry. */ package net.tinyos.tinydb; import java.util.*; import net.tinyos.message.*; /** TinyDBQuery is a Java data structure representing a query running (or to be run) on a set of motes. Queries consist of: - a list of fields to select - a list of expressions over those fields, where an expression is - an filter that rejects some readings - an aggregate that combines local readings with readings from neighbors. In addition to allowing a query to be built, this class includes methods to generate radio messages so the query can be distributed over the network or to abort the query */ public class TinyDBQuery { /** Constructor @param qid The id of the query @param epochDur The rate (in ms) at which results from the query should be generated */ public TinyDBQuery(byte qid, int epochDur) { fields = new ArrayList(); exprs = new ArrayList(); this.qid = qid; this.from_qid = NO_FROM_QUERY; this.epochDur = (short)(epochDur / MS_PER_EPOCH_DUR_UNIT); this.numEpochs = 0; } /** Reload information about a detached query from the database Note that you must still register as a listener for results from this query to begin receiving results. @param name The name of the query to restore @param nw The network to instantiate the query in @returns The restored query, or null if the query could not be found. */ public static TinyDBQuery restore(String name, TinyDBNetwork nw) { try { DBLogger db = new DBLogger(); QueryState qs = db.restoreQueryState(name); if (qs != null) { TinyDBQuery q = net.tinyos.tinydb.parser.SensorQueryer.translateQuery(qs.queryString, (byte)qs.qid); if (q == null) return null; TinyDBMain.notifyAddedQuery(q); nw.setLastEpoch(qs.qid, qs.lastEpoch); if (qs.tableName != null) db.setupLoggingInfo(q, nw, qs.tableName); return q; } else return null; } catch (java.sql.SQLException e) { return null; } catch (net.tinyos.tinydb.parser.ParseException e) { //weird ! return null; } } /** Write information about this query to the database, using the specified name as the key with which it can be restored. @param name The name to save this query under @param nw Network to fetch current query info from @returns true iff the query was successfully saved. */ public boolean saveQuery(String name, TinyDBNetwork nw) { boolean ok = false; try { DBLogger db = DBLogger.getLoggerForQid(getId()); if (db == null) db = new DBLogger(); QueryState qs = new QueryState(); qs.qid = getId(); qs.queryString = getSQL(); qs.lastEpoch = nw.getLastEpoch(getId()); qs.tableName = db.getTableName(); ok = db.saveQueryState(name, qs); db.close(); } catch (java.sql.SQLException e) { //oh well } return ok; } /** Return the id of the query */ public int getId() { return qid; } /** Set the id of the query. Added by Kyle */ public void setId(byte qid) { this.qid = qid; } /** Set the epoch duration of the query in ms*/ public void setEpoch(int epochDur) { if (epochDur == kEPOCH_DUR_ONE_SHOT) this.epochDur = kEPOCH_DUR_ONE_SHOT; else this.epochDur = (short)(epochDur/MS_PER_EPOCH_DUR_UNIT); } /** Get the epoch duration of the query in ms*/ public int getEpoch() { if (epochDur == kEPOCH_DUR_ONE_SHOT) return kEPOCH_DUR_ONE_SHOT; else return epochDur * MS_PER_EPOCH_DUR_UNIT; } /** Set the number of epochs for whicht this query will run*/ public void setNumEpochs(short n) { this.numEpochs = n; } /** Add the specified field to the query */ public void addField(QueryField f) { int idx = f.getIdx(); /* Ick -- insure that the field is inserted at the correct index (as indicated by f.getIdx) ArrayList.insureCapacity doesn't work, so explicitly insert nulls for fields we haven't seen yet. */ int diff = (idx + 1) - fields.size(); while (diff-- > 0) fields.add(null); try { fields.set(idx,f); } catch (Exception e) { e.printStackTrace(); } } /** Add the specified expression to the query */ public void addExpr(QueryExpr e) { /* Aggregate expressions must appear at the end of the expression list or else the query won't run properly. */ if (e.isAgg()) { exprs.add(exprs.size(), e); AggExpr ae = (AggExpr)e; if (TinyDBMain.debug) System.out.println("ae's groupField = " + ae.getGroupField()); if (ae.getGroupField() != AggExpr.NO_GROUPING) { isGrouped = true; groupExpr = ae; } } else { SelExpr se = (SelExpr)e; //assume that whoever's submitting the query has already verified //that this is a "proper" expression... -- e.g., if it's a string //based query the types of the fields are strings exprs.add(0,e); lastSelExpr++; } } /** Return true if the query is grouped (e.g. contains one or more aggregates with a group by expression) */ public boolean grouped() { return isGrouped; } public void setGrouped(boolean isGrouped) { this.isGrouped = isGrouped; } public void setGroupExpr(AggExpr ae) { groupExpr = ae; } public AggExpr getGroupExpr() { return groupExpr; } /** Return the name of the group by column */ public String groupColName() { if (TinyDBMain.debug) System.out.println("isGrouped = " + isGrouped); if (isGrouped) { String fname = getField(groupExpr.getGroupField()).getName(); return (fname + " " + ArithOps.getStringValue(groupExpr.getGroupFieldOp()) + " " + groupExpr.getGroupFieldConst()); } else return null; } /** Return the text of the SQL for this query as set by setSQL (Note that TinyDBQuery does not include an interface for generating SQL from an arbitrary query.) */ public String getSQL() { return sql; } /** Set the SQL string associated with this query. Note that this string doesn't not neccessarily have any relationship to the fields / expressions in this object */ public void setSQL(String s) { sql = s; } /** Return true if this query contains one or more aggregate expressions */ public boolean isAgg() { Iterator i = exprs.iterator(); while (i.hasNext()) { QueryExpr e = (QueryExpr)i.next(); if (e.isAgg()) return true; } return false; } /* Return the number of expressions in this query */ public int numExprs() { return exprs.size(); } /* Return the ith expression in this query Expression are (currently) either selections or aggregates @throws ArrayIndexOutOfBoundsException if i < 0 or i >= numExprs() */ public QueryExpr getExpr(int i) throws ArrayIndexOutOfBoundsException { try { return (QueryExpr)exprs.get(i); } catch (IndexOutOfBoundsException e) { throw new ArrayIndexOutOfBoundsException(i); } } /* Return the number of selection expressions in this query */ public int numSelExprs() { return lastSelExpr+1; } /* Return the ith selection expression in this query @throws ArrayIndexOutOfBoundsException if i < 0 or i >= numSelExprs() */ public QueryExpr getSelExpr(int i) throws ArrayIndexOutOfBoundsException { if (i >= numSelExprs() || i < 0) throw new ArrayIndexOutOfBoundsException(i); return (QueryExpr)exprs.get(i); } /* Replace the selection expressions with the ones in the specified vector. @throws IllegalArgumentException if an element of v is not a QueryExpr @throws ArrayIndexOutOfBoundsExcpetion if v.size() != numSelExprs() */ public void setSelExprs(Vector v) throws IllegalArgumentException, ArrayIndexOutOfBoundsException{ if (v.size() != numSelExprs()) throw new ArrayIndexOutOfBoundsException(); for (int i = 0; i < v.size(); i ++) exprs.set(i, (QueryExpr)v.elementAt(i)); } /* Display list of expressions contained in query */ public String toString() { QueryExpr temp; String result = ""; int i; result += "Fields in query:\n"; for (i = 0; i < numFields(); i++) result += (i + " " + getField(i) + "\n"); result += numExprs() + " expressions representing query:\n"; for (i = 0; i < numExprs(); i++) { try { temp = getExpr(i); result += temp; } catch (IndexOutOfBoundsException e) {} } result += "Epoch Duration = " + epochDur + "\n"; result += "Query ID = " + qid + "\n"; return result; } /** Returns true iff the query contains a field that isn't contained in any aggregate. NOTE: Will return FALSE in this example "Select light, avg(light) from sensors" But, tinydb processes this query if it were "Select avg(light) from sensors" */ public boolean containsNonAggFields() { QueryField qf; QueryExpr qe; boolean isAggField; for (int i = 0; i < numFields(); i++) { qf = getField(i); isAggField = false; for (int expIndx = 0; expIndx < numExprs(); expIndx++) { qe = getExpr(expIndx); //if the query field is found in an aggregate expression if ((qe.getField() == qf.getIdx()) && qe.isAgg()) isAggField = true; } if (!isAggField) return true; } return false; } public void setOutputCommand(String cmd, short param) { hasCmd = true; paramVal = param; cmdName = cmd; hasParam = false; } public void setOutputCommand(String cmd) { setOutputCommand(cmd, (short)0); hasParam = false; } public boolean hasOutputAction() { //if we're logging results or executing a commands, we won't hear values over the radio return hasCmd || hasName; } public boolean hasEvent() { return hasEvent; } public String getEvent() { if (hasEvent) return eventName; else return null; } public void setEvent(String name) { hasEvent = true; eventName = name; } /** Return the number of fields in this query */ public int numFields() { return fields.size(); } /** Return the ith field in this query @throws ArrayIndexOutOfBoundsException if i < 0 or i >= numFields() */ public QueryField getField(int i) throws ArrayIndexOutOfBoundsException { try { return (QueryField)fields.get(i); } catch (IndexOutOfBoundsException e) { throw new ArrayIndexOutOfBoundsException(i); } } /** Return a byte array representing a radio message that will tell motes to abort this query */ public Message abortMessage() { QueryMsg m = new QueryMsg(); initCommonFields(m); m.set_u_ttl(DEL_MSG_TTL); m.set_msgType(DEL_MSG); return m; } /** Return a message that, when injected, will change the rate of a currently running query. */ public Message setRateMessage(int rate) { QueryMsg m = new QueryMsg(); initCommonFields(m); m.set_msgType(SET_RATE_MSG); this.epochDur = (short)(rate / MS_PER_EPOCH_DUR_UNIT); m.set_epochDuration(epochDur); return m; } public void setDropTables() { this.dropTables = true; } /* Return a vector of strings containing the headings for the columns in this query */ public Vector getColumnHeadings() { Vector cols = new Vector(); boolean addedGroupCol = false; cols.addElement("Epoch"); if (isAgg()) { //it's an agg; the columns that are returned //are the group and the aggregate value for (int i = 0; i < numExprs(); i++) { QueryExpr e = getExpr(i); //System.out.println("Expression " + i + " is " + e.isAgg() + " " + e); if (e.isAgg()) { AggExpr ae = (AggExpr)e; if (ae.getGroupField() != -1 && !addedGroupCol) { cols.addElement(groupColName()); addedGroupCol = true; } String aggString = ""; aggString += ae.getAgg().toString() + "(" + getField(ae.getField()).getName(); if (ae.getFieldOp() != ArithOps.NO_OP) { aggString += ArithOps.getStringValue(ae.getFieldOp()) + " "; aggString += ae.getFieldConst(); } aggString += ")"; cols.addElement(aggString); } if (TinyDBMain.debug) System.out.println(cols); } } else { //its a selection; the columns that are returned //are the exprs for (int i =0; i < numFields(); i++) { QueryField qf = getField(i); if (qf != null) cols.addElement(qf.getName()); } } return cols; } //Returns the type (as defined in QueryField) of the specified //column in the result set. public byte getFieldType(int idx) throws ArrayIndexOutOfBoundsException { boolean addedGroupCol = false; if (idx == 0) return QueryField.INTTWO; if (isAgg()) { for (int i = 0; i < numExprs(); i++) { QueryExpr e = getExpr(i); if (e.isAgg()) { AggExpr ae = (AggExpr)e; if (ae.getGroupField() != -1 && !addedGroupCol) { if (--idx == 0) return getField(groupExpr.getGroupField()).getType(); addedGroupCol = true; } if (--idx == 0) return getField(ae.getField()).getType(); } } throw new ArrayIndexOutOfBoundsException(); } else { for (int i = 0; i < numFields(); i++) { QueryField qf = getField(i); if (--idx == 0) return qf.getType(); } throw new ArrayIndexOutOfBoundsException(); } } /** Return an Iterator over messages to be sent to start sensors running this query */ public Iterator messageIterator() { ArrayList messages = new ArrayList(); Message msg; QueryMsg qrm; //first, set up all the fields for (int i = 0; i < fields.size(); i++) { QueryField f = (QueryField)fields.get(i); qrm = new QueryMsg(); msg = qrm; initCommonFields(qrm); qrm.set_type(FIELD); qrm.set_idx((byte)i); qrm.set_u_field_op(f.getOp()); qrm.setString_u_field_name(f.getName()); qrm.set_u_field_type(f.getType()); if (TinyDBMain.debug) System.out.println(qrm.toString()); messages.add(msg); } //then all the exprs for (int i = 0; i < exprs.size(); i++) { QueryExpr e = (QueryExpr)exprs.get(i); qrm = new QueryMsg(); msg = qrm; initCommonFields(qrm); qrm.set_type(EXPR); qrm.set_idx((byte)i); qrm.set_u_expr_opType((byte)(e.isAgg()?(((AggExpr)e).isTemporalAgg()?TEMPORAL_AGG_EXPR:AGG_EXPR):SEL_EXPR)); qrm.set_u_expr_fieldOp(e.getFieldOp()); qrm.set_u_expr_fieldConst(e.getFieldConst()); if (e.isAgg()) { AggExpr a = (AggExpr)e; qrm.set_u_expr_ex_agg_field(e.getField()); qrm.set_u_expr_ex_agg_op(a.getAggOpCode()); qrm.set_u_expr_ex_agg_groupingField(a.getGroupField()); qrm.set_u_expr_ex_agg_groupFieldOp(a.getGroupFieldOp()); qrm.set_u_expr_ex_agg_groupFieldConst(a.getGroupFieldConst()); // set up arguments, for both temporal and non-temporal ones AggOp ag = a.getAgg();//needs renaming? for (int j=0; j < ag.getArguments().size(); j++) { qrm.setElement_u_expr_ex_tagg_args(j, ag.getArgument(j)); } } else { SelExpr s = (SelExpr)e; if (s.isString()) { qrm.set_u_expr_isStringExp((byte)1); qrm.set_u_expr_ex_sexp_field(e.getField()); qrm.set_u_expr_ex_sexp_op((byte)s.getSelOpCode()); qrm.setString_u_expr_ex_sexp_s(s.getStringConst()); } else { qrm.set_u_expr_isStringExp((byte)0); qrm.set_u_expr_ex_opval_field(e.getField()); qrm.set_u_expr_ex_opval_op((byte)s.getSelOpCode()); qrm.set_u_expr_ex_opval_value(s.getValue()); } } if (TinyDBMain.debug) { System.out.println("expr msg: "); System.out.print(qrm.toString()); } messages.add(msg); } //the command, if this is a command buffer if (hasCmd) { qrm = new QueryMsg(); msg = qrm; initCommonFields(qrm); qrm.set_type(BUFFER); qrm.setString_u_buf_cmd_name(cmdName); qrm.set_u_buf_cmd_hasParam((short)(hasParam?1:0)); qrm.set_u_buf_cmd_param(paramVal); if (TinyDBMain.debug) System.out.println("command msg: " + qrm.toString()); messages.add(msg); } else if (ramBuffer) { //or, might be a ram buffer qrm = new QueryMsg(); msg = qrm; initCommonFields(qrm); qrm.set_type(BUFFER); qrm.set_u_buf_ram_numRows(bufSize); qrm.set_u_buf_ram_policy(EVICT_OLDEST_POLICY); qrm.set_u_buf_ram_create(createTable?(byte)1:(byte)0); qrm.set_u_buf_ram_hasOutput(hasName?(byte)1:(byte)0); qrm.setString_u_buf_ram_outBufName(queryName); qrm.set_u_buf_ram_hasInput(hasInputBuf?(byte)1:(byte)0); qrm.setString_u_buf_ram_inBufName(inputBufferName); if (TinyDBMain.debug) System.out.println("ram buffer msg: " + qrm.toString()); messages.add(msg); } //if this query is triggered by an event, send in the event if (hasEvent) { qrm = new QueryMsg(); msg = qrm; initCommonFields(qrm); qrm.set_type(EVENT); qrm.setString_u_eventName(eventName); if (TinyDBMain.debug) System.out.println("event message: " + qrm.toString()); messages.add(msg); } //if this query is for a fixed number of epochs, send the number of epochs if (numEpochs > 0) { qrm = new QueryMsg(); msg = qrm; initCommonFields(qrm); qrm.set_type(N_EPOCHS); qrm.set_u_numEpochs(numEpochs); if (TinyDBMain.debug) System.out.println("num epochs message: " + qrm.toString()); messages.add(msg); } //if this is a drop message, that's it if (dropTables) { qrm = new QueryMsg(); msg = qrm; initCommonFields(qrm); qrm.set_msgType(DROP_TABLE); if (TinyDBMain.debug) System.out.println("drop message: " + qrm.toString()); qrm.set_u_ttl(DEL_MSG_TTL); messages.add(msg); } return messages.iterator(); } // set up common fields in radio messages private void initCommonFields(QueryMsg m) { m.set_msgType(ADD_MSG); m.set_qid(qid); m.set_fwdNode(TinyDBNetwork.UART_ADDR); m.set_numFields((byte)fields.size()); m.set_numExprs((byte)exprs.size()); m.set_fromCatalogBuffer(fromCatalogBuf?(byte)1:(byte)0); m.set_fromBuffer(fromCatalogBuf?catalogTableId:from_qid); m.set_bufferType(hasCmd?COMMAND_BUFFER:(ramBuffer?EEPROM_BUFFER:RADIO_BUFFER)); m.set_epochDuration(epochDur); if (hasEvent) m.set_hasEvent((byte)1); else m.set_hasEvent((byte)0); if (numEpochs > 0) m.set_hasForClause((byte)1); else m.set_hasForClause((byte)0); for (int i = 0; i < 5; i++) { m.setElement_timeSyncData(i, (short)0); } m.set_clockCount((short)0); } /* Return the id fo the query this query reads results from */ public byte getFromQid() { return from_qid; } /** Set the id of the query this query reads results from */ public void setFromQid(byte qid) { this.from_qid = qid; } public void setFromCatalogTable(byte catalogTable) { this.fromCatalogBuf = true; this.catalogTableId = catalogTable; } public boolean isFromCatalogTable() { return fromCatalogBuf; } /** Specify that this query should output results to a RAM based buffer */ public void useRamBuffer(short size) { bufSize = size; ramBuffer = true; } /** Specify the name of the buffer this query outputs results to -- other queries may refer to this buffer name. If share is true, associate this name with this query (globally), so that other queries can reference the local schema. */ public void setBufferName(String name, boolean share) { //overwrite old values, if they exist... if (share) nameHashMap.put(name.toLowerCase(), this); this.queryName = name; hasName = true; } public void setInputBufferName(String name) { this.inputBufferName = name; hasInputBuf = true; } /** Given a buffer name, lookup the query which corresponds to it. */ public static TinyDBQuery getQueryForBufName(String name) { return (TinyDBQuery)nameHashMap.get(name.toLowerCase()); } public void setBufferCreateTable(boolean create) { createTable = create; } public boolean getBufferCreateTable() { return createTable; } /** Inactive queries have been "stopped" -- e.g. cancelled on the motes, but we may still want to keep state about them so the can be restarted at the previous epoch */ public boolean active() { return isRunning; } public void setActive(boolean active) { isRunning = active; } public byte qid,from_qid; private short epochDur; public short numEpochs; private boolean fromCatalogBuf = false; private byte catalogTableId; private static HashMap nameHashMap = new HashMap(); private boolean ramBuffer = false; private short bufSize; private boolean isGrouped = false; private AggExpr groupExpr = null; private ArrayList fields; private ArrayList exprs; private int lastSelExpr = -1; private String sql = ""; private boolean hasCmd = false; private String cmdName; private short paramVal = 0; private boolean hasParam = false; private String queryName = ""; private String inputBufferName = ""; private boolean hasName = false; private boolean hasInputBuf = false; private boolean hasEvent = false; private boolean createTable = false; private boolean dropTables = false; private String eventName; static final byte FIELD = 0; static final byte EXPR = 1; static final byte BUFFER = 2; static final byte EVENT = 3; static final byte N_EPOCHS = 4; static final byte DROP_TABLE = 5; static final byte ADD_MSG = 0; static final byte DEL_MSG = 1; static final byte MODIFY_MSG = 2; static final byte SET_RATE_MSG = 3; static final byte DEL_MSG_TTL = 3; //ttl on delete messages public static final byte NO_FROM_QUERY = (byte)0xFF; static final byte SEL_EXPR = 0; static final byte AGG_EXPR = 1; static final byte TEMPORAL_AGG_EXPR = 2; static final byte RADIO_BUFFER = 0; static final byte RAM_BUFFER = 1; static final byte EEPROM_BUFFER = 2; static final byte COMMAND_BUFFER = 3; static final byte ATTRLIST = 4; static final byte EVENTLIST = 5; static final byte COMMANDLIST = 6; static final byte QUERYLIST = 7; static final byte EVICT_OLDEST_POLICY = 0; static final short MS_PER_EPOCH_DUR_UNIT =10; public static final short kEPOCH_DUR_ONE_SHOT=(short)0x7FFF; private boolean isRunning = false; //have we seen any results for this query lately? }
package org.apache.lucene.index; /** * 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. */ import java.io.IOException; import java.io.Reader; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.MockAnalyzer; import org.apache.lucene.analysis.TokenFilter; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.WhitespaceTokenizer; import org.apache.lucene.analysis.tokenattributes.PayloadAttribute; import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute; import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.Fieldable; import org.apache.lucene.document.Field.Index; import org.apache.lucene.document.Field.Store; import org.apache.lucene.document.Field.TermVector; import org.apache.lucene.index.FieldInfo.IndexOptions; import org.apache.lucene.store.Directory; import org.apache.lucene.util.AttributeSource; import org.apache.lucene.util.LuceneTestCase; import org.apache.lucene.util._TestUtil; public class TestDocumentWriter extends LuceneTestCase { private Directory dir; @Override public void setUp() throws Exception { super.setUp(); dir = newDirectory(); } @Override public void tearDown() throws Exception { dir.close(); super.tearDown(); } public void test() { assertTrue(dir != null); } public void testAddDocument() throws Exception { Document testDoc = new Document(); DocHelper.setupDoc(testDoc); IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random))); writer.addDocument(testDoc); writer.commit(); SegmentInfo info = writer.newestSegment(); writer.close(); //After adding the document, we should be able to read it back in SegmentReader reader = SegmentReader.get(true, info, IndexReader.DEFAULT_TERMS_INDEX_DIVISOR); assertTrue(reader != null); Document doc = reader.document(0); assertTrue(doc != null); //System.out.println("Document: " + doc); Fieldable [] fields = doc.getFields("textField2"); assertTrue(fields != null && fields.length == 1); assertTrue(fields[0].stringValue().equals(DocHelper.FIELD_2_TEXT)); assertTrue(fields[0].isTermVectorStored()); fields = doc.getFields("textField1"); assertTrue(fields != null && fields.length == 1); assertTrue(fields[0].stringValue().equals(DocHelper.FIELD_1_TEXT)); assertFalse(fields[0].isTermVectorStored()); fields = doc.getFields("keyField"); assertTrue(fields != null && fields.length == 1); assertTrue(fields[0].stringValue().equals(DocHelper.KEYWORD_TEXT)); fields = doc.getFields(DocHelper.NO_NORMS_KEY); assertTrue(fields != null && fields.length == 1); assertTrue(fields[0].stringValue().equals(DocHelper.NO_NORMS_TEXT)); fields = doc.getFields(DocHelper.TEXT_FIELD_3_KEY); assertTrue(fields != null && fields.length == 1); assertTrue(fields[0].stringValue().equals(DocHelper.FIELD_3_TEXT)); // test that the norms are not present in the segment if // omitNorms is true for (int i = 0; i < reader.core.fieldInfos.size(); i++) { FieldInfo fi = reader.core.fieldInfos.fieldInfo(i); if (fi.isIndexed) { assertTrue(fi.omitNorms == !reader.hasNorms(fi.name)); } } reader.close(); } public void testPositionIncrementGap() throws IOException { Analyzer analyzer = new Analyzer() { @Override public TokenStream tokenStream(String fieldName, Reader reader) { return new WhitespaceTokenizer(TEST_VERSION_CURRENT, reader); } @Override public int getPositionIncrementGap(String fieldName) { return 500; } }; IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, analyzer)); Document doc = new Document(); doc.add(newField("repeated", "repeated one", Field.Store.YES, Field.Index.ANALYZED)); doc.add(newField("repeated", "repeated two", Field.Store.YES, Field.Index.ANALYZED)); writer.addDocument(doc); writer.commit(); SegmentInfo info = writer.newestSegment(); writer.close(); SegmentReader reader = SegmentReader.get(true, info, IndexReader.DEFAULT_TERMS_INDEX_DIVISOR); TermPositions termPositions = reader.termPositions(new Term("repeated", "repeated")); assertTrue(termPositions.next()); int freq = termPositions.freq(); assertEquals(2, freq); assertEquals(0, termPositions.nextPosition()); assertEquals(502, termPositions.nextPosition()); reader.close(); } public void testTokenReuse() throws IOException { Analyzer analyzer = new Analyzer() { @Override public TokenStream tokenStream(String fieldName, Reader reader) { return new TokenFilter(new WhitespaceTokenizer(TEST_VERSION_CURRENT, reader)) { boolean first = true; AttributeSource.State state; @Override public boolean incrementToken() throws IOException { if (state != null) { restoreState(state); payloadAtt.setPayload(null); posIncrAtt.setPositionIncrement(0); termAtt.setEmpty().append("b"); state = null; return true; } boolean hasNext = input.incrementToken(); if (!hasNext) return false; if (Character.isDigit(termAtt.buffer()[0])) { posIncrAtt.setPositionIncrement(termAtt.buffer()[0] - '0'); } if (first) { // set payload on first position only payloadAtt.setPayload(new Payload(new byte[]{100})); first = false; } // index a "synonym" for every token state = captureState(); return true; } @Override public void reset() throws IOException { super.reset(); first = true; state = null; } final CharTermAttribute termAtt = addAttribute(CharTermAttribute.class); final PayloadAttribute payloadAtt = addAttribute(PayloadAttribute.class); final PositionIncrementAttribute posIncrAtt = addAttribute(PositionIncrementAttribute.class); }; } }; IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, analyzer)); Document doc = new Document(); doc.add(newField("f1", "a 5 a a", Field.Store.YES, Field.Index.ANALYZED)); writer.addDocument(doc); writer.commit(); SegmentInfo info = writer.newestSegment(); writer.close(); SegmentReader reader = SegmentReader.get(true, info, IndexReader.DEFAULT_TERMS_INDEX_DIVISOR); TermPositions termPositions = reader.termPositions(new Term("f1", "a")); assertTrue(termPositions.next()); int freq = termPositions.freq(); assertEquals(3, freq); assertEquals(0, termPositions.nextPosition()); assertEquals(true, termPositions.isPayloadAvailable()); assertEquals(6, termPositions.nextPosition()); assertEquals(false, termPositions.isPayloadAvailable()); assertEquals(7, termPositions.nextPosition()); assertEquals(false, termPositions.isPayloadAvailable()); reader.close(); } public void testPreAnalyzedField() throws IOException { IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig( TEST_VERSION_CURRENT, new MockAnalyzer(random))); Document doc = new Document(); doc.add(new Field("preanalyzed", new TokenStream() { private String[] tokens = new String[] {"term1", "term2", "term3", "term2"}; private int index = 0; private CharTermAttribute termAtt = addAttribute(CharTermAttribute.class); @Override public boolean incrementToken() throws IOException { if (index == tokens.length) { return false; } else { clearAttributes(); termAtt.setEmpty().append(tokens[index++]); return true; } } }, TermVector.NO)); writer.addDocument(doc); writer.commit(); SegmentInfo info = writer.newestSegment(); writer.close(); SegmentReader reader = SegmentReader.get(true, info, IndexReader.DEFAULT_TERMS_INDEX_DIVISOR); TermPositions termPositions = reader.termPositions(new Term("preanalyzed", "term1")); assertTrue(termPositions.next()); assertEquals(1, termPositions.freq()); assertEquals(0, termPositions.nextPosition()); termPositions.seek(new Term("preanalyzed", "term2")); assertTrue(termPositions.next()); assertEquals(2, termPositions.freq()); assertEquals(1, termPositions.nextPosition()); assertEquals(3, termPositions.nextPosition()); termPositions.seek(new Term("preanalyzed", "term3")); assertTrue(termPositions.next()); assertEquals(1, termPositions.freq()); assertEquals(2, termPositions.nextPosition()); reader.close(); } /** * Test adding two fields with the same name, but * with different term vector setting (LUCENE-766). */ public void testMixedTermVectorSettingsSameField() throws Exception { Document doc = new Document(); // f1 first without tv then with tv doc.add(newField("f1", "v1", Store.YES, Index.NOT_ANALYZED, TermVector.NO)); doc.add(newField("f1", "v2", Store.YES, Index.NOT_ANALYZED, TermVector.WITH_POSITIONS_OFFSETS)); // f2 first with tv then without tv doc.add(newField("f2", "v1", Store.YES, Index.NOT_ANALYZED, TermVector.WITH_POSITIONS_OFFSETS)); doc.add(newField("f2", "v2", Store.YES, Index.NOT_ANALYZED, TermVector.NO)); IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig( TEST_VERSION_CURRENT, new MockAnalyzer(random))); writer.addDocument(doc); writer.close(); _TestUtil.checkIndex(dir); IndexReader reader = IndexReader.open(dir, true); // f1 TermFreqVector tfv1 = reader.getTermFreqVector(0, "f1"); assertNotNull(tfv1); assertEquals("the 'with_tv' setting should rule!",2,tfv1.getTerms().length); // f2 TermFreqVector tfv2 = reader.getTermFreqVector(0, "f2"); assertNotNull(tfv2); assertEquals("the 'with_tv' setting should rule!",2,tfv2.getTerms().length); reader.close(); } /** * Test adding two fields with the same name, one indexed * the other stored only. The omitNorms and omitTermFreqAndPositions setting * of the stored field should not affect the indexed one (LUCENE-1590) */ public void testLUCENE_1590() throws Exception { Document doc = new Document(); // f1 has no norms doc.add(newField("f1", "v1", Store.NO, Index.ANALYZED_NO_NORMS)); doc.add(newField("f1", "v2", Store.YES, Index.NO)); // f2 has no TF Field f = newField("f2", "v1", Store.NO, Index.ANALYZED); f.setIndexOptions(IndexOptions.DOCS_ONLY); doc.add(f); doc.add(newField("f2", "v2", Store.YES, Index.NO)); IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig( TEST_VERSION_CURRENT, new MockAnalyzer(random))); writer.addDocument(doc); writer.forceMerge(1); // be sure to have a single segment writer.close(); _TestUtil.checkIndex(dir); SegmentReader reader = SegmentReader.getOnlySegmentReader(dir); FieldInfos fi = reader.fieldInfos(); // f1 assertFalse("f1 should have no norms", reader.hasNorms("f1")); assertEquals("omitTermFreqAndPositions field bit should not be set for f1", IndexOptions.DOCS_AND_FREQS_AND_POSITIONS, fi.fieldInfo("f1").indexOptions); // f2 assertTrue("f2 should have norms", reader.hasNorms("f2")); assertEquals("omitTermFreqAndPositions field bit should be set for f2", IndexOptions.DOCS_ONLY, fi.fieldInfo("f2").indexOptions); reader.close(); } }
/* * Copyright 2011 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.grails.plugin.freemarker; import java.io.CharArrayWriter; import java.io.IOException; import java.io.Writer; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.codehaus.groovy.grails.web.taglib.GroovyPageAttributes; import freemarker.core.Environment; import freemarker.template.ObjectWrapper; import freemarker.template.TemplateDirectiveBody; import freemarker.template.TemplateDirectiveModel; import freemarker.template.TemplateException; import freemarker.template.TemplateHashModelEx; import freemarker.template.TemplateMethodModelEx; import freemarker.template.TemplateModel; import freemarker.template.TemplateModelException; import freemarker.template.TemplateModelIterator; import freemarker.template.utility.DeepUnwrap; import groovy.lang.Closure; import groovy.lang.GroovyObject; /** * @author Daniel Henrique Alves Lima */ public class TagLibToDirectiveAndFunction implements TemplateDirectiveModel, TemplateMethodModelEx { private static final Map<String, String> RESERVED_WORDS_TRANSLATION; private final Log log = LogFactory.getLog(getClass()); @SuppressWarnings("serial") private static final Closure EMPTY_BODY = new Closure( TagLibToDirectiveAndFunction.class) { @SuppressWarnings("unused") public Object doCall(Object[] it) throws IOException, TemplateException { return ""; } }; static { Map<String, String> m = new LinkedHashMap<String, String>(); m.put("as", "_as"); RESERVED_WORDS_TRANSLATION = Collections.unmodifiableMap(m); } private String namespace; @SuppressWarnings("unused") private GroovyObject tagLibInstance; private String tagName; private Closure tagInstance; private boolean hasReturnValue; public TagLibToDirectiveAndFunction(String namespace, GroovyObject tagLibInstance, String tagName, Closure tagInstance, boolean hasReturnValue) { this.namespace = namespace; this.tagLibInstance = tagLibInstance; this.tagName = tagName; this.tagInstance = tagInstance; this.hasReturnValue = hasReturnValue; } @SuppressWarnings("serial") @Override public Object exec(@SuppressWarnings("rawtypes") List arguments) throws TemplateModelException { if (log.isDebugEnabled()) { log.debug("exec(): @" + namespace + "." + tagName); } try { CharArrayWriter writer = new CharArrayWriter(); tagInstance.invokeMethod("pushOut", writer); Object args = null; Object body = null; if (arguments != null) { if (arguments.size() > 0) { args = arguments.get(0); } if (arguments.size() > 1) { body = arguments.get(1); } } Object result = null; args = args != null ? unwrapParams((TemplateHashModelEx) args, Boolean.TRUE) : unwrapParams(Collections.EMPTY_MAP, Boolean.TRUE); if (log.isDebugEnabled()) { log.debug("exec(): args " + args); log.debug("exec(): body " + body); } if (tagInstance.getMaximumNumberOfParameters() == 1) { result = tagInstance.call(args); } else { Closure bodyClosure = EMPTY_BODY; if (body != null || hasReturnValue) { final Object fBody = body; bodyClosure = new Closure(this) { @SuppressWarnings("unused") public Object doCall(Object it) throws IOException, TemplateException { return fBody; } }; } result = tagInstance.call(new Object[] { args, bodyClosure }); if (result == null) { // writer.flush(); result = writer.toString(); } } return result; } catch (RuntimeException e) { throw new TemplateModelException(e); } finally { tagInstance.invokeMethod("popOut", null); } } @SuppressWarnings("serial") @Override public void execute(final Environment env, @SuppressWarnings("rawtypes") Map params, TemplateModel[] loopVars, final TemplateDirectiveBody body) throws TemplateException, IOException { if (log.isDebugEnabled()) { log.debug("execute(): @" + namespace + "." + tagName); } try { tagInstance.invokeMethod("pushOut", env.getOut()); params = unwrapParams(params, Boolean.TRUE); if (log.isDebugEnabled()) { log.debug("execute(): params " + params); log.debug("exec(): body " + body); } Object result = null; if (tagInstance.getMaximumNumberOfParameters() == 1) { result = tagInstance.call(params); } else { Closure bodyClosure = EMPTY_BODY; if (body != null) { bodyClosure = new Closure(this) { @SuppressWarnings({ "unused", "rawtypes", "unchecked" }) public Object doCall(Object it) throws IOException, TemplateException { ObjectWrapper objectWrapper = env .getObjectWrapper(); Map<String, TemplateModel> oldVariables = null; TemplateModel oldIt = null; if (log.isDebugEnabled()) { log.debug("it " + it); } boolean itIsAMap = false; if (it != null) { if (it instanceof Map) { itIsAMap = true; oldVariables = new LinkedHashMap<String, TemplateModel>(); Map<String, Object> itMap = (Map) it; for (Map.Entry<String, Object> entry : itMap .entrySet()) { oldVariables .put(entry.getKey(), env .getVariable(entry .getKey())); } } else { oldIt = env.getVariable("it"); } } try { if (it != null) { if (itIsAMap) { Map<String, Object> itMap = (Map) it; for (Map.Entry<String, Object> entry : itMap .entrySet()) { env.setVariable(entry.getKey(), objectWrapper.wrap(entry .getValue())); } } else { env.setVariable("it", objectWrapper.wrap(it)); } } body.render((Writer) tagInstance .getProperty("out")); } finally { if (oldVariables != null) { for (Map.Entry<String, TemplateModel> entry : oldVariables .entrySet()) { env.setVariable(entry.getKey(), entry.getValue()); } } else if (oldIt != null) { env.setVariable("it", oldIt); } } return ""; } }; } result = tagInstance.call(new Object[] { params, bodyClosure }); } if (log.isDebugEnabled()) { log.debug("hasReturnValue " + hasReturnValue); log.debug("result " + result); } if (result != null && hasReturnValue) { env.getOut().append(result.toString()); } } catch (RuntimeException e) { throw new TemplateException(e, env); } finally { tagInstance.invokeMethod("popOut", null); } } @SuppressWarnings({ "rawtypes", "unchecked" }) protected Map unwrapParams(TemplateHashModelEx params, Boolean translateReservedWords) throws TemplateModelException { if (translateReservedWords == null) { translateReservedWords = Boolean.TRUE; } Map unwrappedParams = new GroovyPageAttributes(new LinkedHashMap()); TemplateModelIterator keys = params.keys().iterator(); while (keys.hasNext()) { String oldKey = keys.next().toString(); Object value = params.get(oldKey); if (value != null) { value = DeepUnwrap.permissiveUnwrap((TemplateModel) value); } String key = null; if (translateReservedWords) { key = RESERVED_WORDS_TRANSLATION.get(oldKey); } if (key == null) { key = oldKey; } unwrappedParams.put(key, value); } return unwrappedParams; } @SuppressWarnings({ "rawtypes", "unchecked" }) protected Map unwrapParams(Map params, Boolean translateReservedWords) throws TemplateModelException { if (translateReservedWords == null) { translateReservedWords = Boolean.TRUE; } Map unwrappedParams = new GroovyPageAttributes(new LinkedHashMap()); Iterator<Map.Entry> iterator = params.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = iterator.next(); Object value = entry.getValue(); if (value != null) { value = DeepUnwrap.permissiveUnwrap((TemplateModel) value); } String key = null; if (translateReservedWords) { key = RESERVED_WORDS_TRANSLATION.get(entry.getKey()); } if (key == null) { key = (String) entry.getKey(); } unwrappedParams.put(key, value); } return unwrappedParams; } }
package org.swtk.commons.dict.wiktionary.terms; import java.util.Collection; import java.util.Set; import java.util.TreeSet; import org.swtk.commons.dict.wiktionary.generated.h.a.a.*; import org.swtk.commons.dict.wiktionary.generated.h.a.b.*; import org.swtk.commons.dict.wiktionary.generated.h.a.c.*; import org.swtk.commons.dict.wiktionary.generated.h.a.d.*; import org.swtk.commons.dict.wiktionary.generated.h.a.e.*; import org.swtk.commons.dict.wiktionary.generated.h.a.f.*; import org.swtk.commons.dict.wiktionary.generated.h.a.g.*; import org.swtk.commons.dict.wiktionary.generated.h.a.h.*; import org.swtk.commons.dict.wiktionary.generated.h.a.i.*; import org.swtk.commons.dict.wiktionary.generated.h.a.k.*; import org.swtk.commons.dict.wiktionary.generated.h.a.l.*; import org.swtk.commons.dict.wiktionary.generated.h.a.m.*; import org.swtk.commons.dict.wiktionary.generated.h.a.n.*; import org.swtk.commons.dict.wiktionary.generated.h.a.o.*; import org.swtk.commons.dict.wiktionary.generated.h.a.p.*; import org.swtk.commons.dict.wiktionary.generated.h.a.r.*; import org.swtk.commons.dict.wiktionary.generated.h.a.s.*; import org.swtk.commons.dict.wiktionary.generated.h.a.t.*; import org.swtk.commons.dict.wiktionary.generated.h.a.u.*; import org.swtk.commons.dict.wiktionary.generated.h.a.v.*; import org.swtk.commons.dict.wiktionary.generated.h.a.w.*; import org.swtk.commons.dict.wiktionary.generated.h.a.x.*; import org.swtk.commons.dict.wiktionary.generated.h.a.y.*; import org.swtk.commons.dict.wiktionary.generated.h.a.z.*; import org.swtk.commons.dict.wiktionary.generated.h.b.o.*; import org.swtk.commons.dict.wiktionary.generated.h.e.a.*; import org.swtk.commons.dict.wiktionary.generated.h.e.b.*; import org.swtk.commons.dict.wiktionary.generated.h.e.c.*; import org.swtk.commons.dict.wiktionary.generated.h.e.d.*; import org.swtk.commons.dict.wiktionary.generated.h.e.e.*; import org.swtk.commons.dict.wiktionary.generated.h.e.f.*; import org.swtk.commons.dict.wiktionary.generated.h.e.g.*; import org.swtk.commons.dict.wiktionary.generated.h.e.i.*; import org.swtk.commons.dict.wiktionary.generated.h.e.j.*; import org.swtk.commons.dict.wiktionary.generated.h.e.l.*; import org.swtk.commons.dict.wiktionary.generated.h.e.m.*; import org.swtk.commons.dict.wiktionary.generated.h.e.n.*; import org.swtk.commons.dict.wiktionary.generated.h.e.o.*; import org.swtk.commons.dict.wiktionary.generated.h.e.p.*; import org.swtk.commons.dict.wiktionary.generated.h.e.r.*; import org.swtk.commons.dict.wiktionary.generated.h.e.s.*; import org.swtk.commons.dict.wiktionary.generated.h.e.t.*; import org.swtk.commons.dict.wiktionary.generated.h.e.u.*; import org.swtk.commons.dict.wiktionary.generated.h.e.w.*; import org.swtk.commons.dict.wiktionary.generated.h.e.x.*; import org.swtk.commons.dict.wiktionary.generated.h.e.y.*; import org.swtk.commons.dict.wiktionary.generated.h.i.a.*; import org.swtk.commons.dict.wiktionary.generated.h.i.b.*; import org.swtk.commons.dict.wiktionary.generated.h.i.c.*; import org.swtk.commons.dict.wiktionary.generated.h.i.d.*; import org.swtk.commons.dict.wiktionary.generated.h.i.e.*; import org.swtk.commons.dict.wiktionary.generated.h.i.g.*; import org.swtk.commons.dict.wiktionary.generated.h.i.j.*; import org.swtk.commons.dict.wiktionary.generated.h.i.k.*; import org.swtk.commons.dict.wiktionary.generated.h.i.l.*; import org.swtk.commons.dict.wiktionary.generated.h.i.m.*; import org.swtk.commons.dict.wiktionary.generated.h.i.n.*; import org.swtk.commons.dict.wiktionary.generated.h.i.p.*; import org.swtk.commons.dict.wiktionary.generated.h.i.r.*; import org.swtk.commons.dict.wiktionary.generated.h.i.s.*; import org.swtk.commons.dict.wiktionary.generated.h.i.t.*; import org.swtk.commons.dict.wiktionary.generated.h.i.v.*; import org.swtk.commons.dict.wiktionary.generated.h.i.x.*; import org.swtk.commons.dict.wiktionary.generated.h.i.z.*; import org.swtk.commons.dict.wiktionary.generated.h.j.e.*; import org.swtk.commons.dict.wiktionary.generated.h.o.a.*; import org.swtk.commons.dict.wiktionary.generated.h.o.b.*; import org.swtk.commons.dict.wiktionary.generated.h.o.c.*; import org.swtk.commons.dict.wiktionary.generated.h.o.d.*; import org.swtk.commons.dict.wiktionary.generated.h.o.e.*; import org.swtk.commons.dict.wiktionary.generated.h.o.g.*; import org.swtk.commons.dict.wiktionary.generated.h.o.h.*; import org.swtk.commons.dict.wiktionary.generated.h.o.i.*; import org.swtk.commons.dict.wiktionary.generated.h.o.j.*; import org.swtk.commons.dict.wiktionary.generated.h.o.k.*; import org.swtk.commons.dict.wiktionary.generated.h.o.l.*; import org.swtk.commons.dict.wiktionary.generated.h.o.m.*; import org.swtk.commons.dict.wiktionary.generated.h.o.n.*; import org.swtk.commons.dict.wiktionary.generated.h.o.o.*; import org.swtk.commons.dict.wiktionary.generated.h.o.p.*; import org.swtk.commons.dict.wiktionary.generated.h.o.r.*; import org.swtk.commons.dict.wiktionary.generated.h.o.s.*; import org.swtk.commons.dict.wiktionary.generated.h.o.t.*; import org.swtk.commons.dict.wiktionary.generated.h.o.u.*; import org.swtk.commons.dict.wiktionary.generated.h.o.v.*; import org.swtk.commons.dict.wiktionary.generated.h.o.w.*; import org.swtk.commons.dict.wiktionary.generated.h.o.x.*; import org.swtk.commons.dict.wiktionary.generated.h.o.y.*; import org.swtk.commons.dict.wiktionary.generated.h.r.y.*; import org.swtk.commons.dict.wiktionary.generated.h.s.i.*; import org.swtk.commons.dict.wiktionary.generated.h.u.a.*; import org.swtk.commons.dict.wiktionary.generated.h.u.b.*; import org.swtk.commons.dict.wiktionary.generated.h.u.c.*; import org.swtk.commons.dict.wiktionary.generated.h.u.d.*; import org.swtk.commons.dict.wiktionary.generated.h.u.e.*; import org.swtk.commons.dict.wiktionary.generated.h.u.f.*; import org.swtk.commons.dict.wiktionary.generated.h.u.g.*; import org.swtk.commons.dict.wiktionary.generated.h.u.i.*; import org.swtk.commons.dict.wiktionary.generated.h.u.l.*; import org.swtk.commons.dict.wiktionary.generated.h.u.m.*; import org.swtk.commons.dict.wiktionary.generated.h.u.n.*; import org.swtk.commons.dict.wiktionary.generated.h.u.p.*; import org.swtk.commons.dict.wiktionary.generated.h.u.r.*; import org.swtk.commons.dict.wiktionary.generated.h.u.s.*; import org.swtk.commons.dict.wiktionary.generated.h.u.t.*; import org.swtk.commons.dict.wiktionary.generated.h.u.x.*; import org.swtk.commons.dict.wiktionary.generated.h.y.a.*; import org.swtk.commons.dict.wiktionary.generated.h.y.b.*; import org.swtk.commons.dict.wiktionary.generated.h.y.d.*; import org.swtk.commons.dict.wiktionary.generated.h.y.e.*; import org.swtk.commons.dict.wiktionary.generated.h.y.g.*; import org.swtk.commons.dict.wiktionary.generated.h.y.l.*; import org.swtk.commons.dict.wiktionary.generated.h.y.m.*; import org.swtk.commons.dict.wiktionary.generated.h.y.o.*; import org.swtk.commons.dict.wiktionary.generated.h.y.p.*; import org.swtk.commons.dict.wiktionary.generated.h.y.r.*; import org.swtk.commons.dict.wiktionary.generated.h.y.s.*; public final class WiktionaryTermsH { public static Collection<String> terms() { Set<String> set = new TreeSet<String>(); set.addAll(WiktionaryHAA000.terms()); set.addAll(WiktionaryHAB000.terms()); set.addAll(WiktionaryHAC000.terms()); set.addAll(WiktionaryHAD000.terms()); set.addAll(WiktionaryHAE000.terms()); set.addAll(WiktionaryHAF000.terms()); set.addAll(WiktionaryHAG000.terms()); set.addAll(WiktionaryHAH000.terms()); set.addAll(WiktionaryHAI000.terms()); set.addAll(WiktionaryHAK000.terms()); set.addAll(WiktionaryHAL000.terms()); set.addAll(WiktionaryHAM000.terms()); set.addAll(WiktionaryHAN000.terms()); set.addAll(WiktionaryHAO000.terms()); set.addAll(WiktionaryHAP000.terms()); set.addAll(WiktionaryHAR000.terms()); set.addAll(WiktionaryHAS000.terms()); set.addAll(WiktionaryHAT000.terms()); set.addAll(WiktionaryHAU000.terms()); set.addAll(WiktionaryHAV000.terms()); set.addAll(WiktionaryHAW000.terms()); set.addAll(WiktionaryHAX000.terms()); set.addAll(WiktionaryHAY000.terms()); set.addAll(WiktionaryHAZ000.terms()); set.addAll(WiktionaryHBO000.terms()); set.addAll(WiktionaryHEA000.terms()); set.addAll(WiktionaryHEB000.terms()); set.addAll(WiktionaryHEC000.terms()); set.addAll(WiktionaryHED000.terms()); set.addAll(WiktionaryHEE000.terms()); set.addAll(WiktionaryHEF000.terms()); set.addAll(WiktionaryHEG000.terms()); set.addAll(WiktionaryHEI000.terms()); set.addAll(WiktionaryHEJ000.terms()); set.addAll(WiktionaryHEL000.terms()); set.addAll(WiktionaryHEM000.terms()); set.addAll(WiktionaryHEN000.terms()); set.addAll(WiktionaryHEO000.terms()); set.addAll(WiktionaryHEP000.terms()); set.addAll(WiktionaryHER000.terms()); set.addAll(WiktionaryHES000.terms()); set.addAll(WiktionaryHET000.terms()); set.addAll(WiktionaryHEU000.terms()); set.addAll(WiktionaryHEW000.terms()); set.addAll(WiktionaryHEX000.terms()); set.addAll(WiktionaryHEY000.terms()); set.addAll(WiktionaryHIA000.terms()); set.addAll(WiktionaryHIB000.terms()); set.addAll(WiktionaryHIC000.terms()); set.addAll(WiktionaryHID000.terms()); set.addAll(WiktionaryHIE000.terms()); set.addAll(WiktionaryHIG000.terms()); set.addAll(WiktionaryHIJ000.terms()); set.addAll(WiktionaryHIK000.terms()); set.addAll(WiktionaryHIL000.terms()); set.addAll(WiktionaryHIM000.terms()); set.addAll(WiktionaryHIN000.terms()); set.addAll(WiktionaryHIP000.terms()); set.addAll(WiktionaryHIR000.terms()); set.addAll(WiktionaryHIS000.terms()); set.addAll(WiktionaryHIT000.terms()); set.addAll(WiktionaryHIV000.terms()); set.addAll(WiktionaryHIX000.terms()); set.addAll(WiktionaryHIZ000.terms()); set.addAll(WiktionaryHJE000.terms()); set.addAll(WiktionaryHOA000.terms()); set.addAll(WiktionaryHOB000.terms()); set.addAll(WiktionaryHOC000.terms()); set.addAll(WiktionaryHOD000.terms()); set.addAll(WiktionaryHOE000.terms()); set.addAll(WiktionaryHOG000.terms()); set.addAll(WiktionaryHOH000.terms()); set.addAll(WiktionaryHOI000.terms()); set.addAll(WiktionaryHOJ000.terms()); set.addAll(WiktionaryHOK000.terms()); set.addAll(WiktionaryHOL000.terms()); set.addAll(WiktionaryHOM000.terms()); set.addAll(WiktionaryHON000.terms()); set.addAll(WiktionaryHOO000.terms()); set.addAll(WiktionaryHOP000.terms()); set.addAll(WiktionaryHOR000.terms()); set.addAll(WiktionaryHOS000.terms()); set.addAll(WiktionaryHOT000.terms()); set.addAll(WiktionaryHOU000.terms()); set.addAll(WiktionaryHOV000.terms()); set.addAll(WiktionaryHOW000.terms()); set.addAll(WiktionaryHOX000.terms()); set.addAll(WiktionaryHOY000.terms()); set.addAll(WiktionaryHRY000.terms()); set.addAll(WiktionaryHSI000.terms()); set.addAll(WiktionaryHUA000.terms()); set.addAll(WiktionaryHUB000.terms()); set.addAll(WiktionaryHUC000.terms()); set.addAll(WiktionaryHUD000.terms()); set.addAll(WiktionaryHUE000.terms()); set.addAll(WiktionaryHUF000.terms()); set.addAll(WiktionaryHUG000.terms()); set.addAll(WiktionaryHUI000.terms()); set.addAll(WiktionaryHUL000.terms()); set.addAll(WiktionaryHUM000.terms()); set.addAll(WiktionaryHUN000.terms()); set.addAll(WiktionaryHUP000.terms()); set.addAll(WiktionaryHUR000.terms()); set.addAll(WiktionaryHUS000.terms()); set.addAll(WiktionaryHUT000.terms()); set.addAll(WiktionaryHUX000.terms()); set.addAll(WiktionaryHYA000.terms()); set.addAll(WiktionaryHYB000.terms()); set.addAll(WiktionaryHYD000.terms()); set.addAll(WiktionaryHYE000.terms()); set.addAll(WiktionaryHYG000.terms()); set.addAll(WiktionaryHYL000.terms()); set.addAll(WiktionaryHYM000.terms()); set.addAll(WiktionaryHYO000.terms()); set.addAll(WiktionaryHYP000.terms()); set.addAll(WiktionaryHYR000.terms()); set.addAll(WiktionaryHYS000.terms()); return set; } }
/* * 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.jdbi.v3.core.mapper.reflect.internal; import java.lang.reflect.Type; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import org.jdbi.v3.core.annotation.Unmappable; import org.jdbi.v3.core.config.ConfigRegistry; import org.jdbi.v3.core.generic.GenericTypes; import org.jdbi.v3.core.internal.exceptions.Unchecked; import org.jdbi.v3.core.mapper.ColumnMapper; import org.jdbi.v3.core.mapper.Nested; import org.jdbi.v3.core.mapper.NoSuchMapperException; import org.jdbi.v3.core.mapper.PropagateNull; import org.jdbi.v3.core.mapper.RowMapper; import org.jdbi.v3.core.mapper.SingleColumnMapper; import org.jdbi.v3.core.mapper.reflect.ColumnName; import org.jdbi.v3.core.mapper.reflect.ColumnNameMatcher; import org.jdbi.v3.core.mapper.reflect.ReflectionMappers; import org.jdbi.v3.core.mapper.reflect.internal.PojoProperties.PojoBuilder; import org.jdbi.v3.core.mapper.reflect.internal.PojoProperties.PojoProperty; import org.jdbi.v3.core.result.UnableToProduceResultException; import org.jdbi.v3.core.statement.StatementContext; import static org.jdbi.v3.core.mapper.reflect.ReflectionMapperUtil.anyColumnsStartWithPrefix; import static org.jdbi.v3.core.mapper.reflect.ReflectionMapperUtil.findColumnIndex; import static org.jdbi.v3.core.mapper.reflect.ReflectionMapperUtil.getColumnNames; /** This class is the future home of BeanMapper functionality. */ public class PojoMapper<T> implements RowMapper<T> { private static final String NO_MATCHING_COLUMNS = "Mapping bean %s didn't find any matching columns in result set"; private static final String UNMATCHED_COLUMNS_STRICT = "Mapping bean %s could not match properties for columns: %s"; protected boolean strictColumnTypeMapping = true; // this should be default (only?) behavior but that's a breaking change protected final Type type; protected final String prefix; private final Map<PojoProperty<T>, PojoMapper<?>> nestedMappers = new ConcurrentHashMap<>(); public PojoMapper(Type type, String prefix) { this.type = type; this.prefix = prefix.toLowerCase(); } @Override public T map(ResultSet rs, StatementContext ctx) throws SQLException { return specialize(rs, ctx).map(rs, ctx); } @Override public RowMapper<T> specialize(ResultSet rs, StatementContext ctx) throws SQLException { final List<String> columnNames = getColumnNames(rs); final List<ColumnNameMatcher> columnNameMatchers = ctx.getConfig(ReflectionMappers.class).getColumnNameMatchers(); final List<String> unmatchedColumns = new ArrayList<>(columnNames); RowMapper<T> result = specialize0(ctx, columnNames, columnNameMatchers, unmatchedColumns) .orElseThrow(() -> new IllegalArgumentException(String.format(NO_MATCHING_COLUMNS, type))); if (ctx.getConfig(ReflectionMappers.class).isStrictMatching() && anyColumnsStartWithPrefix(unmatchedColumns, prefix, columnNameMatchers)) { throw new IllegalArgumentException( String.format(UNMATCHED_COLUMNS_STRICT, type, unmatchedColumns)); } return result; } private Optional<RowMapper<T>> specialize0(StatementContext ctx, List<String> columnNames, List<ColumnNameMatcher> columnNameMatchers, List<String> unmatchedColumns) { final List<PropertyData<T>> propList = new ArrayList<>(); for (PojoProperty<T> property : getProperties(ctx.getConfig()).getProperties().values()) { Nested anno = property.getAnnotation(Nested.class).orElse(null); if (property.getAnnotation(Unmappable.class).map(Unmappable::value).orElse(false)) { continue; } if (anno == null) { String paramName = prefix + getName(property); findColumnIndex(paramName, columnNames, columnNameMatchers, () -> debugName(property)) .ifPresent(index -> { @SuppressWarnings({ "unchecked", "rawtypes" }) ColumnMapper<?> mapper = ctx.findColumnMapperFor(property.getQualifiedType().mapType(GenericTypes::box)) .orElseGet(() -> (ColumnMapper) defaultColumnMapper(property)); propList.add(new PropertyData<>(property, new SingleColumnMapper<>(mapper, index + 1))); unmatchedColumns.remove(columnNames.get(index)); }); } else { String nestedPrefix = prefix + anno.value(); if (anyColumnsStartWithPrefix(columnNames, nestedPrefix, columnNameMatchers)) { nestedMappers .computeIfAbsent(property, d -> createNestedMapper(ctx, d, nestedPrefix)) .specialize0(ctx, columnNames, columnNameMatchers, unmatchedColumns) .ifPresent(nestedMapper -> propList.add(new PropertyData<>(property, nestedMapper))); } } } if (propList.isEmpty() && !columnNames.isEmpty()) { return Optional.empty(); } Collections.sort(propList, Comparator.comparing(p -> p.propagateNull ? 1 : 0)); final Optional<String> nullMarkerColumn = Optional.ofNullable(GenericTypes.getErasedType(type).getAnnotation(PropagateNull.class)) .map(PropagateNull::value); return Optional.of((r, c) -> { if (propagateNull(r, nullMarkerColumn)) { return null; } final PojoBuilder<T> pojo = getProperties(c.getConfig()).create(); for (PropertyData<T> p : propList) { Object value = p.mapper.map(r, ctx); if (p.propagateNull && (value == null || p.isPrimitive && r.wasNull())) { return null; } if (value != null) { pojo.set(p.property, value); } } return pojo.build(); }); } @SuppressWarnings("unchecked") protected PojoProperties<T> getProperties(ConfigRegistry config) { return (PojoProperties<T>) config.get(PojoTypes.class).findFor(type) .orElseThrow(() -> new UnableToProduceResultException("Couldn't find properties for " + type)); } @SuppressWarnings("rawtypes") // Type loses <T> protected PojoMapper<?> createNestedMapper(StatementContext ctx, PojoProperty<T> property, String nestedPrefix) { final Type propertyType = property.getQualifiedType().getType(); return new PojoMapper( GenericTypes.getErasedType(propertyType), nestedPrefix); } public static boolean propagateNull(ResultSet r, Optional<String> nullMarkerColumn) { return nullMarkerColumn.map( Unchecked.function(col -> { r.getObject(col); return r.wasNull(); })) .orElse(false); } private ColumnMapper<?> defaultColumnMapper(PojoProperty<T> property) { if (strictColumnTypeMapping) { throw new NoSuchMapperException(String.format( "Couldn't find mapper for property '%s' of type '%s' from %s", property.getName(), property.getQualifiedType(), type)); } return (r, n, c) -> r.getObject(n); } private String getName(PojoProperty<T> property) { return property.getAnnotation(ColumnName.class) .map(ColumnName::value) .orElseGet(property::getName); } private String debugName(PojoProperty<T> p) { return String.format("%s.%s", type, p.getName()); } private static class PropertyData<T> { PropertyData(PojoProperty<T> property, RowMapper<?> mapper) { this.property = property; this.mapper = mapper; propagateNull = property.getAnnotation(PropagateNull.class).isPresent(); isPrimitive = GenericTypes.getErasedType(property.getQualifiedType().getType()).isPrimitive(); } final PojoProperty<T> property; final RowMapper<?> mapper; final boolean propagateNull; final boolean isPrimitive; } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.io.hfile; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Random; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.ArrayBackedTag; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.CellComparator; import org.apache.hadoop.hbase.CellComparatorImpl; import org.apache.hadoop.hbase.HBaseClassTestRule; import org.apache.hadoop.hbase.HBaseTestingUtil; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.Tag; import org.apache.hadoop.hbase.io.ByteBuffAllocator; import org.apache.hadoop.hbase.io.FSDataInputStreamWrapper; import org.apache.hadoop.hbase.io.compress.Compression; import org.apache.hadoop.hbase.io.encoding.DataBlockEncoder; import org.apache.hadoop.hbase.io.encoding.DataBlockEncoding; import org.apache.hadoop.hbase.io.encoding.HFileBlockDecodingContext; import org.apache.hadoop.hbase.nio.ByteBuff; import org.apache.hadoop.hbase.testclassification.IOTests; import org.apache.hadoop.hbase.testclassification.MediumTests; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.Writables; import org.apache.hadoop.io.Text; import org.junit.Assert; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Testing writing a version 3 {@link HFile} for all encoded blocks */ @RunWith(Parameterized.class) @Category({IOTests.class, MediumTests.class}) public class TestHFileWriterV3WithDataEncoders { @ClassRule public static final HBaseClassTestRule CLASS_RULE = HBaseClassTestRule.forClass(TestHFileWriterV3WithDataEncoders.class); private static final Logger LOG = LoggerFactory.getLogger(TestHFileWriterV3WithDataEncoders.class); private static final HBaseTestingUtil TEST_UTIL = new HBaseTestingUtil(); private static final Random RNG = new Random(9713312); // Just a fixed seed. private Configuration conf; private FileSystem fs; private boolean useTags; private DataBlockEncoding dataBlockEncoding; public TestHFileWriterV3WithDataEncoders(boolean useTags, DataBlockEncoding dataBlockEncoding) { this.useTags = useTags; this.dataBlockEncoding = dataBlockEncoding; } @Parameterized.Parameters public static Collection<Object[]> parameters() { DataBlockEncoding[] dataBlockEncodings = DataBlockEncoding.values(); Object[][] params = new Object[dataBlockEncodings.length * 2 - 2][]; int i = 0; for (DataBlockEncoding dataBlockEncoding : dataBlockEncodings) { if (dataBlockEncoding == DataBlockEncoding.NONE) { continue; } params[i++] = new Object[]{false, dataBlockEncoding}; params[i++] = new Object[]{true, dataBlockEncoding}; } return Arrays.asList(params); } @Before public void setUp() throws IOException { conf = TEST_UTIL.getConfiguration(); fs = FileSystem.get(conf); } @Test public void testHFileFormatV3() throws IOException { testHFileFormatV3Internals(useTags); } private void testHFileFormatV3Internals(boolean useTags) throws IOException { Path hfilePath = new Path(TEST_UTIL.getDataTestDir(), "testHFileFormatV3"); final Compression.Algorithm compressAlgo = Compression.Algorithm.GZ; final int entryCount = 10000; writeDataAndReadFromHFile(hfilePath, compressAlgo, entryCount, false, useTags); } @Test public void testMidKeyInHFile() throws IOException{ testMidKeyInHFileInternals(useTags); } private void testMidKeyInHFileInternals(boolean useTags) throws IOException { Path hfilePath = new Path(TEST_UTIL.getDataTestDir(), "testMidKeyInHFile"); Compression.Algorithm compressAlgo = Compression.Algorithm.NONE; int entryCount = 50000; writeDataAndReadFromHFile(hfilePath, compressAlgo, entryCount, true, useTags); } private void writeDataAndReadFromHFile(Path hfilePath, Compression.Algorithm compressAlgo, int entryCount, boolean findMidKey, boolean useTags) throws IOException { HFileContext context = new HFileContextBuilder() .withBlockSize(4096) .withIncludesTags(useTags) .withDataBlockEncoding(dataBlockEncoding) .withCellComparator(CellComparatorImpl.COMPARATOR) .withCompression(compressAlgo).build(); CacheConfig cacheConfig = new CacheConfig(conf); HFile.Writer writer = new HFile.WriterFactory(conf, cacheConfig) .withPath(fs, hfilePath) .withFileContext(context) .create(); List<KeyValue> keyValues = new ArrayList<>(entryCount); writeKeyValues(entryCount, useTags, writer, RNG, keyValues); FSDataInputStream fsdis = fs.open(hfilePath); long fileSize = fs.getFileStatus(hfilePath).getLen(); FixedFileTrailer trailer = FixedFileTrailer.readFromStream(fsdis, fileSize); Assert.assertEquals(3, trailer.getMajorVersion()); Assert.assertEquals(entryCount, trailer.getEntryCount()); HFileContext meta = new HFileContextBuilder() .withCompression(compressAlgo) .withIncludesMvcc(true) .withIncludesTags(useTags) .withDataBlockEncoding(dataBlockEncoding) .withHBaseCheckSum(true).build(); ReaderContext readerContext = new ReaderContextBuilder() .withInputStreamWrapper(new FSDataInputStreamWrapper(fsdis)) .withFilePath(hfilePath) .withFileSystem(fs) .withFileSize(fileSize).build(); HFileBlock.FSReader blockReader = new HFileBlock.FSReaderImpl(readerContext, meta, ByteBuffAllocator.HEAP, conf); // Comparator class name is stored in the trailer in version 3. CellComparator comparator = trailer.createComparator(); HFileBlockIndex.BlockIndexReader dataBlockIndexReader = new HFileBlockIndex.CellBasedKeyBlockIndexReader(comparator, trailer.getNumDataIndexLevels()); HFileBlockIndex.BlockIndexReader metaBlockIndexReader = new HFileBlockIndex.ByteArrayKeyBlockIndexReader(1); HFileBlock.BlockIterator blockIter = blockReader.blockRange( trailer.getLoadOnOpenDataOffset(), fileSize - trailer.getTrailerSize()); // Data index. We also read statistics about the block index written after // the root level. dataBlockIndexReader.readMultiLevelIndexRoot( blockIter.nextBlockWithBlockType(BlockType.ROOT_INDEX), trailer.getDataIndexCount()); FSDataInputStreamWrapper wrapper = new FSDataInputStreamWrapper(fs, hfilePath); readerContext = new ReaderContextBuilder() .withFilePath(hfilePath) .withFileSize(fileSize) .withFileSystem(wrapper.getHfs()) .withInputStreamWrapper(wrapper) .build(); HFileInfo hfile = new HFileInfo(readerContext, conf); HFile.Reader reader = new HFilePreadReader(readerContext, hfile, cacheConfig, conf); hfile.initMetaAndIndex(reader); if (findMidKey) { Cell midkey = dataBlockIndexReader.midkey(reader); Assert.assertNotNull("Midkey should not be null", midkey); } // Meta index. metaBlockIndexReader.readRootIndex( blockIter.nextBlockWithBlockType(BlockType.ROOT_INDEX) .getByteStream(), trailer.getMetaIndexCount()); // File info HFileInfo fileInfo = new HFileInfo(); fileInfo.read(blockIter.nextBlockWithBlockType(BlockType.FILE_INFO).getByteStream()); byte [] keyValueFormatVersion = fileInfo.get(HFileWriterImpl.KEY_VALUE_VERSION); boolean includeMemstoreTS = keyValueFormatVersion != null && Bytes.toInt(keyValueFormatVersion) > 0; // Counters for the number of key/value pairs and the number of blocks int entriesRead = 0; int blocksRead = 0; long memstoreTS = 0; DataBlockEncoder encoder = dataBlockEncoding.getEncoder(); long curBlockPos = scanBlocks(entryCount, context, keyValues, fsdis, trailer, meta, blockReader, entriesRead, blocksRead, encoder); // Meta blocks. We can scan until the load-on-open data offset (which is // the root block index offset in version 2) because we are not testing // intermediate-level index blocks here. int metaCounter = 0; while (fsdis.getPos() < trailer.getLoadOnOpenDataOffset()) { LOG.info("Current offset: {}, scanning until {}", fsdis.getPos(), trailer.getLoadOnOpenDataOffset()); HFileBlock block = blockReader.readBlockData(curBlockPos, -1, false, false, true) .unpack(context, blockReader); Assert.assertEquals(BlockType.META, block.getBlockType()); Text t = new Text(); ByteBuff buf = block.getBufferWithoutHeader(); if (Writables.getWritable(buf.array(), buf.arrayOffset(), buf.limit(), t) == null) { throw new IOException("Failed to deserialize block " + this + " into a " + t.getClass().getSimpleName()); } Text expectedText = (metaCounter == 0 ? new Text("Paris") : metaCounter == 1 ? new Text( "Moscow") : new Text("Washington, D.C.")); Assert.assertEquals(expectedText, t); LOG.info("Read meta block data: " + t); ++metaCounter; curBlockPos += block.getOnDiskSizeWithHeader(); } fsdis.close(); reader.close(); } private long scanBlocks(int entryCount, HFileContext context, List<KeyValue> keyValues, FSDataInputStream fsdis, FixedFileTrailer trailer, HFileContext meta, HFileBlock.FSReader blockReader, int entriesRead, int blocksRead, DataBlockEncoder encoder) throws IOException { // Scan blocks the way the reader would scan them fsdis.seek(0); long curBlockPos = 0; while (curBlockPos <= trailer.getLastDataBlockOffset()) { HFileBlockDecodingContext ctx = blockReader.getBlockDecodingContext(); HFileBlock block = blockReader.readBlockData(curBlockPos, -1, false, false, true) .unpack(context, blockReader); Assert.assertEquals(BlockType.ENCODED_DATA, block.getBlockType()); ByteBuff origBlock = block.getBufferReadOnly(); int pos = block.headerSize() + DataBlockEncoding.ID_SIZE; origBlock.position(pos); origBlock.limit(pos + block.getUncompressedSizeWithoutHeader() - DataBlockEncoding.ID_SIZE); ByteBuff buf = origBlock.slice(); DataBlockEncoder.EncodedSeeker seeker = encoder.createSeeker(encoder.newDataBlockDecodingContext(conf, meta)); seeker.setCurrentBuffer(buf); Cell res = seeker.getCell(); KeyValue kv = keyValues.get(entriesRead); Assert.assertEquals(0, CellComparatorImpl.COMPARATOR.compare(res, kv)); ++entriesRead; while(seeker.next()) { res = seeker.getCell(); kv = keyValues.get(entriesRead); Assert.assertEquals(0, CellComparatorImpl.COMPARATOR.compare(res, kv)); ++entriesRead; } ++blocksRead; curBlockPos += block.getOnDiskSizeWithHeader(); } LOG.info("Finished reading: entries={}, blocksRead = {}", entriesRead, blocksRead); Assert.assertEquals(entryCount, entriesRead); return curBlockPos; } private void writeKeyValues(int entryCount, boolean useTags, HFile.Writer writer, Random rand, List<KeyValue> keyValues) throws IOException { for (int i = 0; i < entryCount; ++i) { byte[] keyBytes = RandomKeyValueUtil.randomOrderedKey(rand, i); // A random-length random value. byte[] valueBytes = RandomKeyValueUtil.randomValue(rand); KeyValue keyValue = null; if (useTags) { ArrayList<Tag> tags = new ArrayList<>(); for (int j = 0; j < 1 + rand.nextInt(4); j++) { byte[] tagBytes = new byte[16]; rand.nextBytes(tagBytes); tags.add(new ArrayBackedTag((byte) 1, tagBytes)); } keyValue = new KeyValue(keyBytes, null, null, HConstants.LATEST_TIMESTAMP, valueBytes, tags); } else { keyValue = new KeyValue(keyBytes, null, null, HConstants.LATEST_TIMESTAMP, valueBytes); } writer.append(keyValue); keyValues.add(keyValue); } // Add in an arbitrary order. They will be sorted lexicographically by // the key. writer.appendMetaBlock("CAPITAL_OF_USA", new Text("Washington, D.C.")); writer.appendMetaBlock("CAPITAL_OF_RUSSIA", new Text("Moscow")); writer.appendMetaBlock("CAPITAL_OF_FRANCE", new Text("Paris")); writer.close(); } }
/* * Copyright 2014-present Facebook, 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.facebook.buck.features.ocaml; import com.facebook.buck.core.build.context.BuildContext; import com.facebook.buck.core.model.BuildTarget; import com.facebook.buck.core.sourcepath.SourcePath; import com.facebook.buck.core.sourcepath.resolver.SourcePathResolver; import com.facebook.buck.cxx.CxxPreprocessorInput; import com.facebook.buck.io.BuildCellRelativePath; import com.facebook.buck.io.filesystem.ProjectFilesystem; import com.facebook.buck.rules.args.Arg; import com.facebook.buck.rules.args.StringArg; import com.facebook.buck.step.ExecutionContext; import com.facebook.buck.step.Step; import com.facebook.buck.step.StepExecutionResult; import com.facebook.buck.step.StepExecutionResults; import com.facebook.buck.step.fs.MakeCleanDirectoryStep; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; /** A step that preprocesses, compiles, and assembles OCaml sources. */ public class OcamlBuildStep implements Step { private final BuildTarget target; private final BuildContext buildContext; private final ProjectFilesystem filesystem; private final OcamlBuildContext ocamlContext; private final ImmutableMap<String, String> cCompilerEnvironment; private final ImmutableList<String> cCompiler; private final ImmutableMap<String, String> cxxCompilerEnvironment; private final ImmutableList<String> cxxCompiler; private final boolean bytecodeOnly; private final boolean hasGeneratedSources; private final OcamlDepToolStep depToolStep; public OcamlBuildStep( BuildTarget target, BuildContext buildContext, ProjectFilesystem filesystem, OcamlBuildContext ocamlContext, ImmutableMap<String, String> cCompilerEnvironment, ImmutableList<String> cCompiler, ImmutableMap<String, String> cxxCompilerEnvironment, ImmutableList<String> cxxCompiler, boolean bytecodeOnly) { this.target = target; this.buildContext = buildContext; this.filesystem = filesystem; this.ocamlContext = ocamlContext; this.cCompilerEnvironment = cCompilerEnvironment; this.cCompiler = cCompiler; this.cxxCompilerEnvironment = cxxCompilerEnvironment; this.cxxCompiler = cxxCompiler; this.bytecodeOnly = bytecodeOnly; hasGeneratedSources = ocamlContext.getLexInput().size() > 0 || ocamlContext.getYaccInput().size() > 0; ImmutableList<String> ocamlDepFlags = ImmutableList.<String>builder() .addAll( this.ocamlContext.getIncludeFlags(/* isBytecode */ false, /* excludeDeps */ true)) .addAll(this.ocamlContext.getOcamlDepFlags()) .build(); this.depToolStep = new OcamlDepToolStep( target, filesystem.getRootPath(), this.ocamlContext.getSourcePathResolver(), this.ocamlContext.getOcamlDepTool().get(), ocamlContext.getMLInput(), ocamlDepFlags); } @Override public String getShortName() { return "OCaml compile"; } @Override public String getDescription(ExecutionContext context) { return depToolStep.getDescription(context); } @Override public StepExecutionResult execute(ExecutionContext context) throws IOException, InterruptedException { if (hasGeneratedSources) { StepExecutionResult genExecutionResult = generateSources(context, filesystem.getRootPath()); if (!genExecutionResult.isSuccess()) { return genExecutionResult; } } StepExecutionResult depToolExecutionResult = depToolStep.execute(context); if (!depToolExecutionResult.isSuccess()) { return depToolExecutionResult; } // OCaml requires module A to be present in command line to ocamlopt or ocamlc before // module B if B depends on A. In OCaml circular dependencies are prohibited, so all // dependency relations among modules form DAG. Topologically sorting this graph satisfies the // requirement. // // To get the DAG we launch ocamldep tool which provides the direct dependency information, like // module A depends on modules B, C, D. ImmutableList<Path> sortedInput = sortDependency( depToolStep.getStdout(), ocamlContext.getSourcePathResolver().getAllAbsolutePaths(ocamlContext.getMLInput())); ImmutableList.Builder<Path> nativeLinkerInputs = ImmutableList.builder(); if (!bytecodeOnly) { StepExecutionResult mlCompileNativeExecutionResult = executeMLNativeCompilation( context, filesystem.getRootPath(), sortedInput, nativeLinkerInputs); if (!mlCompileNativeExecutionResult.isSuccess()) { return mlCompileNativeExecutionResult; } } ImmutableList.Builder<Path> bytecodeLinkerInputs = ImmutableList.builder(); StepExecutionResult mlCompileBytecodeExecutionResult = executeMLBytecodeCompilation( context, filesystem.getRootPath(), sortedInput, bytecodeLinkerInputs); if (!mlCompileBytecodeExecutionResult.isSuccess()) { return mlCompileBytecodeExecutionResult; } ImmutableList.Builder<Path> cLinkerInputs = ImmutableList.builder(); StepExecutionResult cCompileExecutionResult = executeCCompilation(context, cLinkerInputs); if (!cCompileExecutionResult.isSuccess()) { return cCompileExecutionResult; } ImmutableList<Path> cObjects = cLinkerInputs.build(); if (!bytecodeOnly) { nativeLinkerInputs.addAll(cObjects); StepExecutionResult nativeLinkExecutionResult = executeNativeLinking(context, nativeLinkerInputs.build()); if (!nativeLinkExecutionResult.isSuccess()) { return nativeLinkExecutionResult; } } bytecodeLinkerInputs.addAll(cObjects); StepExecutionResult bytecodeLinkExecutionResult = executeBytecodeLinking(context, bytecodeLinkerInputs.build()); if (!bytecodeLinkExecutionResult.isSuccess()) { return bytecodeLinkExecutionResult; } if (!ocamlContext.isLibrary()) { Step debugLauncher = new OcamlDebugLauncherStep( filesystem, getResolver(), new OcamlDebugLauncherStep.Args( ocamlContext.getOcamlDebug().get(), ocamlContext.getBytecodeOutput(), ocamlContext.getTransitiveBytecodeIncludes(), ocamlContext.getBytecodeIncludeFlags())); return debugLauncher.execute(context); } else { return StepExecutionResults.SUCCESS; } } private StepExecutionResult executeCCompilation( ExecutionContext context, ImmutableList.Builder<Path> linkerInputs) throws IOException, InterruptedException { ImmutableList.Builder<Arg> cCompileFlags = ImmutableList.builder(); cCompileFlags.addAll(ocamlContext.getCCompileFlags()); cCompileFlags.addAll(StringArg.from(ocamlContext.getCommonCFlags())); CxxPreprocessorInput cxxPreprocessorInput = ocamlContext.getCxxPreprocessorInput(); for (SourcePath cSrc : ocamlContext.getCInput()) { Path outputPath = ocamlContext.getCOutput(getResolver().getAbsolutePath(cSrc)); linkerInputs.add(outputPath); Step compileStep = new OcamlCCompileStep( target, getResolver(), filesystem.getRootPath(), new OcamlCCompileStep.Args( cCompilerEnvironment, cCompiler, ocamlContext.getOcamlCompiler().get(), ocamlContext.getOcamlInteropIncludesDir(), outputPath, cSrc, cCompileFlags.build(), cxxPreprocessorInput.getIncludes())); StepExecutionResult compileExecutionResult = compileStep.execute(context); if (!compileExecutionResult.isSuccess()) { return compileExecutionResult; } } return StepExecutionResults.SUCCESS; } private StepExecutionResult executeNativeLinking( ExecutionContext context, ImmutableList<Path> linkerInputs) throws IOException, InterruptedException { ImmutableList.Builder<Arg> flags = ImmutableList.builder(); flags.addAll(ocamlContext.getFlags()); flags.addAll(StringArg.from(ocamlContext.getCommonCLinkerFlags())); OcamlLinkStep linkStep = OcamlLinkStep.create( target, filesystem.getRootPath(), cxxCompilerEnvironment, cxxCompiler, ocamlContext.getOcamlCompiler().get().getCommandPrefix(getResolver()), flags.build(), ocamlContext.getOcamlInteropIncludesDir(), ocamlContext.getNativeOutput(), ocamlContext.getNativeLinkableInput().getArgs(), ocamlContext.getCLinkableInput().getArgs(), linkerInputs, ocamlContext.isLibrary(), /* isBytecode */ false, getResolver()); return linkStep.execute(context); } private StepExecutionResult executeBytecodeLinking( ExecutionContext context, ImmutableList<Path> linkerInputs) throws IOException, InterruptedException { ImmutableList.Builder<Arg> flags = ImmutableList.builder(); flags.addAll(ocamlContext.getFlags()); flags.addAll(StringArg.from(ocamlContext.getCommonCLinkerFlags())); OcamlLinkStep linkStep = OcamlLinkStep.create( target, filesystem.getRootPath(), cxxCompilerEnvironment, cxxCompiler, ocamlContext.getOcamlBytecodeCompiler().get().getCommandPrefix(getResolver()), flags.build(), ocamlContext.getOcamlInteropIncludesDir(), ocamlContext.getBytecodeOutput(), ocamlContext.getBytecodeLinkableInput().getArgs(), ocamlContext.getCLinkableInput().getArgs(), linkerInputs, ocamlContext.isLibrary(), /* isBytecode */ true, getResolver()); return linkStep.execute(context); } private ImmutableList<Arg> getCompileFlags(boolean isBytecode, boolean excludeDeps) { String output = isBytecode ? ocamlContext.getCompileBytecodeOutputDir().toString() : ocamlContext.getCompileNativeOutputDir().toString(); ImmutableList.Builder<Arg> flagBuilder = ImmutableList.builder(); flagBuilder.addAll( StringArg.from(ocamlContext.getIncludeFlags(isBytecode, /* excludeDeps */ excludeDeps))); flagBuilder.addAll(ocamlContext.getFlags()); flagBuilder.add(StringArg.of(OcamlCompilables.OCAML_INCLUDE_FLAG), StringArg.of(output)); return flagBuilder.build(); } private StepExecutionResult executeMLNativeCompilation( ExecutionContext context, Path workingDirectory, ImmutableList<Path> sortedInput, ImmutableList.Builder<Path> linkerInputs) throws IOException, InterruptedException { for (Step step : MakeCleanDirectoryStep.of( BuildCellRelativePath.fromCellRelativePath( context.getBuildCellRootPath(), filesystem, ocamlContext.getCompileNativeOutputDir()))) { StepExecutionResult mkDirExecutionResult = step.execute(context); if (!mkDirExecutionResult.isSuccess()) { return mkDirExecutionResult; } } for (Path inputOutput : sortedInput) { String inputFileName = inputOutput.getFileName().toString(); String outputFileName = inputFileName .replaceFirst(OcamlCompilables.OCAML_ML_REGEX, OcamlCompilables.OCAML_CMX) .replaceFirst(OcamlCompilables.OCAML_RE_REGEX, OcamlCompilables.OCAML_CMX) .replaceFirst(OcamlCompilables.OCAML_MLI_REGEX, OcamlCompilables.OCAML_CMI) .replaceFirst(OcamlCompilables.OCAML_REI_REGEX, OcamlCompilables.OCAML_CMI); Path outputPath = ocamlContext.getCompileNativeOutputDir().resolve(outputFileName); if (!outputFileName.endsWith(OcamlCompilables.OCAML_CMI)) { linkerInputs.add(outputPath); } ImmutableList<Arg> compileFlags = getCompileFlags(/* isBytecode */ false, /* excludeDeps */ false); Step compileStep = new OcamlMLCompileStep( target, workingDirectory, getResolver(), new OcamlMLCompileStep.Args( filesystem::resolve, cCompilerEnvironment, cCompiler, ocamlContext.getOcamlCompiler().get(), ocamlContext.getOcamlInteropIncludesDir(), outputPath, inputOutput, compileFlags)); StepExecutionResult compileExecutionResult = compileStep.execute(context); if (!compileExecutionResult.isSuccess()) { return compileExecutionResult; } } return StepExecutionResults.SUCCESS; } private StepExecutionResult executeMLBytecodeCompilation( ExecutionContext context, Path workingDirectory, ImmutableList<Path> sortedInput, ImmutableList.Builder<Path> linkerInputs) throws IOException, InterruptedException { for (Step step : MakeCleanDirectoryStep.of( BuildCellRelativePath.fromCellRelativePath( context.getBuildCellRootPath(), filesystem, ocamlContext.getCompileBytecodeOutputDir()))) { StepExecutionResult mkDirExecutionResult = step.execute(context); if (!mkDirExecutionResult.isSuccess()) { return mkDirExecutionResult; } } for (Path inputOutput : sortedInput) { String inputFileName = inputOutput.getFileName().toString(); String outputFileName = inputFileName .replaceFirst(OcamlCompilables.OCAML_ML_REGEX, OcamlCompilables.OCAML_CMO) .replaceFirst(OcamlCompilables.OCAML_RE_REGEX, OcamlCompilables.OCAML_CMO) .replaceFirst(OcamlCompilables.OCAML_MLI_REGEX, OcamlCompilables.OCAML_CMI) .replaceFirst(OcamlCompilables.OCAML_REI_REGEX, OcamlCompilables.OCAML_CMI); Path outputPath = ocamlContext.getCompileBytecodeOutputDir().resolve(outputFileName); if (!outputFileName.endsWith(OcamlCompilables.OCAML_CMI)) { linkerInputs.add(outputPath); } ImmutableList<Arg> compileFlags = getCompileFlags(/* isBytecode */ true, /* excludeDeps */ false); Step compileBytecodeStep = new OcamlMLCompileStep( target, workingDirectory, getResolver(), new OcamlMLCompileStep.Args( filesystem::resolve, cCompilerEnvironment, cCompiler, ocamlContext.getOcamlBytecodeCompiler().get(), ocamlContext.getOcamlInteropIncludesDir(), outputPath, inputOutput, compileFlags)); StepExecutionResult compileExecutionResult = compileBytecodeStep.execute(context); if (!compileExecutionResult.isSuccess()) { return compileExecutionResult; } } return StepExecutionResults.SUCCESS; } private StepExecutionResult generateSources(ExecutionContext context, Path workingDirectory) throws IOException, InterruptedException { for (Step step : MakeCleanDirectoryStep.of( BuildCellRelativePath.fromCellRelativePath( context.getBuildCellRootPath(), filesystem, ocamlContext.getGeneratedSourceDir()))) { StepExecutionResult mkDirExecutionResult = step.execute(context); if (!mkDirExecutionResult.isSuccess()) { return mkDirExecutionResult; } } for (SourcePath yaccSource : ocamlContext.getYaccInput()) { SourcePath output = ocamlContext.getYaccOutput(ImmutableSet.of(yaccSource)).get(0); OcamlYaccStep yaccStep = new OcamlYaccStep( target, workingDirectory, getResolver(), new OcamlYaccStep.Args( ocamlContext.getYaccCompiler().get(), getResolver().getAbsolutePath(output), getResolver().getAbsolutePath(yaccSource))); StepExecutionResult yaccExecutionResult = yaccStep.execute(context); if (!yaccExecutionResult.isSuccess()) { return yaccExecutionResult; } } for (SourcePath lexSource : ocamlContext.getLexInput()) { SourcePath output = ocamlContext.getLexOutput(ImmutableSet.of(lexSource)).get(0); OcamlLexStep lexStep = new OcamlLexStep( target, workingDirectory, getResolver(), new OcamlLexStep.Args( ocamlContext.getLexCompiler().get(), getResolver().getAbsolutePath(output), getResolver().getAbsolutePath(lexSource))); StepExecutionResult lexExecutionResult = lexStep.execute(context); if (!lexExecutionResult.isSuccess()) { return lexExecutionResult; } } return StepExecutionResults.SUCCESS; } private ImmutableList<Path> sortDependency( String depOutput, ImmutableSet<Path> mlInput) { // NOPMD doesn't understand method reference OcamlDependencyGraphGenerator graphGenerator = new OcamlDependencyGraphGenerator(); return FluentIterable.from(graphGenerator.generate(depOutput)) .transform(Paths::get) // The output of generate needs to be filtered as .cmo dependencies // are generated as both .ml and .re files. .filter(mlInput::contains) .toList(); } private SourcePathResolver getResolver() { return buildContext.getSourcePathResolver(); } }
package org.ovirt.engine.core.bll; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.text.MessageFormat; import java.util.Arrays; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.ovirt.engine.core.bll.context.CommandContext; import org.ovirt.engine.core.bll.context.EngineContext; import org.ovirt.engine.core.common.action.VdcActionParametersBase; import org.ovirt.engine.core.common.action.VdcActionType; import org.ovirt.engine.core.common.queries.VdcQueryParametersBase; import org.ovirt.engine.core.common.queries.VdcQueryType; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.di.Injector; import org.ovirt.engine.core.utils.ReflectionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public final class CommandsFactory { private static final Logger log = LoggerFactory.getLogger(CommandsFactory.class); private static final String CLASS_NAME_FORMAT = "%1$s.%2$s%3$s"; private static final String COMMAND_SUFFIX = "Command"; private static final String QUERY_SUFFIX = "Query"; private static final String CTOR_MISMATCH = "could not find matching constructor for Command class {0}"; private static final String CTOR_NOT_FOUND_FOR_PARAMETERS = "Can't find constructor for type {} with parameter types: {}"; private static final String[] COMMAND_PACKAGES = new String[] { "org.ovirt.engine.core.bll", "org.ovirt.engine.core.bll.aaa", "org.ovirt.engine.core.bll.gluster", "org.ovirt.engine.core.bll.hostdeploy", "org.ovirt.engine.core.bll.hostdev", "org.ovirt.engine.core.bll.network", "org.ovirt.engine.core.bll.network.cluster", "org.ovirt.engine.core.bll.network.dc", "org.ovirt.engine.core.bll.network.host", "org.ovirt.engine.core.bll.network.template", "org.ovirt.engine.core.bll.network.vm", "org.ovirt.engine.core.bll.numa.host", "org.ovirt.engine.core.bll.numa.vm", "org.ovirt.engine.core.bll.pm", "org.ovirt.engine.core.bll.profiles", "org.ovirt.engine.core.bll.provider", "org.ovirt.engine.core.bll.provider.network", "org.ovirt.engine.core.bll.provider.storage", "org.ovirt.engine.core.bll.qos", "org.ovirt.engine.core.bll.scheduling.commands", "org.ovirt.engine.core.bll.scheduling.queries", "org.ovirt.engine.core.bll.snapshots", "org.ovirt.engine.core.bll.storage", "org.ovirt.engine.core.bll.storage.connection", "org.ovirt.engine.core.bll.storage.connection.iscsibond", "org.ovirt.engine.core.bll.storage.disk", "org.ovirt.engine.core.bll.storage.disk.cinder", "org.ovirt.engine.core.bll.storage.disk.image", "org.ovirt.engine.core.bll.storage.disk.lun", "org.ovirt.engine.core.bll.storage.domain", "org.ovirt.engine.core.bll.storage.export", "org.ovirt.engine.core.bll.storage.lsm", "org.ovirt.engine.core.bll.storage.ovfstore", "org.ovirt.engine.core.bll.storage.pool", "org.ovirt.engine.core.bll.storage.repoimage" }; protected String[] getCommandPackages() { return COMMAND_PACKAGES; } private static ConcurrentMap<String, Class<CommandBase<? extends VdcActionParametersBase>>> commandsCache = new ConcurrentHashMap<>(VdcActionType.values().length); public static <P extends VdcActionParametersBase> CommandBase<P> createCommand(VdcActionType action, P parameters) { return createCommand(action, parameters, null); } public static <P extends VdcActionParametersBase> CommandBase<P> createCommand(VdcActionType action, P parameters, CommandContext commandContext) { try { return Injector.injectMembers(instantiateCommand(action, parameters, commandContext)); } catch (InvocationTargetException ex) { log.error("Error in invocating CTOR of command '{}': {}", action.name(), ex.getMessage()); log.debug("Exception", ex); return null; } catch (Exception ex) { log.error("An exception has occured while trying to create a command object for command '{}': {}", action.name(), ex.getMessage()); log.debug("Exception", ex); return null; } } @SuppressWarnings("unchecked") private static <P extends VdcActionParametersBase> CommandBase<P> instantiateCommand(VdcActionType action, P parameters, CommandContext commandContext) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { CommandBase<P> command; if (commandContext != null && CommandsFactory.hasConstructor(action, parameters, commandContext)) { command = (CommandBase<P>) findCommandConstructor(getCommandClass(action.name()), parameters.getClass(), commandContext.getClass()).newInstance(parameters, commandContext); } else { command = (CommandBase<P>) findCommandConstructor( getCommandClass(action.name()), parameters.getClass()).newInstance(parameters); if (commandContext != null) { command.getContext().withExecutionContext(commandContext.getExecutionContext()); } } return command; } /** * Creates an instance of the given command class and passed the command id to it's constructor * * @param className * command class name to be created * @param commandId * the command id used by the compensation. * @return command instance or null if exception occurred. */ public static CommandBase<?> createCommand(String className, Guid commandId) { try { Constructor<?> constructor = Class.forName(className).getDeclaredConstructor(Guid.class); CommandBase<?> cmd = (CommandBase<?>) constructor.newInstance(commandId); return Injector.injectMembers(cmd); } catch (Exception e) { log.error("CommandsFactory : Failed to get type information using reflection for Class '{}', Command Id '{}': {}", className, commandId, e.getMessage()); log.error("Exception", e); return null; } } public static QueriesCommandBase<?> createQueryCommand(VdcQueryType query, VdcQueryParametersBase parameters, EngineContext engineContext) { Class<?> type = null; try { type = getQueryClass(query.name()); QueriesCommandBase<?> result; if (engineContext == null) { result = (QueriesCommandBase<?>) findCommandConstructor(type, parameters.getClass()).newInstance(parameters); } else { result = (QueriesCommandBase<?>) findCommandConstructor(type, parameters.getClass(), EngineContext.class).newInstance(parameters, engineContext); } return Injector.injectMembers(result); } catch (Exception e) { log.error("Command Factory: Failed to create command '{}' using reflection: {}", type, e.getMessage()); log.error("Exception", e); throw new RuntimeException(e); } } public static Class<CommandBase<? extends VdcActionParametersBase>> getCommandClass(String name) { return getCommandClass(name, COMMAND_SUFFIX); } public static Class<CommandBase<? extends VdcActionParametersBase>> getQueryClass(String name) { return getCommandClass(name, QUERY_SUFFIX); } private static <P extends VdcActionParametersBase> boolean hasConstructor(VdcActionType action, P parameters, CommandContext cmdContext) { return ReflectionUtils.findConstructor(getCommandClass(action.name()), parameters.getClass(), cmdContext.getClass()) != null; } private static Class<CommandBase<? extends VdcActionParametersBase>> getCommandClass(String name, String suffix) { // try the cache first String key = name + suffix; Class<CommandBase<? extends VdcActionParametersBase>> clazz = commandsCache.get(key); if (clazz != null) { return clazz; } for (String commandPackage : COMMAND_PACKAGES) { String className = String.format(CLASS_NAME_FORMAT, commandPackage, name, suffix); Class<CommandBase<? extends VdcActionParametersBase>> type = loadClass(className); if (type != null) { Class<CommandBase<? extends VdcActionParametersBase>> cachedType = commandsCache.putIfAbsent(key, type); // update cache return cachedType == null ? type : cachedType; } } // nothing found log.warn("Unable to find class for action '{}'", key); return null; } @SuppressWarnings("unchecked") private static Class<CommandBase<? extends VdcActionParametersBase>> loadClass(String className) { try { return (Class<CommandBase<? extends VdcActionParametersBase>>) Class.forName(className); } catch (ClassNotFoundException e) { return null; } } /** * Return the constructor for the command. * * @param <T> * The command type to look for. * @param type * A class representing the command type to look for. * @param expectedParams * The parameters which the constructor is expected to have (can * be empty). * * @return The first matching constructor for the command. * @throws RuntimeException * If a matching constructor can't be found. * * @see ReflectionUtils#findConstructor(Class, Class...) */ private static <T> Constructor<T> findCommandConstructor(Class<T> type, Class<?>... expectedParams) { Constructor<T> constructor = ReflectionUtils.findConstructor(type, expectedParams); if (constructor == null) { log.error(CTOR_NOT_FOUND_FOR_PARAMETERS, type.getName(), Arrays.toString(expectedParams)); throw new RuntimeException(MessageFormat.format(CTOR_MISMATCH, type)); } return constructor; } }
package org.drip.sample.netting; import org.drip.analytics.date.*; import org.drip.measure.discretemarginal.SequenceGenerator; import org.drip.measure.dynamics.DiffusionEvaluatorLogarithmic; import org.drip.measure.process.DiffusionEvolver; import org.drip.measure.realization.*; import org.drip.quant.common.FormatUtil; import org.drip.service.env.EnvManager; import org.drip.xva.trajectory.*; /* * -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /*! * Copyright (C) 2017 Lakshmi Krishnamurthy * * This file is part of DRIP, a free-software/open-source library for buy/side financial/trading model * libraries targeting analysts and developers * https://lakshmidrip.github.io/DRIP/ * * DRIP is composed of four main libraries: * * - DRIP Fixed Income - https://lakshmidrip.github.io/DRIP-Fixed-Income/ * - DRIP Asset Allocation - https://lakshmidrip.github.io/DRIP-Asset-Allocation/ * - DRIP Numerical Optimizer - https://lakshmidrip.github.io/DRIP-Numerical-Optimizer/ * - DRIP Statistical Learning - https://lakshmidrip.github.io/DRIP-Statistical-Learning/ * * - DRIP Fixed Income: Library for Instrument/Trading Conventions, Treasury Futures/Options, * Funding/Forward/Overnight Curves, Multi-Curve Construction/Valuation, Collateral Valuation and XVA * Metric Generation, Calibration and Hedge Attributions, Statistical Curve Construction, Bond RV * Metrics, Stochastic Evolution and Option Pricing, Interest Rate Dynamics and Option Pricing, LMM * Extensions/Calibrations/Greeks, Algorithmic Differentiation, and Asset Backed Models and Analytics. * * - DRIP Asset Allocation: Library for model libraries for MPT framework, Black Litterman Strategy * Incorporator, Holdings Constraint, and Transaction Costs. * * - DRIP Numerical Optimizer: Library for Numerical Optimization and Spline Functionality. * * - DRIP Statistical Learning: Library for Statistical Evaluation and Machine Learning. * * 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. */ /** * PortfolioGroupRun demonstrates a Set of Netting Group Exposure Simulations. The References are: * * - Burgard, C., and M. Kjaer (2014): PDE Representations of Derivatives with Bilateral Counter-party Risk * and Funding Costs, Journal of Credit Risk, 7 (3) 1-19. * * - Burgard, C., and M. Kjaer (2014): In the Balance, Risk, 24 (11) 72-75. * * - Gregory, J. (2009): Being Two-faced over Counter-party Credit Risk, Risk 20 (2) 86-90. * * - Li, B., and Y. Tang (2007): Quantitative Analysis, Derivatives Modeling, and Trading Strategies in the * Presence of Counter-party Credit Risk for the Fixed Income Market, World Scientific Publishing, * Singapore. * * - Piterbarg, V. (2010): Funding Beyond Discounting: Collateral Agreements and Derivatives Pricing, Risk * 21 (2) 97-102. * * @author Lakshmi Krishnamurthy */ public class PortfolioGroupSimulation { private static final JumpDiffusionEdge[][] PortfolioRealization ( final DiffusionEvolver dePortfolio, final double dblInitialAssetValue, final double dblTime, final double dblTimeWidth, final int iNumStep, final int iNumSimulation) throws Exception { JumpDiffusionEdge[][] aaJDE = new JumpDiffusionEdge[iNumSimulation][]; for (int i = 0; i < iNumSimulation; ++i) aaJDE[i] = dePortfolio.incrementSequence ( new JumpDiffusionVertex ( dblTime, dblInitialAssetValue, 0., false ), UnitRandom.Diffusion (SequenceGenerator.Gaussian (iNumStep)), dblTimeWidth ); return aaJDE; } public static final void main ( final String[] astrArgs) throws Exception { EnvManager.InitEnv (""); int iNumStep = 10; double dblTime = 5.; int iNumSimulation = 10000; double dblAssetDrift = 0.06; double dblAssetVolatility = 0.15; double dblInitialAssetValue = 1.; double dblCollateralDrift = 0.01; double dblBankHazardRate = 0.015; double dblBankRecoveryRate = 0.40; double dblCounterPartyHazardRate = 0.030; double dblCounterPartyRecoveryRate = 0.30; double dblTimeWidth = dblTime / iNumStep; double[] adblCollateral = new double[iNumStep]; double[] adblBankSurvival = new double[iNumStep]; double[] adblBankRecovery = new double[iNumStep]; JulianDate[] adtVertex = new JulianDate[iNumStep]; double[] adblBankFundingSpread = new double[iNumStep]; double[] adblCounterPartySurvival = new double[iNumStep]; double[] adblCounterPartyRecovery = new double[iNumStep]; CollateralGroupPath[] aCGP = new CollateralGroupPath[iNumSimulation]; double dblBankFundingSpread = dblBankHazardRate / (1. - dblBankRecoveryRate); CollateralGroupVertex[][] aaCGV = new CollateralGroupVertex[iNumSimulation][iNumStep]; JulianDate dtSpot = DateUtil.Today(); DiffusionEvolver dePortfolio = new DiffusionEvolver ( DiffusionEvaluatorLogarithmic.Standard ( dblAssetDrift, dblAssetVolatility ) ); JumpDiffusionEdge[][] aaJDEPortfolio = PortfolioRealization ( dePortfolio, dblInitialAssetValue, dblTime, dblTimeWidth, iNumStep, iNumSimulation ); for (int i = 0; i < iNumStep; ++i) { adblBankRecovery[i] = dblBankRecoveryRate; adblBankFundingSpread[i] = dblBankFundingSpread; adblCounterPartyRecovery[i] = dblCounterPartyRecoveryRate; adtVertex[i] = dtSpot.addMonths (6 * i + 6); adblCollateral[i] = Math.exp (0.5 * dblCollateralDrift * (i + 1)); adblBankSurvival[i] = Math.exp (-0.5 * dblBankHazardRate * (i + 1)); adblCounterPartySurvival[i] = Math.exp (-0.5 * dblCounterPartyHazardRate * (i + 1)); } for (int i = 0; i < iNumStep; ++i) { for (int j = 0; j < iNumSimulation; ++j) aaCGV[j][i] = new CollateralGroupVertex ( adtVertex[i], new CollateralGroupVertexExposure ( aaJDEPortfolio[j][i].finish(), 0., 0. ), new CollateralGroupVertexNumeraire ( adblCollateral[i], adblBankSurvival[i], adblBankRecovery[i], adblBankFundingSpread[i], adblCounterPartySurvival[i], adblCounterPartyRecovery[i] ) ); } for (int j = 0; j < iNumSimulation; ++j) { CollateralGroupEdge[] aCGE = new CollateralGroupEdge[iNumStep - 1]; for (int i = 1; i < iNumStep; ++i) aCGE[i - 1] = new CollateralGroupEdge ( aaCGV[j][i - 1], aaCGV[j][i] ); aCGP[j] = new CollateralGroupPath (aCGE); } NettingGroupPathAggregator ngpa = NettingGroupPathAggregator.Standard (aCGP); JulianDate[] adtVertexNode = ngpa.vertexes(); System.out.println(); System.out.println ("\t|-------------------------------------------------------------------------------------------------------------------------------------------------------------------|"); String strDump = "\t| DATE =>" ; for (int i = 0; i < adtVertexNode.length; ++i) strDump = strDump + " " + adtVertexNode[i] + " |"; System.out.println (strDump); System.out.println ("\t|-------------------------------------------------------------------------------------------------------------------------------------------------------------------|"); double[] adblEE = ngpa.collateralizedExposure(); strDump = "\t| EXPOSURE => " + FormatUtil.FormatDouble (dblInitialAssetValue, 1, 4, 1.) + " |"; for (int j = 0; j < adblEE.length; ++j) strDump = strDump + " " + FormatUtil.FormatDouble (adblEE[j], 1, 4, 1.) + " |"; System.out.println (strDump); double[] adblEPE = ngpa.collateralizedPositiveExposure(); strDump = "\t| POSITIVE EXPOSURE => " + FormatUtil.FormatDouble (dblInitialAssetValue, 1, 4, 1.) + " |"; for (int j = 0; j < adblEPE.length; ++j) strDump = strDump + " " + FormatUtil.FormatDouble (adblEPE[j], 1, 4, 1.) + " |"; System.out.println (strDump); double[] adblENE = ngpa.collateralizedNegativeExposure(); strDump = "\t| NEGATIVE EXPOSURE => " + FormatUtil.FormatDouble (0., 1, 4, 1.) + " |"; for (int j = 0; j < adblENE.length; ++j) strDump = strDump + " " + FormatUtil.FormatDouble (adblENE[j], 1, 4, 1.) + " |"; System.out.println (strDump); double[] adblEEPV = ngpa.collateralizedExposurePV(); strDump = "\t| EXPOSURE PV => " + FormatUtil.FormatDouble (dblInitialAssetValue, 1, 4, 1.) + " |"; for (int j = 0; j < adblEEPV.length; ++j) strDump = strDump + " " + FormatUtil.FormatDouble (adblEEPV[j], 1, 4, 1.) + " |"; System.out.println (strDump); double[] adblEPEPV = ngpa.collateralizedPositiveExposurePV(); strDump = "\t| POSITIVE EXPOSURE PV => " + FormatUtil.FormatDouble (dblInitialAssetValue, 1, 4, 1.) + " |"; for (int j = 0; j < adblEPEPV.length; ++j) strDump = strDump + " " + FormatUtil.FormatDouble (adblEPEPV[j], 1, 4, 1.) + " |"; System.out.println (strDump); double[] adblENEPV = ngpa.collateralizedNegativeExposurePV(); strDump = "\t| NEGATIVE EXPOSURE PV => " + FormatUtil.FormatDouble (0., 1, 4, 1.) + " |"; for (int j = 0; j < adblENEPV.length; ++j) strDump = strDump + " " + FormatUtil.FormatDouble (adblENEPV[j], 1, 4, 1.) + " |"; System.out.println (strDump); System.out.println ("\t|-------------------------------------------------------------------------------------------------------------------------------------------------------------------|"); System.out.println(); System.out.println ("\t||----------------||"); System.out.println ("\t|| CVA => " + FormatUtil.FormatDouble (ngpa.cva(), 2, 2, 100.) + "% ||"); System.out.println ("\t|| DVA => " + FormatUtil.FormatDouble (ngpa.dva(), 2, 2, 100.) + "% ||"); System.out.println ("\t|| FVA => " + FormatUtil.FormatDouble (ngpa.fca(), 2, 2, 100.) + "% ||"); System.out.println ("\t||----------------||"); System.out.println(); } }
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/gkehub/v1beta/feature.proto package com.google.cloud.gkehub.v1beta; /** * * * <pre> * MembershipFeatureState contains Feature status information for a single * Membership. * </pre> * * Protobuf type {@code google.cloud.gkehub.v1beta.MembershipFeatureState} */ public final class MembershipFeatureState extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.gkehub.v1beta.MembershipFeatureState) MembershipFeatureStateOrBuilder { private static final long serialVersionUID = 0L; // Use MembershipFeatureState.newBuilder() to construct. private MembershipFeatureState(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private MembershipFeatureState() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new MembershipFeatureState(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private MembershipFeatureState( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.cloud.gkehub.v1beta.FeatureState.Builder subBuilder = null; if (state_ != null) { subBuilder = state_.toBuilder(); } state_ = input.readMessage( com.google.cloud.gkehub.v1beta.FeatureState.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(state_); state_ = subBuilder.buildPartial(); } break; } case 834: { com.google.cloud.gkehub.metering.v1beta.MembershipState.Builder subBuilder = null; if (featureStateCase_ == 104) { subBuilder = ((com.google.cloud.gkehub.metering.v1beta.MembershipState) featureState_) .toBuilder(); } featureState_ = input.readMessage( com.google.cloud.gkehub.metering.v1beta.MembershipState.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom( (com.google.cloud.gkehub.metering.v1beta.MembershipState) featureState_); featureState_ = subBuilder.buildPartial(); } featureStateCase_ = 104; break; } case 850: { com.google.cloud.gkehub.configmanagement.v1beta.MembershipState.Builder subBuilder = null; if (featureStateCase_ == 106) { subBuilder = ((com.google.cloud.gkehub.configmanagement.v1beta.MembershipState) featureState_) .toBuilder(); } featureState_ = input.readMessage( com.google.cloud.gkehub.configmanagement.v1beta.MembershipState.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom( (com.google.cloud.gkehub.configmanagement.v1beta.MembershipState) featureState_); featureState_ = subBuilder.buildPartial(); } featureStateCase_ = 106; break; } default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.gkehub.v1beta.FeatureProto .internal_static_google_cloud_gkehub_v1beta_MembershipFeatureState_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.gkehub.v1beta.FeatureProto .internal_static_google_cloud_gkehub_v1beta_MembershipFeatureState_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.gkehub.v1beta.MembershipFeatureState.class, com.google.cloud.gkehub.v1beta.MembershipFeatureState.Builder.class); } private int featureStateCase_ = 0; private java.lang.Object featureState_; public enum FeatureStateCase implements com.google.protobuf.Internal.EnumLite, com.google.protobuf.AbstractMessage.InternalOneOfEnum { METERING(104), CONFIGMANAGEMENT(106), FEATURESTATE_NOT_SET(0); private final int value; private FeatureStateCase(int value) { this.value = value; } /** * @param value The number of the enum to look for. * @return The enum associated with the given number. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static FeatureStateCase valueOf(int value) { return forNumber(value); } public static FeatureStateCase forNumber(int value) { switch (value) { case 104: return METERING; case 106: return CONFIGMANAGEMENT; case 0: return FEATURESTATE_NOT_SET; default: return null; } } public int getNumber() { return this.value; } }; public FeatureStateCase getFeatureStateCase() { return FeatureStateCase.forNumber(featureStateCase_); } public static final int METERING_FIELD_NUMBER = 104; /** * * * <pre> * Metering-specific spec. * </pre> * * <code>.google.cloud.gkehub.metering.v1beta.MembershipState metering = 104;</code> * * @return Whether the metering field is set. */ @java.lang.Override public boolean hasMetering() { return featureStateCase_ == 104; } /** * * * <pre> * Metering-specific spec. * </pre> * * <code>.google.cloud.gkehub.metering.v1beta.MembershipState metering = 104;</code> * * @return The metering. */ @java.lang.Override public com.google.cloud.gkehub.metering.v1beta.MembershipState getMetering() { if (featureStateCase_ == 104) { return (com.google.cloud.gkehub.metering.v1beta.MembershipState) featureState_; } return com.google.cloud.gkehub.metering.v1beta.MembershipState.getDefaultInstance(); } /** * * * <pre> * Metering-specific spec. * </pre> * * <code>.google.cloud.gkehub.metering.v1beta.MembershipState metering = 104;</code> */ @java.lang.Override public com.google.cloud.gkehub.metering.v1beta.MembershipStateOrBuilder getMeteringOrBuilder() { if (featureStateCase_ == 104) { return (com.google.cloud.gkehub.metering.v1beta.MembershipState) featureState_; } return com.google.cloud.gkehub.metering.v1beta.MembershipState.getDefaultInstance(); } public static final int CONFIGMANAGEMENT_FIELD_NUMBER = 106; /** * * * <pre> * Config Management-specific state. * </pre> * * <code>.google.cloud.gkehub.configmanagement.v1beta.MembershipState configmanagement = 106; * </code> * * @return Whether the configmanagement field is set. */ @java.lang.Override public boolean hasConfigmanagement() { return featureStateCase_ == 106; } /** * * * <pre> * Config Management-specific state. * </pre> * * <code>.google.cloud.gkehub.configmanagement.v1beta.MembershipState configmanagement = 106; * </code> * * @return The configmanagement. */ @java.lang.Override public com.google.cloud.gkehub.configmanagement.v1beta.MembershipState getConfigmanagement() { if (featureStateCase_ == 106) { return (com.google.cloud.gkehub.configmanagement.v1beta.MembershipState) featureState_; } return com.google.cloud.gkehub.configmanagement.v1beta.MembershipState.getDefaultInstance(); } /** * * * <pre> * Config Management-specific state. * </pre> * * <code>.google.cloud.gkehub.configmanagement.v1beta.MembershipState configmanagement = 106; * </code> */ @java.lang.Override public com.google.cloud.gkehub.configmanagement.v1beta.MembershipStateOrBuilder getConfigmanagementOrBuilder() { if (featureStateCase_ == 106) { return (com.google.cloud.gkehub.configmanagement.v1beta.MembershipState) featureState_; } return com.google.cloud.gkehub.configmanagement.v1beta.MembershipState.getDefaultInstance(); } public static final int STATE_FIELD_NUMBER = 1; private com.google.cloud.gkehub.v1beta.FeatureState state_; /** * * * <pre> * The high-level state of this Feature for a single membership. * </pre> * * <code>.google.cloud.gkehub.v1beta.FeatureState state = 1;</code> * * @return Whether the state field is set. */ @java.lang.Override public boolean hasState() { return state_ != null; } /** * * * <pre> * The high-level state of this Feature for a single membership. * </pre> * * <code>.google.cloud.gkehub.v1beta.FeatureState state = 1;</code> * * @return The state. */ @java.lang.Override public com.google.cloud.gkehub.v1beta.FeatureState getState() { return state_ == null ? com.google.cloud.gkehub.v1beta.FeatureState.getDefaultInstance() : state_; } /** * * * <pre> * The high-level state of this Feature for a single membership. * </pre> * * <code>.google.cloud.gkehub.v1beta.FeatureState state = 1;</code> */ @java.lang.Override public com.google.cloud.gkehub.v1beta.FeatureStateOrBuilder getStateOrBuilder() { return getState(); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (state_ != null) { output.writeMessage(1, getState()); } if (featureStateCase_ == 104) { output.writeMessage( 104, (com.google.cloud.gkehub.metering.v1beta.MembershipState) featureState_); } if (featureStateCase_ == 106) { output.writeMessage( 106, (com.google.cloud.gkehub.configmanagement.v1beta.MembershipState) featureState_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (state_ != null) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getState()); } if (featureStateCase_ == 104) { size += com.google.protobuf.CodedOutputStream.computeMessageSize( 104, (com.google.cloud.gkehub.metering.v1beta.MembershipState) featureState_); } if (featureStateCase_ == 106) { size += com.google.protobuf.CodedOutputStream.computeMessageSize( 106, (com.google.cloud.gkehub.configmanagement.v1beta.MembershipState) featureState_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.gkehub.v1beta.MembershipFeatureState)) { return super.equals(obj); } com.google.cloud.gkehub.v1beta.MembershipFeatureState other = (com.google.cloud.gkehub.v1beta.MembershipFeatureState) obj; if (hasState() != other.hasState()) return false; if (hasState()) { if (!getState().equals(other.getState())) return false; } if (!getFeatureStateCase().equals(other.getFeatureStateCase())) return false; switch (featureStateCase_) { case 104: if (!getMetering().equals(other.getMetering())) return false; break; case 106: if (!getConfigmanagement().equals(other.getConfigmanagement())) return false; break; case 0: default: } if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasState()) { hash = (37 * hash) + STATE_FIELD_NUMBER; hash = (53 * hash) + getState().hashCode(); } switch (featureStateCase_) { case 104: hash = (37 * hash) + METERING_FIELD_NUMBER; hash = (53 * hash) + getMetering().hashCode(); break; case 106: hash = (37 * hash) + CONFIGMANAGEMENT_FIELD_NUMBER; hash = (53 * hash) + getConfigmanagement().hashCode(); break; case 0: default: } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.gkehub.v1beta.MembershipFeatureState parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.gkehub.v1beta.MembershipFeatureState parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.gkehub.v1beta.MembershipFeatureState parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.gkehub.v1beta.MembershipFeatureState parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.gkehub.v1beta.MembershipFeatureState parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.gkehub.v1beta.MembershipFeatureState parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.gkehub.v1beta.MembershipFeatureState parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.gkehub.v1beta.MembershipFeatureState parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.gkehub.v1beta.MembershipFeatureState parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.gkehub.v1beta.MembershipFeatureState parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.gkehub.v1beta.MembershipFeatureState parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.gkehub.v1beta.MembershipFeatureState parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.gkehub.v1beta.MembershipFeatureState prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * MembershipFeatureState contains Feature status information for a single * Membership. * </pre> * * Protobuf type {@code google.cloud.gkehub.v1beta.MembershipFeatureState} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.gkehub.v1beta.MembershipFeatureState) com.google.cloud.gkehub.v1beta.MembershipFeatureStateOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.gkehub.v1beta.FeatureProto .internal_static_google_cloud_gkehub_v1beta_MembershipFeatureState_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.gkehub.v1beta.FeatureProto .internal_static_google_cloud_gkehub_v1beta_MembershipFeatureState_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.gkehub.v1beta.MembershipFeatureState.class, com.google.cloud.gkehub.v1beta.MembershipFeatureState.Builder.class); } // Construct using com.google.cloud.gkehub.v1beta.MembershipFeatureState.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } @java.lang.Override public Builder clear() { super.clear(); if (stateBuilder_ == null) { state_ = null; } else { state_ = null; stateBuilder_ = null; } featureStateCase_ = 0; featureState_ = null; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.gkehub.v1beta.FeatureProto .internal_static_google_cloud_gkehub_v1beta_MembershipFeatureState_descriptor; } @java.lang.Override public com.google.cloud.gkehub.v1beta.MembershipFeatureState getDefaultInstanceForType() { return com.google.cloud.gkehub.v1beta.MembershipFeatureState.getDefaultInstance(); } @java.lang.Override public com.google.cloud.gkehub.v1beta.MembershipFeatureState build() { com.google.cloud.gkehub.v1beta.MembershipFeatureState result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.gkehub.v1beta.MembershipFeatureState buildPartial() { com.google.cloud.gkehub.v1beta.MembershipFeatureState result = new com.google.cloud.gkehub.v1beta.MembershipFeatureState(this); if (featureStateCase_ == 104) { if (meteringBuilder_ == null) { result.featureState_ = featureState_; } else { result.featureState_ = meteringBuilder_.build(); } } if (featureStateCase_ == 106) { if (configmanagementBuilder_ == null) { result.featureState_ = featureState_; } else { result.featureState_ = configmanagementBuilder_.build(); } } if (stateBuilder_ == null) { result.state_ = state_; } else { result.state_ = stateBuilder_.build(); } result.featureStateCase_ = featureStateCase_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.gkehub.v1beta.MembershipFeatureState) { return mergeFrom((com.google.cloud.gkehub.v1beta.MembershipFeatureState) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.gkehub.v1beta.MembershipFeatureState other) { if (other == com.google.cloud.gkehub.v1beta.MembershipFeatureState.getDefaultInstance()) return this; if (other.hasState()) { mergeState(other.getState()); } switch (other.getFeatureStateCase()) { case METERING: { mergeMetering(other.getMetering()); break; } case CONFIGMANAGEMENT: { mergeConfigmanagement(other.getConfigmanagement()); break; } case FEATURESTATE_NOT_SET: { break; } } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.cloud.gkehub.v1beta.MembershipFeatureState parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.cloud.gkehub.v1beta.MembershipFeatureState) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int featureStateCase_ = 0; private java.lang.Object featureState_; public FeatureStateCase getFeatureStateCase() { return FeatureStateCase.forNumber(featureStateCase_); } public Builder clearFeatureState() { featureStateCase_ = 0; featureState_ = null; onChanged(); return this; } private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.gkehub.metering.v1beta.MembershipState, com.google.cloud.gkehub.metering.v1beta.MembershipState.Builder, com.google.cloud.gkehub.metering.v1beta.MembershipStateOrBuilder> meteringBuilder_; /** * * * <pre> * Metering-specific spec. * </pre> * * <code>.google.cloud.gkehub.metering.v1beta.MembershipState metering = 104;</code> * * @return Whether the metering field is set. */ @java.lang.Override public boolean hasMetering() { return featureStateCase_ == 104; } /** * * * <pre> * Metering-specific spec. * </pre> * * <code>.google.cloud.gkehub.metering.v1beta.MembershipState metering = 104;</code> * * @return The metering. */ @java.lang.Override public com.google.cloud.gkehub.metering.v1beta.MembershipState getMetering() { if (meteringBuilder_ == null) { if (featureStateCase_ == 104) { return (com.google.cloud.gkehub.metering.v1beta.MembershipState) featureState_; } return com.google.cloud.gkehub.metering.v1beta.MembershipState.getDefaultInstance(); } else { if (featureStateCase_ == 104) { return meteringBuilder_.getMessage(); } return com.google.cloud.gkehub.metering.v1beta.MembershipState.getDefaultInstance(); } } /** * * * <pre> * Metering-specific spec. * </pre> * * <code>.google.cloud.gkehub.metering.v1beta.MembershipState metering = 104;</code> */ public Builder setMetering(com.google.cloud.gkehub.metering.v1beta.MembershipState value) { if (meteringBuilder_ == null) { if (value == null) { throw new NullPointerException(); } featureState_ = value; onChanged(); } else { meteringBuilder_.setMessage(value); } featureStateCase_ = 104; return this; } /** * * * <pre> * Metering-specific spec. * </pre> * * <code>.google.cloud.gkehub.metering.v1beta.MembershipState metering = 104;</code> */ public Builder setMetering( com.google.cloud.gkehub.metering.v1beta.MembershipState.Builder builderForValue) { if (meteringBuilder_ == null) { featureState_ = builderForValue.build(); onChanged(); } else { meteringBuilder_.setMessage(builderForValue.build()); } featureStateCase_ = 104; return this; } /** * * * <pre> * Metering-specific spec. * </pre> * * <code>.google.cloud.gkehub.metering.v1beta.MembershipState metering = 104;</code> */ public Builder mergeMetering(com.google.cloud.gkehub.metering.v1beta.MembershipState value) { if (meteringBuilder_ == null) { if (featureStateCase_ == 104 && featureState_ != com.google.cloud.gkehub.metering.v1beta.MembershipState.getDefaultInstance()) { featureState_ = com.google.cloud.gkehub.metering.v1beta.MembershipState.newBuilder( (com.google.cloud.gkehub.metering.v1beta.MembershipState) featureState_) .mergeFrom(value) .buildPartial(); } else { featureState_ = value; } onChanged(); } else { if (featureStateCase_ == 104) { meteringBuilder_.mergeFrom(value); } meteringBuilder_.setMessage(value); } featureStateCase_ = 104; return this; } /** * * * <pre> * Metering-specific spec. * </pre> * * <code>.google.cloud.gkehub.metering.v1beta.MembershipState metering = 104;</code> */ public Builder clearMetering() { if (meteringBuilder_ == null) { if (featureStateCase_ == 104) { featureStateCase_ = 0; featureState_ = null; onChanged(); } } else { if (featureStateCase_ == 104) { featureStateCase_ = 0; featureState_ = null; } meteringBuilder_.clear(); } return this; } /** * * * <pre> * Metering-specific spec. * </pre> * * <code>.google.cloud.gkehub.metering.v1beta.MembershipState metering = 104;</code> */ public com.google.cloud.gkehub.metering.v1beta.MembershipState.Builder getMeteringBuilder() { return getMeteringFieldBuilder().getBuilder(); } /** * * * <pre> * Metering-specific spec. * </pre> * * <code>.google.cloud.gkehub.metering.v1beta.MembershipState metering = 104;</code> */ @java.lang.Override public com.google.cloud.gkehub.metering.v1beta.MembershipStateOrBuilder getMeteringOrBuilder() { if ((featureStateCase_ == 104) && (meteringBuilder_ != null)) { return meteringBuilder_.getMessageOrBuilder(); } else { if (featureStateCase_ == 104) { return (com.google.cloud.gkehub.metering.v1beta.MembershipState) featureState_; } return com.google.cloud.gkehub.metering.v1beta.MembershipState.getDefaultInstance(); } } /** * * * <pre> * Metering-specific spec. * </pre> * * <code>.google.cloud.gkehub.metering.v1beta.MembershipState metering = 104;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.gkehub.metering.v1beta.MembershipState, com.google.cloud.gkehub.metering.v1beta.MembershipState.Builder, com.google.cloud.gkehub.metering.v1beta.MembershipStateOrBuilder> getMeteringFieldBuilder() { if (meteringBuilder_ == null) { if (!(featureStateCase_ == 104)) { featureState_ = com.google.cloud.gkehub.metering.v1beta.MembershipState.getDefaultInstance(); } meteringBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.gkehub.metering.v1beta.MembershipState, com.google.cloud.gkehub.metering.v1beta.MembershipState.Builder, com.google.cloud.gkehub.metering.v1beta.MembershipStateOrBuilder>( (com.google.cloud.gkehub.metering.v1beta.MembershipState) featureState_, getParentForChildren(), isClean()); featureState_ = null; } featureStateCase_ = 104; onChanged(); ; return meteringBuilder_; } private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.gkehub.configmanagement.v1beta.MembershipState, com.google.cloud.gkehub.configmanagement.v1beta.MembershipState.Builder, com.google.cloud.gkehub.configmanagement.v1beta.MembershipStateOrBuilder> configmanagementBuilder_; /** * * * <pre> * Config Management-specific state. * </pre> * * <code>.google.cloud.gkehub.configmanagement.v1beta.MembershipState configmanagement = 106; * </code> * * @return Whether the configmanagement field is set. */ @java.lang.Override public boolean hasConfigmanagement() { return featureStateCase_ == 106; } /** * * * <pre> * Config Management-specific state. * </pre> * * <code>.google.cloud.gkehub.configmanagement.v1beta.MembershipState configmanagement = 106; * </code> * * @return The configmanagement. */ @java.lang.Override public com.google.cloud.gkehub.configmanagement.v1beta.MembershipState getConfigmanagement() { if (configmanagementBuilder_ == null) { if (featureStateCase_ == 106) { return (com.google.cloud.gkehub.configmanagement.v1beta.MembershipState) featureState_; } return com.google.cloud.gkehub.configmanagement.v1beta.MembershipState.getDefaultInstance(); } else { if (featureStateCase_ == 106) { return configmanagementBuilder_.getMessage(); } return com.google.cloud.gkehub.configmanagement.v1beta.MembershipState.getDefaultInstance(); } } /** * * * <pre> * Config Management-specific state. * </pre> * * <code>.google.cloud.gkehub.configmanagement.v1beta.MembershipState configmanagement = 106; * </code> */ public Builder setConfigmanagement( com.google.cloud.gkehub.configmanagement.v1beta.MembershipState value) { if (configmanagementBuilder_ == null) { if (value == null) { throw new NullPointerException(); } featureState_ = value; onChanged(); } else { configmanagementBuilder_.setMessage(value); } featureStateCase_ = 106; return this; } /** * * * <pre> * Config Management-specific state. * </pre> * * <code>.google.cloud.gkehub.configmanagement.v1beta.MembershipState configmanagement = 106; * </code> */ public Builder setConfigmanagement( com.google.cloud.gkehub.configmanagement.v1beta.MembershipState.Builder builderForValue) { if (configmanagementBuilder_ == null) { featureState_ = builderForValue.build(); onChanged(); } else { configmanagementBuilder_.setMessage(builderForValue.build()); } featureStateCase_ = 106; return this; } /** * * * <pre> * Config Management-specific state. * </pre> * * <code>.google.cloud.gkehub.configmanagement.v1beta.MembershipState configmanagement = 106; * </code> */ public Builder mergeConfigmanagement( com.google.cloud.gkehub.configmanagement.v1beta.MembershipState value) { if (configmanagementBuilder_ == null) { if (featureStateCase_ == 106 && featureState_ != com.google.cloud.gkehub.configmanagement.v1beta.MembershipState .getDefaultInstance()) { featureState_ = com.google.cloud.gkehub.configmanagement.v1beta.MembershipState.newBuilder( (com.google.cloud.gkehub.configmanagement.v1beta.MembershipState) featureState_) .mergeFrom(value) .buildPartial(); } else { featureState_ = value; } onChanged(); } else { if (featureStateCase_ == 106) { configmanagementBuilder_.mergeFrom(value); } configmanagementBuilder_.setMessage(value); } featureStateCase_ = 106; return this; } /** * * * <pre> * Config Management-specific state. * </pre> * * <code>.google.cloud.gkehub.configmanagement.v1beta.MembershipState configmanagement = 106; * </code> */ public Builder clearConfigmanagement() { if (configmanagementBuilder_ == null) { if (featureStateCase_ == 106) { featureStateCase_ = 0; featureState_ = null; onChanged(); } } else { if (featureStateCase_ == 106) { featureStateCase_ = 0; featureState_ = null; } configmanagementBuilder_.clear(); } return this; } /** * * * <pre> * Config Management-specific state. * </pre> * * <code>.google.cloud.gkehub.configmanagement.v1beta.MembershipState configmanagement = 106; * </code> */ public com.google.cloud.gkehub.configmanagement.v1beta.MembershipState.Builder getConfigmanagementBuilder() { return getConfigmanagementFieldBuilder().getBuilder(); } /** * * * <pre> * Config Management-specific state. * </pre> * * <code>.google.cloud.gkehub.configmanagement.v1beta.MembershipState configmanagement = 106; * </code> */ @java.lang.Override public com.google.cloud.gkehub.configmanagement.v1beta.MembershipStateOrBuilder getConfigmanagementOrBuilder() { if ((featureStateCase_ == 106) && (configmanagementBuilder_ != null)) { return configmanagementBuilder_.getMessageOrBuilder(); } else { if (featureStateCase_ == 106) { return (com.google.cloud.gkehub.configmanagement.v1beta.MembershipState) featureState_; } return com.google.cloud.gkehub.configmanagement.v1beta.MembershipState.getDefaultInstance(); } } /** * * * <pre> * Config Management-specific state. * </pre> * * <code>.google.cloud.gkehub.configmanagement.v1beta.MembershipState configmanagement = 106; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.gkehub.configmanagement.v1beta.MembershipState, com.google.cloud.gkehub.configmanagement.v1beta.MembershipState.Builder, com.google.cloud.gkehub.configmanagement.v1beta.MembershipStateOrBuilder> getConfigmanagementFieldBuilder() { if (configmanagementBuilder_ == null) { if (!(featureStateCase_ == 106)) { featureState_ = com.google.cloud.gkehub.configmanagement.v1beta.MembershipState.getDefaultInstance(); } configmanagementBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.gkehub.configmanagement.v1beta.MembershipState, com.google.cloud.gkehub.configmanagement.v1beta.MembershipState.Builder, com.google.cloud.gkehub.configmanagement.v1beta.MembershipStateOrBuilder>( (com.google.cloud.gkehub.configmanagement.v1beta.MembershipState) featureState_, getParentForChildren(), isClean()); featureState_ = null; } featureStateCase_ = 106; onChanged(); ; return configmanagementBuilder_; } private com.google.cloud.gkehub.v1beta.FeatureState state_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.gkehub.v1beta.FeatureState, com.google.cloud.gkehub.v1beta.FeatureState.Builder, com.google.cloud.gkehub.v1beta.FeatureStateOrBuilder> stateBuilder_; /** * * * <pre> * The high-level state of this Feature for a single membership. * </pre> * * <code>.google.cloud.gkehub.v1beta.FeatureState state = 1;</code> * * @return Whether the state field is set. */ public boolean hasState() { return stateBuilder_ != null || state_ != null; } /** * * * <pre> * The high-level state of this Feature for a single membership. * </pre> * * <code>.google.cloud.gkehub.v1beta.FeatureState state = 1;</code> * * @return The state. */ public com.google.cloud.gkehub.v1beta.FeatureState getState() { if (stateBuilder_ == null) { return state_ == null ? com.google.cloud.gkehub.v1beta.FeatureState.getDefaultInstance() : state_; } else { return stateBuilder_.getMessage(); } } /** * * * <pre> * The high-level state of this Feature for a single membership. * </pre> * * <code>.google.cloud.gkehub.v1beta.FeatureState state = 1;</code> */ public Builder setState(com.google.cloud.gkehub.v1beta.FeatureState value) { if (stateBuilder_ == null) { if (value == null) { throw new NullPointerException(); } state_ = value; onChanged(); } else { stateBuilder_.setMessage(value); } return this; } /** * * * <pre> * The high-level state of this Feature for a single membership. * </pre> * * <code>.google.cloud.gkehub.v1beta.FeatureState state = 1;</code> */ public Builder setState(com.google.cloud.gkehub.v1beta.FeatureState.Builder builderForValue) { if (stateBuilder_ == null) { state_ = builderForValue.build(); onChanged(); } else { stateBuilder_.setMessage(builderForValue.build()); } return this; } /** * * * <pre> * The high-level state of this Feature for a single membership. * </pre> * * <code>.google.cloud.gkehub.v1beta.FeatureState state = 1;</code> */ public Builder mergeState(com.google.cloud.gkehub.v1beta.FeatureState value) { if (stateBuilder_ == null) { if (state_ != null) { state_ = com.google.cloud.gkehub.v1beta.FeatureState.newBuilder(state_) .mergeFrom(value) .buildPartial(); } else { state_ = value; } onChanged(); } else { stateBuilder_.mergeFrom(value); } return this; } /** * * * <pre> * The high-level state of this Feature for a single membership. * </pre> * * <code>.google.cloud.gkehub.v1beta.FeatureState state = 1;</code> */ public Builder clearState() { if (stateBuilder_ == null) { state_ = null; onChanged(); } else { state_ = null; stateBuilder_ = null; } return this; } /** * * * <pre> * The high-level state of this Feature for a single membership. * </pre> * * <code>.google.cloud.gkehub.v1beta.FeatureState state = 1;</code> */ public com.google.cloud.gkehub.v1beta.FeatureState.Builder getStateBuilder() { onChanged(); return getStateFieldBuilder().getBuilder(); } /** * * * <pre> * The high-level state of this Feature for a single membership. * </pre> * * <code>.google.cloud.gkehub.v1beta.FeatureState state = 1;</code> */ public com.google.cloud.gkehub.v1beta.FeatureStateOrBuilder getStateOrBuilder() { if (stateBuilder_ != null) { return stateBuilder_.getMessageOrBuilder(); } else { return state_ == null ? com.google.cloud.gkehub.v1beta.FeatureState.getDefaultInstance() : state_; } } /** * * * <pre> * The high-level state of this Feature for a single membership. * </pre> * * <code>.google.cloud.gkehub.v1beta.FeatureState state = 1;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.gkehub.v1beta.FeatureState, com.google.cloud.gkehub.v1beta.FeatureState.Builder, com.google.cloud.gkehub.v1beta.FeatureStateOrBuilder> getStateFieldBuilder() { if (stateBuilder_ == null) { stateBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.gkehub.v1beta.FeatureState, com.google.cloud.gkehub.v1beta.FeatureState.Builder, com.google.cloud.gkehub.v1beta.FeatureStateOrBuilder>( getState(), getParentForChildren(), isClean()); state_ = null; } return stateBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.gkehub.v1beta.MembershipFeatureState) } // @@protoc_insertion_point(class_scope:google.cloud.gkehub.v1beta.MembershipFeatureState) private static final com.google.cloud.gkehub.v1beta.MembershipFeatureState DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.gkehub.v1beta.MembershipFeatureState(); } public static com.google.cloud.gkehub.v1beta.MembershipFeatureState getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<MembershipFeatureState> PARSER = new com.google.protobuf.AbstractParser<MembershipFeatureState>() { @java.lang.Override public MembershipFeatureState parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new MembershipFeatureState(input, extensionRegistry); } }; public static com.google.protobuf.Parser<MembershipFeatureState> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<MembershipFeatureState> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.gkehub.v1beta.MembershipFeatureState getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
// Copyright 2000-2020 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.codeInspection.classCanBeRecord; import com.intellij.codeInsight.AnnotationTargetUtil; import com.intellij.codeInsight.AnnotationUtil; import com.intellij.codeInsight.ExceptionUtil; import com.intellij.codeInsight.daemon.impl.analysis.HighlightControlFlowUtil; import com.intellij.codeInsight.daemon.impl.analysis.HighlightUtil; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.codeInspection.util.IntentionFamilyName; import com.intellij.java.JavaBundle; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.intellij.psi.PsiAnnotation.TargetType; import com.intellij.psi.search.searches.ClassInheritorsSearch; import com.intellij.psi.util.PropertyUtil; import com.intellij.psi.util.PropertyUtilBase; import com.intellij.psi.util.PsiUtil; import com.intellij.util.ObjectUtils; import com.intellij.util.SmartList; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.MultiMap; import com.siyeh.ig.InspectionGadgetsFix; import com.siyeh.ig.callMatcher.CallMatcher; import com.siyeh.ig.psiutils.TypeUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.stream.Collectors; import static com.intellij.psi.CommonClassNames.JAVA_LANG_OBJECT; import static com.intellij.psi.PsiModifier.*; public class ConvertToRecordFix extends InspectionGadgetsFix { private final boolean myShowAffectedMembers; private final boolean mySuggestAccessorsRenaming; ConvertToRecordFix(boolean showAffectedMembers, boolean suggestAccessorsRenaming) { myShowAffectedMembers = showAffectedMembers; mySuggestAccessorsRenaming = suggestAccessorsRenaming; } @Override public @IntentionFamilyName @NotNull String getFamilyName() { return JavaBundle.message("class.can.be.record.quick.fix"); } @Override public boolean startInWriteAction() { return false; } @Override protected void doFix(Project project, ProblemDescriptor descriptor) { PsiElement psiElement = descriptor.getPsiElement(); if (psiElement == null) return; PsiClass psiClass = ObjectUtils.tryCast(psiElement.getParent(), PsiClass.class); if (psiClass == null) return; RecordCandidate recordCandidate = getClassDefinition(psiClass, mySuggestAccessorsRenaming); if (recordCandidate == null) return; ConvertToRecordProcessor processor = new ConvertToRecordProcessor(recordCandidate, myShowAffectedMembers); processor.setPrepareSuccessfulSwingThreadCallback(() -> {}); processor.run(); } /** * There are some restrictions for records: * https://docs.oracle.com/javase/specs/jls/se15/preview/specs/records-jls.html. */ public static RecordCandidate getClassDefinition(@NotNull PsiClass psiClass, boolean suggestAccessorsRenaming) { boolean isNotAppropriatePsiClass = psiClass.isEnum() || psiClass.isAnnotationType() || psiClass instanceof PsiAnonymousClass || psiClass.isInterface() || psiClass.isRecord(); if (isNotAppropriatePsiClass) return null; PsiModifierList psiClassModifiers = psiClass.getModifierList(); if (psiClassModifiers == null || psiClassModifiers.hasModifierProperty(ABSTRACT) || psiClassModifiers.hasModifierProperty(SEALED)) { return null; } if (!mayBeFinal(psiClass)) return null; // todo support local classes later if (PsiUtil.isLocalClass(psiClass)) return null; if (psiClass.getContainingClass() != null && !psiClass.hasModifierProperty(STATIC)) return null; PsiClass superClass = psiClass.getSuperClass(); if (superClass == null || !JAVA_LANG_OBJECT.equals(superClass.getQualifiedName())) return null; if (ContainerUtil.exists(psiClass.getInitializers(), initializer -> !initializer.hasModifierProperty(STATIC))) return null; RecordCandidate result = new RecordCandidate(psiClass, suggestAccessorsRenaming); if (!result.isValid()) return null; return ClassInheritorsSearch.search(psiClass, false).findFirst() == null ? result : null; } /** * Some classes might be proxied e.g. according to JPA spec an entity class can't be final. */ private static boolean mayBeFinal(@NotNull PsiClass psiClass) { return !psiClass.hasAnnotation("javax.persistence.Entity"); } /** * Encapsulates necessary information about the converting class e.g its existing fields, accessors... * It helps to validate whether a class will be a well-formed record and supports performing a refactoring. */ static class RecordCandidate { private static final CallMatcher OBJECT_METHOD_CALLS = CallMatcher.anyOf( CallMatcher.exactInstanceCall(JAVA_LANG_OBJECT, "equals").parameterCount(1), CallMatcher.exactInstanceCall(JAVA_LANG_OBJECT, "hashCode", "toString").parameterCount(0) ); private final PsiClass myClass; private final boolean mySuggestAccessorsRenaming; private final MultiMap<PsiField, FieldAccessorCandidate> myFieldAccessors = new MultiMap<>(); private final List<PsiMethod> myOrdinaryMethods = new SmartList<>(); private final List<RecordConstructorCandidate> myConstructors = new SmartList<>(); private Map<PsiField, FieldAccessorCandidate> myFieldAccessorsCache; private RecordCandidate(@NotNull PsiClass psiClass, boolean suggestAccessorsRenaming) { myClass = psiClass; mySuggestAccessorsRenaming = suggestAccessorsRenaming; prepare(); } Project getProject() { return myClass.getProject(); } PsiClass getPsiClass() { return myClass; } @NotNull Map<PsiField, @Nullable FieldAccessorCandidate> getFieldAccessors() { if (myFieldAccessorsCache != null) return myFieldAccessorsCache; Map<PsiField, FieldAccessorCandidate> result = new HashMap<>(); for (var entry : myFieldAccessors.entrySet()) { PsiField newKey = entry.getKey(); Collection<FieldAccessorCandidate> oldValue = entry.getValue(); FieldAccessorCandidate newValue = ContainerUtil.getOnlyItem(oldValue); result.put(newKey, newValue); } myFieldAccessorsCache = result; return result; } @Nullable PsiMethod getCanonicalConstructor() { return myConstructors.size() == 1 ? myConstructors.get(0).myConstructor : null; } private boolean isValid() { if (myConstructors.size() > 1) return false; if (myConstructors.size() == 1) { RecordConstructorCandidate ctorCandidate = myConstructors.get(0); boolean isCanonical = ctorCandidate.myCanonical && throwsOnlyUncheckedExceptions(ctorCandidate.myConstructor); if (!isCanonical) return false; if (containsObjectMethodCalls(ctorCandidate.myConstructor)) return false; } if (myFieldAccessors.size() == 0) return false; for (var entry : myFieldAccessors.entrySet()) { PsiField field = entry.getKey(); if (!field.hasModifierProperty(FINAL) || field.hasInitializer()) return false; if (HighlightUtil.RESTRICTED_RECORD_COMPONENT_NAMES.contains(field.getName())) return false; if (entry.getValue().size() > 1) return false; FieldAccessorCandidate firstAccessor = ContainerUtil.getFirstItem(entry.getValue()); if (firstAccessor == null) continue; if (containsObjectMethodCalls(firstAccessor.getAccessor())) return false; } for (PsiMethod ordinaryMethod : myOrdinaryMethods) { if (ordinaryMethod.hasModifierProperty(NATIVE)) return false; boolean conflictsWithPotentialAccessor = ordinaryMethod.getParameterList().isEmpty() && ContainerUtil.exists(myFieldAccessors.keySet(), field -> field.getName().equals(ordinaryMethod.getName())); if (conflictsWithPotentialAccessor) return false; if (containsObjectMethodCalls(ordinaryMethod)) return false; } return true; } private void prepare() { Arrays.stream(myClass.getFields()).filter(field -> !field.hasModifierProperty(STATIC)) .forEach(field -> myFieldAccessors.put(field, new ArrayList<>())); for (PsiMethod method : myClass.getMethods()) { if (method.isConstructor()) { myConstructors.add(new RecordConstructorCandidate(method, myFieldAccessors.keySet())); continue; } if (!throwsOnlyUncheckedExceptions(method)) { myOrdinaryMethods.add(method); continue; } FieldAccessorCandidate fieldAccessorCandidate = createFieldAccessor(method); if (fieldAccessorCandidate == null) { myOrdinaryMethods.add(method); } else { myFieldAccessors.putValue(fieldAccessorCandidate.myBackingField, fieldAccessorCandidate); } } } private static boolean throwsOnlyUncheckedExceptions(@NotNull PsiMethod psiMethod) { for (PsiClassType throwsType : psiMethod.getThrowsList().getReferencedTypes()) { PsiClassType throwsClassType = ObjectUtils.tryCast(throwsType, PsiClassType.class); if (throwsClassType == null) continue; if (!ExceptionUtil.isUncheckedException(throwsClassType)) { return false; } } return true; } private static boolean containsObjectMethodCalls(@NotNull PsiMethod psiMethod) { var visitor = new JavaRecursiveElementWalkingVisitor() { boolean existsSuperMethodCalls; @Override public void visitMethodCallExpression(PsiMethodCallExpression expression) { super.visitMethodCallExpression(expression); if (hasSuperQualifier(expression.getMethodExpression()) && OBJECT_METHOD_CALLS.test(expression)) { existsSuperMethodCalls = true; stopWalking(); } } @Override public void visitMethodReferenceExpression(PsiMethodReferenceExpression expression) { super.visitMethodReferenceExpression(expression); if (hasSuperQualifier(expression) && OBJECT_METHOD_CALLS.methodReferenceMatches(expression)) { existsSuperMethodCalls = true; stopWalking(); } } private boolean hasSuperQualifier(@NotNull PsiReferenceExpression expression) { PsiElement qualifier = expression.getQualifier(); return qualifier != null && PsiKeyword.SUPER.equals(qualifier.getText()); } }; psiMethod.accept(visitor); return visitor.existsSuperMethodCalls; } @Nullable private FieldAccessorCandidate createFieldAccessor(@NotNull PsiMethod psiMethod) { if (!psiMethod.getParameterList().isEmpty()) return null; String methodName = psiMethod.getName(); PsiField backingField = null; boolean recordStyleNaming = false; for (PsiField field : myFieldAccessors.keySet()) { if (!field.getType().equals(psiMethod.getReturnType())) continue; String fieldName = field.getName(); if (fieldName.equals(methodName)) { backingField = field; recordStyleNaming = true; break; } if (mySuggestAccessorsRenaming && fieldName.equals(PropertyUtilBase.getPropertyNameByGetter(psiMethod))) { backingField = field; break; } } return backingField == null ? null : new FieldAccessorCandidate(psiMethod, backingField, recordStyleNaming); } } /** * Encapsulates information about the converting constructor e.g whether its canonical or not. */ private static class RecordConstructorCandidate { private final PsiMethod myConstructor; private final boolean myCanonical; private RecordConstructorCandidate(@NotNull PsiMethod constructor, @NotNull Set<PsiField> instanceFields) { myConstructor = constructor; if (myConstructor.getTypeParameters().length > 0) { myCanonical = false; return; } Set<String> instanceFieldNames = instanceFields.stream().map(PsiField::getName).collect(Collectors.toSet()); if (instanceFieldNames.size() != instanceFields.size()) { myCanonical = false; return; } PsiParameter[] ctorParams = myConstructor.getParameterList().getParameters(); if (instanceFields.size() != ctorParams.length) { myCanonical = false; return; } PsiCodeBlock ctorBody = myConstructor.getBody(); if (ctorBody == null) { myCanonical = false; return; } Map<String, PsiType> ctorParamsWithType = Arrays.stream(ctorParams) .collect(Collectors.toMap(param -> param.getName(), param -> param.getType(), (first, second) -> first)); for (PsiField instanceField : instanceFields) { PsiType ctorParamType = ObjectUtils.tryCast(ctorParamsWithType.get(instanceField.getName()), PsiType.class); if (ctorParamType instanceof PsiEllipsisType) { ctorParamType = ((PsiEllipsisType)ctorParamType).toArrayType(); } if (ctorParamType == null || !TypeUtils.typeEquals(ctorParamType.getCanonicalText(), instanceField.getType())) { myCanonical = false; return; } if (!HighlightControlFlowUtil.variableDefinitelyAssignedIn(instanceField, ctorBody)) { myCanonical = false; return; } } myCanonical = true; } } /** * Encapsulates information about the converting of field accessors. * For instance an existing default accessor may be removed during further record creation. */ static class FieldAccessorCandidate { private final PsiMethod myFieldAccessor; private final PsiField myBackingField; private final boolean myDefault; private final boolean myRecordStyleNaming; private FieldAccessorCandidate(@NotNull PsiMethod accessor, @NotNull PsiField backingField, boolean recordStyleNaming) { myFieldAccessor = accessor; myBackingField = backingField; myRecordStyleNaming = recordStyleNaming; if (accessor.getDocComment() != null) { myDefault = false; return; } PsiExpression returnExpr = PropertyUtilBase.getSingleReturnValue(accessor); boolean isDefaultAccessor = backingField.equals(PropertyUtil.getFieldOfGetter(accessor, returnExpr, false)); if (!isDefaultAccessor) { myDefault = false; return; } myDefault = !hasAnnotationConflict(accessor, backingField, TargetType.FIELD) && !hasAnnotationConflict(backingField, accessor, TargetType.METHOD); } @NotNull PsiMethod getAccessor() { return myFieldAccessor; } @NotNull PsiField getBackingField() { return myBackingField; } boolean isDefault() { return myDefault; } boolean isRecordStyleNaming() { return myRecordStyleNaming; } } /** * During record creation we have to move the field annotations to the record component. * For instance, if an annotation's target includes both field and method target, * then we have to check whether the method is already marked by this annotation * as a compiler propagates annotations of the record components to appropriate targets automatically. */ private static boolean hasAnnotationConflict(@NotNull PsiModifierListOwner first, @NotNull PsiModifierListOwner second, @NotNull TargetType targetType) { boolean result = false; for (PsiAnnotation firstAnn : first.getAnnotations()) { TargetType firstAnnTarget = AnnotationTargetUtil.findAnnotationTarget(firstAnn, targetType); boolean hasDesiredTarget = firstAnnTarget != null && firstAnnTarget != TargetType.UNKNOWN; if (!hasDesiredTarget) continue; if (!ContainerUtil.exists(second.getAnnotations(), secondAnn -> AnnotationUtil.equal(firstAnn, secondAnn))) { result = true; break; } } return result; } }
/* * Copyright 2002-2004 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.binding.form.support; import org.springframework.binding.convert.ConversionContext; import org.springframework.binding.convert.ConversionException; import org.springframework.binding.convert.ConversionExecutor; import org.springframework.binding.convert.Converter; import org.springframework.binding.form.BindingErrorMessageProvider; import org.springframework.binding.form.FormModel; import org.springframework.binding.form.ValidatingFormModel; import org.springframework.binding.support.BeanPropertyAccessStrategy; import org.springframework.binding.support.TestBean; import org.springframework.binding.support.TestPropertyChangeListener; import org.springframework.binding.validation.ValidationMessage; import org.springframework.binding.validation.ValidationResults; import org.springframework.binding.validation.ValidationResultsModel; import org.springframework.binding.validation.Validator; import org.springframework.binding.validation.support.DefaultValidationMessage; import org.springframework.binding.validation.support.DefaultValidationResults; import org.springframework.binding.value.ValueModel; import org.springframework.binding.value.support.ValueHolder; import org.springframework.richclient.core.Severity; import java.util.Set; /** * Tests for @link DefaultFormModel * * @author Oliver Hutchison */ public class DefaultFormModelTests extends AbstractFormModelTests { protected AbstractFormModel getFormModel(Object formObject) { return new TestDefaultFormModel(formObject); } protected AbstractFormModel getFormModel(BeanPropertyAccessStrategy pas, boolean buffering) { return new TestDefaultFormModel(pas, buffering); } public void testPropertyChangeCausesValidation() { DefaultFormModel fm = (DefaultFormModel) getFormModel(new TestBean()); TestValidator v = new TestValidator(); fm.setValidator(v); TestConversionService cs = new TestConversionService(); cs.executer = new ConversionExecutor(String.class, String.class, new CopiedPublicNoOpConverter(String.class, String.class)); fm.setConversionService(cs); ValueModel vm = fm.getValueModel("simpleProperty"); // starting at 2: constructing a formmodel + creating valueModel int expectedCount = 2; assertEquals(expectedCount++, v.count); vm.setValue("1"); assertEquals(expectedCount, v.count); // no change in value, no validation triggered. vm.setValue("1"); assertEquals(expectedCount++, v.count); vm.setValue(null); assertEquals(expectedCount++, v.count); vm = fm.getValueModel("simpleProperty", Integer.class); vm.setValue("1"); assertEquals(expectedCount++, v.count); vm.setValue("2"); assertEquals(expectedCount++, v.count); } public void testValidationMessages() { DefaultFormModel fm = (DefaultFormModel) getFormModel(new TestBean()); ValidationResultsModel r = fm.getValidationResults(); TestValidator v = new TestValidator(); fm.setValidator(v); ValueModel vm = fm.getValueModel("simpleProperty"); // starting at 2: constructing a formmodel + creating valueModel int expectedCount = 2; assertEquals(expectedCount++, v.count); assertEquals(0, r.getMessageCount()); v.results = getValidationResults("message1"); vm.setValue("1"); assertEquals(expectedCount++, v.count); assertEquals(1, r.getMessageCount()); assertContainsMessage("message1", r.getMessages()); v.results = getValidationResults("message2"); vm.setValue("2"); assertEquals(expectedCount, v.count); assertEquals(1, r.getMessageCount()); assertContainsMessage("message2", r.getMessages()); // this will cause a binding exception vm.setValue(new Object()); assertEquals(expectedCount++, v.count); assertEquals(2, r.getMessageCount()); assertContainsMessage("message2", r.getMessages()); // this will clear the binding exception vm.setValue("3"); assertEquals(expectedCount++, v.count); assertEquals(1, r.getMessageCount()); assertContainsMessage("message2", r.getMessages()); fm.validate(); assertEquals(expectedCount++, v.count); assertEquals(1, r.getMessageCount()); assertContainsMessage("message2", r.getMessages()); } public void testRaiseClearValidationMessage() { DefaultFormModel fm = (DefaultFormModel) getFormModel(new TestBean()); ValidationResultsModel r = fm.getValidationResults(); TestValidator v = new TestValidator(); fm.setValidator(v); ValueModel vm = fm.getValueModel("simpleProperty"); // starting at 2: constructing a formmodel + creating valueModel int expectedCount = 2; final DefaultValidationMessage message1 = new DefaultValidationMessage("simpleProperty", Severity.ERROR, "1"); fm.raiseValidationMessage(message1); assertEquals(expectedCount++, v.count); assertEquals(1, r.getMessageCount()); assertContainsMessage("1", r.getMessages()); fm.clearValidationMessage(message1); assertEquals(0, r.getMessageCount()); fm.raiseValidationMessage(message1); fm.setValidating(false); assertEquals(0, r.getMessageCount()); fm.setValidating(true); assertEquals(expectedCount++, v.count); assertEquals(1, r.getMessageCount()); v.results = getValidationResults("2"); vm.setValue("3"); assertEquals(expectedCount++, v.count); assertEquals(2, r.getMessageCount()); fm.clearValidationMessage(message1); assertEquals(1, r.getMessageCount()); } public void testChangingValidatingClearsMessagesOrValidates() { DefaultFormModel fm = (DefaultFormModel) getFormModel(new TestBean()); ValidationResultsModel r = fm.getValidationResults(); TestValidator v = new TestValidator(); // starting at 2: constructing a formmodel + creating valueModel int expectedCount = 2; v.results = getValidationResults("message1"); fm.setValidator(v); ValueModel vm = fm.getValueModel("simpleProperty"); assertEquals(expectedCount, v.count); assertEquals(1, r.getMessageCount()); fm.setValidating(false); assertEquals(expectedCount++, v.count); assertEquals(0, r.getMessageCount()); fm.setValidating(true); assertEquals(expectedCount, v.count); assertEquals(1, r.getMessageCount()); // this will cause a binding exception vm.setValue(new Object()); assertEquals(expectedCount, v.count); assertEquals(2, r.getMessageCount()); fm.setValidating(false); assertEquals(expectedCount, v.count); assertEquals(0, r.getMessageCount()); // this will cause a another binding exception fm.getValueModel("listProperty").setValue(new Object()); assertEquals(expectedCount, v.count); assertEquals(0, r.getMessageCount()); vm.setValue("test"); assertEquals(expectedCount++, v.count); assertEquals(0, r.getMessageCount()); fm.setValidating(true); assertEquals(expectedCount++, v.count); assertEquals(2, r.getMessageCount()); } public void testSetThrowsExceptionRaisesValidationMessage() { final ErrorBean errorBean = new ErrorBean(); DefaultFormModel fm = (DefaultFormModel) getFormModel(errorBean); final ValueModel vm = fm.getValueModel("error"); vm.setValue("test"); assertEquals(1, fm.getValidationResults().getMessageCount()); errorBean.errorToThrow = null; vm.setValue("test"); assertEquals(0, fm.getValidationResults().getMessageCount()); } public void testTypeConversionThrowsExceptionRaisesValidationMessage() { DefaultFormModel fm = (DefaultFormModel) getFormModel(new TestBean()); TestConversionService cs = new TestConversionService(); cs.executer = new ConversionExecutor(String.class, Integer.class, new ExceptionConverter(String.class, Integer.class)); fm.setConversionService(cs); final ValueModel vm = fm.getValueModel("simpleProperty", Integer.class); vm.setValue("test"); assertEquals(1, fm.getValidationResults().getMessageCount()); } public void testValidatingEvents() { TestPropertyChangeListener pcl = new TestPropertyChangeListener(ValidatingFormModel.VALIDATING_PROPERTY); DefaultFormModel fm = (DefaultFormModel) getFormModel(new TestBean()); fm.addPropertyChangeListener(ValidatingFormModel.VALIDATING_PROPERTY, pcl); assertTrue(fm.isEnabled()); fm.setValidating(false); assertTrue(!fm.isValidating()); assertEquals(1, pcl.eventCount()); fm.setValidating(false); assertTrue(!fm.isValidating()); assertEquals(1, pcl.eventCount()); fm.setValidating(true); assertTrue(fm.isValidating()); assertEquals(2, pcl.eventCount()); fm.setEnabled(true); assertTrue(fm.isValidating()); assertEquals(2, pcl.eventCount()); } public void testReadOnlyRevert() { FormModel fm = getFormModel(new TestBean()); fm.getValueModel("readOnly"); fm.revert(); // no additional asserts, this test should just not throw an exception! } public void testDefaultFormModelFromValueModel() throws Exception { TestBean testBean = new TestBean(); ValueModel valueModel = new ValueHolder(testBean); DefaultFormModel model = new DefaultFormModel(valueModel); assertEquals(testBean, model.getFormObject()); } private DefaultValidationResults getValidationResults(String message) { DefaultValidationResults res = new DefaultValidationResults(); res.addMessage("simpleProperty", Severity.ERROR, message); return res; } private void assertContainsMessage(String message, Set messages) { assertTrue("Set of messages does not contain expected message '" + message + "'", messages .contains(new DefaultValidationMessage("simpleProperty", Severity.ERROR, message))); } public static class TestValidator implements Validator { public ValidationResults results = new DefaultValidationResults(); public int count; public ValidationResults validate(Object object) { count++; return results; } } public class ErrorBean { public RuntimeException errorToThrow = new UnsupportedOperationException(); public Object getError() { return null; } public void setError(Object error) { if (errorToThrow != null) { throw errorToThrow; } } } private static class TestDefaultFormModel extends DefaultFormModel { public TestDefaultFormModel(Object bean) { super(bean, false); } public TestDefaultFormModel(BeanPropertyAccessStrategy pas, boolean buffering) { super(pas, buffering); } public void init() { super.init(); setValidator(new TestValidator()); setBindingErrorMessageProvider(new BindingErrorMessageProvider() { public ValidationMessage getErrorMessage(FormModel formModel, String propertyName, Object valueBeingSet, Exception e) { return new DefaultValidationMessage(propertyName, Severity.ERROR, ""); } }); } } private static class ExceptionConverter implements Converter { private final Class sourceClass; private final Class targetClass; public ExceptionConverter(Class sourceClass, Class targetClass) { this.sourceClass = sourceClass; this.targetClass = targetClass; } public Object convert(Object source, Class targetClass, ConversionContext context) throws ConversionException { throw new ConversionException("test", targetClass); } public Class[] getSourceClasses() { return new Class[] { sourceClass }; } public Class[] getTargetClasses() { return new Class[] { targetClass }; } } }
/* * Copyright 2011 LMAX Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package yow2013.immutable; import static com.lmax.disruptor.RingBuffer.createSingleProducer; import java.io.PrintStream; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.HdrHistogram.Histogram; import com.lmax.disruptor.BatchEventProcessor; import com.lmax.disruptor.EventHandler; import com.lmax.disruptor.LifecycleAware; import com.lmax.disruptor.RingBuffer; import com.lmax.disruptor.SequenceBarrier; import com.lmax.disruptor.SingleProducerSequencer; import com.lmax.disruptor.YieldingWaitStrategy; import com.lmax.disruptor.util.DaemonThreadFactory; /** * <pre> * Disruptor: * ========== * +----------+ * | | * | get V * waitFor +=====+ +=====+ claim * +------>| SB2 | | RB2 |<------+ * | +=====+ +=====+ | * | | * +-----+ +=====+ +=====+ +-----+ * | EP1 |--->| RB1 | | SB1 |<---| EP2 | * +-----+ +=====+ +=====+ +-----+ * claim ^ get | waitFor * | | * +----------+ * * EP1 - Pinger * EP2 - Ponger * RB1 - PingBuffer * SB1 - PingBarrier * RB2 - PongBuffer * SB2 - PongBarrier * * </pre> * * Note: <b>This test is only useful on a system using an invariant TSC in user space from the System.nanoTime() call.</b> */ public final class CustomPingPongLatencyTest { private static final int BUFFER_SIZE = 1 << 16; private static final long ITERATIONS = 10_000_000L; private static final long PAUSE_NANOS = 500L; private final ExecutorService executor = Executors.newCachedThreadPool(DaemonThreadFactory.INSTANCE); private final Histogram histogram = new Histogram(TimeUnit.HOURS.toMicros(1), 4); /////////////////////////////////////////////////////////////////////////////////////////////// private final CustomRingBuffer<SimpleEvent> pingBuffer = new CustomRingBuffer<>(new SingleProducerSequencer(BUFFER_SIZE, new YieldingWaitStrategy())); private final CustomRingBuffer<SimpleEvent> pongBuffer = new CustomRingBuffer<>(new SingleProducerSequencer(BUFFER_SIZE, new YieldingWaitStrategy())); private final Pinger pinger = new Pinger(pingBuffer, ITERATIONS, PAUSE_NANOS); private final Ponger ponger = new Ponger(pongBuffer); private final BatchEventProcessor<EventAccessor<SimpleEvent>> pingProcessor = pongBuffer.createHandler(pinger); private final BatchEventProcessor<EventAccessor<SimpleEvent>> pongProcessor = pingBuffer.createHandler(ponger); /////////////////////////////////////////////////////////////////////////////////////////////// public void runTest() throws Exception { final int runs = 3; for (int i = 0; i < runs; i++) { System.gc(); histogram.reset(); runDisruptorPass(); if (histogram.getHistogramData().getTotalCount() < ITERATIONS) { throw new IllegalStateException(); } System.out.format("%s run %d Disruptor %s\n", getClass().getSimpleName(), Long.valueOf(i), histogram); dumpHistogram(histogram, System.out); } } private static void dumpHistogram(Histogram histogram, final PrintStream out) { histogram.getHistogramData().outputPercentileDistribution(out, 1, 1000.0); } private void runDisruptorPass() throws InterruptedException, BrokenBarrierException { CountDownLatch latch = new CountDownLatch(1); CyclicBarrier barrier = new CyclicBarrier(3); pinger.reset(barrier, latch, histogram); ponger.reset(barrier); executor.submit(pongProcessor); executor.submit(pingProcessor); barrier.await(); latch.await(); pingProcessor.halt(); pongProcessor.halt(); } public static void main(String[] args) throws Exception { CustomPingPongLatencyTest test = new CustomPingPongLatencyTest(); test.runTest(); } private static class Pinger implements EventHandler<SimpleEvent>, LifecycleAware { private final CustomRingBuffer<SimpleEvent> buffer; private final long maxEvents; private final long pauseTimeNs; private long counter = 0; private CyclicBarrier barrier; private CountDownLatch latch; private Histogram histogram; private long t0; public Pinger(CustomRingBuffer<SimpleEvent> buffer, long maxEvents, long pauseTimeNs) { this.buffer = buffer; this.maxEvents = maxEvents; this.pauseTimeNs = pauseTimeNs; } @Override public void onEvent(SimpleEvent event, long sequence, boolean endOfBatch) throws Exception { long t1 = System.nanoTime(); histogram.recordValueWithExpectedInterval(t1 - t0, pauseTimeNs); if (event.getCounter() < maxEvents) { while (pauseTimeNs > (System.nanoTime() - t1)) { Thread.yield(); } send(); } else { latch.countDown(); } } private void send() { t0 = System.nanoTime(); buffer.put(new SimpleEvent(t0, counter, counter, counter)); counter++; } @Override public void onStart() { try { barrier.await(); Thread.sleep(1000); send(); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void onShutdown() { } public void reset(CyclicBarrier barrier, CountDownLatch latch, Histogram histogram) { this.histogram = histogram; this.barrier = barrier; this.latch = latch; counter = 0; } } private static class Ponger implements EventHandler<SimpleEvent>, LifecycleAware { private final CustomRingBuffer<SimpleEvent> buffer; private CyclicBarrier barrier; public Ponger(CustomRingBuffer<SimpleEvent> buffer) { this.buffer = buffer; } @Override public void onEvent(SimpleEvent event, long sequence, boolean endOfBatch) throws Exception { buffer.put(event); } @Override public void onStart() { try { barrier.await(); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void onShutdown() { } public void reset(CyclicBarrier barrier) { this.barrier = barrier; } } }
/* * Copyright 2017 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.workbench.common.stunner.core.client.canvas.controls.select; import java.util.Collections; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.kie.workbench.common.stunner.core.client.canvas.AbstractCanvas; import org.kie.workbench.common.stunner.core.client.canvas.AbstractCanvasHandler; import org.kie.workbench.common.stunner.core.client.canvas.Layer; import org.kie.workbench.common.stunner.core.client.canvas.event.registration.CanvasShapeRemovedEvent; import org.kie.workbench.common.stunner.core.client.canvas.event.selection.CanvasClearSelectionEvent; import org.kie.workbench.common.stunner.core.client.canvas.event.selection.CanvasSelectionEvent; import org.kie.workbench.common.stunner.core.client.shape.Shape; import org.kie.workbench.common.stunner.core.client.shape.ShapeState; import org.kie.workbench.common.stunner.core.client.shape.ShapeViewExtStub; import org.kie.workbench.common.stunner.core.client.shape.view.HasControlPoints; import org.kie.workbench.common.stunner.core.client.shape.view.HasEventHandlers; import org.kie.workbench.common.stunner.core.client.shape.view.ShapeView; import org.kie.workbench.common.stunner.core.client.shape.view.event.MouseClickEvent; import org.kie.workbench.common.stunner.core.client.shape.view.event.MouseClickHandler; import org.kie.workbench.common.stunner.core.client.shape.view.event.ViewEventType; import org.kie.workbench.common.stunner.core.diagram.Diagram; import org.kie.workbench.common.stunner.core.diagram.Metadata; import org.kie.workbench.common.stunner.core.graph.Element; import org.kie.workbench.common.stunner.core.graph.content.view.BoundsImpl; import org.kie.workbench.common.stunner.core.graph.content.view.ViewImpl; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.uberfire.mocks.EventSourceMock; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class MapSelectionControlTest { private static final String ROOT_UUID = "root-uuid1"; private static final String ELEMENT_UUID = "element-uuid1"; @Mock private EventSourceMock<CanvasSelectionEvent> elementSelectedEvent; @Mock private EventSourceMock<CanvasClearSelectionEvent> clearSelectionEvent; @Mock private AbstractCanvasHandler canvasHandler; @Mock private AbstractCanvas canvas; @Mock private Layer layer; @Mock private Diagram diagram; @Mock private Metadata metadata; @Mock private Object definition; @Mock private Element element; @Mock private Shape<ShapeView> shape; @Mock private HasEventHandlers<ShapeViewExtStub, Object> shapeEventHandler; @Mock private HasControlPoints<ShapeViewExtStub> hasControlPoints; private MapSelectionControl<AbstractCanvasHandler> tested; @Before @SuppressWarnings("unchecked") public void setup() throws Exception { ShapeViewExtStub shapeView = new ShapeViewExtStub(shapeEventHandler, hasControlPoints); when(element.getUUID()).thenReturn(ELEMENT_UUID); when(element.getContent()).thenReturn(new ViewImpl<>(definition, BoundsImpl.build(0, 0, 10, 10))); when(canvasHandler.getDiagram()).thenReturn(diagram); when(diagram.getMetadata()).thenReturn(metadata); when(metadata.getCanvasRootUUID()).thenReturn(ROOT_UUID); when(canvasHandler.getCanvas()).thenReturn(canvas); when(canvas.getLayer()).thenReturn(layer); when(canvas.getShape(eq(ELEMENT_UUID))).thenReturn(shape); when(canvas.getShapes()).thenReturn(Collections.singletonList(shape)); when(shape.getUUID()).thenReturn(ELEMENT_UUID); when(shape.getShapeView()).thenReturn(shapeView); when(shapeEventHandler.supports(eq(ViewEventType.MOUSE_CLICK))).thenReturn(true); this.tested = new MapSelectionControl(e -> elementSelectedEvent.fire((CanvasSelectionEvent) e), e -> clearSelectionEvent.fire((CanvasClearSelectionEvent) e)); this.tested.setReadonly(false); } @Test public void testEnable() { tested.init(canvasHandler); verify(layer, times(1)).addHandler(eq(ViewEventType.MOUSE_CLICK), any(MouseClickHandler.class)); } @Test public void testLayerClickAndSelectRootElement() { tested.init(canvasHandler); final ArgumentCaptor<MouseClickHandler> clickHandlerArgumentCaptor = ArgumentCaptor.forClass(MouseClickHandler.class); verify(layer, times(1)).addHandler(eq(ViewEventType.MOUSE_CLICK), clickHandlerArgumentCaptor.capture()); final MouseClickHandler clickHandler = clickHandlerArgumentCaptor.getValue(); final MouseClickEvent event = new MouseClickEvent(12, 20, 30, 40); event.setButtonLeft(true); event.setShiftKeyDown(false); clickHandler.handle(event); final ArgumentCaptor<CanvasSelectionEvent> elementSelectedEventArgumentCaptor = ArgumentCaptor.forClass(CanvasSelectionEvent.class); verify(elementSelectedEvent, times(1)).fire(elementSelectedEventArgumentCaptor.capture()); verify(clearSelectionEvent, times(1)).fire(any(CanvasClearSelectionEvent.class)); final CanvasSelectionEvent ese = elementSelectedEventArgumentCaptor.getValue(); assertEquals(ROOT_UUID, ese.getIdentifiers().iterator().next()); } @Test public void testLayerClickAndClear() { when(metadata.getCanvasRootUUID()).thenReturn(null); tested.init(canvasHandler); final ArgumentCaptor<MouseClickHandler> clickHandlerArgumentCaptor = ArgumentCaptor.forClass(MouseClickHandler.class); verify(layer, times(1)).addHandler(eq(ViewEventType.MOUSE_CLICK), clickHandlerArgumentCaptor.capture()); final MouseClickHandler clickHandler = clickHandlerArgumentCaptor.getValue(); final MouseClickEvent event = new MouseClickEvent(12, 20, 30, 40); event.setButtonLeft(true); event.setShiftKeyDown(false); clickHandler.handle(event); verify(clearSelectionEvent, times(1)).fire(any(CanvasClearSelectionEvent.class)); verify(elementSelectedEvent, never()).fire(any(CanvasSelectionEvent.class)); } @Test public void testRegisterElement() { tested.init(canvasHandler); assertFalse(isRegistered(element)); tested.register(element); assertTrue(isRegistered(element)); } @Test @SuppressWarnings("unchecked") public void testDeregisterElement() { tested.init(canvasHandler); tested.register(element); tested.deregister(element); assertFalse(isRegistered(element)); } @Test public void testSelect() { tested.init(canvasHandler); tested.register(element); tested.select(element); assertEquals(1, tested.getSelectedItems().size()); assertEquals(ELEMENT_UUID, tested.getSelectedItems().iterator().next()); verify(shape, times(1)).applyState(eq(ShapeState.SELECTED)); verify(shape, never()).applyState(eq(ShapeState.NONE)); verify(shape, never()).applyState(eq(ShapeState.INVALID)); verify(shape, never()).applyState(eq(ShapeState.HIGHLIGHT)); final ArgumentCaptor<CanvasSelectionEvent> elementSelectedEventArgumentCaptor = ArgumentCaptor.forClass(CanvasSelectionEvent.class); verify(elementSelectedEvent, times(1)).fire(elementSelectedEventArgumentCaptor.capture()); final CanvasSelectionEvent event = elementSelectedEventArgumentCaptor.getValue(); assertEquals(1, event.getIdentifiers().size()); assertEquals(ELEMENT_UUID, event.getIdentifiers().iterator().next()); } @Test public void testSelectReadOnly() { tested.init(canvasHandler); tested.register(element); tested.setReadonly(true); tested.select(element); verify(shape, never()).applyState(eq(ShapeState.SELECTED)); verify(shape, never()).applyState(eq(ShapeState.NONE)); verify(shape, never()).applyState(eq(ShapeState.INVALID)); verify(shape, times(1)).applyState(eq(ShapeState.HIGHLIGHT)); } @Test public void testDeselect() { tested.init(canvasHandler); tested.register(element); tested.select(element); tested.deselect(element); assertTrue(tested.getSelectedItems().isEmpty()); verify(shape, times(1)).applyState(eq(ShapeState.SELECTED)); verify(shape, times(1)).applyState(eq(ShapeState.NONE)); verify(shape, never()).applyState(eq(ShapeState.INVALID)); verify(shape, never()).applyState(eq(ShapeState.HIGHLIGHT)); } @Test public void testClearSelection() { tested.init(canvasHandler); tested.register(element); tested.select(element); tested.clearSelection(); assertTrue(tested.getSelectedItems().isEmpty()); verify(canvas, atLeastOnce()).draw(); verify(shape, times(1)).applyState(eq(ShapeState.SELECTED)); verify(shape, times(1)).applyState(eq(ShapeState.NONE)); verify(shape, never()).applyState(eq(ShapeState.INVALID)); verify(shape, never()).applyState(eq(ShapeState.HIGHLIGHT)); verify(clearSelectionEvent, times(1)).fire(any(CanvasClearSelectionEvent.class)); } @Test public void testOnShapeRemovedEvent() { tested.init(canvasHandler); tested.register(element); tested.select(element); CanvasShapeRemovedEvent shapeRemovedEvent = new CanvasShapeRemovedEvent(canvas, shape); tested.onShapeRemoved(shapeRemovedEvent); assertTrue(tested.getSelectedItems().isEmpty()); verify(shape, times(1)).applyState(eq(ShapeState.SELECTED)); verify(shape, times(1)).applyState(eq(ShapeState.NONE)); verify(shape, never()).applyState(eq(ShapeState.INVALID)); verify(shape, never()).applyState(eq(ShapeState.HIGHLIGHT)); } @Test public void testOnClearSelectionEvent() { tested.init(canvasHandler); tested.register(element); tested.select(element); CanvasClearSelectionEvent event = new CanvasClearSelectionEvent(canvasHandler); tested.onCanvasClearSelection(event); assertTrue(tested.getSelectedItems().isEmpty()); verify(canvas, atLeastOnce()).draw(); verify(shape, times(1)).applyState(eq(ShapeState.SELECTED)); verify(shape, times(1)).applyState(eq(ShapeState.NONE)); verify(shape, never()).applyState(eq(ShapeState.INVALID)); verify(shape, never()).applyState(eq(ShapeState.HIGHLIGHT)); verify(clearSelectionEvent, never()).fire(any(CanvasClearSelectionEvent.class)); } @Test public void testOnSelectEvent() { tested.init(canvasHandler); tested.register(element); CanvasSelectionEvent event = new CanvasSelectionEvent(canvasHandler, ELEMENT_UUID); tested.onCanvasElementSelected(event); assertEquals(1, tested.getSelectedItems().size()); assertEquals(ELEMENT_UUID, tested.getSelectedItems().iterator().next()); verify(shape, times(1)).applyState(eq(ShapeState.SELECTED)); verify(shape, times(1)).applyState(eq(ShapeState.NONE)); verify(shape, never()).applyState(eq(ShapeState.INVALID)); verify(shape, never()).applyState(eq(ShapeState.HIGHLIGHT)); final ArgumentCaptor<CanvasSelectionEvent> elementSelectedEventArgumentCaptor = ArgumentCaptor.forClass(CanvasSelectionEvent.class); verify(elementSelectedEvent, times(1)).fire(elementSelectedEventArgumentCaptor.capture()); final CanvasSelectionEvent selectionEvent = elementSelectedEventArgumentCaptor.getValue(); assertEquals(1, selectionEvent.getIdentifiers().size()); assertEquals(ELEMENT_UUID, selectionEvent.getIdentifiers().iterator().next()); } private boolean isRegistered(Element e) { return tested.itemsRegistered().test(e.getUUID()); } }
/* * Copyright 1999,2004 The Apache Software Foundation. * * 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 net.sf.webdav.methods; import java.io.IOException; import java.util.HashMap; import java.util.Hashtable; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.parsers.DocumentBuilder; import net.sf.webdav.ITransaction; import net.sf.webdav.IWebdavStore; import net.sf.webdav.StoredObject; import net.sf.webdav.WebdavStatus; import net.sf.webdav.exceptions.LockFailedException; import net.sf.webdav.exceptions.WebdavException; import net.sf.webdav.fromcatalina.XMLWriter; import net.sf.webdav.locking.IResourceLocks; import net.sf.webdav.locking.LockedObject; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; public class DoLock extends AbstractMethod { private static org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(DoLock.class); private IWebdavStore _store; private IResourceLocks _resourceLocks; private boolean _readOnly; private boolean _macLockRequest = false; private boolean _exclusive = false; private String _type = null; private String _lockOwner = null; private String _path = null; private String _parentPath = null; private String _userAgent = null; public DoLock(IWebdavStore store, IResourceLocks resourceLocks, boolean readOnly) { _store = store; _resourceLocks = resourceLocks; _readOnly = readOnly; } public void execute(ITransaction transaction, HttpServletRequest req, HttpServletResponse resp) throws IOException, LockFailedException { LOG.trace("-- " + this.getClass().getName()); if (_readOnly) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return; } else { _path = getRelativePath(req); _parentPath = getParentPath(getCleanPath(_path)); // Hashtable<String, Integer> errorList = new Hashtable<String, // Integer>(); if (!checkLocks(transaction, req, resp, _resourceLocks, _path)) { resp.setStatus(WebdavStatus.SC_LOCKED); return; // resource is locked } if (!checkLocks(transaction, req, resp, _resourceLocks, _parentPath)) { resp.setStatus(WebdavStatus.SC_LOCKED); return; // parent is locked } // Mac OS Finder (whether 10.4.x or 10.5) can't store files // because executing a LOCK without lock information causes a // SC_BAD_REQUEST _userAgent = req.getHeader("User-Agent"); if (_userAgent != null && _userAgent.indexOf("Darwin") != -1) { _macLockRequest = true; String timeString = new Long(System.currentTimeMillis()).toString(); _lockOwner = _userAgent.concat(timeString); } String tempLockOwner = "doLock" + System.currentTimeMillis() + req.toString(); if (_resourceLocks.lock(transaction, _path, tempLockOwner, false, 0, TEMP_TIMEOUT, TEMPORARY)) { try { if (req.getHeader("If") != null) { doRefreshLock(transaction, req, resp); } else { doLock(transaction, req, resp); } } catch (LockFailedException e) { resp.sendError(WebdavStatus.SC_LOCKED); LOG.error("Lockfailed exception", e); } finally { _resourceLocks.unlockTemporaryLockedObjects(transaction, _path, tempLockOwner); } } } } private void doLock(ITransaction transaction, HttpServletRequest req, HttpServletResponse resp) throws IOException, LockFailedException { StoredObject so = _store.getStoredObject(transaction, _path); if (so != null) { doLocking(transaction, req, resp); } else { // resource doesn't exist, null-resource lock doNullResourceLock(transaction, req, resp); } so = null; _exclusive = false; _type = null; _lockOwner = null; } private void doLocking(ITransaction transaction, HttpServletRequest req, HttpServletResponse resp) throws IOException { // Tests if LockObject on requested path exists, and if so, tests // exclusivity LockedObject lo = _resourceLocks.getLockedObjectByPath(transaction, _path); if (lo != null) { if (lo.isExclusive()) { sendLockFailError(transaction, req, resp); return; } } try { // Thats the locking itself executeLock(transaction, req, resp); } catch (ServletException e) { resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR); LOG.trace(e.toString()); } catch (LockFailedException e) { sendLockFailError(transaction, req, resp); } finally { lo = null; } } private void doNullResourceLock(ITransaction transaction, HttpServletRequest req, HttpServletResponse resp) throws IOException { StoredObject parentSo, nullSo = null; try { parentSo = _store.getStoredObject(transaction, _parentPath); if (_parentPath != null && parentSo == null) { _store.createFolder(transaction, _parentPath); } else if (_parentPath != null && parentSo != null && parentSo.isResource()) { resp.sendError(WebdavStatus.SC_PRECONDITION_FAILED); return; } nullSo = _store.getStoredObject(transaction, _path); if (nullSo == null) { // resource doesn't exist _store.createResource(transaction, _path); // Transmit expects 204 response-code, not 201 if (_userAgent != null && _userAgent.indexOf("Transmit") != -1) { LOG.trace("DoLock.execute() : do workaround for user agent '" + _userAgent + "'"); resp.setStatus(WebdavStatus.SC_NO_CONTENT); } else { resp.setStatus(WebdavStatus.SC_CREATED); } } else { // resource already exists, could not execute null-resource lock sendLockFailError(transaction, req, resp); return; } nullSo = _store.getStoredObject(transaction, _path); // define the newly created resource as null-resource nullSo.setNullResource(true); // Thats the locking itself executeLock(transaction, req, resp); } catch (LockFailedException e) { sendLockFailError(transaction, req, resp); } catch (WebdavException e) { resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR); LOG.error("Webdav exception", e); } catch (ServletException e) { resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR); LOG.error("Servlet exception", e); } finally { parentSo = null; nullSo = null; } } private void doRefreshLock(ITransaction transaction, HttpServletRequest req, HttpServletResponse resp) throws IOException, LockFailedException { String[] lockTokens = getLockIdFromIfHeader(req); String lockToken = null; if (lockTokens != null) lockToken = lockTokens[0]; if (lockToken != null) { // Getting LockObject of specified lockToken in If header LockedObject refreshLo = _resourceLocks.getLockedObjectByID(transaction, lockToken); if (refreshLo != null) { int timeout = getTimeout(transaction, req); refreshLo.refreshTimeout(timeout); // sending success response generateXMLReport(transaction, resp, refreshLo); refreshLo = null; } else { // no LockObject to given lockToken resp.sendError(WebdavStatus.SC_PRECONDITION_FAILED); } } else { resp.sendError(WebdavStatus.SC_PRECONDITION_FAILED); } } // ------------------------------------------------- helper methods /** * Executes the LOCK */ private void executeLock(ITransaction transaction, HttpServletRequest req, HttpServletResponse resp) throws LockFailedException, IOException, ServletException { // Mac OS lock request workaround if (_macLockRequest) { LOG.trace("DoLock.execute() : do workaround for user agent '" + _userAgent + "'"); doMacLockRequestWorkaround(transaction, req, resp); } else { // Getting LockInformation from request if (getLockInformation(transaction, req, resp)) { int depth = getDepth(req); int lockDuration = getTimeout(transaction, req); boolean lockSuccess = false; if (_exclusive) { lockSuccess = _resourceLocks.exclusiveLock(transaction, _path, _lockOwner, depth, lockDuration); } else { lockSuccess = _resourceLocks.sharedLock(transaction, _path, _lockOwner, depth, lockDuration); } if (lockSuccess) { // Locks successfully placed - return information about LockedObject lo = _resourceLocks.getLockedObjectByPath(transaction, _path); if (lo != null) { generateXMLReport(transaction, resp, lo); } else { resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR); } } else { sendLockFailError(transaction, req, resp); throw new LockFailedException(); } } else { // information for LOCK could not be read successfully resp.setContentType("text/xml; charset=UTF-8"); resp.sendError(WebdavStatus.SC_BAD_REQUEST); } } } /** * Tries to get the LockInformation from LOCK request */ private boolean getLockInformation(ITransaction transaction, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Node lockInfoNode = null; DocumentBuilder documentBuilder = null; documentBuilder = getDocumentBuilder(); try { Document document = documentBuilder.parse(new InputSource(req.getInputStream())); // Get the root element of the document Element rootElement = document.getDocumentElement(); lockInfoNode = rootElement; if (lockInfoNode != null) { NodeList childList = lockInfoNode.getChildNodes(); Node lockScopeNode = null; Node lockTypeNode = null; Node lockOwnerNode = null; Node currentNode = null; String nodeName = null; for (int i = 0; i < childList.getLength(); i++) { currentNode = childList.item(i); if (currentNode.getNodeType() == Node.ELEMENT_NODE || currentNode.getNodeType() == Node.TEXT_NODE) { nodeName = currentNode.getNodeName(); if (nodeName.endsWith("locktype")) { lockTypeNode = currentNode; } if (nodeName.endsWith("lockscope")) { lockScopeNode = currentNode; } if (nodeName.endsWith("owner")) { lockOwnerNode = currentNode; } } else { return false; } } if (lockScopeNode != null) { String scope = null; childList = lockScopeNode.getChildNodes(); for (int i = 0; i < childList.getLength(); i++) { currentNode = childList.item(i); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { scope = currentNode.getNodeName(); if (scope.endsWith("exclusive")) { _exclusive = true; } else if (scope.equals("shared")) { _exclusive = false; } } } if (scope == null) { return false; } } else { return false; } if (lockTypeNode != null) { childList = lockTypeNode.getChildNodes(); for (int i = 0; i < childList.getLength(); i++) { currentNode = childList.item(i); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { _type = currentNode.getNodeName(); if (_type.endsWith("write")) { _type = "write"; } else if (_type.equals("read")) { _type = "read"; } } } if (_type == null) { return false; } } else { return false; } if (lockOwnerNode != null) { childList = lockOwnerNode.getChildNodes(); for (int i = 0; i < childList.getLength(); i++) { currentNode = childList.item(i); if (currentNode.getNodeType() == Node.ELEMENT_NODE || currentNode.getNodeType() == Node.TEXT_NODE) { // _lockOwner = currentNode.getFirstChild().getNodeValue(); _lockOwner = currentNode.getTextContent(); } } } if (_lockOwner == null) { _lockOwner = ""; return true; } } else { return false; } } catch (DOMException e) { resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR); LOG.error("DOM exception", e); return false; } catch (SAXException e) { resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR); LOG.error("SAX exception", e); return false; } return true; } /** * Ties to read the timeout from request */ private int getTimeout(ITransaction transaction, HttpServletRequest req) { int lockDuration = DEFAULT_TIMEOUT; String lockDurationStr = req.getHeader("Timeout"); if (lockDurationStr == null) { lockDuration = DEFAULT_TIMEOUT; } else { int commaPos = lockDurationStr.indexOf(','); // if multiple timeouts, just use the first one if (commaPos != -1) { lockDurationStr = lockDurationStr.substring(0, commaPos); } if (lockDurationStr.startsWith("Second-")) { lockDuration = new Integer(lockDurationStr.substring(7)).intValue(); } else { if (lockDurationStr.equalsIgnoreCase("infinity")) { lockDuration = MAX_TIMEOUT; } else { try { lockDuration = new Integer(lockDurationStr).intValue(); } catch (NumberFormatException e) { lockDuration = MAX_TIMEOUT; } } } if (lockDuration <= 0) { lockDuration = DEFAULT_TIMEOUT; } if (lockDuration > MAX_TIMEOUT) { lockDuration = MAX_TIMEOUT; } } return lockDuration; } /** * Generates the response XML with all lock information */ private void generateXMLReport(ITransaction transaction, HttpServletResponse resp, LockedObject lo) throws IOException { HashMap<String, String> namespaces = new HashMap<String, String>(); namespaces.put("DAV:", "D"); resp.setStatus(WebdavStatus.SC_OK); resp.setContentType("text/xml; charset=UTF-8"); XMLWriter generatedXML = new XMLWriter(resp.getWriter(), namespaces); generatedXML.writeXMLHeader(); generatedXML.writeElement("DAV::prop", XMLWriter.OPENING); generatedXML.writeElement("DAV::lockdiscovery", XMLWriter.OPENING); generatedXML.writeElement("DAV::activelock", XMLWriter.OPENING); generatedXML.writeElement("DAV::locktype", XMLWriter.OPENING); generatedXML.writeProperty("DAV::" + _type); generatedXML.writeElement("DAV::locktype", XMLWriter.CLOSING); generatedXML.writeElement("DAV::lockscope", XMLWriter.OPENING); if (_exclusive) { generatedXML.writeProperty("DAV::exclusive"); } else { generatedXML.writeProperty("DAV::shared"); } generatedXML.writeElement("DAV::lockscope", XMLWriter.CLOSING); int depth = lo.getLockDepth(); generatedXML.writeElement("DAV::depth", XMLWriter.OPENING); if (depth == INFINITY) { generatedXML.writeText("Infinity"); } else { generatedXML.writeText(String.valueOf(depth)); } generatedXML.writeElement("DAV::depth", XMLWriter.CLOSING); generatedXML.writeElement("DAV::owner", XMLWriter.OPENING); generatedXML.writeElement("DAV::href", XMLWriter.OPENING); generatedXML.writeText(_lockOwner); generatedXML.writeElement("DAV::href", XMLWriter.CLOSING); generatedXML.writeElement("DAV::owner", XMLWriter.CLOSING); long timeout = lo.getTimeoutMillis(); generatedXML.writeElement("DAV::timeout", XMLWriter.OPENING); generatedXML.writeText("Second-" + timeout / 1000); generatedXML.writeElement("DAV::timeout", XMLWriter.CLOSING); String lockToken = lo.getID(); generatedXML.writeElement("DAV::locktoken", XMLWriter.OPENING); generatedXML.writeElement("DAV::href", XMLWriter.OPENING); generatedXML.writeText("opaquelocktoken:" + lockToken); generatedXML.writeElement("DAV::href", XMLWriter.CLOSING); generatedXML.writeElement("DAV::locktoken", XMLWriter.CLOSING); generatedXML.writeElement("DAV::activelock", XMLWriter.CLOSING); generatedXML.writeElement("DAV::lockdiscovery", XMLWriter.CLOSING); generatedXML.writeElement("DAV::prop", XMLWriter.CLOSING); resp.addHeader("Lock-Token", "<opaquelocktoken:" + lockToken + ">"); generatedXML.sendData(); } /** * Executes the lock for a Mac OS Finder client */ private void doMacLockRequestWorkaround(ITransaction transaction, HttpServletRequest req, HttpServletResponse resp) throws LockFailedException, IOException { LockedObject lo; int depth = getDepth(req); int lockDuration = getTimeout(transaction, req); if (lockDuration < 0 || lockDuration > MAX_TIMEOUT) lockDuration = DEFAULT_TIMEOUT; boolean lockSuccess = false; lockSuccess = _resourceLocks.exclusiveLock(transaction, _path, _lockOwner, depth, lockDuration); if (lockSuccess) { // Locks successfully placed - return information about lo = _resourceLocks.getLockedObjectByPath(transaction, _path); if (lo != null) { generateXMLReport(transaction, resp, lo); } else { resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR); } } else { // Locking was not successful sendLockFailError(transaction, req, resp); } } /** * Sends an error report to the client */ private void sendLockFailError(ITransaction transaction, HttpServletRequest req, HttpServletResponse resp) throws IOException { Hashtable<String, Integer> errorList = new Hashtable<String, Integer>(); errorList.put(_path, WebdavStatus.SC_LOCKED); sendReport(req, resp, errorList); } }
/******************************************************************************* * Copyright 2015 MobileMan GmbH * www.mobileman.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. ******************************************************************************/ /** * HtmlManipulator.java * Copyright 2007 - 2008 Zach Scrivena * [email protected] * http://zs.freeshell.org/ * * TERMS AND CONDITIONS: * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mobileman.projecth.util.text; import java.util.HashMap; import java.util.Map; /** * Perform HTML-related operations. */ public final class HtmlManipulator { /** * Table of HTML entities obtained from http://www.w3.org/TR/html401/sgml/entities.html * - Formatted as a series of space-delimited triplets (entity_name,entity_value,Unicode_value), * e.g. (nbsp,#160,00A0). * - entity_name and entity_value have been stripped of the surrounding "&" and ";", * e.g. "nbsp" instead of "&nbsp;", "#160" instead of "&#160;". */ private static final String RAW_HTML_ENTITY_TABLE = "nbsp #160 00A0 iexcl #161 00A1 cent #162 00A2 pound #163 00A3 curren #164 00A4 yen #165 00A5 " + "brvbar #166 00A6 sect #167 00A7 uml #168 00A8 copy #169 00A9 ordf #170 00AA laquo #171 00AB " + "not #172 00AC shy #173 00AD reg #174 00AE macr #175 00AF deg #176 00B0 plusmn #177 00B1 " + "sup2 #178 00B2 sup3 #179 00B3 acute #180 00B4 micro #181 00B5 para #182 00B6 middot #183 00B7 " + "cedil #184 00B8 sup1 #185 00B9 ordm #186 00BA raquo #187 00BB frac14 #188 00BC frac12 #189 00BD " + "frac34 #190 00BE iquest #191 00BF Agrave #192 00C0 Aacute #193 00C1 Acirc #194 00C2 Atilde #195 00C3 " + "Auml #196 00C4 Aring #197 00C5 AElig #198 00C6 Ccedil #199 00C7 Egrave #200 00C8 Eacute #201 00C9 " + "Ecirc #202 00CA Euml #203 00CB Igrave #204 00CC Iacute #205 00CD Icirc #206 00CE Iuml #207 00CF " + "ETH #208 00D0 Ntilde #209 00D1 Ograve #210 00D2 Oacute #211 00D3 Ocirc #212 00D4 Otilde #213 00D5 " + "Ouml #214 00D6 times #215 00D7 Oslash #216 00D8 Ugrave #217 00D9 Uacute #218 00DA Ucirc #219 00DB " + "Uuml #220 00DC Yacute #221 00DD THORN #222 00DE szlig #223 00DF agrave #224 00E0 aacute #225 00E1 " + "acirc #226 00E2 atilde #227 00E3 auml #228 00E4 aring #229 00E5 aelig #230 00E6 ccedil #231 00E7 " + "egrave #232 00E8 eacute #233 00E9 ecirc #234 00EA euml #235 00EB igrave #236 00EC iacute #237 00ED " + "icirc #238 00EE iuml #239 00EF eth #240 00F0 ntilde #241 00F1 ograve #242 00F2 oacute #243 00F3 " + "ocirc #244 00F4 otilde #245 00F5 ouml #246 00F6 divide #247 00F7 oslash #248 00F8 ugrave #249 00F9 " + "uacute #250 00FA ucirc #251 00FB uuml #252 00FC yacute #253 00FD thorn #254 00FE yuml #255 00FF " + "fnof #402 0192 Alpha #913 0391 Beta #914 0392 Gamma #915 0393 Delta #916 0394 Epsilon #917 0395 " + "Zeta #918 0396 Eta #919 0397 Theta #920 0398 Iota #921 0399 Kappa #922 039A Lambda #923 039B " + "Mu #924 039C Nu #925 039D Xi #926 039E Omicron #927 039F Pi #928 03A0 Rho #929 03A1 " + "Sigma #931 03A3 Tau #932 03A4 Upsilon #933 03A5 Phi #934 03A6 Chi #935 03A7 Psi #936 03A8 " + "Omega #937 03A9 alpha #945 03B1 beta #946 03B2 gamma #947 03B3 delta #948 03B4 epsilon #949 03B5 " + "zeta #950 03B6 eta #951 03B7 theta #952 03B8 iota #953 03B9 kappa #954 03BA lambda #955 03BB " + "mu #956 03BC nu #957 03BD xi #958 03BE omicron #959 03BF pi #960 03C0 rho #961 03C1 " + "sigmaf #962 03C2 sigma #963 03C3 tau #964 03C4 upsilon #965 03C5 phi #966 03C6 chi #967 03C7 " + "psi #968 03C8 omega #969 03C9 thetasym #977 03D1 upsih #978 03D2 piv #982 03D6 bull #8226 2022 " + "hellip #8230 2026 prime #8242 2032 Prime #8243 2033 oline #8254 203E frasl #8260 2044 weierp #8472 2118 " + "image #8465 2111 real #8476 211C trade #8482 2122 alefsym #8501 2135 larr #8592 2190 uarr #8593 2191 " + "rarr #8594 2192 darr #8595 2193 harr #8596 2194 crarr #8629 21B5 lArr #8656 21D0 uArr #8657 21D1 " + "rArr #8658 21D2 dArr #8659 21D3 hArr #8660 21D4 forall #8704 2200 part #8706 2202 exist #8707 2203 " + "empty #8709 2205 nabla #8711 2207 isin #8712 2208 notin #8713 2209 ni #8715 220B prod #8719 220F " + "sum #8721 2211 minus #8722 2212 lowast #8727 2217 radic #8730 221A prop #8733 221D infin #8734 221E " + "ang #8736 2220 and #8743 2227 or #8744 2228 cap #8745 2229 cup #8746 222A int #8747 222B " + "there4 #8756 2234 sim #8764 223C cong #8773 2245 asymp #8776 2248 ne #8800 2260 equiv #8801 2261 " + "le #8804 2264 ge #8805 2265 sub #8834 2282 sup #8835 2283 nsub #8836 2284 sube #8838 2286 " + "supe #8839 2287 oplus #8853 2295 otimes #8855 2297 perp #8869 22A5 sdot #8901 22C5 lceil #8968 2308 " + "rceil #8969 2309 lfloor #8970 230A rfloor #8971 230B lang #9001 2329 rang #9002 232A loz #9674 25CA " + "spades #9824 2660 clubs #9827 2663 hearts #9829 2665 diams #9830 2666 " + "quot #34 0022 amp #38 0026 lt #60 003C gt #62 003E OElig #338 0152 oelig #339 0153 " + "Scaron #352 0160 Yuml #376 0178 circ #710 02C6 tilde #732 02DC ensp #8194 2002 emsp #8195 2003 " + "thinsp #8201 2009 zwnj #8204 200C zwj #8205 200D lrm #8206 200E rlm #8207 200F ndash #8211 2013 " + "mdash #8212 2014 lsquo #8216 2018 rsquo #8217 2019 sbquo #8218 201A ldquo #8220 201C rdquo #8221 201D " + "bdquo #8222 201E dagger #8224 2020 Dagger #8225 2021 permil #8240 2030 lsaquo #8249 2039 rsaquo #8250 203A " + "euro #8364 20AC"; /** value given by RAW_HTML_ENTITY_TABLE.hashCode(), used to guard against accidental modification */ private static final int RAW_HTML_ENTITY_TABLE_HASHCODE = -301953893; /** mapping: HTML entity ---> Unicode character */ private static final Map<String,Character> HTML_ENTITY_TO_UNICODE_MAP = new HashMap<String,Character>(); /** mapping: Unicode character ---> HTML entity */ private static final Map<Character,String> UNICODE_TO_HTML_ENTITY_MAP = new HashMap<Character,String>(); /** * Static initialization block. * Populates HTML_ENTITY_TO_UNICODE_MAP and UNICODE_TO_HTML_ENTITY_MAP. */ static { /* check hash code of RAW_HTML_ENTITY_TABLE */ if (RAW_HTML_ENTITY_TABLE.hashCode() != RAW_HTML_ENTITY_TABLE_HASHCODE) { throw new RuntimeException("(INTERNAL) Malformed HtmlManipulator.RAW_HTML_ENTITY_TABLE."); } /* populate HTML entity <---> Unicode character maps */ final String[] elements = RAW_HTML_ENTITY_TABLE.split("[\\s]++"); for (int i = 0; i < elements.length; i += 3) { final char unicode = (char) Integer.parseInt(elements[i + 2], 16); HTML_ENTITY_TO_UNICODE_MAP.put(elements[i], unicode); HTML_ENTITY_TO_UNICODE_MAP.put(elements[i + 1], unicode); UNICODE_TO_HTML_ENTITY_MAP.put(unicode, elements[i]); } } /** * Private constructor that should never be called. */ private HtmlManipulator() {} /** * Replace HTML entities in a given string with their Unicode character representations. * * @param s * input string * @return * string with HTML entities replaced */ public static String replaceHtmlEntities( final String s) { final StringBuilder t = new StringBuilder(); for (int i = 0, n = s.length(); i < n; i++) { final char c = s.charAt(i); if (c == '&') { /* candidate HTML entity */ final int j = s.indexOf(';', i); if (j >= 0) { final Character unicode = HTML_ENTITY_TO_UNICODE_MAP.get(s.substring(i + 1, j)); if (unicode != null) { /* insert Unicode representation */ t.append((char) unicode); i = j; /* advance index */ continue; } } } /* treat as a literal character */ t.append(c); } return t.toString(); } /** * Quote a specified string as HTML, by replacing all special characters with their * equivalent HTML entities. * * @param s * input string * @return * string with special characters replaced */ public static String quoteHtml( final String s) { final StringBuilder t = new StringBuilder(); for (char c : s.toCharArray()) { final String entity = UNICODE_TO_HTML_ENTITY_MAP.get(c); if (entity == null) { t.append(c); } else { t.append('&'); t.append(entity); t.append(';'); } } return t.toString(); } }
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2007, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------- * PaintMap.java * ------------- * (C) Copyright 2006, 2007, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes: * -------- * 27-Sep-2006 : Version 1 (DG); * 17-Jan-2007 : Changed TreeMap to HashMap, so that different classes that * implement Comparable can be used as keys (DG); * */ package org.jfree.chart; import java.awt.Paint; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.jfree.io.SerialUtilities; import org.jfree.util.PaintUtilities; /** * A storage structure that maps <code>Comparable</code> instances with * <code>Paint</code> instances. * <br><br> * To support cloning and serialization, you should only use keys that are * cloneable and serializable. Special handling for the <code>Paint</code> * instances is included in this class. * * @since 1.0.3 */ public class PaintMap implements Cloneable, Serializable { /** For serialization. */ static final long serialVersionUID = -4639833772123069274L; /** Storage for the keys and values. */ private transient Map store; /** * Creates a new (empty) map. */ public PaintMap() { this.store = new HashMap(); } /** * Returns the paint associated with the specified key, or * <code>null</code>. * * @param key the key (<code>null</code> not permitted). * * @return The paint, or <code>null</code>. * * @throws IllegalArgumentException if <code>key</code> is * <code>null</code>. */ public Paint getPaint(Comparable key) { if (key == null) { throw new IllegalArgumentException("Null 'key' argument."); } return (Paint) this.store.get(key); } /** * Returns <code>true</code> if the map contains the specified key, and * <code>false</code> otherwise. * * @param key the key. * * @return <code>true</code> if the map contains the specified key, and * <code>false</code> otherwise. */ public boolean containsKey(Comparable key) { return this.store.containsKey(key); } /** * Adds a mapping between the specified <code>key</code> and * <code>paint</code> values. * * @param key the key (<code>null</code> not permitted). * @param paint the paint. * * @throws IllegalArgumentException if <code>key</code> is * <code>null</code>. */ public void put(Comparable key, Paint paint) { if (key == null) { throw new IllegalArgumentException("Null 'key' argument."); } this.store.put(key, paint); } /** * Resets the map to empty. */ public void clear() { this.store.clear(); } /** * Tests this map for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof PaintMap)) { return false; } PaintMap that = (PaintMap) obj; if (this.store.size() != that.store.size()) { return false; } Set keys = this.store.keySet(); Iterator iterator = keys.iterator(); while (iterator.hasNext()) { Comparable key = (Comparable) iterator.next(); Paint p1 = getPaint(key); Paint p2 = that.getPaint(key); if (!PaintUtilities.equal(p1, p2)) { return false; } } return true; } /** * Returns a clone of this <code>PaintMap</code>. * * @return A clone of this instance. * * @throws CloneNotSupportedException if any key is not cloneable. */ public Object clone() throws CloneNotSupportedException { // TODO: I think we need to make sure the keys are actually cloned, // whereas the paint instances are always immutable so they're OK return super.clone(); } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); stream.writeInt(this.store.size()); Set keys = this.store.keySet(); Iterator iterator = keys.iterator(); while (iterator.hasNext()) { Comparable key = (Comparable) iterator.next(); stream.writeObject(key); Paint paint = getPaint(key); SerialUtilities.writePaint(paint, stream); } } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.store = new HashMap(); int keyCount = stream.readInt(); for (int i = 0; i < keyCount; i++) { Comparable key = (Comparable) stream.readObject(); Paint paint = SerialUtilities.readPaint(stream); this.store.put(key, paint); } } }
/* * Copyright 2016 LINE Corporation * * LINE Corporation 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: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.linecorp.armeria.server; import static com.linecorp.armeria.common.SessionProtocol.H1; import static com.linecorp.armeria.common.SessionProtocol.H1C; import static com.linecorp.armeria.common.SessionProtocol.H2; import static com.linecorp.armeria.common.SessionProtocol.H2C; import static com.linecorp.armeria.common.SessionProtocol.HTTP; import static com.linecorp.armeria.common.SessionProtocol.HTTPS; import static com.linecorp.armeria.common.SessionProtocol.PROXY; import static java.util.Objects.requireNonNull; import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.EnumSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; import javax.net.ssl.SSLException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.ImmutableList; import com.linecorp.armeria.common.SessionProtocol; import com.linecorp.armeria.common.metric.MoreMeters; import com.linecorp.armeria.common.util.Exceptions; import com.linecorp.armeria.internal.common.KeepAliveHandler; import com.linecorp.armeria.internal.common.ReadSuppressingHandler; import com.linecorp.armeria.internal.common.TrafficLoggingHandler; import com.linecorp.armeria.internal.common.util.ChannelUtil; import io.micrometer.core.instrument.Tag; import io.micrometer.core.instrument.Timer; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.handler.codec.ByteToMessageDecoder; import io.netty.handler.codec.DecoderException; import io.netty.handler.codec.MessageToMessageDecoder; import io.netty.handler.codec.haproxy.HAProxyMessage; import io.netty.handler.codec.haproxy.HAProxyMessageDecoder; import io.netty.handler.codec.haproxy.HAProxyProxiedProtocol.AddressFamily; import io.netty.handler.codec.http.HttpServerCodec; import io.netty.handler.codec.http.HttpServerUpgradeHandler; import io.netty.handler.codec.http2.Http2CodecUtil; import io.netty.handler.codec.http2.Http2ConnectionHandler; import io.netty.handler.codec.http2.Http2ServerUpgradeCodec; import io.netty.handler.codec.http2.Http2Settings; import io.netty.handler.flush.FlushConsolidationHandler; import io.netty.handler.ssl.ApplicationProtocolNames; import io.netty.handler.ssl.ApplicationProtocolNegotiationHandler; import io.netty.handler.ssl.SniHandler; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslHandler; import io.netty.util.AsciiString; import io.netty.util.Mapping; import io.netty.util.NetUtil; import io.netty.util.concurrent.ScheduledFuture; /** * Configures Netty {@link ChannelPipeline} to serve HTTP/1 and 2 requests. */ final class HttpServerPipelineConfigurator extends ChannelInitializer<Channel> { private static final Logger logger = LoggerFactory.getLogger(HttpServerPipelineConfigurator.class); private static final int SSL_RECORD_HEADER_LENGTH = 5; private static final AsciiString SCHEME_HTTP = AsciiString.cached("http"); private static final AsciiString SCHEME_HTTPS = AsciiString.cached("https"); private static final int UPGRADE_REQUEST_MAX_LENGTH = 16384; private static final byte[] PROXY_V1_MAGIC_BYTES = { (byte) 'P', (byte) 'R', (byte) 'O', (byte) 'X', (byte) 'Y' }; private static final byte[] PROXY_V2_MAGIC_BYTES = { (byte) 0x0D, (byte) 0x0A, (byte) 0x0D, (byte) 0x0A, (byte) 0x00, (byte) 0x0D, (byte) 0x0A, (byte) 0x51, (byte) 0x55, (byte) 0x49, (byte) 0x54, (byte) 0x0A }; private final ServerConfig config; private final ServerPort port; @Nullable private final Mapping<String, SslContext> sslContexts; private final GracefulShutdownSupport gracefulShutdownSupport; /** * Creates a new instance. */ HttpServerPipelineConfigurator( ServerConfig config, ServerPort port, @Nullable Mapping<String, SslContext> sslContexts, GracefulShutdownSupport gracefulShutdownSupport) { this.config = requireNonNull(config, "config"); this.port = requireNonNull(port, "port"); this.sslContexts = sslContexts; this.gracefulShutdownSupport = requireNonNull(gracefulShutdownSupport, "gracefulShutdownSupport"); } @Override protected void initChannel(Channel ch) throws Exception { ChannelUtil.disableWriterBufferWatermark(ch); final ChannelPipeline p = ch.pipeline(); p.addLast(new FlushConsolidationHandler()); p.addLast(ReadSuppressingHandler.INSTANCE); configurePipeline(p, port.protocols(), null); } private void configurePipeline(ChannelPipeline p, Set<SessionProtocol> protocols, @Nullable ProxiedAddresses proxiedAddresses) { if (protocols.size() == 1) { switch (protocols.iterator().next()) { case HTTP: configureHttp(p, proxiedAddresses); break; case HTTPS: configureHttps(p, proxiedAddresses); break; default: // Should never reach here. throw new Error(); } return; } // More than one protocol were specified. Detect the protocol. final ScheduledFuture<?> protocolDetectionTimeoutFuture; // FIXME(trustin): Add a dedicated timeout option to ServerConfig. final long requestTimeoutMillis = config.defaultVirtualHost().requestTimeoutMillis(); if (requestTimeoutMillis > 0) { // Close the connection if the protocol detection is not finished in time. final Channel ch = p.channel(); protocolDetectionTimeoutFuture = ch.eventLoop().schedule( (Runnable) ch::close, requestTimeoutMillis, TimeUnit.MILLISECONDS); } else { protocolDetectionTimeoutFuture = null; } p.addLast(new ProtocolDetectionHandler(protocols, proxiedAddresses, protocolDetectionTimeoutFuture)); } private void configureHttp(ChannelPipeline p, @Nullable ProxiedAddresses proxiedAddresses) { final long idleTimeoutMillis = config.idleTimeoutMillis(); final KeepAliveHandler keepAliveHandler; if (idleTimeoutMillis > 0) { final Timer keepAliveTimer = newKeepAliveTimer(H1C); keepAliveHandler = new Http1ServerKeepAliveHandler( p.channel(), keepAliveTimer, idleTimeoutMillis, config.maxConnectionAgeMillis()); } else { keepAliveHandler = null; } final ServerHttp1ObjectEncoder responseEncoder = new ServerHttp1ObjectEncoder( p.channel(), H1C, keepAliveHandler, config.isDateHeaderEnabled(), config.isServerHeaderEnabled() ); p.addLast(TrafficLoggingHandler.SERVER); p.addLast(new Http2PrefaceOrHttpHandler(responseEncoder)); p.addLast(new HttpServerHandler(config, gracefulShutdownSupport, responseEncoder, H1C, proxiedAddresses)); } private Timer newKeepAliveTimer(SessionProtocol protocol) { return MoreMeters.newTimer(config.meterRegistry(), "armeria.server.connections.lifespan", ImmutableList.of(Tag.of("protocol", protocol.uriText()))); } private void configureHttps(ChannelPipeline p, @Nullable ProxiedAddresses proxiedAddresses) { assert sslContexts != null; p.addLast(new SniHandler(sslContexts)); p.addLast(TrafficLoggingHandler.SERVER); p.addLast(new Http2OrHttpHandler(proxiedAddresses)); } private Http2ConnectionHandler newHttp2ConnectionHandler(ChannelPipeline pipeline, AsciiString scheme) { final Timer keepAliveTimer = newKeepAliveTimer(scheme == SCHEME_HTTP ? H2C : H2); return new Http2ServerConnectionHandlerBuilder(pipeline.channel(), config, keepAliveTimer, gracefulShutdownSupport, scheme.toString()) .server(true) .initialSettings(http2Settings()) .build(); } private Http2Settings http2Settings() { final Http2Settings settings = new Http2Settings(); final int initialWindowSize = config.http2InitialStreamWindowSize(); if (initialWindowSize != Http2CodecUtil.DEFAULT_WINDOW_SIZE) { settings.initialWindowSize(initialWindowSize); } final int maxFrameSize = config.http2MaxFrameSize(); if (maxFrameSize != Http2CodecUtil.DEFAULT_MAX_FRAME_SIZE) { settings.maxFrameSize(maxFrameSize); } // Not using the value greater than 2^31-1 because some HTTP/2 client implementations use a signed // 32-bit integer to represent an HTTP/2 SETTINGS parameter value. settings.maxConcurrentStreams(Math.min(config.http2MaxStreamsPerConnection(), Integer.MAX_VALUE)); settings.maxHeaderListSize(config.http2MaxHeaderListSize()); return settings; } private final class ProtocolDetectionHandler extends ByteToMessageDecoder { private final EnumSet<SessionProtocol> candidates; @Nullable private final EnumSet<SessionProtocol> proxiedCandidates; @Nullable private final ProxiedAddresses proxiedAddresses; @Nullable private final ScheduledFuture<?> timeoutFuture; ProtocolDetectionHandler(Set<SessionProtocol> protocols, @Nullable ProxiedAddresses proxiedAddresses, @Nullable ScheduledFuture<?> timeoutFuture) { candidates = EnumSet.copyOf(protocols); if (protocols.contains(PROXY)) { proxiedCandidates = EnumSet.copyOf(candidates); proxiedCandidates.remove(PROXY); } else { proxiedCandidates = null; } this.proxiedAddresses = proxiedAddresses; this.timeoutFuture = timeoutFuture; } @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { final int readableBytes = in.readableBytes(); SessionProtocol detected = null; for (final Iterator<SessionProtocol> i = candidates.iterator(); i.hasNext();/* noop */) { final SessionProtocol protocol = i.next(); switch (protocol) { case HTTPS: if (readableBytes < SSL_RECORD_HEADER_LENGTH) { break; } if (SslHandler.isEncrypted(in)) { detected = HTTPS; break; } // Certainly not HTTPS. i.remove(); break; case PROXY: // It's obvious that the magic bytes are longer in PROXY v2, but just in case. assert PROXY_V1_MAGIC_BYTES.length < PROXY_V2_MAGIC_BYTES.length; if (readableBytes < PROXY_V1_MAGIC_BYTES.length) { break; } if (match(PROXY_V1_MAGIC_BYTES, in)) { detected = PROXY; break; } if (readableBytes < PROXY_V2_MAGIC_BYTES.length) { break; } if (match(PROXY_V2_MAGIC_BYTES, in)) { detected = PROXY; break; } // Certainly not PROXY protocol. i.remove(); break; } } if (detected == null) { if (candidates.size() == 1) { // There's only one candidate left - HTTP. detected = HTTP; } else { // No protocol was detected and there are more than one candidate left. return; } } if (timeoutFuture != null) { timeoutFuture.cancel(false); } final ChannelPipeline p = ctx.pipeline(); switch (detected) { case HTTP: configureHttp(p, proxiedAddresses); break; case HTTPS: configureHttps(p, proxiedAddresses); break; case PROXY: assert proxiedCandidates != null; p.addLast(new HAProxyMessageDecoder(config.proxyProtocolMaxTlvSize())); p.addLast(new ProxiedPipelineConfigurator(proxiedCandidates)); break; default: // Never reaches here. throw new Error(); } p.remove(this); } private boolean match(byte[] prefix, ByteBuf buffer) { final int idx = buffer.readerIndex(); for (int i = 0; i < prefix.length; i++) { final byte b = buffer.getByte(idx + i); if (b != prefix[i]) { return false; } } return true; } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { if (!Exceptions.isExpected(cause)) { logger.warn("{} Unexpected exception while detecting the session protocol.", ctx, cause); } ctx.close(); } } private final class ProxiedPipelineConfigurator extends MessageToMessageDecoder<HAProxyMessage> { private final EnumSet<SessionProtocol> proxiedCandidates; ProxiedPipelineConfigurator(EnumSet<SessionProtocol> proxiedCandidates) { this.proxiedCandidates = proxiedCandidates; } @Override protected void decode(ChannelHandlerContext ctx, HAProxyMessage msg, List<Object> out) throws Exception { if (logger.isDebugEnabled()) { logger.debug("PROXY message {}: {}:{} -> {}:{} (next: {})", msg.protocolVersion().name(), msg.sourceAddress(), msg.sourcePort(), msg.destinationAddress(), msg.destinationPort(), proxiedCandidates); } final ProxiedAddresses proxiedAddresses; if (msg.proxiedProtocol().addressFamily() == AddressFamily.AF_UNSPEC) { proxiedAddresses = null; } else { final InetAddress src = InetAddress.getByAddress( NetUtil.createByteArrayFromIpAddressString(msg.sourceAddress())); final InetAddress dst = InetAddress.getByAddress( NetUtil.createByteArrayFromIpAddressString(msg.destinationAddress())); proxiedAddresses = ProxiedAddresses.of(new InetSocketAddress(src, msg.sourcePort()), new InetSocketAddress(dst, msg.destinationPort())); } final ChannelPipeline p = ctx.pipeline(); configurePipeline(p, proxiedCandidates, proxiedAddresses); p.remove(this); } } private final class Http2OrHttpHandler extends ApplicationProtocolNegotiationHandler { @Nullable private final ProxiedAddresses proxiedAddresses; Http2OrHttpHandler(@Nullable ProxiedAddresses proxiedAddresses) { super(ApplicationProtocolNames.HTTP_1_1); this.proxiedAddresses = proxiedAddresses; } @Override protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception { if (ApplicationProtocolNames.HTTP_2.equals(protocol)) { addHttp2Handlers(ctx); return; } if (ApplicationProtocolNames.HTTP_1_1.equals(protocol)) { addHttpHandlers(ctx); return; } throw new IllegalStateException("unknown protocol: " + protocol); } private void addHttp2Handlers(ChannelHandlerContext ctx) { final ChannelPipeline p = ctx.pipeline(); p.addLast(newHttp2ConnectionHandler(p, SCHEME_HTTPS)); p.addLast(new HttpServerHandler(config, gracefulShutdownSupport, null, H2, proxiedAddresses)); } private void addHttpHandlers(ChannelHandlerContext ctx) { final Channel ch = ctx.channel(); final ChannelPipeline p = ctx.pipeline(); final long idleTimeoutMillis = config.idleTimeoutMillis(); final KeepAliveHandler keepAliveHandler; if (idleTimeoutMillis > 0) { keepAliveHandler = new Http1ServerKeepAliveHandler( ch, newKeepAliveTimer(H1), idleTimeoutMillis, config.maxConnectionAgeMillis()); } else { keepAliveHandler = null; } final ServerHttp1ObjectEncoder writer = new ServerHttp1ObjectEncoder( ch, H1, keepAliveHandler, config.isDateHeaderEnabled(), config.isServerHeaderEnabled()); p.addLast(new HttpServerCodec( config.http1MaxInitialLineLength(), config.http1MaxHeaderSize(), config.http1MaxChunkSize())); p.addLast(new Http1RequestDecoder(config, ch, SCHEME_HTTPS, writer)); p.addLast(new HttpServerHandler(config, gracefulShutdownSupport, writer, H1, proxiedAddresses)); } @Override protected void handshakeFailure(ChannelHandlerContext ctx, Throwable cause) throws Exception { if (!Exceptions.isExpected(cause)) { logger.warn("{} TLS handshake failed:", ctx.channel(), cause); } ctx.close(); // On handshake failure, ApplicationProtocolNegotiationHandler will remove itself, // leaving no handlers behind it. Add a handler that handles the exceptions raised after this point. ctx.pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { if (cause instanceof DecoderException && cause.getCause() instanceof SSLException) { // Swallow an SSLException raised after handshake failure. return; } Exceptions.logIfUnexpected(logger, ctx.channel(), cause); } }); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { Exceptions.logIfUnexpected(logger, ctx.channel(), cause); ctx.close(); } } private final class Http2PrefaceOrHttpHandler extends ByteToMessageDecoder { private final ServerHttp1ObjectEncoder responseEncoder; @Nullable private final KeepAliveHandler keepAliveHandler; @Nullable private String name; Http2PrefaceOrHttpHandler(ServerHttp1ObjectEncoder responseEncoder) { this.responseEncoder = responseEncoder; keepAliveHandler = responseEncoder.keepAliveHandler(); } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { if (keepAliveHandler != null) { keepAliveHandler.initialize(ctx); } super.handlerAdded(ctx); name = ctx.name(); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { if (keepAliveHandler != null) { keepAliveHandler.destroy(); } super.channelInactive(ctx); } @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if (keepAliveHandler != null) { keepAliveHandler.onReadOrWrite(); } if (in.readableBytes() < 4) { return; } if (in.getInt(in.readerIndex()) == 0x50524920) { // If starts with 'PRI ' // Probably HTTP/2; received the HTTP/2 preface string. configureHttp2(ctx); } else { // Probably HTTP/1; the client can still upgrade using the traditional HTTP/1 upgrade request. configureHttp1WithUpgrade(ctx); } ctx.pipeline().remove(this); } private void configureHttp1WithUpgrade(ChannelHandlerContext ctx) { final ChannelPipeline p = ctx.pipeline(); final HttpServerCodec http1codec = new HttpServerCodec( config.http1MaxInitialLineLength(), config.http1MaxHeaderSize(), config.http1MaxChunkSize()); String baseName = name; assert baseName != null; baseName = addAfter(p, baseName, http1codec); baseName = addAfter(p, baseName, new HttpServerUpgradeHandler( http1codec, protocol -> { if (!AsciiString.contentEquals(Http2CodecUtil.HTTP_UPGRADE_PROTOCOL_NAME, protocol)) { return null; } return new Http2ServerUpgradeCodec( newHttp2ConnectionHandler(p, SCHEME_HTTP)); }, UPGRADE_REQUEST_MAX_LENGTH)); addAfter(p, baseName, new Http1RequestDecoder(config, ctx.channel(), SCHEME_HTTP, responseEncoder)); } private void configureHttp2(ChannelHandlerContext ctx) { final ChannelPipeline p = ctx.pipeline(); assert name != null; addAfter(p, name, newHttp2ConnectionHandler(p, SCHEME_HTTP)); } private String addAfter(ChannelPipeline p, String baseName, ChannelHandler handler) { p.addAfter(baseName, null, handler); return p.context(handler).name(); } } }
/* * Copyright (c) 2014, salesforce.com, inc. * All rights reserved. * Redistribution and use of this software in source and binary forms, with or * without modification, are permitted provided that the following conditions * are met: * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of salesforce.com, inc. nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission of salesforce.com, inc. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.salesforce.androidsdk.rest; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; import java.util.Map; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import android.util.Log; import com.android.volley.AuthFailureError; import com.android.volley.NetworkResponse; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.BasicNetwork; import com.android.volley.toolbox.HttpHeaderParser; import com.android.volley.toolbox.HttpStack; import com.android.volley.toolbox.NoCache; import com.google.common.collect.Maps; import com.salesforce.androidsdk.auth.HttpAccess; import com.salesforce.androidsdk.auth.HttpAccess.Execution; import com.salesforce.androidsdk.rest.RestRequest.RestMethod; /** * RestClient allows you to send authenticated HTTP requests to a force.com server. */ public class RestClient { private static Map<String, RequestQueue> REQUEST_QUEUES; private ClientInfo clientInfo; private RequestQueue requestQueue; private SalesforceHttpStack httpStack; /** * AuthTokenProvider interface. * RestClient will call its authTokenProvider to refresh its authToken once it has expired. */ public interface AuthTokenProvider { String getNewAuthToken(); String getRefreshToken(); long getLastRefreshTime(); } /** * AsyncRequestCallback interface. * Interface through which the result of an asynchronous request is handled. */ public interface AsyncRequestCallback { void onSuccess(RestRequest request, RestResponse response); void onError(Exception exception); } /** * Constructs a RestClient with the given clientInfo, authToken, httpAccessor and authTokenProvider. * When it gets a 401 (not authorized) response from the server: * <ul> * <li> If authTokenProvider is not null, it will ask the authTokenProvider for a new access token and retry the request a second time.</li> * <li> Otherwise it will return the 401 response.</li> * </ul> * @param clientInfo * @param authToken * @param httpAccessor * @param authTokenProvider */ public RestClient(ClientInfo clientInfo, String authToken, HttpAccess httpAccessor, AuthTokenProvider authTokenProvider) { this(clientInfo, new SalesforceHttpStack(authToken, httpAccessor, authTokenProvider)); } public RestClient(ClientInfo clientInfo, SalesforceHttpStack httpStack) { this.clientInfo = clientInfo; this.httpStack = httpStack; setRequestQueue(); } /** * Sets the request queue associated with this user account. The request * queues are cached in a map and reused as and when a user account * switch occurs, to prevent multiple threads being spawned unnecessarily. */ private synchronized void setRequestQueue() { if (REQUEST_QUEUES == null) { REQUEST_QUEUES = new HashMap<String, RequestQueue>(); } final String uniqueId = clientInfo.userId + clientInfo.orgId; RequestQueue queue = null; if (uniqueId != null) { queue = REQUEST_QUEUES.get(uniqueId); if (queue == null) { queue = new RequestQueue(new NoCache(), new BasicNetwork(httpStack)); queue.start(); REQUEST_QUEUES.put(uniqueId, queue); } } this.requestQueue = queue; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("RestClient: {\n") .append(getClientInfo()) // Un-comment if you must: tokens should not be printed to the log // .append(" authToken: ").append(getAuthToken()).append("\n") // .append(" refreshToken: ").append(getRefreshToken()).append("\n") .append(" timeSinceLastRefresh: ").append(httpStack.getElapsedTimeSinceLastRefresh()).append("\n") .append("}\n"); return sb.toString(); } /** * @return The authToken for this RestClient. */ public synchronized String getAuthToken() { return httpStack.getAuthToken(); } /** * @return The refresh token, if available. */ public String getRefreshToken() { return httpStack.getRefreshToken(); } /** * @return The client info. */ public ClientInfo getClientInfo() { return clientInfo; } /** * @return underlying RequestQueue (using when calling sendAsync) */ public RequestQueue getRequestQueue() { return requestQueue; } /** * Send the given restRequest and process the result asynchronously with the given callback. * Note: Intended to be used by code on the UI thread. * @param restRequest * @param callback * @return volley.Request object wrapped around the restRequest (to allow cancellation etc) */ public Request<?> sendAsync(RestRequest restRequest, AsyncRequestCallback callback) { WrappedRestRequest wrappedRestRequest = new WrappedRestRequest(clientInfo, restRequest, callback); return requestQueue.add(wrappedRestRequest); } /** * Send the given restRequest synchronously and return a RestResponse * Note: Cannot be used by code on the UI thread (use sendAsync instead). * @param restRequest * @return * @throws IOException */ public RestResponse sendSync(RestRequest restRequest) throws IOException { return sendSync(restRequest.getMethod(), restRequest.getPath(), restRequest.getRequestEntity(), restRequest.getAdditionalHttpHeaders()); } /** * Send an arbitrary HTTP request synchronously, using the given method, path and httpEntity. * Note: Cannot be used by code on the UI thread (use sendAsync instead). * * @param method the HTTP method for the request (GET/POST/DELETE etc) * @param path the URI path, this will automatically be resolved against the users current instance host. * @param httpEntity the request body if there is one, can be null. * @param additionalHttpHeaders additional HTTP headers to add the generated HTTP request, can be null. * @return a RestResponse instance that has information about the HTTP response returned by the server. */ public RestResponse sendSync(RestMethod method, String path, HttpEntity httpEntity) throws IOException { return sendSync(method, path, httpEntity, null); } /** * Send an arbitrary HTTP request synchronously, using the given method, path, httpEntity and additionalHttpHeaders. * Note: Cannot be used by code on the UI thread (use sendAsync instead). * * @param method the HTTP method for the request (GET/POST/DELETE etc) * @param path the URI path, this will automatically be resolved against the users current instance host. * @param httpEntity the request body if there is one, can be null. * @param additionalHttpHeaders additional HTTP headers to add the generated HTTP request, can be null. * @return a RestResponse instance that has information about the HTTP response returned by the server. * * @throws IOException */ public RestResponse sendSync(RestMethod method, String path, HttpEntity httpEntity, Map<String, String> additionalHttpHeaders) throws IOException { return new RestResponse(httpStack.performRequest(method.asVolleyMethod(), clientInfo.resolveUrl(path), httpEntity, additionalHttpHeaders, true)); } /** * Only used in tests * @param httpAccessor */ public void setHttpAccessor(HttpAccess httpAccessor) { this.httpStack.setHttpAccessor(httpAccessor); } /** * All immutable information for an authenticated client (e.g. username, org ID, etc.). */ public static class ClientInfo { public final String clientId; public final URI instanceUrl; public final URI loginUrl; public final URI identityUrl; public final String accountName; public final String username; public final String userId; public final String orgId; public final String communityId; public final String communityUrl; /** * Parameterized constructor. * * @param clientId Client ID. * @param instanceUrl Instance URL. * @param loginUrl Login URL. * @param identityUrl Identity URL. * @param accountName Account name. * @param username User name. * @param userId User ID. * @param orgId Org ID. * @param communityId Community ID. * @param communityUrl Community URL. */ public ClientInfo(String clientId, URI instanceUrl, URI loginUrl, URI identityUrl, String accountName, String username, String userId, String orgId, String communityId, String communityUrl) { this.clientId = clientId; this.instanceUrl = instanceUrl; this.loginUrl = loginUrl; this.identityUrl = identityUrl; this.accountName = accountName; this.username = username; this.userId = userId; this.orgId = orgId; this.communityId = communityId; this.communityUrl = communityUrl; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(" ClientInfo: {\n") .append(" loginUrl: ").append(loginUrl.toString()).append("\n") .append(" identityUrl: ").append(identityUrl.toString()).append("\n") .append(" instanceUrl: ").append(instanceUrl.toString()).append("\n") .append(" accountName: ").append(accountName).append("\n") .append(" username: ").append(username).append("\n") .append(" userId: ").append(userId).append("\n") .append(" orgId: ").append(orgId).append("\n") .append(" communityId: ").append(communityId).append("\n") .append(" communityUrl: ").append(communityUrl).append("\n") .append(" }\n"); return sb.toString(); } /** * Returns a string representation of the instance URL. If this is a * community user, the community URL will be returned. If not, the * instance URL will be returned. * * @return Instance URL. */ public String getInstanceUrlAsString() { if (communityUrl != null && !"".equals(communityUrl.trim())) { return communityUrl; } return instanceUrl.toString(); } /** * Returns a URI representation of the instance URL. If this is a * community user, the community URL will be returned. If not, the * instance URL will be returned. * * @return Instance URL. */ public URI getInstanceUrl() { if (communityUrl != null && !"".equals(communityUrl.trim())) { URI uri = null; try { uri = new URI(communityUrl); } catch (URISyntaxException e) { Log.e("ClientInfo: getCommunityInstanceUrl", "URISyntaxException thrown on URL: " + communityUrl); } return uri; } return instanceUrl; } /** * Resolves the given path against the community URL or the instance * URL, depending on whether the user is a community user or not. * * @param path Path. * @return Resolved URL. */ public URI resolveUrl(String path) { final StringBuilder commInstanceUrl = new StringBuilder(); if (communityUrl != null && !"".equals(communityUrl.trim())) { commInstanceUrl.append(communityUrl); } else { commInstanceUrl.append(instanceUrl.toString()); } if (!commInstanceUrl.toString().endsWith("/")) { commInstanceUrl.append("/"); } if (path.startsWith("/")) { path = path.substring(1); } commInstanceUrl.append(path); URI uri = null; try { uri = new URI(commInstanceUrl.toString()); } catch (URISyntaxException e) { Log.e("ClientInfo: resolveUrl", "URISyntaxException thrown on URL: " + commInstanceUrl.toString()); } return uri; } } /** * HttpStack for talking to Salesforce (sets oauth header and does oauth refresh when needed) */ public static class SalesforceHttpStack implements HttpStack { private final AuthTokenProvider authTokenProvider; private HttpAccess httpAccessor; private String authToken; /** * Constructs a SalesforceHttpStack with the given clientInfo, authToken, httpAccessor and authTokenProvider. * When it gets a 401 (not authorized) response from the server: * <ul> * <li> If authTokenProvider is not null, it will ask the authTokenProvider for a new access token and retry the request a second time.</li> * <li> Otherwise it will return the 401 response.</li> * </ul> * @param authToken * @param httpAccessor * @param authTokenProvider */ public SalesforceHttpStack(String authToken, HttpAccess httpAccessor, AuthTokenProvider authTokenProvider) { this.authToken = authToken; this.httpAccessor = httpAccessor; this.authTokenProvider = authTokenProvider; } @Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { int method = request.getMethod(); URI url = URI.create(request.getUrl()); HttpEntity requestEntity = null; if (request instanceof WrappedRestRequest) { RestRequest restRequest = ((WrappedRestRequest) request).getRestRequest(); // To avoid httpEntity -> bytes -> httpEntity conversion requestEntity = restRequest.getRequestEntity(); // Combine headers if (restRequest.getAdditionalHttpHeaders() != null) { if (additionalHeaders == null) { additionalHeaders = restRequest.getAdditionalHttpHeaders(); } else { additionalHeaders = Maps.newHashMap(additionalHeaders); additionalHeaders.putAll(restRequest.getAdditionalHttpHeaders()); } } } else { if (request.getBody() != null) { requestEntity = new ByteArrayEntity(request.getBody()); } } return performRequest(method, url, requestEntity, additionalHeaders, true); } /** * @return The authToken for this RestClient. */ public synchronized String getAuthToken() { return authToken; } /** * Change authToken for this RestClient * @param newAuthToken */ private synchronized void setAuthToken(String newAuthToken) { authToken = newAuthToken; } /** * @return The refresh token, if available. */ public String getRefreshToken() { return (authTokenProvider != null ? authTokenProvider.getRefreshToken() : null); } /** * @return Elapsed time (ms) since the last refresh. */ public long getElapsedTimeSinceLastRefresh() { long lastRefreshTime = (authTokenProvider != null ? authTokenProvider.getLastRefreshTime() : -1); if (lastRefreshTime < 0) { return -1; } else { return System.currentTimeMillis() - lastRefreshTime; } } /** * Only used in tests * @param httpAccessor */ public void setHttpAccessor(HttpAccess httpAccessor) { this.httpAccessor = httpAccessor; } /** * @param method * @param url * @param httpEntity * @param additionalHttpHeaders * @param retryInvalidToken * @return * @throws IOException */ public HttpResponse performRequest(int method, URI url, HttpEntity httpEntity, Map<String, String> additionalHttpHeaders, boolean retryInvalidToken) throws IOException { Execution exec = null; // Prepare headers Map<String, String> headers = new HashMap<String, String>(); if (additionalHttpHeaders != null) { headers.putAll(additionalHttpHeaders); } if (getAuthToken() != null) { headers.put("Authorization", "Bearer " + authToken); } // Do the actual call switch(method) { case Request.Method.DELETE: exec = httpAccessor.doDelete(headers, url); break; case Request.Method.GET: exec = httpAccessor.doGet(headers, url); break; case RestMethod.MethodHEAD: exec = httpAccessor.doHead(headers, url); break; case RestMethod.MethodPATCH: exec = httpAccessor.doPatch(headers, url, httpEntity); break; case Request.Method.POST: exec = httpAccessor.doPost(headers, url, httpEntity); break; case Request.Method.PUT: exec = httpAccessor.doPut(headers, url, httpEntity); break; } HttpResponse response = exec.response; int statusCode = response.getStatusLine().getStatusCode(); // 401 bad access token * if (statusCode == HttpStatus.SC_UNAUTHORIZED) { // If we haven't retried already and we have an accessTokenProvider // Then let's try to get a new authToken if (retryInvalidToken && authTokenProvider != null) { // remember to consume this response so the connection can get re-used HttpEntity entity = response.getEntity(); if (entity != null && entity.isStreaming()) { InputStream instream = entity.getContent(); if (instream != null) { instream.close(); } } String newAuthToken = authTokenProvider.getNewAuthToken(); if (newAuthToken != null) { setAuthToken(newAuthToken); // Retry with the new authToken return performRequest(method, url, httpEntity, additionalHttpHeaders, false); } } } // Done return response; } } /** * A RestRequest wrapped in a Request<?> */ public static class WrappedRestRequest extends Request<RestResponse> { private RestRequest restRequest; private AsyncRequestCallback callback; /** * Constructor * @param restRequest * @param callback */ public WrappedRestRequest(ClientInfo clientInfo, RestRequest restRequest, final AsyncRequestCallback callback) { super(restRequest.getMethod().asVolleyMethod(), clientInfo.resolveUrl(restRequest.getPath()).toString(), new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { callback.onError(error); } }); this.restRequest = restRequest; this.callback = callback; } public RestRequest getRestRequest() { return restRequest; } public HttpEntity getRequestEntity() { return restRequest.getRequestEntity(); } @Override public byte[] getBody() throws AuthFailureError { try { HttpEntity requestEntity = restRequest.getRequestEntity(); return requestEntity == null ? null : EntityUtils.toByteArray(requestEntity); } catch (IOException e) { Log.e("WrappedRestRequest.getBody", "Could not read request entity", e); return null; } } @Override public String getBodyContentType() { HttpEntity requestEntity = restRequest.getRequestEntity(); Header contentType = requestEntity == null ? null : requestEntity.getContentType(); return (contentType == null ? "application/x-www-form-urlencoded" : contentType.getValue()) + "; charset=" + HTTP.UTF_8; } @Override protected void deliverResponse(RestResponse restResponse) { callback.onSuccess(restRequest, restResponse); } @Override protected Response<RestResponse> parseNetworkResponse( NetworkResponse networkResponse) { return Response.success(new RestResponse(networkResponse), HttpHeaderParser.parseCacheHeaders(networkResponse)); } } }
/* * Copyright 2014 Lukas Benda <lbenda at lbenda.cz>. * * 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 cz.lbenda.dataman.db; import cz.lbenda.common.*; import cz.lbenda.dataman.db.dialect.ColumnType; import cz.lbenda.rcp.SimpleDateProperty; import cz.lbenda.rcp.SimpleLocalDateProperty; import cz.lbenda.rcp.SimpleLocalDateTimeProperty; import cz.lbenda.rcp.SimpleLocalTimeProperty; import javafx.beans.InvalidationListener; import javafx.beans.Observable; import javafx.beans.property.*; import javafx.beans.value.ObservableValue; import javafx.scene.control.SingleSelectionModel; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; import java.io.IOException; import java.math.BigDecimal; import java.sql.*; import java.sql.Date; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.*; /** Created by Lukas Benda <lbenda @ lbenda.cz> on 13.9.15. * Description of row */ public class RowDesc implements Observable { @SuppressWarnings("unused") private static final Logger LOG = LoggerFactory.getLogger(RowDesc.class); public enum RowDescState { /** Row is newly added */ NEW, /** Row loaded from database */ LOADED, /** Removed for from database */ REMOVED, /** Row is changed */ CHANGED, ; } /** Array for calculate has code */ private static int[] PRIMES = {17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997}; private List<InvalidationListener> invalidationListeners = new ArrayList<>(); private Object id; public Object getId() { return id; } public void setId(Object id) { this.id = id; } private final SQLQueryMetaData metaData; private Object[] oldValues; private ObservableValue[] newValues; private RowDescState state; /** Row in state new */ public static RowDesc createNewRow(SQLQueryMetaData metaData) { RowDesc result = new RowDesc(metaData); result.state = RowDescState.NEW; return result; } /** Row in state new */ public static RowDesc createNewRow(SQLQueryMetaData metaData, RowDescState state) { RowDesc result = new RowDesc(metaData); result.state = state; return result; } private RowDesc(SQLQueryMetaData metaData) { this.metaData = metaData; newValues = new ObservableValue[metaData.getColumns().size()]; int i = 0; for (ColumnDesc columnDesc : metaData.getColumns()) { newValues[i] = createObjectProperty(columnDesc); //noinspection unchecked newValues[i].addListener((observable, oldValue, newValue) -> { if (!AbstractHelper.nullEquals(oldValue, newValue)) { setColumnValue(columnDesc, newValue); } }); i++; } oldValues = new Object[metaData.getColumns().size()]; } RowDesc(SQLQueryMetaData metaData, RowDescState state) { this(metaData); this.state = state; } /* RowDesc(Object id, Object[] values, RowDescState state) { this.id = id; this.oldValues = values; this.newValues = values.clone(); this.state = state; } */ public void setState(RowDescState state) { this.state = state; doInvalidation(); } public RowDescState getState() { return state; } public void cancelChanges() { metaData.getColumns().forEach(columnDesc -> setColumnValue(columnDesc, oldValues[columnDesc.getPosition() - 1])); if (state == RowDescState.CHANGED) { state = RowDescState.LOADED; } doInvalidation(); } /** The changes was saved */ public void savedChanges() { oldValues = newValues.clone(); state = RowDescState.LOADED; doInvalidation(); } @Override public void addListener(InvalidationListener invalidationListener) { invalidationListeners.add(invalidationListener); } @Override public void removeListener(InvalidationListener invalidationListener) { invalidationListeners.remove(invalidationListener); } /** Call invalidation on all invalidation listener */ public void doInvalidation() { invalidationListeners.forEach(listener -> listener.invalidated(this)); } /** Return value from column */ @SuppressWarnings("unchecked") public <T> T getColumnValue(ColumnDesc column) { return repairClassOfValue(column, (T) newValues[column.getPosition() - 1].getValue()); } /** Return value of column in string */ @SuppressWarnings("unchecked") public String getColumnValueStr(ColumnDesc column) { return column.getStringConverter().toString(getColumnValue(column)); } @SuppressWarnings({"unchecked", "RedundantCast"}) private <T> T repairClassOfValue(ColumnDesc column, T value) { if (value == null) { return null; } if (column.getDataType().getJavaClass().equals(value.getClass())) { return value; } if (column.getDataType() == ColumnType.TIME) { if (value instanceof LocalTime) { return (T) (Object) java.sql.Time.valueOf((LocalTime) value); } } else if (column.getDataType() == ColumnType.DATE) { if (value instanceof LocalDate) { return (T) (Object) java.sql.Date.valueOf((LocalDate) value); } } else if (column.getDataType() == ColumnType.TIMESTAMP) { if (value instanceof LocalDateTime) { return (T) (Object) java.sql.Timestamp.valueOf((LocalDateTime) value); } } else { Long val; if (value instanceof Long) { val = (Long) value; } else if (value instanceof Integer) { val = ((Integer) value).longValue(); } else if (value instanceof Short) { val = ((Short) value).longValue(); } else if (value instanceof Byte) { val = ((Byte) value).longValue(); } else { return value; } if (column.getDataType() == ColumnType.INTEGER) { return (T) (Object) val.intValue(); } if (column.getDataType() == ColumnType.BYTE) { return (T) (Object) val.byteValue(); } if (column.getDataType() == ColumnType.SHORT) { return (T) (Object) val.shortValue(); } } return value; } /** Set value for both rows - old and new */ public <T> void setInitialColumnValue(ColumnDesc column, T value) { value = repairClassOfValue(column, value); Object v = value; if (column.getDataType() == ColumnType.BLOB) { v = new BlobBinaryData(column.toString(), (Blob) value); } else if (column.getDataType() == ColumnType.CLOB) { v = new ClobBinaryData(column.toString(), (Clob) value); } else if (column.getDataType() == ColumnType.BYTE_ARRAY) { v = new ByteArrayBinaryData(column.toString(), (byte[]) value); } else if (column.getDataType() == ColumnType.BIT_ARRAY) { v = new BitArrayBinaryData(column.toString(), (byte[]) value); } oldValues[column.getPosition() - 1] = v; setPropertyValue(column, v); } /** Load initial column value from rs */ public void loadInitialColumnValue(ColumnDesc columnDesc, ResultSet rs) throws SQLException { Object val; if (columnDesc.getDataType() == ColumnType.BIT) { val = rs.getBoolean(columnDesc.getPosition()); if (Boolean.TRUE.equals(val)) { val = (byte) 1; } else if (Boolean.FALSE.equals(val)) { val = (byte) 0; } } else if (columnDesc.getDataType() == ColumnType.BIT_ARRAY) { val = rs.getBytes(columnDesc.getPosition()); } else { val = rs.getObject(columnDesc.getPosition()); } setInitialColumnValue(columnDesc, val); } /** Return initial value of column */ @SuppressWarnings("unchecked") public <T> T getInitialColumnValue(ColumnDesc column) { return (T) oldValues[column.getPosition() - 1]; } /** Return set value for given column */ public <T> void setColumnValue(ColumnDesc column, T value) { value = repairClassOfValue(column, value); if (AbstractHelper.nullEquals(oldValues[column.getPosition() - 1], value)) { return; } if (column.getDataType() == ColumnType.ARRAY) { LOG.warn("The editing of ARRAY isn't implemented yet"); return; } if (value instanceof SingleSelectionModel) { throw new ClassCastException("The value of column can't be selection model type."); } setPropertyValue(column, value); if (RowDescState.LOADED == state && !AbstractHelper.nullEquals(getColumnValue(column), oldValues[column.getPosition() - 1])) { this.setState(RowDescState.CHANGED); } else if (state == RowDescState.CHANGED) { boolean noChanged = true; for (int i = 0; i < oldValues.length; i++) { noChanged = noChanged && AbstractHelper.nullEquals(newValues[i].getValue(), oldValues[i]); } if (noChanged) { setState(RowDescState.LOADED); } } } /** True if value in column is NULL */ public boolean isColumnNull(ColumnDesc column) { Object o = getColumnValue(column); return o == null || o instanceof BinaryData && ((BinaryData) o).isNull(); } @Override public boolean equals(Object o) { if (o == null) { return false; } if (!(o instanceof RowDesc)) { return false; } RowDesc sqr = (RowDesc) o; if (id != null) { return id.equals(sqr.getId()); } else if (sqr.getId() != null) { return false; } if (oldValues == null) { return sqr.oldValues == null; } else if (sqr.oldValues == null) { return false; } return Arrays.equals(oldValues, sqr.oldValues); } @Override public int hashCode() { if (id != null) { return id.hashCode(); } if (oldValues == null) { return 0; } int result = 1; int primeI = 0; for (Object v : oldValues) { if (primeI >= PRIMES.length) { primeI = 0; } result *= PRIMES[primeI]; if (v != null) { result += v.hashCode(); } } return result; } @SuppressWarnings("CloneDoesntCallSuperClone") @Override public RowDesc clone() { RowDesc result = new RowDesc(metaData, state); for (ColumnDesc columnDesc : metaData.getColumns()) { result.setInitialColumnValue(columnDesc, oldValues[columnDesc.getPosition() - 1]); result.setColumnValue(columnDesc, getColumnValue(columnDesc)); } return result; } @SuppressWarnings("unchecked") private <T> void setPropertyValue(@Nonnull ColumnDesc columnDesc, T value) { ObservableValue<T> ov = newValues[columnDesc.getPosition() - 1]; if (ov instanceof BooleanProperty) { ((BooleanProperty) ov).setValue(Boolean.TRUE.equals(value)); } else if (ov instanceof StringProperty) { ((StringProperty) ov).setValue(columnDesc.getStringConverter().toString(value)); } else if (ov instanceof SimpleLocalDateProperty) { final java.sql.Date date; if (value == null) { date = null; } else if (value instanceof LocalDate) { date = java.sql.Date.valueOf((LocalDate) value); } else if (value instanceof java.sql.Date) { date = (java.sql.Date) value; } else { date = new java.sql.Date(((java.util.Date) value).getTime()); } ((SimpleLocalDateProperty) ov).setDate(date); } else if (ov instanceof SimpleDateProperty) { final java.sql.Date date; if (value == null) { date = null; } else if (value instanceof LocalDate) { date = java.sql.Date.valueOf((LocalDate) value); } else if (value instanceof java.sql.Date) { date = (java.sql.Date) value; } else { date = new java.sql.Date(((java.util.Date) value).getTime()); } ((SimpleDateProperty) ov).setValue(date); } else if (ov instanceof SimpleLocalTimeProperty) { final java.sql.Time time; if (value == null) { time = null; } else if (value instanceof LocalTime) { time = java.sql.Time.valueOf((LocalTime) value); } else if (value instanceof java.sql.Time) { time = (java.sql.Time) value; } else { time = new java.sql.Time(((java.util.Date) value).getTime()); } ((SimpleLocalTimeProperty) ov).setTime(time); } else if (ov instanceof SimpleLocalDateTimeProperty) { final java.sql.Timestamp timestamp; if (value == null) { timestamp = null; } else if (value instanceof LocalDateTime) { timestamp = java.sql.Timestamp.valueOf((LocalDateTime) value); } else if (value instanceof java.sql.Timestamp) { timestamp = (java.sql.Timestamp) value; } else { timestamp = new java.sql.Timestamp(((java.util.Date) value).getTime()); } ((SimpleLocalDateTimeProperty) ov).setTimestamp(timestamp); } else if (ov instanceof ObjectProperty) { ((ObjectProperty<T>) ov).setValue(value); } } @SuppressWarnings("unchecked") private <T> ObservableValue<T> createObjectProperty(@Nonnull ColumnDesc columnDesc) { switch (columnDesc.getDataType()) { case BOOLEAN: return (ObservableValue<T>) new SimpleBooleanProperty(null, null); case BYTE: case SHORT: case LONG: case INTEGER: case FLOAT: case DOUBLE: case DECIMAL: return new SimpleObjectProperty<>(); case DATE: return (ObservableValue<T>) new SimpleLocalDateProperty(); case TIMESTAMP: return (ObservableValue<T>) new SimpleLocalDateTimeProperty(); case TIME: return (ObservableValue<T>) new SimpleLocalTimeProperty(); case STRING: return (ObservableValue<T>) new SimpleStringProperty(); case BYTE_ARRAY: case CLOB: case BLOB: return (ObservableValue<T>) new SimpleObjectProperty<>(); default: return (ObservableValue<T>) new SimpleObjectProperty<>(); } } public ObservableValue valueProperty(@Nonnull ColumnDesc columnDesc) { return newValues[columnDesc.getPosition() - 1]; } /** return true if value in column was changed */ public boolean isColumnChanged(ColumnDesc columnDesc) { return !AbstractHelper.nullEquals(oldValues[columnDesc.getPosition() - 1], newValues[columnDesc.getPosition() - 1]); } /** Insert into prepared statement initial value from current column * @param columnDesc column which values is inserted * @param ps prepared statement to which is data write * @param position position where are values inserted * @throws SQLException prepare statement can throw exception */ public final void putInitialValueToPS(ColumnDesc columnDesc, PreparedStatement ps, int position) throws SQLException { putToPS(columnDesc, getInitialColumnValue(columnDesc), ps, position); } /** Insert into prepared statement value from current column * @param columnDesc column which values is inserted * @param ps prepared statement to which is data write * @param position position where are values inserted * @throws SQLException prepare statement can throw exception */ public final void putValueToPS(ColumnDesc columnDesc, PreparedStatement ps, int position) throws SQLException { putToPS(columnDesc, getColumnValue(columnDesc), ps, position); } @SuppressWarnings("ConstantConditions") private <T> void putToPS(ColumnDesc columnDesc, T value, PreparedStatement ps, int position) throws SQLException { if (value == null) { ps.setObject(position, null); return; } BinaryData bd = value instanceof BinaryData ? (BinaryData) value : null; switch (columnDesc.getDataType()) { case STRING: ps.setString(position, (String) value); break; case BOOLEAN: ps.setBoolean(position, (Boolean) value); break; case TIMESTAMP: ps.setTimestamp(position, (Timestamp) value); break; case DATE: ps.setDate(position, (Date) value); break; case TIME: ps.setTime(position, (Time) value); break; case BYTE: ps.setByte(position, (Byte) value); break; case SHORT: ps.setShort(position, (Short) value); break; case INTEGER: ps.setInt(position, (Integer) value); break; case LONG: ps.setLong(position, (Long) value); break; case FLOAT: ps.setFloat(position, (Float) value); break; case DOUBLE: ps.setDouble(position, (Double) value); break; case DECIMAL: ps.setBigDecimal(position, (BigDecimal) value); break; case UUID: ps.setBytes(position, AbstractHelper.uuidToByteArray((UUID) value)); break; case ARRAY: throw new UnsupportedOperationException("The saving changes in ARRAY isn't supported."); // ps.setArray(position, (Array) value); break; // FIXME the value isn't in type java.sql.Array case BYTE_ARRAY: if (bd == null || bd.isNull()) { ps.setBytes(position, null); } else { try { ps.setBytes(position, IOUtils.toByteArray(bd.getInputStream())); } catch (IOException e) { throw new SQLException(e); } } break; case CLOB: if (bd == null || bd.isNull()) { ps.setNull(position, Types.CLOB); } else { ps.setClob(position, bd.getReader()); } break; case BLOB: if (bd == null || bd.isNull()) { ps.setNull(position, Types.BLOB); } else { ps.setBlob(position, bd.getInputStream()); } break; case OBJECT: ps.setObject(position, value); } } }
package humanize.spi.context; import static humanize.util.Constants.EMPTY; import static humanize.util.Constants.SPACE; import humanize.spi.MessageFormat; import humanize.spi.cache.CacheProvider; import humanize.text.MaskFormat; import humanize.time.PrettyTimeFormat; import humanize.util.UTF8Control; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.Locale; import java.util.ResourceBundle; import java.util.ServiceLoader; import java.util.concurrent.Callable; /** * Default implementation of {@link Context}. * * @author mfornos * */ public class DefaultContext implements Context, StandardContext { private static final String BUNDLE_LOCATION = "i18n.Humanize"; private static final String ORDINAL_SUFFIXES = "ordinal.suffixes"; private static final String TIME_SUFFIXES = "time.suffixes"; private static final String CURRENCY = "currency"; private static final String DECIMAL = "decimal"; private static final String NUMBER = "number"; private static final String DIGITS = "digits"; private static final String PERCENT = "percent"; private static final String DATE_FORMAT = "date"; private static final String DATE_TIME_FORMAT = "date.time"; private static final String SIMPLE_DATE = "simple.date"; private static final String PRETTY_TIME = "pretty.time"; private static final String MASK = "mask"; private final static CacheProvider sharedCache = loadCacheProvider(); private static CacheProvider loadCacheProvider() { ServiceLoader<CacheProvider> ldr = ServiceLoader.load(CacheProvider.class); for (CacheProvider provider : ldr) { return provider; } throw new RuntimeException("No CacheProvider was found"); } private final CacheProvider localCache = loadCacheProvider(); private Locale locale; public DefaultContext() { this(Locale.getDefault()); } public DefaultContext(Locale locale) { setLocale(locale); } @Override public String digitStrings(int index) { return getStringByIndex(DIGITS, index); } @Override public String formatDate(int style, Date value) { return getDateFormat(style).format(value); } @Override public String formatDateTime(Date date) { return getDateTimeFormat().format(date); } @Override public String formatDateTime(int dateStyle, int timeStyle, Date date) { return getDateTimeFormat(dateStyle, timeStyle).format(date); } @Override public String formatDecimal(Number value) { return getNumberFormat().format(value); } @Override public String formatMessage(String key, Object... args) { MessageFormat fmt = getMessageFormat(); fmt.applyPattern(getBundle().getString(key)); return fmt.render(args); } @Override public String formatRelativeDate(Date reference, Date duration) { return getPrettyTimeFormat().format(reference, duration); } @Override public String formatRelativeDate(Date reference, Date duration, long precision) { return getPrettyTimeFormat().format(reference, duration, precision); } @Override public ResourceBundle getBundle() { return sharedCache.getBundle(locale, new Callable<ResourceBundle>() { @Override public ResourceBundle call() throws Exception { return ResourceBundle.getBundle(BUNDLE_LOCATION, locale, new UTF8Control()); } }); } @Override public DecimalFormat getCurrencyFormat() { return sharedCache.getFormat(CURRENCY, locale, new Callable<DecimalFormat>() { @Override public DecimalFormat call() throws Exception { return (DecimalFormat) NumberFormat.getCurrencyInstance(locale); } }); } @Override public DateFormat getDateFormat(final int style) { String name = DATE_FORMAT + style; return localCache.getFormat(name, locale, new Callable<DateFormat>() { @Override public DateFormat call() throws Exception { return DateFormat.getDateInstance(style, locale); } }); } @Override public DateFormat getDateFormat(final String pattern) { return localCache.getFormat(SIMPLE_DATE + pattern.hashCode(), locale, new Callable<DateFormat>() { @Override public DateFormat call() throws Exception { return new SimpleDateFormat(pattern, locale); } }); } @Override public DateFormat getDateTimeFormat() { return getDateTimeFormat(DateFormat.SHORT, DateFormat.SHORT); } @Override public DateFormat getDateTimeFormat(final int dateStyle, final int timeStyle) { String name = DATE_TIME_FORMAT + dateStyle + timeStyle; return localCache.getFormat(name, locale, new Callable<DateFormat>() { @Override public DateFormat call() throws Exception { return DateFormat.getDateTimeInstance(dateStyle, timeStyle, locale); } }); } @Override public DecimalFormat getDecimalFormat() { return localCache.getFormat(DECIMAL, locale, new Callable<DecimalFormat>() { @Override public DecimalFormat call() throws Exception { return (DecimalFormat) DecimalFormat.getInstance(locale); } }); } @Override public Locale getLocale() { return locale; } @Override public MaskFormat getMaskFormat() { return localCache.getFormat(MASK, Locale.ROOT, new Callable<MaskFormat>() { @Override public MaskFormat call() throws Exception { return new MaskFormat(""); } }); } @Override public String getMessage(String key) { return getBundle().getString(key); } @Override public MessageFormat getMessageFormat() { return new MessageFormat(EMPTY, locale); } @Override public NumberFormat getNumberFormat() { return sharedCache.getFormat(NUMBER, locale, new Callable<NumberFormat>() { @Override public NumberFormat call() throws Exception { return NumberFormat.getInstance(locale); } }); } @Override public DecimalFormat getPercentFormat() { return sharedCache.getFormat(PERCENT, locale, new Callable<DecimalFormat>() { @Override public DecimalFormat call() throws Exception { return (DecimalFormat) NumberFormat.getPercentInstance(locale); } }); } @Override public PrettyTimeFormat getPrettyTimeFormat() { return sharedCache.getFormat(PRETTY_TIME, locale, new Callable<PrettyTimeFormat>() { @Override public PrettyTimeFormat call() throws Exception { return new PrettyTimeFormat(locale); } }); } @Override public String ordinalSuffix(int index) { return getStringByIndex(ORDINAL_SUFFIXES, index); } @Override public void setLocale(Locale locale) { this.locale = locale; } @Override public String timeSuffix(int index) { return getStringByIndex(TIME_SUFFIXES, index); } protected String getStringByIndex(final String cacheName, final int index) { return getStrings(cacheName)[index]; } protected Collection<String> getStringList(final String cacheName) { return Arrays.asList(getStrings(cacheName)); } protected String[] getStrings(final String cacheName) { return sharedCache.getStrings(cacheName, locale, new Callable<String[]>() { @Override public String[] call() throws Exception { return getBundle().getString(cacheName).split(SPACE); } }); } }
/* * Copyright (C) 2015 Google 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.google.cloud.dataflow.sdk.io.datastore; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Verify.verify; import static com.google.datastore.v1beta3.PropertyFilter.Operator.EQUAL; import static com.google.datastore.v1beta3.PropertyOrder.Direction.DESCENDING; import static com.google.datastore.v1beta3.QueryResultBatch.MoreResultsType.NOT_FINISHED; import static com.google.datastore.v1beta3.client.DatastoreHelper.makeFilter; import static com.google.datastore.v1beta3.client.DatastoreHelper.makeOrder; import static com.google.datastore.v1beta3.client.DatastoreHelper.makeUpsert; import static com.google.datastore.v1beta3.client.DatastoreHelper.makeValue; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.util.BackOff; import com.google.api.client.util.BackOffUtils; import com.google.api.client.util.Sleeper; import com.google.cloud.dataflow.sdk.annotations.Experimental; import com.google.cloud.dataflow.sdk.options.GcpOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.Flatten; import com.google.cloud.dataflow.sdk.transforms.GroupByKey; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.ParDo; import com.google.cloud.dataflow.sdk.transforms.Values; import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.transforms.display.DisplayData.Builder; import com.google.cloud.dataflow.sdk.util.AttemptBoundedExponentialBackOff; import com.google.cloud.dataflow.sdk.util.RetryHttpRequestInitializer; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PBegin; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PDone; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; import com.google.datastore.v1beta3.CommitRequest; import com.google.datastore.v1beta3.Entity; import com.google.datastore.v1beta3.EntityResult; import com.google.datastore.v1beta3.Key; import com.google.datastore.v1beta3.Key.PathElement; import com.google.datastore.v1beta3.PartitionId; import com.google.datastore.v1beta3.Query; import com.google.datastore.v1beta3.QueryResultBatch; import com.google.datastore.v1beta3.RunQueryRequest; import com.google.datastore.v1beta3.RunQueryResponse; import com.google.datastore.v1beta3.client.Datastore; import com.google.datastore.v1beta3.client.DatastoreException; import com.google.datastore.v1beta3.client.DatastoreFactory; import com.google.datastore.v1beta3.client.DatastoreHelper; import com.google.datastore.v1beta3.client.DatastoreOptions; import com.google.datastore.v1beta3.client.QuerySplitter; import com.google.protobuf.Int32Value; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; import javax.annotation.Nullable; /** * <p>{@link V1Beta3} provides an API to Read and Write {@link PCollection PCollections} of * <a href="https://developers.google.com/datastore/">Google Cloud Datastore</a> version v1beta3 * {@link Entity} objects. * * <p>This API currently requires an authentication workaround. To use {@link V1Beta3}, users * must use the {@code gcloud} command line tool to get credentials for Datastore: * <pre> * $ gcloud auth login * </pre> * * <p>To read a {@link PCollection} from a query to Datastore, use {@link V1Beta3#read} and * its methods {@link V1Beta3.Read#withProjectId} and {@link V1Beta3.Read#withQuery} to * specify the project to query and the query to read from. You can optionally provide a namespace * to query within using {@link V1Beta3.Read#withNamespace}. You could also optionally specify * how many splits you want for the query using {@link V1Beta3.Read#withNumQuerySplits}. * * <p>For example: * * <pre> {@code * // Read a query from Datastore * PipelineOptions options = PipelineOptionsFactory.fromArgs(args).create(); * Query query = ...; * String projectId = "..."; * * Pipeline p = Pipeline.create(options); * PCollection<Entity> entities = p.apply( * DatastoreIO.v1beta3().read() * .withProjectId(projectId) * .withQuery(query)); * } </pre> * * <p><b>Note:</b> Normally, a Cloud Dataflow job will read from Cloud Datastore in parallel across * many workers. However, when the {@link Query} is configured with a limit using * {@link com.google.datastore.v1beta3.Query.Builder#setLimit(Int32Value)}, then * all returned results will be read by a single Dataflow worker in order to ensure correct data. * * <p>To write a {@link PCollection} to a Datastore, use {@link V1Beta3#write}, * specifying the Cloud Datastore project to write to: * * <pre> {@code * PCollection<Entity> entities = ...; * entities.apply(DatastoreIO.v1beta3().write().withProjectId(projectId)); * p.run(); * } </pre> * * <p>{@link Entity Entities} in the {@code PCollection} to be written must have complete * {@link Key Keys}. Complete {@code Keys} specify the {@code name} and {@code id} of the * {@code Entity}, where incomplete {@code Keys} do not. A {@code namespace} other than * {@code projectId} default may be used by specifying it in the {@code Entity} {@code Keys}. * * <pre>{@code * Key.Builder keyBuilder = DatastoreHelper.makeKey(...); * keyBuilder.getPartitionIdBuilder().setNamespace(namespace); * }</pre> * * <p>{@code Entities} will be committed as upsert (update or insert) mutations. Please read * <a href="https://cloud.google.com/datastore/docs/concepts/entities">Entities, Properties, and * Keys</a> for more information about {@code Entity} keys. * * <p><h3>Permissions</h3> * Permission requirements depend on the {@code PipelineRunner} that is used to execute the * Dataflow job. Please refer to the documentation of corresponding {@code PipelineRunner}s for * more details. * * <p>Please see <a href="https://cloud.google.com/datastore/docs/activate">Cloud Datastore Sign Up * </a>for security and permission related information specific to Datastore. * * @see com.google.cloud.dataflow.sdk.runners.PipelineRunner */ @Experimental(Experimental.Kind.SOURCE_SINK) public class V1Beta3 { // A package-private constructor to prevent direct instantiation from outside of this package V1Beta3() {} /** * Datastore has a limit of 500 mutations per batch operation, so we flush * changes to Datastore every 500 entities. */ @VisibleForTesting static final int DATASTORE_BATCH_UPDATE_LIMIT = 500; /** * Returns an empty {@link V1Beta3.Read} builder. Configure the source {@code projectId}, * {@code query}, and optionally {@code namespace} and {@code numQuerySplits} using * {@link V1Beta3.Read#withProjectId}, {@link V1Beta3.Read#withQuery}, * {@link V1Beta3.Read#withNamespace}, {@link V1Beta3.Read#withNumQuerySplits}. */ public V1Beta3.Read read() { return new V1Beta3.Read(null, null, null, 0); } /** * A {@link PTransform} that reads the result rows of a Datastore query as {@code Entity} * objects. * * @see DatastoreIO */ public static class Read extends PTransform<PBegin, PCollection<Entity>> { private static final Logger LOG = LoggerFactory.getLogger(Read.class); /** An upper bound on the number of splits for a query. */ public static final int NUM_QUERY_SPLITS_MAX = 50000; /** A lower bound on the number of splits for a query. */ static final int NUM_QUERY_SPLITS_MIN = 12; /** Default bundle size of 64MB. */ static final long DEFAULT_BUNDLE_SIZE_BYTES = 64 * 1024 * 1024; /** * Maximum number of results to request per query. * * <p>Must be set, or it may result in an I/O error when querying Cloud Datastore. */ static final int QUERY_BATCH_LIMIT = 500; @Nullable private final String projectId; @Nullable private final Query query; @Nullable private final String namespace; private final int numQuerySplits; /** * Computes the number of splits to be performed on the given query by querying the estimated * size from Datastore. */ static int getEstimatedNumSplits(Datastore datastore, Query query, @Nullable String namespace) { int numSplits; try { long estimatedSizeBytes = getEstimatedSizeBytes(datastore, query, namespace); numSplits = (int) Math.min(NUM_QUERY_SPLITS_MAX, Math.round(((double) estimatedSizeBytes) / DEFAULT_BUNDLE_SIZE_BYTES)); } catch (Exception e) { LOG.warn("Failed the fetch estimatedSizeBytes for query: {}", query, e); // Fallback in case estimated size is unavailable. numSplits = NUM_QUERY_SPLITS_MIN; } return Math.max(numSplits, NUM_QUERY_SPLITS_MIN); } /** * Get the estimated size of the data returned by the given query. * * <p>Datastore provides no way to get a good estimate of how large the result of a query * entity kind being queried, using the __Stat_Kind__ system table, assuming exactly 1 kind * is specified in the query. * * <p>See https://cloud.google.com/datastore/docs/concepts/stats. */ static long getEstimatedSizeBytes(Datastore datastore, Query query, @Nullable String namespace) throws DatastoreException { String ourKind = query.getKind(0).getName(); Query.Builder queryBuilder = Query.newBuilder(); if (namespace == null) { queryBuilder.addKindBuilder().setName("__Stat_Kind__"); } else { queryBuilder.addKindBuilder().setName("__Ns_Stat_Kind__"); } queryBuilder.setFilter(makeFilter("kind_name", EQUAL, makeValue(ourKind).build())); // Get the latest statistics queryBuilder.addOrder(makeOrder("timestamp", DESCENDING)); queryBuilder.setLimit(Int32Value.newBuilder().setValue(1)); RunQueryRequest request = makeRequest(queryBuilder.build(), namespace); long now = System.currentTimeMillis(); RunQueryResponse response = datastore.runQuery(request); LOG.debug("Query for per-kind statistics took {}ms", System.currentTimeMillis() - now); QueryResultBatch batch = response.getBatch(); if (batch.getEntityResultsCount() == 0) { throw new NoSuchElementException( "Datastore statistics for kind " + ourKind + " unavailable"); } Entity entity = batch.getEntityResults(0).getEntity(); return entity.getProperties().get("entity_bytes").getIntegerValue(); } /** Builds a {@link RunQueryRequest} from the {@code query} and {@code namespace}. */ static RunQueryRequest makeRequest(Query query, @Nullable String namespace) { RunQueryRequest.Builder requestBuilder = RunQueryRequest.newBuilder().setQuery(query); if (namespace != null) { requestBuilder.getPartitionIdBuilder().setNamespaceId(namespace); } return requestBuilder.build(); } /** * A helper function to get the split queries, taking into account the optional * {@code namespace}. */ private static List<Query> splitQuery(Query query, @Nullable String namespace, Datastore datastore, QuerySplitter querySplitter, int numSplits) throws DatastoreException { // If namespace is set, include it in the split request so splits are calculated accordingly. PartitionId.Builder partitionBuilder = PartitionId.newBuilder(); if (namespace != null) { partitionBuilder.setNamespaceId(namespace); } return querySplitter.getSplits(query, partitionBuilder.build(), numSplits, datastore); } /** * Note that only {@code namespace} is really {@code @Nullable}. The other parameters may be * {@code null} as a matter of build order, but if they are {@code null} at instantiation time, * an error will be thrown. */ private Read(@Nullable String projectId, @Nullable Query query, @Nullable String namespace, int numQuerySplits) { this.projectId = projectId; this.query = query; this.namespace = namespace; this.numQuerySplits = numQuerySplits; } /** * Returns a new {@link V1Beta3.Read} that reads from the Datastore for the specified project. */ public V1Beta3.Read withProjectId(String projectId) { checkNotNull(projectId, "projectId"); return new V1Beta3.Read(projectId, query, namespace, numQuerySplits); } /** * Returns a new {@link V1Beta3.Read} that reads the results of the specified query. * * <p><b>Note:</b> Normally, {@code DatastoreIO} will read from Cloud Datastore in parallel * across many workers. However, when the {@link Query} is configured with a limit using * {@link Query.Builder#setLimit}, then all results will be read by a single worker in order * to ensure correct results. */ public V1Beta3.Read withQuery(Query query) { checkNotNull(query, "query"); checkArgument(!query.hasLimit() || query.getLimit().getValue() > 0, "Invalid query limit %s: must be positive", query.getLimit().getValue()); return new V1Beta3.Read(projectId, query, namespace, numQuerySplits); } /** * Returns a new {@link V1Beta3.Read} that reads from the given namespace. */ public V1Beta3.Read withNamespace(String namespace) { return new V1Beta3.Read(projectId, query, namespace, numQuerySplits); } /** * Returns a new {@link V1Beta3.Read} that reads by splitting the given {@code query} into * {@code numQuerySplits}. * * <p>The semantics for the query splitting is defined below: * <ul> * <li>Any value less than or equal to 0 will be ignored, and the number of splits will be * chosen dynamically at runtime based on the query data size. * <li>Any value greater than {@link Read#NUM_QUERY_SPLITS_MAX} will be capped at * {@code NUM_QUERY_SPLITS_MAX}. * <li>If the {@code query} has a user limit set, then {@code numQuerySplits} will be * ignored and no split will be performed. * <li>Under certain cases Cloud Datastore is unable to split query to the requested number of * splits. In such cases we just use whatever the Datastore returns. * </ul> */ public V1Beta3.Read withNumQuerySplits(int numQuerySplits) { return new V1Beta3.Read(projectId, query, namespace, Math.min(Math.max(numQuerySplits, 0), NUM_QUERY_SPLITS_MAX)); } @Nullable public Query getQuery() { return query; } @Nullable public String getProjectId() { return projectId; } @Nullable public String getNamespace() { return namespace; } /** * {@inheritDoc} */ @Override public PCollection<Entity> apply(PBegin input) { V1Beta3Options v1Beta3Options = V1Beta3Options.from(getProjectId(), getQuery(), getNamespace()); /* * This composite transform involves the following steps: * 1. Create a singleton of the user provided {@code query} and apply a {@link ParDo} that * splits the query into {@code numQuerySplits} and assign each split query a unique * {@code Integer} as the key. The resulting output is of the type * {@code PCollection<KV<Integer, Query>>}. * * If the value of {@code numQuerySplits} is less than or equal to 0, then the number of * splits will be computed dynamically based on the size of the data for the {@code query}. * * 2. The resulting {@code PCollection} is sharded using a {@link GroupByKey} operation. The * queries are extracted from they {@code KV<Integer, Iterable<Query>>} and flattened to * output a {@code PCollection<Query>}. * * 3. In the third step, a {@code ParDo} reads entities for each query and outputs * a {@code PCollection<Entity>}. */ PCollection<KV<Integer, Query>> queries = input .apply(Create.of(query)) .apply(ParDo.of(new SplitQueryFn(v1Beta3Options, numQuerySplits))); PCollection<Query> shardedQueries = queries .apply(GroupByKey.<Integer, Query>create()) .apply(Values.<Iterable<Query>>create()) .apply(Flatten.<Query>iterables()); PCollection<Entity> entities = shardedQueries .apply(ParDo.of(new ReadFn(v1Beta3Options))); return entities; } @Override public void validate(PBegin input) { checkNotNull(projectId, "projectId"); checkNotNull(query, "query"); } @Override public void populateDisplayData(DisplayData.Builder builder) { super.populateDisplayData(builder); builder .addIfNotNull(DisplayData.item("projectId", projectId) .withLabel("ProjectId")) .addIfNotNull(DisplayData.item("namespace", namespace) .withLabel("Namespace")) .addIfNotNull(DisplayData.item("query", query.toString()) .withLabel("Query")); } @Override public String toString() { return MoreObjects.toStringHelper(getClass()) .add("projectId", projectId) .add("query", query) .add("namespace", namespace) .toString(); } /** * A class for v1beta3 Datastore related options. */ @VisibleForTesting static class V1Beta3Options implements Serializable { private final Query query; private final String projectId; @Nullable private final String namespace; private V1Beta3Options(String projectId, Query query, @Nullable String namespace) { this.projectId = checkNotNull(projectId, "projectId"); this.query = checkNotNull(query, "query"); this.namespace = namespace; } public static V1Beta3Options from(String projectId, Query query, @Nullable String namespace) { return new V1Beta3Options(projectId, query, namespace); } public Query getQuery() { return query; } public String getProjectId() { return projectId; } @Nullable public String getNamespace() { return namespace; } } /** * A {@link DoFn} that splits a given query into multiple sub-queries, assigns them unique keys * and outputs them as {@link KV}. */ @VisibleForTesting static class SplitQueryFn extends DoFn<Query, KV<Integer, Query>> { private final V1Beta3Options options; // number of splits to make for a given query private final int numSplits; private final V1Beta3DatastoreFactory datastoreFactory; // Datastore client private transient Datastore datastore; // Query splitter private transient QuerySplitter querySplitter; public SplitQueryFn(V1Beta3Options options, int numSplits) { this(options, numSplits, new V1Beta3DatastoreFactory()); } @VisibleForTesting SplitQueryFn(V1Beta3Options options, int numSplits, V1Beta3DatastoreFactory datastoreFactory) { this.options = options; this.numSplits = numSplits; this.datastoreFactory = datastoreFactory; } @Override public void startBundle(Context c) throws Exception { datastore = datastoreFactory.getDatastore(c.getPipelineOptions(), options.projectId); querySplitter = datastoreFactory.getQuerySplitter(); } @Override public void processElement(ProcessContext c) throws Exception { int key = 1; Query query = c.element(); // If query has a user set limit, then do not split. if (query.hasLimit()) { c.output(KV.of(key, query)); return; } int estimatedNumSplits; // Compute the estimated numSplits if numSplits is not specified by the user. if (numSplits <= 0) { estimatedNumSplits = getEstimatedNumSplits(datastore, query, options.getNamespace()); } else { estimatedNumSplits = numSplits; } List<Query> querySplits; try { querySplits = splitQuery(query, options.getNamespace(), datastore, querySplitter, estimatedNumSplits); } catch (Exception e) { LOG.warn("Unable to parallelize the given query: {}", query, e); querySplits = ImmutableList.of(query); } // assign unique keys to query splits. for (Query subquery : querySplits) { c.output(KV.of(key++, subquery)); } } @Override public void populateDisplayData(Builder builder) { super.populateDisplayData(builder); builder .addIfNotNull(DisplayData.item("projectId", options.getProjectId()) .withLabel("ProjectId")) .addIfNotNull(DisplayData.item("namespace", options.getNamespace()) .withLabel("Namespace")) .addIfNotNull(DisplayData.item("query", options.getQuery().toString()) .withLabel("Query")); } } /** * A {@link DoFn} that reads entities from Datastore for each query. */ @VisibleForTesting static class ReadFn extends DoFn<Query, Entity> { private final V1Beta3Options options; private final V1Beta3DatastoreFactory datastoreFactory; // Datastore client private transient Datastore datastore; public ReadFn(V1Beta3Options options) { this(options, new V1Beta3DatastoreFactory()); } @VisibleForTesting ReadFn(V1Beta3Options options, V1Beta3DatastoreFactory datastoreFactory) { this.options = options; this.datastoreFactory = datastoreFactory; } @Override public void startBundle(Context c) throws Exception { datastore = datastoreFactory.getDatastore(c.getPipelineOptions(), options.getProjectId()); } /** Read and output entities for the given query. */ @Override public void processElement(ProcessContext context) throws Exception { Query query = context.element(); String namespace = options.getNamespace(); int userLimit = query.hasLimit() ? query.getLimit().getValue() : Integer.MAX_VALUE; boolean moreResults = true; QueryResultBatch currentBatch = null; while (moreResults) { Query.Builder queryBuilder = query.toBuilder().clone(); queryBuilder.setLimit(Int32Value.newBuilder().setValue( Math.min(userLimit, QUERY_BATCH_LIMIT))); if (currentBatch != null && !currentBatch.getEndCursor().isEmpty()) { queryBuilder.setStartCursor(currentBatch.getEndCursor()); } RunQueryRequest request = makeRequest(queryBuilder.build(), namespace); RunQueryResponse response = datastore.runQuery(request); currentBatch = response.getBatch(); // MORE_RESULTS_AFTER_LIMIT is not implemented yet: // https://groups.google.com/forum/#!topic/gcd-discuss/iNs6M1jA2Vw, so // use result count to determine if more results might exist. int numFetch = currentBatch.getEntityResultsCount(); if (query.hasLimit()) { verify(userLimit >= numFetch, "Expected userLimit %s >= numFetch %s, because query limit %s must be <= userLimit", userLimit, numFetch, query.getLimit()); userLimit -= numFetch; } // output all the entities from the current batch. for (EntityResult entityResult : currentBatch.getEntityResultsList()) { context.output(entityResult.getEntity()); } // Check if we have more entities to be read. moreResults = // User-limit does not exist (so userLimit == MAX_VALUE) and/or has not been satisfied (userLimit > 0) // All indications from the API are that there are/may be more results. && ((numFetch == QUERY_BATCH_LIMIT) || (currentBatch.getMoreResults() == NOT_FINISHED)); } } } } /** * Returns an empty {@link V1Beta3.Write} builder. Configure the destination * {@code projectId} using {@link V1Beta3.Write#withProjectId}. */ public Write write() { return new Write(null); } /** * A {@link PTransform} that writes {@link Entity} objects to Cloud Datastore. * * @see DatastoreIO */ public static class Write extends PTransform<PCollection<Entity>, PDone> { @Nullable private final String projectId; /** * Note that {@code projectId} is only {@code @Nullable} as a matter of build order, but if * it is {@code null} at instantiation time, an error will be thrown. */ public Write(@Nullable String projectId) { this.projectId = projectId; } /** * Returns a new {@link Write} that writes to the Cloud Datastore for the specified project. */ public Write withProjectId(String projectId) { checkNotNull(projectId, "projectId"); return new Write(projectId); } @Override public PDone apply(PCollection<Entity> input) { input.apply(ParDo.of(new DatastoreWriterFn(projectId))); return PDone.in(input.getPipeline()); } @Override public void validate(PCollection<Entity> input) { checkNotNull(projectId, "projectId"); } @Nullable public String getProjectId() { return projectId; } @Override public String toString() { return MoreObjects.toStringHelper(getClass()) .add("projectId", projectId) .toString(); } @Override public void populateDisplayData(DisplayData.Builder builder) { super.populateDisplayData(builder); builder .addIfNotNull(DisplayData.item("projectId", projectId) .withLabel("Output Project")); } } /** * A {@link DoFn} that writes {@link Entity} objects to Cloud Datastore. Entities are written in * batches, where the maximum batch size is {@link V1Beta3#DATASTORE_BATCH_UPDATE_LIMIT}. * Entities are committed as upsert mutations (either update if the key already exists, or * insert if it is a new key). If an entity does not have a complete key (i.e., it has no name * or id), the bundle will fail. * * <p>See <a * href="https://cloud.google.com/datastore/docs/concepts/entities"> * Datastore: Entities, Properties, and Keys</a> for information about entity keys and entities. * * <p>Commits are non-transactional. If a commit fails because of a conflict over an entity * group, the commit will be retried (up to {@link V1Beta3#DATASTORE_BATCH_UPDATE_LIMIT} * times). */ @VisibleForTesting static class DatastoreWriterFn extends DoFn<Entity, Void> { private static final Logger LOG = LoggerFactory.getLogger(DatastoreWriterFn.class); private final String projectId; private transient Datastore datastore; private final V1Beta3DatastoreFactory datastoreFactory; // Current batch of entities to be written. private final List<Entity> entities = new ArrayList<>(); /** * Since a bundle is written in batches, we should retry the commit of a batch in order to * prevent transient errors from causing the bundle to fail. */ private static final int MAX_RETRIES = 5; /** * Initial backoff time for exponential backoff for retry attempts. */ private static final int INITIAL_BACKOFF_MILLIS = 5000; public DatastoreWriterFn(String projectId) { this(projectId, new V1Beta3DatastoreFactory()); } @VisibleForTesting DatastoreWriterFn(String projectId, V1Beta3DatastoreFactory datastoreFactory) { this.projectId = checkNotNull(projectId, "projectId"); this.datastoreFactory = datastoreFactory; } @Override public void startBundle(Context c) { datastore = datastoreFactory.getDatastore(c.getPipelineOptions(), projectId); } @Override public void processElement(ProcessContext c) throws Exception { // Verify that the entity to write has a complete key. if (!isValidKey(c.element().getKey())) { throw new IllegalArgumentException( "Entities to be written to the Datastore must have complete keys"); } entities.add(c.element()); if (entities.size() >= V1Beta3.DATASTORE_BATCH_UPDATE_LIMIT) { flushBatch(); } } @Override public void finishBundle(Context c) throws Exception { if (entities.size() > 0) { flushBatch(); } } /** * Writes a batch of entities to Cloud Datastore. * * <p>If a commit fails, it will be retried (up to {@link DatastoreWriterFn#MAX_RETRIES} * times). All entities in the batch will be committed again, even if the commit was partially * successful. If the retry limit is exceeded, the last exception from the Datastore will be * thrown. * * @throws DatastoreException if the commit fails or IOException or InterruptedException if * backing off between retries fails. */ private void flushBatch() throws DatastoreException, IOException, InterruptedException { LOG.debug("Writing batch of {} entities", entities.size()); Sleeper sleeper = Sleeper.DEFAULT; BackOff backoff = new AttemptBoundedExponentialBackOff(MAX_RETRIES, INITIAL_BACKOFF_MILLIS); while (true) { // Batch upsert entities. try { CommitRequest.Builder commitRequest = CommitRequest.newBuilder(); for (Entity entity: entities) { commitRequest.addMutations(makeUpsert(entity)); } commitRequest.setMode(CommitRequest.Mode.NON_TRANSACTIONAL); datastore.commit(commitRequest.build()); // Break if the commit threw no exception. break; } catch (DatastoreException exception) { // Only log the code and message for potentially-transient errors. The entire exception // will be propagated upon the last retry. LOG.error("Error writing to the Datastore ({}): {}", exception.getCode(), exception.getMessage()); if (!BackOffUtils.next(sleeper, backoff)) { LOG.error("Aborting after {} retries.", MAX_RETRIES); throw exception; } } } LOG.debug("Successfully wrote {} entities", entities.size()); entities.clear(); } @Override public void populateDisplayData(Builder builder) { super.populateDisplayData(builder); builder .addIfNotNull(DisplayData.item("projectId", projectId) .withLabel("Output Project")); } } /** * Returns true if a Datastore key is complete. A key is complete if its last element * has either an id or a name. */ static boolean isValidKey(Key key) { List<PathElement> elementList = key.getPathList(); if (elementList.isEmpty()) { return false; } PathElement lastElement = elementList.get(elementList.size() - 1); return (lastElement.getId() != 0 || !lastElement.getName().isEmpty()); } /** * A wrapper factory class for Datastore singleton classes {@link DatastoreFactory} and * {@link QuerySplitter} * * <p>{@link DatastoreFactory} and {@link QuerySplitter} are not java serializable, hence * wrapping them under this class, which implements {@link Serializable}. */ @VisibleForTesting static class V1Beta3DatastoreFactory implements Serializable { /** * Builds a Datastore client for the given pipeline options and project. */ public Datastore getDatastore(PipelineOptions pipelineOptions, String projectId) { DatastoreOptions.Builder builder = new DatastoreOptions.Builder() .projectId(projectId) .initializer( new RetryHttpRequestInitializer() ); Credential credential = pipelineOptions.as(GcpOptions.class).getGcpCredential(); if (credential != null) { builder.credential(credential); } return DatastoreFactory.get().create(builder.build()); } /** * Builds a Datastore {@link QuerySplitter}. */ public QuerySplitter getQuerySplitter() { return DatastoreHelper.getQuerySplitter(); } } }
/* * Copyright 2018 APPNEXUS 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.appnexus.opensdk; import com.appnexus.opensdk.mar.MultiAdRequestListener; import com.appnexus.opensdk.mocks.MockDefaultExecutorSupplier; import com.appnexus.opensdk.shadows.ShadowAsyncTaskNoExecutor; import com.appnexus.opensdk.shadows.ShadowCustomWebView; import com.appnexus.opensdk.shadows.ShadowSettings; import com.appnexus.opensdk.shadows.ShadowWebSettings; import com.appnexus.opensdk.util.MockServerResponses; import com.squareup.okhttp.mockwebserver.MockResponse; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import static android.os.Looper.getMainLooper; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import static org.robolectric.Shadows.shadowOf; @Config(sdk = 21, shadows = {ShadowAsyncTaskNoExecutor.class, ShadowCustomWebView.class, ShadowWebSettings.class, ShadowSettings.class}) @RunWith(RobolectricTestRunner.class) public class ANMultiAdRequestLoadTests extends BaseViewAdTest { ANMultiAdRequest anMultiAdRequest; private boolean secondMarCompleted, secondMarFailed; @Override public void setup() { super.setup(); anMultiAdRequest = new ANMultiAdRequest(activity, 0, 1234, this); anMultiAdRequest.addAdUnit(bannerAdView); anMultiAdRequest.addAdUnit(interstitialAdView); } @Override public void tearDown() { anMultiAdRequest = null; shadowOf(getMainLooper()).quitUnchecked(); super.tearDown(); } //This verifies that the AsyncTask for Request is being executed on the Correct Executor. @Test public void testRequestExecutorForBackgroundTasks() { SDKSettings.setExternalExecutor(MockDefaultExecutorSupplier.getInstance().forBackgroundTasks()); assertNotSame(ShadowAsyncTaskNoExecutor.getExecutor(), MockDefaultExecutorSupplier.getInstance().forBackgroundTasks()); anMultiAdRequest.load(); Robolectric.flushBackgroundThreadScheduler(); Robolectric.flushForegroundThreadScheduler(); assertEquals(ShadowAsyncTaskNoExecutor.getExecutor(), MockDefaultExecutorSupplier.getInstance().forBackgroundTasks()); } //MAR Success @Test public void testMARSuccessWithSingleInitializationMethod() { server.enqueue(new MockResponse().setResponseCode(200).setBody(MockServerResponses.marSuccess())); assertFalse(marCompleted); executeMARRequest(); assertTrue(marCompleted); } @Test public void testMARSuccessWithConvenience() { server.enqueue(new MockResponse().setResponseCode(200).setBody(MockServerResponses.marSuccess())); assertFalse(marCompleted); initMARWithConvenience(); assertTrue(marCompleted); } @Test public void testMARWithSingleInitializationMethodAndStop() { server.enqueue(new MockResponse().setResponseCode(200).setBody(MockServerResponses.marSuccess())); assertFalse(marCompleted); reset(); anMultiAdRequest.load(); anMultiAdRequest.stop(); assertTrue(marFailed); } @Test public void testMARWithSingleInitializationMethodAndStopRemoveAddAndLoad() { server.enqueue(new MockResponse().setResponseCode(200).setBody(MockServerResponses.marSuccess())); assertFalse(marCompleted); reset(); anMultiAdRequest.load(); anMultiAdRequest.stop(); assertTrue(marFailed); anMultiAdRequest.removeAdUnit(interstitialAdView); InterstitialAdView interstitialAdView2 = new InterstitialAdView(activity); interstitialAdView2.setPlacementID("0"); interstitialAdView2.setAdListener(this); anMultiAdRequest.addAdUnit(interstitialAdView2); anMultiAdRequest.load(); waitForTasks(); Robolectric.flushBackgroundThreadScheduler(); Robolectric.flushForegroundThreadScheduler(); Robolectric.flushBackgroundThreadScheduler(); Robolectric.flushForegroundThreadScheduler(); assertTrue(marCompleted); } @Test public void testMARWithConvenienceAndStop() { server.enqueue(new MockResponse().setResponseCode(200).setBody(MockServerResponses.marSuccess())); assertFalse(marCompleted); reset(); BannerAdView bannerAdView = new BannerAdView(activity); bannerAdView.setPlacementID("0"); bannerAdView.setAdListener(this); bannerAdView.setAdSize(320, 50); bannerAdView.setAutoRefreshInterval(-1); InterstitialAdView interstitialAdView = new InterstitialAdView(activity); interstitialAdView.setPlacementID("0"); interstitialAdView.setAdListener(this); ANMultiAdRequest anMultiAdRequestLocal = new ANMultiAdRequest(activity, 0, 1234, this, true, bannerAdView, interstitialAdView); anMultiAdRequestLocal.stop(); assertTrue(marFailed); } @Test public void testMARWithConvenienceAndStopRemoveAddAndLoad() { server.enqueue(new MockResponse().setResponseCode(200).setBody(MockServerResponses.marSuccess())); assertFalse(marCompleted); reset(); BannerAdView bannerAdView = new BannerAdView(activity); bannerAdView.setPlacementID("0"); bannerAdView.setAdListener(this); bannerAdView.setAdSize(320, 50); bannerAdView.setAutoRefreshInterval(-1); InterstitialAdView interstitialAdView = new InterstitialAdView(activity); interstitialAdView.setPlacementID("0"); interstitialAdView.setAdListener(this); ANMultiAdRequest anMultiAdRequestLocal = new ANMultiAdRequest(activity, 0, 1234, this, true, bannerAdView, interstitialAdView); anMultiAdRequestLocal.stop(); assertTrue(marFailed); anMultiAdRequest.removeAdUnit(interstitialAdView); InterstitialAdView interstitialAdView2 = new InterstitialAdView(activity); interstitialAdView2.setPlacementID("0"); interstitialAdView2.setAdListener(this); anMultiAdRequest.addAdUnit(interstitialAdView2); anMultiAdRequest.load(); waitForTasks(); Robolectric.flushBackgroundThreadScheduler(); Robolectric.flushForegroundThreadScheduler(); Robolectric.flushBackgroundThreadScheduler(); Robolectric.flushForegroundThreadScheduler(); assertTrue(marCompleted); } //MAR Success With NoBid Response for AdUnits @Test public void testMARSuccessAdUnitNoBid() { server.enqueue(new MockResponse().setResponseCode(200).setBody(MockServerResponses.marSuccessAdUnitNoBid())); assertFalse(marCompleted); executeMARRequest(); assertTrue(marCompleted); } //MAR Failure with empty response @Test public void testMARFailure() { server.enqueue(new MockResponse().setResponseCode(200).setBody("")); assertFalse(marFailed); executeMARRequest(); assertTrue(marFailed); } //MAR Success with the AdListener success calls for the AdUnits @Test public void testMARSuccessWithAdListenerLoad() { server.enqueue(new MockResponse().setResponseCode(200).setBody(MockServerResponses.marSuccess())); assertFalse(marCompleted); executeMARRequest(); assertTrue(marCompleted); Robolectric.flushBackgroundThreadScheduler(); Robolectric.flushForegroundThreadScheduler(); Robolectric.flushBackgroundThreadScheduler(); Robolectric.flushForegroundThreadScheduler(); assertCallbacks(true); assertBannerAdResponse(true); assertInterstitialAdResponse(true); } //MAR Success with the AdListener failure calls for the AdUnits @Test public void testMARSuccessAdUnitNoBidWithAdListenerFailure() { server.enqueue(new MockResponse().setResponseCode(200).setBody(MockServerResponses.marSuccessAdUnitNoBid())); assertFalse(marFailed); assertFalse(marCompleted); executeMARRequest(); assertTrue(marCompleted); assertFalse(marFailed); Robolectric.flushBackgroundThreadScheduler(); Robolectric.flushForegroundThreadScheduler(); assertCallbacks(false); assertBannerAdResponse(false); assertInterstitialAdResponse(false); } //MAR Success with the AdListener success calls for the AdUnits @Test public void testMARSuccessWithAdListenerLazyLoad() { bannerAdView.enableLazyLoad(); server.enqueue(new MockResponse().setResponseCode(200).setBody(MockServerResponses.marSuccess())); assertFalse(marCompleted); executeMARRequest(); assertTrue(marCompleted); Robolectric.flushBackgroundThreadScheduler(); Robolectric.flushForegroundThreadScheduler(); Robolectric.flushBackgroundThreadScheduler(); Robolectric.flushForegroundThreadScheduler(); assertTrue(adLazyLoaded); assertInterstitialAdResponse(true); assertBannerAdResponse(false); bannerAdView.loadLazyAd(); Robolectric.flushBackgroundThreadScheduler(); Robolectric.flushForegroundThreadScheduler(); Robolectric.flushBackgroundThreadScheduler(); Robolectric.flushForegroundThreadScheduler(); assertBannerAdResponse(true); } //MAR Success with the AdListener success calls for the AdUnits @Test public void testMARSuccessWithAdListenerLazyLoadBeforeAndAfterInititializingMARRequest() { bannerAdView.enableLazyLoad(); server.enqueue(new MockResponse().setResponseCode(200).setBody(MockServerResponses.marSuccess())); assertFalse(marCompleted); assertFalse(bannerAdView.loadLazyAd()); executeMARRequest(); assertTrue(marCompleted); Robolectric.flushBackgroundThreadScheduler(); Robolectric.flushForegroundThreadScheduler(); Robolectric.flushBackgroundThreadScheduler(); Robolectric.flushForegroundThreadScheduler(); assertTrue(adLazyLoaded); assertInterstitialAdResponse(true); assertBannerAdResponse(false); assertTrue(bannerAdView.loadLazyAd()); Robolectric.flushBackgroundThreadScheduler(); Robolectric.flushForegroundThreadScheduler(); Robolectric.flushBackgroundThreadScheduler(); Robolectric.flushForegroundThreadScheduler(); assertBannerAdResponse(true); } //MAR Success with Success Reload @Test public void testMARSuccessAndReloadSuccess() { server.enqueue(new MockResponse().setResponseCode(200).setBody(MockServerResponses.marSuccess())); server.enqueue(new MockResponse().setResponseCode(200).setBody(MockServerResponses.marSuccess())); assertFalse(marFailed); assertFalse(marCompleted); executeMARRequest(); assertTrue(marCompleted); assertFalse(marFailed); executeMARRequest(); assertTrue(marCompleted); assertFalse(marFailed); } //MAR Success with Success Reload @Test public void testMARSuccessAndReloadSuccessWithBannerPlacementChanges() { server.enqueue(new MockResponse().setResponseCode(200).setBody(MockServerResponses.marSuccess())); server.enqueue(new MockResponse().setResponseCode(200).setBody(MockServerResponses.marSuccess())); assertFalse(marFailed); assertFalse(marCompleted); executeMARRequest(); assertTrue(marCompleted); assertFalse(marFailed); bannerAdView.setPlacementID("123456"); executeMARRequest(); assertTrue(marCompleted); assertFalse(marFailed); } //MAR Success with Failure Reload @Test public void testMARSuccessAndReloadFailure() { server.enqueue(new MockResponse().setResponseCode(200).setBody(MockServerResponses.marSuccess())); server.enqueue(new MockResponse().setResponseCode(200).setBody("")); assertFalse(marFailed); assertFalse(marCompleted); executeMARRequest(); assertTrue(marCompleted); assertFalse(marFailed); //Reload executeMARRequest(); assertTrue(marFailed); assertFalse(marCompleted); } //MAR Failure with Success Reload @Test public void testMARFailureAndReloadSuccess() { server.enqueue(new MockResponse().setResponseCode(200).setBody("")); server.enqueue(new MockResponse().setResponseCode(200).setBody(MockServerResponses.marSuccess())); assertFalse(marFailed); assertFalse(marCompleted); executeMARRequest(); assertTrue(marFailed); assertFalse(marCompleted); //Reload waitForTasks(); Robolectric.flushBackgroundThreadScheduler(); Robolectric.flushForegroundThreadScheduler(); executeMARRequest(); assertTrue(marCompleted); assertFalse(marFailed); } //MAR Success with No bid response for AdUnits with AdUnits Success Reload @Test public void testMARSuccessAdUnitNoBidWithAdListenerFailureReloadSuccess() { server.enqueue(new MockResponse().setResponseCode(200).setBody(MockServerResponses.marSuccessAdUnitNoBid())); assertFalse(marCompleted); executeMARRequest(); assertTrue(marCompleted); Robolectric.flushBackgroundThreadScheduler(); Robolectric.flushForegroundThreadScheduler(); assertCallbacks(false); assertBannerAdResponse(false); assertInterstitialAdResponse(false); //Reload waitForTasks(); Robolectric.flushBackgroundThreadScheduler(); Robolectric.flushForegroundThreadScheduler(); server.enqueue(new MockResponse().setResponseCode(200).setBody(MockServerResponses.marSuccess())); executeMARRequest(); assertTrue(marCompleted); Robolectric.flushBackgroundThreadScheduler(); Robolectric.flushForegroundThreadScheduler(); assertCallbacks(true); assertBannerAdResponse(true); assertInterstitialAdResponse(true); } //MAR Success with an attached BannerAdView request @Test public void testMARSuccessAdUnitNoBidWithBannerRequest() { server.enqueue(new MockResponse().setResponseCode(200).setBody(MockServerResponses.marSuccessAdUnitNoBid())); assertFalse(marCompleted); executeMARRequest(); assertTrue(marCompleted); Robolectric.flushBackgroundThreadScheduler(); Robolectric.flushForegroundThreadScheduler(); assertCallbacks(false); assertBannerAdResponse(false); assertInterstitialAdResponse(false); //Load Banner waitForTasks(); Robolectric.flushBackgroundThreadScheduler(); Robolectric.flushForegroundThreadScheduler(); server.enqueue(new MockResponse().setResponseCode(200).setBody(TestResponsesUT.banner())); executeBannerRequest(); assertFalse(marCompleted); assertFalse(marFailed); Robolectric.flushBackgroundThreadScheduler(); Robolectric.flushForegroundThreadScheduler(); assertCallbacks(true); assertBannerAdResponse(true); assertInterstitialAdResponse(false); } //MAR Success with an attached Interstitial request @Test public void testMARSuccessAdUnitNoBidWithInterstitialRequest() { server.enqueue(new MockResponse().setResponseCode(200).setBody(MockServerResponses.marSuccessAdUnitNoBid())); assertFalse(marCompleted); executeMARRequest(); Robolectric.flushBackgroundThreadScheduler(); Robolectric.flushForegroundThreadScheduler(); assertTrue(marCompleted); assertCallbacks(false); assertBannerAdResponse(false); assertInterstitialAdResponse(false); //Load Banner waitForTasks(); Robolectric.flushBackgroundThreadScheduler(); Robolectric.flushForegroundThreadScheduler(); server.enqueue(new MockResponse().setResponseCode(200).setBody(TestResponsesUT.banner())); executeInterstitialRequest(); assertFalse(marCompleted); assertFalse(marFailed); Robolectric.flushBackgroundThreadScheduler(); Robolectric.flushForegroundThreadScheduler(); assertCallbacks(true); assertInterstitialAdResponse(true); assertBannerAdResponse(false); } //Concurrent MAR Success @Test public void testConcurrentMARSuccess() { server.enqueue(new MockResponse().setResponseCode(200).setBody(MockServerResponses.marSuccess())); assertFalse(marCompleted); executeMARRequest(); server.enqueue(new MockResponse().setResponseCode(200).setBody(MockServerResponses.marSuccess())); executeSecondMARRequest(); assertTrue(marCompleted); assertTrue(secondMarCompleted); } @Test public void testConcurrentMARSuccessWithConvenience() { server.enqueue(new MockResponse().setResponseCode(200).setBody(MockServerResponses.marSuccess())); assertFalse(marCompleted); assertFalse(secondMarCompleted); initMARWithConvenience(); server.enqueue(new MockResponse().setResponseCode(200).setBody(MockServerResponses.marSuccess())); executeSecondMARRequest(); assertTrue(marCompleted); assertTrue(secondMarCompleted); } private void initMARWithConvenience() { BannerAdView bannerAdView = new BannerAdView(activity); bannerAdView.setPlacementID("0"); bannerAdView.setAdListener(this); bannerAdView.setAdSize(320, 50); bannerAdView.setAutoRefreshInterval(-1); InterstitialAdView interstitialAdView = new InterstitialAdView(activity); interstitialAdView.setPlacementID("0"); interstitialAdView.setAdListener(this); new ANMultiAdRequest(activity, 0, 1234, this, true, bannerAdView, interstitialAdView); waitForTasks(); Robolectric.flushBackgroundThreadScheduler(); Robolectric.flushForegroundThreadScheduler(); waitForTasks(); Robolectric.flushBackgroundThreadScheduler(); Robolectric.flushForegroundThreadScheduler(); // ShadowLooper shadowLooper = shadowOf(getMainLooper()); // if (!shadowLooper.isIdle()) { // shadowLooper.idle(); // } // RuntimeEnvironment.getMasterScheduler().advanceToNextPostedRunnable(); } //Concurrent MAR Success @Test public void testReloadMARSuccess() { server.enqueue(new MockResponse().setResponseCode(200).setBody(MockServerResponses.marSuccess())); assertFalse(marCompleted); executeMARRequest(); server.enqueue(new MockResponse().setResponseCode(200).setBody(MockServerResponses.marSuccess())); executeSecondMARRequest(); assertTrue(marCompleted); assertTrue(secondMarCompleted); } private void executeSecondMARRequest() { ANMultiAdRequest anMultiAdRequest = new ANMultiAdRequest(activity, 123, 1234, new MultiAdRequestListener() { @Override public void onMultiAdRequestCompleted() { secondMarCompleted = true; secondMarFailed = false; } @Override public void onMultiAdRequestFailed(ResultCode code) { secondMarCompleted = false; secondMarFailed = true; } }); BannerAdView bannerAdView = new BannerAdView(activity); bannerAdView.setPlacementID("0"); bannerAdView.setAdListener(this); bannerAdView.setAdSize(320, 50); bannerAdView.setAutoRefreshInterval(-1); InterstitialAdView interstitialAdView = new InterstitialAdView(activity); interstitialAdView.setPlacementID("0"); interstitialAdView.setAdListener(this); anMultiAdRequest.addAdUnit(bannerAdView); anMultiAdRequest.addAdUnit(interstitialAdView); executeMARRequest(anMultiAdRequest); } private void executeBannerRequest() { reset(); bannerAdView.setAutoRefreshInterval(15000); bannerAdView.loadAd(); waitForTasks(); Robolectric.flushBackgroundThreadScheduler(); Robolectric.flushForegroundThreadScheduler(); waitForTasks(); Robolectric.flushBackgroundThreadScheduler(); Robolectric.flushForegroundThreadScheduler(); // Robolectric.getBackgroundThreadScheduler().advanceToNextPostedRunnable(); // Robolectric.getForegroundThreadScheduler().advanceToNextPostedRunnable(); } private void executeInterstitialRequest() { reset(); interstitialAdView.loadAd(); waitForTasks(); Robolectric.flushBackgroundThreadScheduler(); Robolectric.flushForegroundThreadScheduler(); waitForTasks(); Robolectric.flushBackgroundThreadScheduler(); Robolectric.flushForegroundThreadScheduler(); } private void executeMARRequest() { reset(); executeMARRequest(anMultiAdRequest); } private void executeMARRequest(ANMultiAdRequest anMultiAdRequest) { // AdViewRequestManager requestManager = new AdViewRequestManager(anMultiAdRequest); // requestManager.execute(); waitForTasks(); Robolectric.flushBackgroundThreadScheduler(); Robolectric.flushForegroundThreadScheduler(); anMultiAdRequest.load(); waitForTasks(); Robolectric.flushBackgroundThreadScheduler(); Robolectric.flushForegroundThreadScheduler(); waitForTasks(); Robolectric.flushBackgroundThreadScheduler(); Robolectric.flushForegroundThreadScheduler(); // ShadowLooper.runUiThreadTasks(); // ShadowLooper.runUiThreadTasksIncludingDelayedTasks(); // ShadowLooper.idleMainLooper(); // ShadowLooper.idleMainLooperConstantly(true); // ShadowLooper.shadowMainLooper().quitUnchecked(); // ShadowLooper shadowLooper = shadowOf(getMainLooper()); // if (!shadowLooper.isIdle()) { // shadowLooper.idle(); // } // RuntimeEnvironment.getMasterScheduler().advanceToNextPostedRunnable(); } private void reset() { adLoaded = false; adFailed = false; adExpanded = false; adCollapsed = false; adClicked = false; adClickedWithUrl = false; isBannerLoaded = false; isInterstitialLoaded = false; marCompleted = false; marFailed = false; secondMarCompleted = false; secondMarFailed = false; } }
/* * 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.presto.metadata; import com.facebook.presto.connector.informationSchema.InformationSchemaMetadata; import com.facebook.presto.spi.ColumnHandle; import com.facebook.presto.spi.ColumnMetadata; import com.facebook.presto.spi.ConnectorMetadata; import com.facebook.presto.spi.ConnectorTableMetadata; import com.facebook.presto.spi.SchemaTableName; import com.facebook.presto.spi.TableHandle; import com.facebook.presto.sql.analyzer.Type; import com.facebook.presto.sql.tree.QualifiedName; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import javax.inject.Singleton; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArrayList; import static com.facebook.presto.metadata.MetadataUtil.checkCatalogName; import static com.facebook.presto.metadata.MetadataUtil.checkColumnName; import static com.facebook.presto.metadata.QualifiedTableName.convertFromSchemaTableName; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.Iterables.transform; @Singleton public class MetadataManager implements Metadata { public static final String INTERNAL_CONNECTOR_ID = "$internal"; // Note this must be a list to assure dual is always checked first private final CopyOnWriteArrayList<ConnectorMetadataEntry> internalSchemas = new CopyOnWriteArrayList<>(); private final ConcurrentMap<String, ConnectorMetadataEntry> connectors = new ConcurrentHashMap<>(); private final ConcurrentMap<String, ConnectorMetadataEntry> informationSchemas = new ConcurrentHashMap<>(); private final FunctionRegistry functions = new FunctionRegistry(); public void addConnectorMetadata(String connectorId, String catalogName, ConnectorMetadata connectorMetadata) { ConnectorMetadataEntry entry = new ConnectorMetadataEntry(connectorId, connectorMetadata); checkState(connectors.putIfAbsent(catalogName, entry) == null, "Catalog '%s' is already registered", catalogName); informationSchemas.put(catalogName, new ConnectorMetadataEntry(INTERNAL_CONNECTOR_ID, new InformationSchemaMetadata(catalogName))); } public void addInternalSchemaMetadata(String connectorId, ConnectorMetadata connectorMetadata) { checkNotNull(connectorId, "connectorId is null"); checkNotNull(connectorMetadata, "connectorMetadata is null"); internalSchemas.add(new ConnectorMetadataEntry(connectorId, connectorMetadata)); } @Override public FunctionInfo getFunction(QualifiedName name, List<Type> parameterTypes) { return functions.get(name, parameterTypes); } @Override public FunctionInfo getFunction(FunctionHandle handle) { return functions.get(handle); } @Override public boolean isAggregationFunction(QualifiedName name) { return functions.isAggregationFunction(name); } @Override public List<FunctionInfo> listFunctions() { return functions.list(); } @Override public List<String> listSchemaNames(String catalogName) { checkCatalogName(catalogName); ImmutableSet.Builder<String> schemaNames = ImmutableSet.builder(); for (ConnectorMetadataEntry entry : allConnectorsFor(catalogName)) { schemaNames.addAll(entry.getMetadata().listSchemaNames()); } return ImmutableList.copyOf(schemaNames.build()); } @Override public Optional<TableHandle> getTableHandle(QualifiedTableName table) { checkNotNull(table, "table is null"); SchemaTableName tableName = table.asSchemaTableName(); for (ConnectorMetadataEntry entry : allConnectorsFor(table.getCatalogName())) { TableHandle tableHandle = entry.getMetadata().getTableHandle(tableName); if (tableHandle != null) { return Optional.of(tableHandle); } } return Optional.absent(); } @Override public TableMetadata getTableMetadata(TableHandle tableHandle) { ConnectorTableMetadata tableMetadata = lookupConnectorFor(tableHandle).getMetadata().getTableMetadata(tableHandle); return new TableMetadata(getConnectorId(tableHandle), tableMetadata); } @Override public Map<String, ColumnHandle> getColumnHandles(TableHandle tableHandle) { return lookupConnectorFor(tableHandle).getMetadata().getColumnHandles(tableHandle); } @Override public ColumnMetadata getColumnMetadata(TableHandle tableHandle, ColumnHandle columnHandle) { checkNotNull(tableHandle, "tableHandle is null"); checkNotNull(columnHandle, "columnHandle is null"); return lookupConnectorFor(tableHandle).getMetadata().getColumnMetadata(tableHandle, columnHandle); } @Override public List<QualifiedTableName> listTables(QualifiedTablePrefix prefix) { checkNotNull(prefix, "prefix is null"); String schemaNameOrNull = prefix.getSchemaName().orNull(); LinkedHashSet<QualifiedTableName> tables = new LinkedHashSet<>(); for (ConnectorMetadataEntry entry : allConnectorsFor(prefix.getCatalogName())) { for (QualifiedTableName tableName : transform(entry.getMetadata().listTables(schemaNameOrNull), convertFromSchemaTableName(prefix.getCatalogName()))) { tables.add(tableName); } } return ImmutableList.copyOf(tables); } @Override public Optional<ColumnHandle> getColumnHandle(TableHandle tableHandle, String columnName) { checkNotNull(tableHandle, "tableHandle is null"); checkColumnName(columnName); return Optional.fromNullable(lookupConnectorFor(tableHandle).getMetadata().getColumnHandle(tableHandle, columnName)); } @Override public Map<QualifiedTableName, List<ColumnMetadata>> listTableColumns(QualifiedTablePrefix prefix) { checkNotNull(prefix, "prefix is null"); LinkedHashMap<QualifiedTableName, List<ColumnMetadata>> tableColumns = new LinkedHashMap<>(); for (ConnectorMetadataEntry connectorMetadata : allConnectorsFor(prefix.getCatalogName())) { for (Entry<SchemaTableName, List<ColumnMetadata>> entry : connectorMetadata.getMetadata().listTableColumns(prefix.asSchemaTablePrefix()).entrySet()) { QualifiedTableName tableName = new QualifiedTableName(prefix.getCatalogName(), entry.getKey().getSchemaName(), entry.getKey().getTableName()); if (!tableColumns.containsKey(tableName)) { tableColumns.put(tableName, entry.getValue()); } } } return ImmutableMap.copyOf(tableColumns); } @Override public TableHandle createTable(String catalogName, TableMetadata tableMetadata) { ConnectorMetadataEntry connectorMetadata = connectors.get(catalogName); checkArgument(connectorMetadata != null, "Catalog %s does not exist", catalogName); return connectorMetadata.getMetadata().createTable(tableMetadata.getMetadata()); } @Override public void dropTable(TableHandle tableHandle) { lookupConnectorFor(tableHandle).getMetadata().dropTable(tableHandle); } @Override public String getConnectorId(TableHandle tableHandle) { return lookupConnectorFor(tableHandle).getConnectorId(); } @Override public Optional<TableHandle> getTableHandle(String connectorId, SchemaTableName tableName) { // use catalog name in place of connector id ConnectorMetadataEntry entry = connectors.get(connectorId); if (entry == null) { return Optional.absent(); } return Optional.fromNullable(entry.getMetadata().getTableHandle(tableName)); } private List<ConnectorMetadataEntry> allConnectorsFor(String catalogName) { ImmutableList.Builder<ConnectorMetadataEntry> builder = ImmutableList.builder(); builder.addAll(internalSchemas); ConnectorMetadataEntry connector = connectors.get(catalogName); if (connector != null) { builder.add(connector); } ConnectorMetadataEntry informationSchema = informationSchemas.get(catalogName); if (informationSchema != null) { builder.add(informationSchema); } return builder.build(); } private ConnectorMetadataEntry lookupConnectorFor(TableHandle tableHandle) { checkNotNull(tableHandle, "tableHandle is null"); for (Entry<String, ConnectorMetadataEntry> entry : informationSchemas.entrySet()) { if (entry.getValue().getMetadata().canHandle(tableHandle)) { return entry.getValue(); } } for (ConnectorMetadataEntry entry : internalSchemas) { if (entry.getMetadata().canHandle(tableHandle)) { return entry; } } for (Entry<String, ConnectorMetadataEntry> entry : connectors.entrySet()) { if (entry.getValue().getMetadata().canHandle(tableHandle)) { return entry.getValue(); } } throw new IllegalArgumentException("Table %s does not exist: " + tableHandle); } private static class ConnectorMetadataEntry { private final String connectorId; private final ConnectorMetadata metadata; private ConnectorMetadataEntry(String connectorId, ConnectorMetadata metadata) { Preconditions.checkNotNull(connectorId, "connectorId is null"); Preconditions.checkNotNull(metadata, "metadata is null"); this.connectorId = connectorId; this.metadata = metadata; } private String getConnectorId() { return connectorId; } private ConnectorMetadata getMetadata() { return metadata; } } }
package com.vladsch.flexmark.formatter.internal; import com.vladsch.flexmark.ast.AnchorRefTarget; import com.vladsch.flexmark.formatter.*; import com.vladsch.flexmark.html.renderer.HtmlIdGenerator; import com.vladsch.flexmark.html.renderer.HtmlIdGeneratorFactory; import com.vladsch.flexmark.util.ast.Document; import com.vladsch.flexmark.util.ast.Node; import com.vladsch.flexmark.util.data.DataHolder; import com.vladsch.flexmark.util.data.MutableDataSet; import com.vladsch.flexmark.util.sequence.BasedSequence; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.function.Supplier; import java.util.regex.Pattern; import static com.vladsch.flexmark.formatter.RenderPurpose.TRANSLATED_SPANS; import static java.lang.Character.isWhitespace; public class TranslationHandlerImpl implements TranslationHandler { final FormatterOptions myFormatterOptions; final HashMap<String, String> myNonTranslatingTexts; // map placeholder to non-translating text replaced before translation so it can be replaced after translation final HashMap<String, String> myAnchorTexts; // map anchor id to non-translating text replaced before translation so it can be replaced after translation final HashMap<String, String> myTranslatingTexts; // map placeholder to translating original text which is to be translated separately from its context and is replaced with placeholder for main context translation final HashMap<String, String> myTranslatedTexts; // map placeholder to translated text which is to be translated separately from its context and was replaced with placeholder for main context translation final ArrayList<String> myTranslatingPlaceholders; // list of placeholders to index in translating and translated texts final ArrayList<String> myTranslatingSpans; final ArrayList<String> myNonTranslatingSpans; final ArrayList<String> myTranslatedSpans; final HtmlIdGeneratorFactory myIdGeneratorFactory; final Pattern myPlaceHolderMarkerPattern; final MutableDataSet myTranslationStore; final HashMap<String, Integer> myOriginalRefTargets; // map ref target id to translation index final HashMap<Integer, String> myTranslatedRefTargets; // map translation index to translated ref target id final HashMap<String, String> myOriginalAnchors; // map placeholder id to original ref id final HashMap<String, String> myTranslatedAnchors; // map placeholder id to translated ref target id private int myPlaceholderId = 0; private int myAnchorId = 0; private int myTranslatingSpanId = 0; private int myNonTranslatingSpanId = 0; private RenderPurpose myRenderPurpose; private MarkdownWriter myWriter; private HtmlIdGenerator myIdGenerator; private TranslationPlaceholderGenerator myPlaceholderGenerator; private Function<String, CharSequence> myNonTranslatingPostProcessor = null; private MergeContext myMergeContext = null; public TranslationHandlerImpl(DataHolder options, HtmlIdGeneratorFactory idGeneratorFactory) { myFormatterOptions = new FormatterOptions(options); myIdGeneratorFactory = idGeneratorFactory; myNonTranslatingTexts = new HashMap<>(); myAnchorTexts = new HashMap<>(); myTranslatingTexts = new HashMap<>(); myTranslatedTexts = new HashMap<>(); myOriginalAnchors = new HashMap<>(); myTranslatedAnchors = new HashMap<>(); myTranslatedRefTargets = new HashMap<>(); myOriginalRefTargets = new HashMap<>(); myTranslatingSpans = new ArrayList<>(); myTranslatedSpans = new ArrayList<>(); myTranslatingPlaceholders = new ArrayList<>(); myNonTranslatingSpans = new ArrayList<>(); myPlaceHolderMarkerPattern = Pattern.compile(myFormatterOptions.translationExcludePattern); //Pattern.compile("^[\\[\\](){}<>]*_{1,2}\\d+_[\\[\\](){}<>]*$"); myTranslationStore = new MutableDataSet(); } @Override public MergeContext getMergeContext() { return myMergeContext; } @Override public void setMergeContext(@NotNull MergeContext context) { myMergeContext = context; } @NotNull @Override public MutableDataSet getTranslationStore() { return myTranslationStore; } @Override public HtmlIdGenerator getIdGenerator() { return myIdGenerator; } @Override public void beginRendering(@NotNull Document node, @NotNull NodeFormatterContext context, @NotNull MarkdownWriter appendable) { // collect anchor ref ids myWriter = appendable; myIdGenerator = myIdGeneratorFactory.create(); myIdGenerator.generateIds(node); } static boolean isNotBlank(CharSequence csq) { int iMax = csq.length(); for (int i = 0; i < iMax; i++) { if (!isWhitespace(csq.charAt(i))) return true; } return false; } @NotNull @Override public List<String> getTranslatingTexts() { myTranslatingPlaceholders.clear(); myTranslatingPlaceholders.ensureCapacity(myTranslatedSpans.size() + myTranslatedTexts.size()); ArrayList<String> translatingSnippets = new ArrayList<>(myTranslatedSpans.size() + myTranslatedTexts.size()); HashMap<String, Integer> repeatedTranslatingIndices = new HashMap<>(); // collect all the translating snippets first for (Map.Entry<String, String> entry : myTranslatingTexts.entrySet()) { if (isNotBlank(entry.getValue()) && !myPlaceHolderMarkerPattern.matcher(entry.getValue()).matches()) { // see if it is repeating if (!repeatedTranslatingIndices.containsKey(entry.getValue())) { // new, index repeatedTranslatingIndices.put(entry.getValue(), translatingSnippets.size()); translatingSnippets.add(entry.getValue()); myTranslatingPlaceholders.add(entry.getKey()); } } } for (CharSequence text : myTranslatingSpans) { if (isNotBlank(text) && !myPlaceHolderMarkerPattern.matcher(text).matches()) { translatingSnippets.add(text.toString()); } } return translatingSnippets; } @Override public void setTranslatedTexts(@NotNull List<? extends CharSequence> translatedTexts) { myTranslatedTexts.clear(); myTranslatedTexts.putAll(myTranslatingTexts); myTranslatedSpans.clear(); myTranslatedSpans.ensureCapacity(myTranslatingSpans.size()); // collect all the translating snippets first int i = 0; int iMax = translatedTexts.size(); int placeholderSize = myTranslatingPlaceholders.size(); HashMap<String, Integer> repeatedTranslatingIndices = new HashMap<>(); for (Map.Entry<String, String> entry : myTranslatingTexts.entrySet()) { if (isNotBlank(entry.getValue()) && !myPlaceHolderMarkerPattern.matcher(entry.getValue()).matches()) { Integer index = repeatedTranslatingIndices.get(entry.getValue()); if (index == null) { if (i >= placeholderSize) break; // new, index repeatedTranslatingIndices.put(entry.getValue(), i); myTranslatedTexts.put(entry.getKey(), translatedTexts.get(i).toString()); i++; } else { myTranslatedTexts.put(entry.getKey(), translatedTexts.get(index).toString()); } // } else { // // already has the same value } } for (CharSequence text : myTranslatingSpans) { if (isNotBlank(text) && !myPlaceHolderMarkerPattern.matcher(text).matches()) { myTranslatedSpans.add(translatedTexts.get(i).toString()); i++; } else { // add original blank sequence myTranslatedSpans.add(text.toString()); } } } @Override public void setRenderPurpose(@NotNull RenderPurpose renderPurpose) { myAnchorId = 0; myTranslatingSpanId = 0; myPlaceholderId = 0; myRenderPurpose = renderPurpose; myNonTranslatingSpanId = 0; } @NotNull @Override public RenderPurpose getRenderPurpose() { return myRenderPurpose; } @Override public boolean isTransformingText() { return myRenderPurpose != RenderPurpose.FORMAT; } @NotNull @Override public CharSequence transformAnchorRef(@NotNull CharSequence pageRef, @NotNull CharSequence anchorRef) { switch (myRenderPurpose) { case TRANSLATION_SPANS: String replacedTextId = String.format(myFormatterOptions.translationIdFormat, ++myAnchorId); myAnchorTexts.put(replacedTextId, anchorRef.toString()); return replacedTextId; case TRANSLATED_SPANS: return String.format(myFormatterOptions.translationIdFormat, ++myAnchorId); case TRANSLATED: String anchorIdText = String.format(myFormatterOptions.translationIdFormat, ++myAnchorId); String resolvedPageRef = myNonTranslatingTexts.get(pageRef.toString()); if (resolvedPageRef != null && resolvedPageRef.length() == 0) { // self reference, add it to the list String refId = myAnchorTexts.get(anchorIdText); if (refId != null) { // original ref id for the heading we should have them all Integer spanIndex = myOriginalRefTargets.get(refId); if (spanIndex != null) { // have the index to translatingSpans String translatedRefId = myTranslatedRefTargets.get(spanIndex); if (translatedRefId != null) { return translatedRefId; } } return refId; } } else { String resolvedAnchorRef = myAnchorTexts.get(anchorIdText); if (resolvedAnchorRef != null) { return resolvedAnchorRef; } } case FORMAT: default: return anchorRef; } } @Override public void customPlaceholderFormat(@NotNull TranslationPlaceholderGenerator generator, @NotNull TranslatingSpanRender render) { if (myRenderPurpose != TRANSLATED_SPANS) { TranslationPlaceholderGenerator savedGenerator = myPlaceholderGenerator; myPlaceholderGenerator = generator; render.render(myWriter.getContext(), myWriter); myPlaceholderGenerator = savedGenerator; } } @Override public void translatingSpan(@NotNull TranslatingSpanRender render) { translatingRefTargetSpan(null, render); } private String renderInSubContext(TranslatingSpanRender render, boolean copyToMain) { StringBuilder span = new StringBuilder(); MarkdownWriter savedMarkdown = myWriter; NodeFormatterContext subContext = myWriter.getContext().getSubContext(); MarkdownWriter writer = subContext.getMarkdown(); myWriter = writer; render.render(subContext, writer); // trim off eol added by toString(0) String spanText = writer.toString(2, -1); myWriter = savedMarkdown; if (copyToMain) { myWriter.append(spanText); } return spanText; } @Override public void translatingRefTargetSpan(@Nullable Node target, @NotNull TranslatingSpanRender render) { switch (myRenderPurpose) { case TRANSLATION_SPANS: { String spanText = renderInSubContext(render, true); if (target != null) { if (!(target instanceof AnchorRefTarget) || !((AnchorRefTarget) target).isExplicitAnchorRefId()) { String id = myIdGenerator.getId(target); myOriginalRefTargets.put(id, myTranslatingSpans.size()); } } myTranslatingSpans.add(spanText); return; } case TRANSLATED_SPANS: { // we output translated text instead of render renderInSubContext(render, false); String translated = myTranslatedSpans.get(myTranslatingSpanId); if (target != null) { if (!(target instanceof AnchorRefTarget) || !((AnchorRefTarget) target).isExplicitAnchorRefId()) { // only if does not have an explicit id then map to translated text id String id = myIdGenerator.getId(translated); myTranslatedRefTargets.put(myTranslatingSpanId, id); //} else { // myTranslatedRefTargets.remove(myTranslatingSpanId); } } myTranslatingSpanId++; myWriter.append(translated); return; } case TRANSLATED: if (target != null) { if (!(target instanceof AnchorRefTarget) || !((AnchorRefTarget) target).isExplicitAnchorRefId()) { // only if does not have an explicit id then map to translated text id String id = myIdGenerator.getId(target); myTranslatedRefTargets.put(myTranslatingSpanId, id); //} else { // myTranslatedRefTargets.remove(myTranslatingSpanId); } } myTranslatingSpanId++; renderInSubContext(render, true); return; case FORMAT: default: render.render(myWriter.getContext(), myWriter); } } public void nonTranslatingSpan(@NotNull TranslatingSpanRender render) { switch (myRenderPurpose) { case TRANSLATION_SPANS: { String spanText = renderInSubContext(render, false); myNonTranslatingSpans.add(spanText); myNonTranslatingSpanId++; String replacedTextId = getPlaceholderId(myFormatterOptions.translationIdFormat, myNonTranslatingSpanId, null, null, null); myWriter.append(replacedTextId); return; } case TRANSLATED_SPANS: { // we output translated text instead of render renderInSubContext(render, false); String translated = myNonTranslatingSpans.get(myNonTranslatingSpanId); myNonTranslatingSpanId++; myWriter.append(translated); return; } case TRANSLATED: { // we output translated text instead of render renderInSubContext(render, true); myNonTranslatingSpanId++; return; } case FORMAT: default: render.render(myWriter.getContext(), myWriter); } } public String getPlaceholderId(String format, int placeholderId, CharSequence prefix, CharSequence suffix, CharSequence suffix2) { String replacedTextId = myPlaceholderGenerator != null ? myPlaceholderGenerator.getPlaceholder(placeholderId) : String.format(format, placeholderId); if (prefix == null && suffix == null && suffix2 == null) return replacedTextId; return addPrefixSuffix(replacedTextId, prefix, suffix, suffix2); } public static String addPrefixSuffix(CharSequence placeholderId, CharSequence prefix, CharSequence suffix, CharSequence suffix2) { if (prefix == null && suffix == null && suffix2 == null) return placeholderId.toString(); StringBuilder sb = new StringBuilder(); if (prefix != null) sb.append(prefix); sb.append(placeholderId); if (suffix != null) sb.append(suffix); if (suffix2 != null) sb.append(suffix2); return sb.toString(); } @Override public void postProcessNonTranslating(@NotNull Function<String, CharSequence> postProcessor, @NotNull Runnable scope) { Function<String, CharSequence> savedValue = myNonTranslatingPostProcessor; try { myNonTranslatingPostProcessor = postProcessor; scope.run(); } finally { myNonTranslatingPostProcessor = savedValue; } } @NotNull @Override public <T> T postProcessNonTranslating(@NotNull Function<String, CharSequence> postProcessor, @NotNull Supplier<T> scope) { Function<String, CharSequence> savedValue = myNonTranslatingPostProcessor; try { myNonTranslatingPostProcessor = postProcessor; return scope.get(); } finally { myNonTranslatingPostProcessor = savedValue; } } @Override public boolean isPostProcessingNonTranslating() { return myNonTranslatingPostProcessor != null; } @NotNull @Override public CharSequence transformNonTranslating(CharSequence prefix, @NotNull CharSequence nonTranslatingText, CharSequence suffix, CharSequence suffix2) { // need to transfer trailing EOLs to id CharSequence trimmedEOL; if (suffix2 != null) { trimmedEOL = suffix2; } else { BasedSequence basedSequence = BasedSequence.of(nonTranslatingText); trimmedEOL = basedSequence.trimmedEOL(); } switch (myRenderPurpose) { case TRANSLATION_SPANS: String replacedTextId = getPlaceholderId(myFormatterOptions.translationIdFormat, ++myPlaceholderId, prefix, suffix, trimmedEOL); String useReplacedTextId = replacedTextId; if (myNonTranslatingPostProcessor != null) { useReplacedTextId = myNonTranslatingPostProcessor.apply(replacedTextId).toString(); } myNonTranslatingTexts.put(useReplacedTextId, nonTranslatingText.toString()); return useReplacedTextId; case TRANSLATED_SPANS: String placeholderId = getPlaceholderId(myFormatterOptions.translationIdFormat, ++myPlaceholderId, prefix, suffix, trimmedEOL); if (myNonTranslatingPostProcessor != null) { return myNonTranslatingPostProcessor.apply(placeholderId); } else { return placeholderId; } case TRANSLATED: if (nonTranslatingText.length() > 0) { String text = myNonTranslatingTexts.get(nonTranslatingText.toString()); if (text == null) { text = ""; } if (myNonTranslatingPostProcessor != null) { return myNonTranslatingPostProcessor.apply(text); } return text; } return nonTranslatingText; case FORMAT: default: return nonTranslatingText; } } @NotNull @Override public CharSequence transformTranslating(CharSequence prefix, @NotNull CharSequence translatingText, CharSequence suffix, CharSequence suffix2) { switch (myRenderPurpose) { case TRANSLATION_SPANS: String replacedTextId = getPlaceholderId(myFormatterOptions.translationIdFormat, ++myPlaceholderId, prefix, suffix, suffix2); myTranslatingTexts.put(replacedTextId, translatingText.toString()); return replacedTextId; case TRANSLATED_SPANS: return getPlaceholderId(myFormatterOptions.translationIdFormat, ++myPlaceholderId, prefix, suffix, suffix2); case TRANSLATED: CharSequence replacedText = prefix == null && suffix == null && suffix2 == null ? translatingText : addPrefixSuffix(translatingText, prefix, suffix, suffix2); CharSequence text = myTranslatedTexts.get(replacedText.toString()); if (text != null && !(prefix == null && suffix == null && suffix2 == null)) { return addPrefixSuffix(text, prefix, suffix, suffix2); } if (text != null) { return text; } case FORMAT: default: return translatingText; } } }
/** * Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.strata.product.bond; import java.io.Serializable; import java.time.LocalDate; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import org.joda.beans.Bean; import org.joda.beans.BeanDefinition; import org.joda.beans.ImmutableBean; import org.joda.beans.ImmutableDefaults; import org.joda.beans.JodaBeanUtils; import org.joda.beans.MetaProperty; import org.joda.beans.Property; import org.joda.beans.PropertyDefinition; import org.joda.beans.impl.direct.DirectFieldsBeanBuilder; import org.joda.beans.impl.direct.DirectMetaBean; import org.joda.beans.impl.direct.DirectMetaProperty; import org.joda.beans.impl.direct.DirectMetaPropertyMap; import com.opengamma.strata.basics.ReferenceData; import com.opengamma.strata.collect.ArgChecker; import com.opengamma.strata.product.ResolvableTrade; import com.opengamma.strata.product.SecuritizedProductTrade; import com.opengamma.strata.product.TradeInfo; /** * A trade representing a fixed coupon bond. * <p> * A trade in an underlying {@link FixedCouponBond}. * * <h4>Price</h4> * Strata uses <i>decimal prices</i> for bonds in the trade model, pricers and market data. * For example, a price of 99.32% is represented in Strata by 0.9932. */ @BeanDefinition(constructorScope = "package") public final class FixedCouponBondTrade implements SecuritizedProductTrade, ResolvableTrade<ResolvedFixedCouponBondTrade>, ImmutableBean, Serializable { /** * The additional trade information, defaulted to an empty instance. * <p> * This allows additional information to be attached to the trade. * Either the trade or settlement date is required when calling {@link FixedCouponBondTrade#resolve(ReferenceData)}. */ @PropertyDefinition(overrideGet = true) private final TradeInfo info; /** * The bond that was traded. * <p> * The product captures the contracted financial details of the trade. */ @PropertyDefinition(validate = "notNull", overrideGet = true) private final FixedCouponBond product; /** * The quantity that was traded. * <p> * This will be positive if buying and negative if selling. */ @PropertyDefinition(overrideGet = true) private final double quantity; /** * The <i>clean</i> price at which the bond was traded, in decimal form. * <p> * The "clean" price excludes any accrued interest. * <p> * Strata uses <i>decimal prices</i> for bonds in the trade model, pricers and market data. * For example, a price of 99.32% is represented in Strata by 0.9932. */ @PropertyDefinition(validate = "ArgChecker.notNegative", overrideGet = true) private final double price; //------------------------------------------------------------------------- @ImmutableDefaults private static void applyDefaults(Builder builder) { builder.info = TradeInfo.empty(); } //------------------------------------------------------------------------- @Override public ResolvedFixedCouponBondTrade resolve(ReferenceData refData) { ResolvedFixedCouponBond resolved = getProduct().resolve(refData); TradeInfo completedInfo = calculateSettlementDate(refData); return new ResolvedFixedCouponBondTrade(completedInfo, resolved, quantity, price); } // calculates the settlement date from the trade date if necessary private TradeInfo calculateSettlementDate(ReferenceData refData) { if (info.getSettlementDate().isPresent()) { return info; } if (info.getTradeDate().isPresent()) { LocalDate tradeDate = info.getTradeDate().get(); LocalDate settlementDate = product.getSettlementDateOffset().adjust(tradeDate, refData); return info.toBuilder().settlementDate(settlementDate).build(); } throw new IllegalStateException("FixedCouponBondTrade.resolve() requires either trade date or settlement date"); } //------------------------- AUTOGENERATED START ------------------------- ///CLOVER:OFF /** * The meta-bean for {@code FixedCouponBondTrade}. * @return the meta-bean, not null */ public static FixedCouponBondTrade.Meta meta() { return FixedCouponBondTrade.Meta.INSTANCE; } static { JodaBeanUtils.registerMetaBean(FixedCouponBondTrade.Meta.INSTANCE); } /** * The serialization version id. */ private static final long serialVersionUID = 1L; /** * Returns a builder used to create an instance of the bean. * @return the builder, not null */ public static FixedCouponBondTrade.Builder builder() { return new FixedCouponBondTrade.Builder(); } /** * Creates an instance. * @param info the value of the property * @param product the value of the property, not null * @param quantity the value of the property * @param price the value of the property */ FixedCouponBondTrade( TradeInfo info, FixedCouponBond product, double quantity, double price) { JodaBeanUtils.notNull(product, "product"); ArgChecker.notNegative(price, "price"); this.info = info; this.product = product; this.quantity = quantity; this.price = price; } @Override public FixedCouponBondTrade.Meta metaBean() { return FixedCouponBondTrade.Meta.INSTANCE; } @Override public <R> Property<R> property(String propertyName) { return metaBean().<R>metaProperty(propertyName).createProperty(this); } @Override public Set<String> propertyNames() { return metaBean().metaPropertyMap().keySet(); } //----------------------------------------------------------------------- /** * Gets the additional trade information, defaulted to an empty instance. * <p> * This allows additional information to be attached to the trade. * Either the trade or settlement date is required when calling {@link FixedCouponBondTrade#resolve(ReferenceData)}. * @return the value of the property */ @Override public TradeInfo getInfo() { return info; } //----------------------------------------------------------------------- /** * Gets the bond that was traded. * <p> * The product captures the contracted financial details of the trade. * @return the value of the property, not null */ @Override public FixedCouponBond getProduct() { return product; } //----------------------------------------------------------------------- /** * Gets the quantity that was traded. * <p> * This will be positive if buying and negative if selling. * @return the value of the property */ @Override public double getQuantity() { return quantity; } //----------------------------------------------------------------------- /** * Gets the <i>clean</i> price at which the bond was traded, in decimal form. * <p> * The "clean" price excludes any accrued interest. * <p> * Strata uses <i>decimal prices</i> for bonds in the trade model, pricers and market data. * For example, a price of 99.32% is represented in Strata by 0.9932. * @return the value of the property */ @Override public double getPrice() { return price; } //----------------------------------------------------------------------- /** * Returns a builder that allows this bean to be mutated. * @return the mutable builder, not null */ public Builder toBuilder() { return new Builder(this); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj != null && obj.getClass() == this.getClass()) { FixedCouponBondTrade other = (FixedCouponBondTrade) obj; return JodaBeanUtils.equal(info, other.info) && JodaBeanUtils.equal(product, other.product) && JodaBeanUtils.equal(quantity, other.quantity) && JodaBeanUtils.equal(price, other.price); } return false; } @Override public int hashCode() { int hash = getClass().hashCode(); hash = hash * 31 + JodaBeanUtils.hashCode(info); hash = hash * 31 + JodaBeanUtils.hashCode(product); hash = hash * 31 + JodaBeanUtils.hashCode(quantity); hash = hash * 31 + JodaBeanUtils.hashCode(price); return hash; } @Override public String toString() { StringBuilder buf = new StringBuilder(160); buf.append("FixedCouponBondTrade{"); buf.append("info").append('=').append(info).append(',').append(' '); buf.append("product").append('=').append(product).append(',').append(' '); buf.append("quantity").append('=').append(quantity).append(',').append(' '); buf.append("price").append('=').append(JodaBeanUtils.toString(price)); buf.append('}'); return buf.toString(); } //----------------------------------------------------------------------- /** * The meta-bean for {@code FixedCouponBondTrade}. */ public static final class Meta extends DirectMetaBean { /** * The singleton instance of the meta-bean. */ static final Meta INSTANCE = new Meta(); /** * The meta-property for the {@code info} property. */ private final MetaProperty<TradeInfo> info = DirectMetaProperty.ofImmutable( this, "info", FixedCouponBondTrade.class, TradeInfo.class); /** * The meta-property for the {@code product} property. */ private final MetaProperty<FixedCouponBond> product = DirectMetaProperty.ofImmutable( this, "product", FixedCouponBondTrade.class, FixedCouponBond.class); /** * The meta-property for the {@code quantity} property. */ private final MetaProperty<Double> quantity = DirectMetaProperty.ofImmutable( this, "quantity", FixedCouponBondTrade.class, Double.TYPE); /** * The meta-property for the {@code price} property. */ private final MetaProperty<Double> price = DirectMetaProperty.ofImmutable( this, "price", FixedCouponBondTrade.class, Double.TYPE); /** * The meta-properties. */ private final Map<String, MetaProperty<?>> metaPropertyMap$ = new DirectMetaPropertyMap( this, null, "info", "product", "quantity", "price"); /** * Restricted constructor. */ private Meta() { } @Override protected MetaProperty<?> metaPropertyGet(String propertyName) { switch (propertyName.hashCode()) { case 3237038: // info return info; case -309474065: // product return product; case -1285004149: // quantity return quantity; case 106934601: // price return price; } return super.metaPropertyGet(propertyName); } @Override public FixedCouponBondTrade.Builder builder() { return new FixedCouponBondTrade.Builder(); } @Override public Class<? extends FixedCouponBondTrade> beanType() { return FixedCouponBondTrade.class; } @Override public Map<String, MetaProperty<?>> metaPropertyMap() { return metaPropertyMap$; } //----------------------------------------------------------------------- /** * The meta-property for the {@code info} property. * @return the meta-property, not null */ public MetaProperty<TradeInfo> info() { return info; } /** * The meta-property for the {@code product} property. * @return the meta-property, not null */ public MetaProperty<FixedCouponBond> product() { return product; } /** * The meta-property for the {@code quantity} property. * @return the meta-property, not null */ public MetaProperty<Double> quantity() { return quantity; } /** * The meta-property for the {@code price} property. * @return the meta-property, not null */ public MetaProperty<Double> price() { return price; } //----------------------------------------------------------------------- @Override protected Object propertyGet(Bean bean, String propertyName, boolean quiet) { switch (propertyName.hashCode()) { case 3237038: // info return ((FixedCouponBondTrade) bean).getInfo(); case -309474065: // product return ((FixedCouponBondTrade) bean).getProduct(); case -1285004149: // quantity return ((FixedCouponBondTrade) bean).getQuantity(); case 106934601: // price return ((FixedCouponBondTrade) bean).getPrice(); } return super.propertyGet(bean, propertyName, quiet); } @Override protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) { metaProperty(propertyName); if (quiet) { return; } throw new UnsupportedOperationException("Property cannot be written: " + propertyName); } } //----------------------------------------------------------------------- /** * The bean-builder for {@code FixedCouponBondTrade}. */ public static final class Builder extends DirectFieldsBeanBuilder<FixedCouponBondTrade> { private TradeInfo info; private FixedCouponBond product; private double quantity; private double price; /** * Restricted constructor. */ private Builder() { applyDefaults(this); } /** * Restricted copy constructor. * @param beanToCopy the bean to copy from, not null */ private Builder(FixedCouponBondTrade beanToCopy) { this.info = beanToCopy.getInfo(); this.product = beanToCopy.getProduct(); this.quantity = beanToCopy.getQuantity(); this.price = beanToCopy.getPrice(); } //----------------------------------------------------------------------- @Override public Object get(String propertyName) { switch (propertyName.hashCode()) { case 3237038: // info return info; case -309474065: // product return product; case -1285004149: // quantity return quantity; case 106934601: // price return price; default: throw new NoSuchElementException("Unknown property: " + propertyName); } } @Override public Builder set(String propertyName, Object newValue) { switch (propertyName.hashCode()) { case 3237038: // info this.info = (TradeInfo) newValue; break; case -309474065: // product this.product = (FixedCouponBond) newValue; break; case -1285004149: // quantity this.quantity = (Double) newValue; break; case 106934601: // price this.price = (Double) newValue; break; default: throw new NoSuchElementException("Unknown property: " + propertyName); } return this; } @Override public Builder set(MetaProperty<?> property, Object value) { super.set(property, value); return this; } @Override public Builder setString(String propertyName, String value) { setString(meta().metaProperty(propertyName), value); return this; } @Override public Builder setString(MetaProperty<?> property, String value) { super.setString(property, value); return this; } @Override public Builder setAll(Map<String, ? extends Object> propertyValueMap) { super.setAll(propertyValueMap); return this; } @Override public FixedCouponBondTrade build() { return new FixedCouponBondTrade( info, product, quantity, price); } //----------------------------------------------------------------------- /** * Sets the additional trade information, defaulted to an empty instance. * <p> * This allows additional information to be attached to the trade. * Either the trade or settlement date is required when calling {@link FixedCouponBondTrade#resolve(ReferenceData)}. * @param info the new value * @return this, for chaining, not null */ public Builder info(TradeInfo info) { this.info = info; return this; } /** * Sets the bond that was traded. * <p> * The product captures the contracted financial details of the trade. * @param product the new value, not null * @return this, for chaining, not null */ public Builder product(FixedCouponBond product) { JodaBeanUtils.notNull(product, "product"); this.product = product; return this; } /** * Sets the quantity that was traded. * <p> * This will be positive if buying and negative if selling. * @param quantity the new value * @return this, for chaining, not null */ public Builder quantity(double quantity) { this.quantity = quantity; return this; } /** * Sets the <i>clean</i> price at which the bond was traded, in decimal form. * <p> * The "clean" price excludes any accrued interest. * <p> * Strata uses <i>decimal prices</i> for bonds in the trade model, pricers and market data. * For example, a price of 99.32% is represented in Strata by 0.9932. * @param price the new value * @return this, for chaining, not null */ public Builder price(double price) { ArgChecker.notNegative(price, "price"); this.price = price; return this; } //----------------------------------------------------------------------- @Override public String toString() { StringBuilder buf = new StringBuilder(160); buf.append("FixedCouponBondTrade.Builder{"); buf.append("info").append('=').append(JodaBeanUtils.toString(info)).append(',').append(' '); buf.append("product").append('=').append(JodaBeanUtils.toString(product)).append(',').append(' '); buf.append("quantity").append('=').append(JodaBeanUtils.toString(quantity)).append(',').append(' '); buf.append("price").append('=').append(JodaBeanUtils.toString(price)); buf.append('}'); return buf.toString(); } } ///CLOVER:ON //-------------------------- AUTOGENERATED END -------------------------- }
package com.java.ui.componentc; import com.java.ui.util.UIResourceManager; import com.java.ui.util.UIUtil; import javax.swing.*; import javax.swing.border.Border; import javax.swing.text.Document; import java.awt.*; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; public class JCPasswordField extends JPasswordField { private static final long serialVersionUID = -8430512245033603572L; private float alpha; private boolean borderChange; private Border disabledBorder; private Image image; private boolean imageOnly; private MouseListener listener; private Border nonEditableBorder; private Border nonEditableRolloverBorder; private Border normalBorder; private Border rolloverBorder; private Insets visibleInsets; private Border focusBorder; private boolean isFocused; public JCPasswordField() { this(null, null, 0); } public JCPasswordField(Document doc, String txt, int columns) { super(doc, txt, columns); setUI(new CPasswordFieldUI()); super.setOpaque(false); setFont(UIUtil.getDefaultFont()); setBackground(UIResourceManager.getWhiteColor()); setForeground(Color.BLACK); setCaretColor(Color.BLACK); setSelectionColor(new Color(49, 106, 197)); setSelectedTextColor(UIResourceManager.getWhiteColor()); setDisabledTextColor(new Color(123, 123, 122)); setCursor(new Cursor(2)); setEchoChar('*'); setMargin(new Insets(0, 0, 0, 0)); super.setBorder(this.normalBorder = new ImageBorder(UIResourceManager .getImageByName("border_normal.png"), 5, 6, 3, 4)); putClientProperty("JPasswordField.cutCopyAllowed", Boolean.valueOf(false)); this.rolloverBorder = UIResourceManager.getBorder("TextRolloverBorder"); this.nonEditableBorder = UIResourceManager .getBorder("TextNonEditableBorder"); this.nonEditableRolloverBorder = UIResourceManager .getBorder("TextNonEditableRolloverBorder"); this.disabledBorder = UIResourceManager.getBorder("TextDisabledBorder"); this.alpha = 1.0F; this.visibleInsets = new Insets(1, 1, 1, 1); this.borderChange = true; this.focusBorder = new ImageBorder(getToolkit().getImage("./Pic/border_focus.png"), 5, 6, 3, 4); this.listener = new MouseAdapter() { public void mouseEntered(MouseEvent e) { JCPasswordField.this.mouseIn(); } public void mouseExited(MouseEvent e) { JCPasswordField.this.mouseOut(); } }; addMouseListener(this.listener); addFocusListener(new FocusAdapter() { public void focusGained(FocusEvent e) { isFocused = true; JCPasswordField.this.gotfocus(); } public void focusLost(FocusEvent e) { isFocused = false; JCPasswordField.this.lostfocus(); } }); } private void gotfocus() { if ((this.normalBorder != null) && (isEnabled())) { super.setBorder(this.focusBorder); } } private void lostfocus() { if ((this.normalBorder != null) && (isEnabled())) { super.setBorder(isEditable() ? this.normalBorder : this.nonEditableBorder); } } public JCPasswordField(int columns) { this(null, null, columns); } public JCPasswordField(String text) { this(null, text, 0); } public JCPasswordField(String text, int columns) { this(null, text, columns); } public void clearBorderListener() { removeMouseListener(this.listener); this.borderChange = false; } public float getAlpha() { return this.alpha; } public Image getImage() { return this.image; } public Insets getVisibleInsets() { return this.visibleInsets; } public boolean isImageOnly() { return this.imageOnly; } private void mouseIn() { if ((this.normalBorder != null) && (isEnabled() && !isFocused)) { super.setBorder(isEditable() ? this.rolloverBorder : this.nonEditableRolloverBorder); } } private void mouseOut() { if ((this.normalBorder != null) && (isEnabled()) && !isFocused) { super.setBorder(isEditable() ? this.normalBorder : this.nonEditableBorder); } } public void setAlpha(float alpha) { if ((alpha >= 0.0F) && (alpha <= 1.0F)) { this.alpha = alpha; repaint(); } else { throw new IllegalArgumentException("Invalid alpha:" + alpha); } } public void setBorder(Border border) { this.normalBorder = border; if ((border == null) && (this.visibleInsets != null)) { this.visibleInsets.set(0, 0, 0, 0); } super.setBorder(border); } public void setEditable(boolean editable) { super.setEditable(editable); if (this.borderChange) { mouseOut(); } } public void setEnabled(boolean enabled) { super.setEnabled(enabled); if (this.borderChange) { if (enabled) { mouseOut(); } else if (this.normalBorder != null) { super.setBorder(this.disabledBorder); } } } public void setImage(Image image) { this.image = image; repaint(); } public void setImageOnly(boolean imageOnly) { this.imageOnly = imageOnly; repaint(); } @Deprecated public void setOpaque(boolean isOpaque) { } public void setVisibleInsets(int top, int left, int bottom, int right) { this.visibleInsets.set(top, left, bottom, right); repaint(); } @Deprecated public void updateUI() { } }
/* * Copyright 2015 West Coast Informatics, LLC */ package org.ihtsdo.otf.ts.test.mojo; import java.io.File; import java.util.Arrays; import java.util.Properties; import org.apache.maven.shared.invoker.DefaultInvocationRequest; import org.apache.maven.shared.invoker.DefaultInvoker; import org.apache.maven.shared.invoker.InvocationRequest; import org.apache.maven.shared.invoker.InvocationResult; import org.ihtsdo.otf.ts.Project; import org.ihtsdo.otf.ts.helpers.ConfigUtility; import org.ihtsdo.otf.ts.jpa.services.ContentServiceJpa; import org.ihtsdo.otf.ts.jpa.services.HistoryServiceJpa; import org.ihtsdo.otf.ts.jpa.services.ProjectServiceJpa; import org.ihtsdo.otf.ts.jpa.services.SecurityServiceJpa; import org.ihtsdo.otf.ts.services.ContentService; import org.ihtsdo.otf.ts.services.HistoryService; import org.ihtsdo.otf.ts.services.ProjectService; import org.ihtsdo.otf.ts.services.SecurityService; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; /** * Implementation of the "RF2 Full Load and Unload Test Case". */ public class Rf2FullLoadAndUnloadTest { /** The properties. */ static Properties config; /** The server. */ static String server = "false"; /** * Create test fixtures for class. * * @throws Exception the exception */ @BeforeClass public static void setupClass() throws Exception { config = ConfigUtility.getConfigProperties(); if (ConfigUtility.isServerActive()) { server = "true"; } } /** * Test the sequence: * * <pre> * Run Updatedb mojo in "create" mode to clear the database * TEST: verify there is a concepts table with no contents * Run Reindex mojo to clear the indexes * TEST: verify there is a ConceptJpa index with no contents. * Run the RF2-full mojo against the sample config/src/resources/data/snomedct-20140731-minif" data. * TEST: verify each content table exists with the expected number of entries. * Create a "SNOMEDCT" project (name="Sample Project" description="Sample project." terminology=SNOMEDCT version=latest scope.concepts=138875005 scope.descendants.flag=true admin.user=admin) * TEST: verify there is a project with the expected name * Start an editing cycle for "SNOMEDCT" * TEST: verify there is a release info with the expected name and "planned" flag equal to true. * Remove the terminology "SNOMEDCT" with version "latest" * TEST: verify there is a concepts table with no contents. * </pre> * @throws Exception the exception */ @SuppressWarnings("static-method") @Test public void test() throws Exception { // Createdb InvocationRequest request = new DefaultInvocationRequest(); request.setPomFile(new File("../admin/db/pom.xml")); request.setProfiles(Arrays.asList("Createdb")); request.setGoals(Arrays.asList("clean", "install")); Properties p = new Properties(); p.setProperty("run.config.ts", System.getProperty("run.config.ts")); p.setProperty("server", server); request.setProperties(p); DefaultInvoker invoker = new DefaultInvoker(); InvocationResult result = invoker.execute(request); if (result.getExitCode() != 0) { throw result.getExecutionException(); } // Reindex request = new DefaultInvocationRequest(); request.setPomFile(new File("../admin/lucene/pom.xml")); request.setProfiles(Arrays.asList("Reindex")); request.setGoals(Arrays.asList("clean", "install")); p = new Properties(); p.setProperty("run.config.ts", System.getProperty("run.config.ts")); p.setProperty("server", server); request.setProperties(p); invoker = new DefaultInvoker(); result = invoker.execute(request); if (result.getExitCode() != 0) { throw result.getExecutionException(); } // Verify no contents ContentService service = new ContentServiceJpa(); Assert.assertEquals(0, service.getAllConcepts("SNOMEDCT", "latest") .getCount()); service.close(); service.closeFactory(); // Load RF2 full request = new DefaultInvocationRequest(); request.setPomFile(new File("../admin/loader/pom.xml")); request.setProfiles(Arrays.asList("RF2-full")); request.setGoals(Arrays.asList("clean", "install")); p = new Properties(); p.setProperty("run.config.ts", System.getProperty("run.config.ts")); p.setProperty("server", server); p.setProperty("terminology", "SNOMEDCT"); p.setProperty("version", "latest"); p.setProperty("input.dir", "../../config/src/main/resources/data/snomedct-20140731-minif"); request.setProperties(p); invoker = new DefaultInvoker(); result = invoker.execute(request); if (result.getExitCode() != 0) { throw result.getExecutionException(); } // Verify expected contents service = new ContentServiceJpa(); Assert.assertEquals(10293, service.getAllConcepts("SNOMEDCT", "latest") .getCount()); service.close(); service.closeFactory(); // Verify release info HistoryService historyService = new HistoryServiceJpa(); Assert.assertNotNull(historyService.getReleaseInfo("SNOMEDCT", "20020131")); Assert.assertNotNull(historyService.getReleaseInfo("SNOMEDCT", "20140731")); historyService.close(); historyService.closeFactory(); // Add a SNOMEDCT project request = new DefaultInvocationRequest(); request.setPomFile(new File("../admin/loader/pom.xml")); request.setProfiles(Arrays.asList("Project")); request.setGoals(Arrays.asList("clean", "install")); p = new Properties(); p.setProperty("run.config.ts", System.getProperty("run.config.ts")); p.setProperty("server", server); p.setProperty("name", "Sample project."); p.setProperty("description", "Sample project."); p.setProperty("terminology", "SNOMEDCT"); p.setProperty("version", "latest"); p.setProperty("scope.concepts", "138875005"); p.setProperty("scope.descendants.flag", "true"); p.setProperty("admin.user", "admin"); request.setProperties(p); invoker = new DefaultInvoker(); result = invoker.execute(request); if (result.getExitCode() != 0) { throw result.getExecutionException(); } // Verify project exists ProjectService projectService = new ProjectServiceJpa(); boolean found = false; for (Project project : projectService.getProjects().getObjects()) { if (project.getName().equals("Sample project.") && project.getDescription().equals("Sample project.") && project.getScopeDescendantsFlag() && project.getTerminology().equals("SNOMEDCT") && project.getTerminologyVersion().equals("latest") && project.getScopeConcepts().iterator().next().equals("138875005")) { found = true; } } Assert.assertTrue(found); projectService.close(); projectService.closeFactory(); // Verify admin user SecurityService securityService = new SecurityServiceJpa(); Assert.assertNotNull(securityService.getUser("admin")); securityService.close(); securityService.closeFactory(); // Start SNOMEDCT editing cycle // Add a SNOMEDCT project request = new DefaultInvocationRequest(); request.setPomFile(new File("../admin/release/pom.xml")); request.setProfiles(Arrays.asList("StartEditingCycle")); request.setGoals(Arrays.asList("clean", "install")); p = new Properties(); p.setProperty("run.config.ts", System.getProperty("run.config.ts")); p.setProperty("server", server); p.setProperty("release.version", "20160131"); p.setProperty("terminology", "SNOMEDCT"); p.setProperty("version", "latest"); request.setProperties(p); invoker = new DefaultInvoker(); result = invoker.execute(request); if (result.getExitCode() != 0) { throw result.getExecutionException(); } // Verify release info for 20160131 as "planned" // Verify release info historyService = new HistoryServiceJpa(); Assert.assertNotNull(historyService.getReleaseInfo("SNOMEDCT", "20160131")); Assert.assertFalse(historyService.getReleaseInfo("SNOMEDCT", "20160131") .isPublished()); Assert.assertTrue(historyService.getReleaseInfo("SNOMEDCT", "20160131") .isPlanned()); historyService.close(); historyService.closeFactory(); // Remove terminology request = new DefaultInvocationRequest(); request.setPomFile(new File("../admin/remover/pom.xml")); request.setProfiles(Arrays.asList("Terminology")); request.setGoals(Arrays.asList("clean", "install")); p = new Properties(); p.setProperty("run.config.ts", System.getProperty("run.config.ts")); p.setProperty("server", server); p.setProperty("terminology", "SNOMEDCT"); p.setProperty("version", "latest"); request.setProperties(p); invoker = new DefaultInvoker(); result = invoker.execute(request); if (result.getExitCode() != 0) { throw result.getExecutionException(); } // Verify no contents service = new ContentServiceJpa(); Assert.assertEquals(0, service.getAllConcepts("SNOMEDCT", "latest") .getCount()); service.close(); service.closeFactory(); // Finish by clearing the DB again request = new DefaultInvocationRequest(); request.setPomFile(new File("../admin/db/pom.xml")); request.setProfiles(Arrays.asList("Createdb")); request.setGoals(Arrays.asList("clean", "install")); p = new Properties(); p.setProperty("run.config.ts", System.getProperty("run.config.ts")); p.setProperty("server", server); request.setProperties(p); invoker = new DefaultInvoker(); result = invoker.execute(request); if (result.getExitCode() != 0) { throw result.getExecutionException(); } } /** * Create test fixtures per test. * * @throws Exception the exception */ @Before public void setup() throws Exception { // n/a } /** * Teardown. * * @throws Exception the exception */ @After public void teardown() throws Exception { // n/a } /** * Teardown class. * * @throws Exception the exception */ @AfterClass public static void teardownClass() throws Exception { // n/a } }
// HSDeskGear // //Copyright (c) 2014 HelpStack (http://helpstack.io) // //Permission is hereby granted, free of charge, to any person obtaining a copy //of this software and associated documentation files (the "Software"), to deal //in the Software without restriction, including without limitation the rights //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //copies of the Software, and to permit persons to whom the Software is //furnished to do so, subject to the following conditions: // //The above copyright notice and this permission notice shall be included in //all copies or substantial portions of the Software. // //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //THE SOFTWARE. package com.tenmiles.helpstack.gears; import android.net.Uri; import android.util.Base64; import com.android.volley.AuthFailureError; import com.android.volley.DefaultRetryPolicy; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.tenmiles.helpstack.logic.HSGear; import com.tenmiles.helpstack.logic.OnFetchedArraySuccessListener; import com.tenmiles.helpstack.logic.OnFetchedSuccessListener; import com.tenmiles.helpstack.logic.OnNewTicketFetchedSuccessListener; import com.tenmiles.helpstack.model.HSKBItem; import com.tenmiles.helpstack.model.HSTicket; import com.tenmiles.helpstack.model.HSTicketUpdate; import com.tenmiles.helpstack.model.HSUploadAttachment; import com.tenmiles.helpstack.model.HSUser; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import static com.tenmiles.helpstack.model.HSUser.createNewUserWithDetails; public class HSDeskGear extends HSGear { private String instanceUrl; private String to_help_email; private String staff_login_email; private String staff_login_password; public HSDeskGear(String instanceUrl, String to_help_email, String staff_login_email, String staff_login_password) { if (!instanceUrl.endsWith("/")) { instanceUrl = instanceUrl.concat("/"); } this.instanceUrl = instanceUrl; this.to_help_email = to_help_email; this.staff_login_email = staff_login_email; this.staff_login_password = staff_login_password; } @Override public void fetchKBArticle(String cancelTag, HSKBItem section, RequestQueue queue, OnFetchedArraySuccessListener successListener, Response.ErrorListener errorListener) { if (section == null) { // String url = getApiUrl().concat("topics"); DeskJsonObjectRequest request = new DeskJsonObjectRequest(cancelTag, url, new DeskArrayBaseListener<JSONObject>(successListener, errorListener) { @Override public void onResponse(JSONObject sectionsArray) { try { JSONArray allSectionsArray = sectionsArray.getJSONObject("_embedded").getJSONArray("entries"); HSKBItem[] array = readSectionsFromEntries(allSectionsArray); successListener.onSuccess(array); } catch (JSONException e) { e.printStackTrace(); errorListener.onErrorResponse(new VolleyError("Parsing failed when getting sections from data")); } } }, errorListener); addRequestAndStartQueue(queue, request); } else { // Fetch articles under that section. DeskJsonObjectRequest request = new DeskJsonObjectRequest(cancelTag, section.getId(), null, new DeskArrayBaseListener<JSONObject>(successListener, errorListener) { @Override public void onResponse(JSONObject sectionsObject) { HSKBItem[] array; try { array = retrieveArticlesFromSection(sectionsObject); successListener.onSuccess(array); } catch (JSONException e) { e.printStackTrace(); errorListener.onErrorResponse(new VolleyError("Error when fetching articles in section")); } } }, errorListener); addRequestAndStartQueue(queue, request); } } @Override public void registerNewUser(final String cancelTag, final String firstName, final String lastname, final String emailAddress, final RequestQueue queue,OnFetchedSuccessListener successListener, Response.ErrorListener errorListener) { HSUser user = createNewUserWithDetails(firstName, lastname, emailAddress); DeskJsonObjectRequest request = new DeskJsonObjectRequest(cancelTag, getApiUrl().concat("customers/search?email=").concat(user.getEmail()), new CreateNewUserSuccessListener(user, successListener, errorListener) { @Override public void onResponse(JSONObject responseObject) { int totalEntries = 0; try { totalEntries = responseObject.getInt("total_entries"); } catch (JSONException e) { e.printStackTrace(); errorListener.onErrorResponse(new VolleyError("Parsing error when getting Total Entries")); } if (totalEntries >= 1) { try { JSONObject validUserDetail = null; JSONArray couldBeValidUsersArray = responseObject.getJSONObject("_embedded").getJSONArray("entries"); int couldBeValidUsersArrayLength = couldBeValidUsersArray.length(); for (int i = 0; i < couldBeValidUsersArrayLength; i++) { JSONObject couldBeValidUserDetail = couldBeValidUsersArray.getJSONObject(i); JSONArray emailsArray = couldBeValidUserDetail.getJSONArray("emails"); int emailsArrayLength = emailsArray.length(); for (int j = 0; j < emailsArrayLength; j++) { JSONObject emailDetails = couldBeValidUsersArray.getJSONObject(j); if (emailDetails.getString("value").equals(user.getEmail())) { validUserDetail = couldBeValidUserDetail; break; } } if (validUserDetail != null) { break; } } if (validUserDetail != null) { String firstName = validUserDetail.getString("first_name"); String lastName = validUserDetail.getString("last_name"); String email = validUserDetail.getJSONArray("emails").getJSONObject(0).getString("value"); String userLink = validUserDetail.getJSONObject("_links").getJSONObject("self").getString("href"); HSUser validUser = createNewUserWithDetails(firstName, lastName, email, userLink); successListener.onSuccess(validUser); } else { errorListener.onErrorResponse(new VolleyError("Error when getting details of users")); } } catch (JSONException e) { e.printStackTrace(); errorListener.onErrorResponse(new VolleyError("Error when getting single user from multiple users")); } } else { //not found in search. //create a new user and send it as valid user. JSONObject emailContents = new JSONObject(); JSONArray emails = new JSONArray(); final JSONObject params = new JSONObject(); try { emailContents.put("type", "home"); emailContents.put("value", user.getEmail()); emails.put(emailContents); params.put("first_name", user.getFirstName()); params.put("last_name", user.getLastName()); params.put("emails", emails); DeskJsonObjectRequest request = new DeskJsonObjectRequest(cancelTag, getApiUrl().concat("customers"), params, new CreateNewUserSuccessListener(user, successListener, errorListener) { @Override public void onResponse(JSONObject responseObject) { String firstName; String lastName; String apiHref; HSUser validatedUser = null; JSONArray emailsArray; try { firstName = responseObject.getString("first_name"); lastName = responseObject.getString("last_name"); apiHref = responseObject.getJSONObject("_links").getJSONObject("self").getString("href"); emailsArray = responseObject.getJSONArray("emails"); int eventsArrayLength = emailsArray.length(); for (int i = 0; i < eventsArrayLength; i++) { JSONObject emailObject = emailsArray.getJSONObject(i); if (emailObject.getString("type").equals("home")) { validatedUser = createNewUserWithDetails(firstName, lastName, emailObject.getString("value"), apiHref); } } successListener.onSuccess(validatedUser); } catch (JSONException e) { e.printStackTrace(); errorListener.onErrorResponse(new VolleyError("Error when creating new user with details")); } } }, errorListener); addRequestAndStartQueue(queue, request); } catch (JSONException e) { e.printStackTrace(); errorListener.onErrorResponse(new VolleyError("Error when setting customer details as parameters")); } } } }, errorListener); addRequestAndStartQueue(queue, request); } @Override public void createNewTicket(final String cancelTag, HSUser user, String message, String body, final HSUploadAttachment[] attachments, final RequestQueue queue, OnNewTicketFetchedSuccessListener successListener, Response.ErrorListener errorListener) { JSONObject ticketJson = null; try { ticketJson = retrieveTicketProperties(user, body, message); } catch (JSONException e) { e.printStackTrace(); errorListener.onErrorResponse(new VolleyError("Error when getting ticket properties")); return; } DeskJsonObjectRequest request = new DeskJsonObjectRequest(cancelTag, getApiUrl().concat("cases"), ticketJson, new CreateNewTicketSuccessListener(user, successListener, errorListener) { @Override public void onResponse(JSONObject response) { try { String subject = response.getString("subject"); String caseIdHref = response.getJSONObject("_links").getJSONObject("self").getString("href"); String caseId = retrieveSectionId(caseIdHref); final HSTicket ticket = HSTicket.createATicket(caseId, subject, caseIdHref); // If there are attachment to be uploaded, upload attachment if (attachments != null && attachments.length > 0) { HSUploadAttachment attachmentObject = attachments[0]; // We are handling the number of attachments in constructor uploadAttachmentToServer(cancelTag, caseIdHref, attachmentObject, queue, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject jsonObject) { successListener.onSuccess(user, ticket); } }, errorListener); } else { successListener.onSuccess(this.user, ticket); } } catch (JSONException e) { e.printStackTrace(); errorListener.onErrorResponse(new VolleyError("Parsing failed when creating a ticket")); } } }, errorListener); addRequestAndStartQueue(queue, request); // For ticket creation } @Override public void fetchAllUpdateOnTicket(final String cancelTag, final HSTicket ticket, final HSUser user, final RequestQueue queue, final OnFetchedArraySuccessListener successListener, Response.ErrorListener errorListener) { final String apiHref = getApiHref(ticket); String url = instanceUrl.concat(apiHref).concat("/message"); String userId = user.getUserId(); DeskJsonObjectRequest request = new DeskJsonObjectRequest(cancelTag, url, new DeskArrayBaseListener<JSONObject>(successListener, errorListener) { @Override public void onResponse(JSONObject responseObject) { try { String content = responseObject.getString("body"); String from = responseObject.getString("from"); final Date update_time = parseTime(responseObject.getString("updated_at")); HSTicketUpdate originalMessage = HSTicketUpdate.createUpdateByUser(ticket.getTicketId(), from, content, update_time, null); final ArrayList<HSTicketUpdate> ticketUpdates = new ArrayList<HSTicketUpdate>(); ticketUpdates.add(originalMessage); String repliesUrl = instanceUrl.concat(apiHref).concat("/replies"); DeskJsonObjectRequest repliesRequest = new DeskJsonObjectRequest(cancelTag, repliesUrl, null, new DeskArrayBaseListener<JSONObject>(successListener, errorListener) { @Override public void onResponse(JSONObject repliesObject) { String from = null; String content = null; boolean isUpdateTypeUserReply; Date updated_time; try { JSONArray entriesArray = repliesObject.getJSONObject("_embedded").getJSONArray("entries"); int eventsArrayLength = entriesArray.length(); for (int i = 0; i < eventsArrayLength; i++) { JSONObject replyObject = entriesArray.getJSONObject(i); if (!replyObject.isNull("from")) { from = replyObject.getString("from"); } content = replyObject.getString("body"); if (replyObject.getString("direction").equals("out")) { isUpdateTypeUserReply = false; } else { isUpdateTypeUserReply = true; } updated_time = parseTime(replyObject.getString("updated_at")); HSTicketUpdate replyForTicket; if (isUpdateTypeUserReply) { replyForTicket = HSTicketUpdate.createUpdateByUser(ticket.getTicketId(), from, content, updated_time, null); } else { replyForTicket = HSTicketUpdate.createUpdateByStaff(ticket.getTicketId(), from, content, updated_time, null); } ticketUpdates.add(replyForTicket); } HSTicketUpdate[] array = new HSTicketUpdate[0]; array = ticketUpdates.toArray(array); successListener.onSuccess(array); } catch (JSONException e) { e.printStackTrace(); errorListener.onErrorResponse(new VolleyError("Parsing failed when fetching all replies for a ticket")); } } }, errorListener); addRequestAndStartQueue(queue, repliesRequest); } catch (JSONException e) { e.printStackTrace(); errorListener.onErrorResponse(new VolleyError("Parsing failed when fetching all updates for a ticket")); } } }, errorListener); addRequestAndStartQueue(queue, request); } @Override public void addReplyOnATicket(final String cancelTag, final String message, final HSUploadAttachment[] attachments, final HSTicket ticket, final HSUser user, final RequestQueue queue, final OnFetchedSuccessListener successListener, Response.ErrorListener errorListener) { JSONObject replyJson = null; try { replyJson = createUserReply(message, to_help_email); } catch (JSONException e) { e.printStackTrace(); errorListener.onErrorResponse(new VolleyError("Error when creating user reply")); } DeskJsonObjectRequest request = new DeskJsonObjectRequest(cancelTag, instanceUrl.concat(getApiHref(ticket)).concat("/replies"), replyJson, new DeskBaseListener<JSONObject>(successListener, errorListener) { @Override public void onResponse(JSONObject responseObject) { String content = null; String userName = null; Date update_time = null; try { if (!responseObject.isNull("from")) { userName = responseObject.getString("from"); } if (!responseObject.isNull("body")) { content = responseObject.getString("body"); } if (!responseObject.isNull("updated_at")) { update_time = parseTime(responseObject.getString("updated_at")); } final HSTicketUpdate userReply = HSTicketUpdate.createUpdateByUser(ticket.getTicketId(), userName, content, update_time, null); if (attachments != null && attachments.length > 0) { HSUploadAttachment attachmentObject = attachments[0]; // We are handling the number of attachments in constructor uploadAttachmentToServer(cancelTag, ticket.getApiHref(), attachmentObject, queue, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject jsonObject) { successListener.onSuccess(userReply); } }, errorListener); } else { successListener.onSuccess(userReply); } } catch (JSONException e) { e.printStackTrace(); errorListener.onErrorResponse(new VolleyError("Error when parsing replies")); } } }, errorListener); addRequestAndStartQueue(queue, request); } private String getApiUrl() { return this.instanceUrl.concat("api/v2/"); } private String getApiHref(HSTicket ticket) { String apiHref = ticket.getApiHref(); if (apiHref.startsWith("/")) { apiHref = apiHref.substring(1); } return apiHref; } private void addRequestAndStartQueue(RequestQueue queue, DeskJsonObjectRequest request) { queue.add(request); queue.start(); } private void uploadAttachmentToServer(String cancelTag, String caseId, HSUploadAttachment attachmentObject, RequestQueue queue, Response.Listener<JSONObject> successListener, Response.ErrorListener errorListener) throws JSONException { Uri.Builder builder = new Uri.Builder(); builder.encodedPath(instanceUrl); builder.appendEncodedPath(caseId.substring(1)); builder.appendEncodedPath("attachments"); String attachmentUrl = builder.build().toString(); String attachmentFileName = attachmentObject.getAttachment().getFileName() == null ? "picture":attachmentObject.getAttachment().getFileName(); String attachmentMimeType = attachmentObject.getAttachment().getMime_type(); try { JSONObject attachmentPostObject = new JSONObject(); InputStream input = attachmentObject.generateInputStreamToUpload(); ByteArrayOutputStream output = new ByteArrayOutputStream(); byte[] buffer = new byte[512]; try { int n = 0; while (-1 != (n = input.read(buffer))) { output.write(buffer, 0, n); } } catch (IOException e) { e.printStackTrace(); } attachmentPostObject.put("content", Base64.encodeToString(output.toByteArray(), Base64.DEFAULT)); attachmentPostObject.put("content_type", attachmentMimeType); attachmentPostObject.put("file_name", attachmentFileName); DeskJsonObjectRequest attachmentRequest = new DeskJsonObjectRequest(cancelTag, attachmentUrl, attachmentPostObject, successListener, errorListener); addRequestAndStartQueue(queue, attachmentRequest); // For Attachments } catch (FileNotFoundException e) { errorListener.onErrorResponse(new VolleyError("File not found")); e.printStackTrace(); } } private String retrieveSectionId(String href) throws JSONException { // href will be of the form: /api/v2/topic/<section id> // <section id> will therefore be the text after the last / return href.substring(href.lastIndexOf("/")+1); } private HSKBItem[] retrieveArticlesFromSection(JSONObject sectionObject) throws JSONException { ArrayList<HSKBItem> kbArticleArray = new ArrayList<HSKBItem>(); JSONArray articleArray = sectionObject.getJSONObject("_embedded").getJSONArray("entries"); for (int j = 0; j < articleArray.length(); j++) { JSONObject arrayObject = articleArray.getJSONObject(j); if (arrayObject.getBoolean("in_support_center")) { HSKBItem item = HSKBItem.createForArticle(null, arrayObject.getString("subject").trim(), arrayObject.getString("body")); kbArticleArray.add(item); } } HSKBItem[] array = new HSKBItem[0]; array = kbArticleArray.toArray(array); return array; } private HSKBItem[] readSectionsFromEntries(JSONArray sectionsArray) throws JSONException { ArrayList<HSKBItem> kbSectionArray = new ArrayList<HSKBItem>(); int count = sectionsArray.length(); for (int i = 0; i < count; i++) { JSONObject sectionObject = sectionsArray.getJSONObject(i); if (sectionObject != null && sectionObject.getBoolean("in_support_center")) { String href = sectionObject.getJSONObject("_links").getJSONObject("articles").getString("href"); href = instanceUrl.concat(href.substring(1)); HSKBItem item = HSKBItem.createForSection(href, sectionObject.getString("name")); kbSectionArray.add(item); } } HSKBItem[] array = new HSKBItem[0]; array = kbSectionArray.toArray(array); return array; } private JSONObject retrieveTicketProperties(HSUser user, String body, String message) throws JSONException { JSONObject messageFields = new JSONObject(); JSONObject customerLinks = new JSONObject(); JSONObject customerParameter = new JSONObject(); JSONObject params = new JSONObject(); messageFields.put("direction", "in"); messageFields.put("from", user.getEmail()); messageFields.put("to", to_help_email); messageFields.put("subject", message); messageFields.put("body", body); customerLinks.put("href", user.getApiHref()); customerLinks.put("class", "customer"); customerParameter.put("customer", customerLinks); params.put("type", "email"); params.put("subject", message); params.put("_links", customerParameter); params.put("message", messageFields); return params; } private JSONObject createUserReply(String message, String email) throws JSONException { JSONObject userReply = new JSONObject(); userReply.put("direction", "in"); userReply.put("body", message); userReply.put("to", email); return userReply; } protected static Date parseTime(String dateString) { Date givenTimeDate = null; try { givenTimeDate = parseUTCString(dateString,"yyyy-MM-dd'T'HH:mm:ss'Z'"); } catch (ParseException e) { try { givenTimeDate = parseUTCString(dateString,"yyyy-MM-dd"); } catch (ParseException e1) { try { givenTimeDate = parseUTCString(dateString,"yyyy-MM-dd HH:mm:ss.SSSSZ"); } catch (ParseException e2) { e2.printStackTrace(); } } } return givenTimeDate; } private static Date parseUTCString(String timeStr, String pattern) throws ParseException { SimpleDateFormat format = new SimpleDateFormat(pattern, Locale.getDefault()); format.setTimeZone(TimeZone.getTimeZone("UTC")); return format.parse(timeStr); } private abstract class DeskArrayBaseListener<T> implements Response.Listener<T> { protected OnFetchedArraySuccessListener successListener; protected Response.ErrorListener errorListener; public DeskArrayBaseListener(OnFetchedArraySuccessListener successListener, Response.ErrorListener errorListener) { this.successListener = successListener; this.errorListener = errorListener; } } private abstract class DeskBaseListener<T> implements Response.Listener<T> { protected OnFetchedSuccessListener successListener; protected Response.ErrorListener errorListener; public DeskBaseListener(OnFetchedSuccessListener successListener, Response.ErrorListener errorListener) { this.successListener = successListener; this.errorListener = errorListener; } } private class DeskJsonObjectRequest extends JsonObjectRequest { protected static final int TIMEOUT_MS = 10000; /** Default number of retries for image requests */ protected static final int MAX_RETRIES = 0; /** Default backoff multiplier for image requests */ protected static final float BACKOFF_MULT = 0f; HashMap<String, String> headers = new HashMap<String, String>(); // Post public DeskJsonObjectRequest(String cancelTag, String url, JSONObject ticketJson, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) { super(url, ticketJson, listener, errorListener); addRequestParameters(cancelTag); } // Get public DeskJsonObjectRequest(String cancelTag, String url, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) { super(url, null, listener, errorListener); addRequestParameters(cancelTag); } private void addRequestParameters(String cancelTag) { this.setTag(cancelTag); this.addCredential(staff_login_email, staff_login_password); this.setRetryPolicy(new DefaultRetryPolicy(DeskJsonObjectRequest.TIMEOUT_MS, DeskJsonObjectRequest.MAX_RETRIES, DeskJsonObjectRequest.BACKOFF_MULT)); } public void addCredential(String name, String password) { String credentials = name.concat(":").concat(password); String base64EncodedCredentials = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP); headers.put("Authorization", "Basic ".concat(base64EncodedCredentials)); } @Override public Map<String, String> getHeaders() throws AuthFailureError { return headers; } } private abstract class CreateNewTicketSuccessListener implements Response.Listener<JSONObject> { protected HSUser user; protected OnNewTicketFetchedSuccessListener successListener; protected Response.ErrorListener errorListener; public CreateNewTicketSuccessListener(HSUser user, OnNewTicketFetchedSuccessListener successListener, Response.ErrorListener errorListener) { this.user = user; this.successListener = successListener; this.errorListener = errorListener; } } private abstract class CreateNewUserSuccessListener implements Response.Listener<JSONObject> { protected HSUser user; protected OnFetchedSuccessListener successListener; protected Response.ErrorListener errorListener; public CreateNewUserSuccessListener(HSUser user, OnFetchedSuccessListener successListener, Response.ErrorListener errorListener) { this.user = user; this.successListener = successListener; this.errorListener = errorListener; } } }
package org.broadinstitute.hellbender.engine.filters; import htsjdk.variant.variantcontext.Allele; import htsjdk.variant.variantcontext.VariantContext; import htsjdk.variant.variantcontext.VariantContextBuilder; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.util.*; public final class CountingVariantFilterUnitTest { static final VariantContext goodVariant = new VariantContextBuilder("Zuul", "1", 2, 2, Collections.singletonList(Allele.create("A", true))).make(); static final VariantContext endBad = new VariantContextBuilder("Peter", "1", 2, 20, Collections.singletonList(Allele.create("TTTTTTTTTTTTTTTTTTT", true))).make(); static final VariantContext startBad = new VariantContextBuilder("Ray", "1", 1, 2, Collections.singletonList(Allele.create("AA", true))).make(); static final VariantContext bothBad = new VariantContextBuilder("Egon", "1", 1, 20, Collections.singletonList(Allele.create("TTTTTTTTTTTTTTTTTTTT", true))).make(); static final VariantFilter startOk = new VariantFilter() { private static final long serialVersionUID = 1L; @Override public boolean test(final VariantContext variant){return variant.getStart() > 1;} }; static final VariantFilter endOk = new VariantFilter() { private static final long serialVersionUID = 1L; @Override public boolean test(final VariantContext variant){return variant.getEnd() <= 10;} }; // Helper to verify post-filtering filter state private void verifyFilterState(CountingVariantFilter vf, boolean expected) { long count = vf.getFilteredCount(); String vfSummary = vf.getSummaryLine(); if (expected) { Assert.assertTrue(0 == count); Assert.assertEquals(0, vfSummary.indexOf("No variants filtered")); } else { Assert.assertTrue(1 == count); Assert.assertEquals(0, vfSummary.indexOf("1 variant(s) filtered")); } } @DataProvider(name = "variantsStartEnd") public Object[][] variantsStartEnd() { return new Object[][]{ {goodVariant, true, true}, {startBad, false, true}, {endBad, true, false}, {bothBad, false, false} }; } @Test(dataProvider = "variantsStartEnd") public void testTest(VariantContext variant, boolean start, boolean end) { CountingVariantFilter startOkCounting = new CountingVariantFilter(startOk); Assert.assertEquals(startOkCounting.test(variant), start); verifyFilterState(startOkCounting, start); CountingVariantFilter endOkCounting = new CountingVariantFilter(endOk); Assert.assertEquals(endOkCounting.test(variant), end); verifyFilterState(endOkCounting, end); } @Test(dataProvider = "variantsStartEnd") public void testNegate(VariantContext variant, boolean start, boolean end) { CountingVariantFilter notStartOkCounting = new CountingVariantFilter(startOk).negate(); Assert.assertEquals(notStartOkCounting.test(variant), !start); verifyFilterState(notStartOkCounting, !start); CountingVariantFilter notEndOkCounting = new CountingVariantFilter(endOk).negate(); Assert.assertEquals(notEndOkCounting.test(variant), !end); verifyFilterState(notEndOkCounting, !end); } @DataProvider(name = "variantsAnd") public Object[][] variantsAnd() { return new Object[][]{ {goodVariant, true}, {startBad, false}, {endBad, false}, {bothBad, false} }; } @Test(dataProvider = "variantsAnd") public void testAnd(VariantContext variant, boolean expected) { CountingVariantFilter startAndEndOk = new CountingVariantFilter(startOk).and(new CountingVariantFilter(endOk)); Assert.assertEquals(startAndEndOk.test(variant), expected); verifyFilterState(startAndEndOk, expected); CountingVariantFilter endAndStartOk = new CountingVariantFilter(endOk).and(new CountingVariantFilter(startOk)); Assert.assertEquals(endAndStartOk.test(variant), expected); verifyFilterState(endAndStartOk, expected); } @DataProvider(name = "variantsOr") public Object[][] variantsOr() { return new Object[][]{ {goodVariant, true}, {startBad, true}, {endBad, true}, {bothBad, false} }; } @Test(dataProvider = "variantsOr") public void testOr(VariantContext variant, boolean expected) { CountingVariantFilter startOrEndOk = new CountingVariantFilter(startOk).or(new CountingVariantFilter(endOk)); Assert.assertEquals(startOrEndOk.test(variant), expected); verifyFilterState(startOrEndOk, expected); CountingVariantFilter endOrStartOk = new CountingVariantFilter(endOk).or(new CountingVariantFilter(startOk)); Assert.assertEquals(endOrStartOk.test(variant), expected); verifyFilterState(endOrStartOk, expected); } @DataProvider(name = "deeper") public Object[][] deeper() { return new Object[][]{ {goodVariant, false}, {startBad, true}, {endBad, true}, {bothBad, false} }; } private CountingVariantFilter variantChecksOut() { return new CountingVariantFilter(startOk) .or(new CountingVariantFilter(endOk)) .and(new CountingVariantFilter(new VariantFilter() { private static final long serialVersionUID = 1L; @Override public boolean test(final VariantContext variant){return !variant.getSource().equals("Zuul");} })); } @Test(dataProvider = "deeper") public void testDeeperChaining(VariantContext variant, boolean expected) { CountingVariantFilter variantCheckOutCounting = variantChecksOut(); Assert.assertEquals(variantCheckOutCounting.test(variant), expected); verifyFilterState(variantCheckOutCounting, expected); variantCheckOutCounting = variantChecksOut().and(variantChecksOut()); Assert.assertEquals(variantCheckOutCounting.test(variant), expected); verifyFilterState(variantCheckOutCounting, expected); variantCheckOutCounting = variantChecksOut().and(new CountingVariantFilter( new VariantFilter() { private static final long serialVersionUID = 1L; @Override public boolean test(final VariantContext variant){return false;} })); Assert.assertEquals(variantCheckOutCounting.test(variant), false); verifyFilterState(variantCheckOutCounting, false); variantCheckOutCounting = variantChecksOut().or(new CountingVariantFilter( new VariantFilter() { private static final long serialVersionUID = 1L; @Override public boolean test(final VariantContext variant){return true;} })); Assert.assertEquals(variantCheckOutCounting.test(variant), true); verifyFilterState(variantCheckOutCounting, true); } @DataProvider(name = "multipleRejection") public Object[][] multipleRejection() { return new Object[][] { { new VariantContext[] {goodVariant, goodVariant, goodVariant}, 0 }, { new VariantContext[] {goodVariant, goodVariant, bothBad }, 1 }, { new VariantContext[] { startBad, bothBad, goodVariant, startBad }, 3 }, }; } @Test(dataProvider = "multipleRejection") public void testRootFilterCounts(VariantContext[] variants, int expectedRejectionCount) { CountingVariantFilter startOkCounting = new CountingVariantFilter(startOk); Arrays.asList(variants).stream().filter(startOkCounting).count(); // force the stream to be consumed Assert.assertEquals(startOkCounting.getFilteredCount(), expectedRejectionCount); startOkCounting.resetFilteredCount(); Assert.assertEquals(startOkCounting.getFilteredCount(), 0); } @DataProvider(name = "subFilterCounts") public Object[][] subFilterCounts() { return new Object[][] { { new VariantContext[]{goodVariant, startBad, bothBad, bothBad}, 1L, 2L, 1L }, { new VariantContext[]{goodVariant, goodVariant, goodVariant, bothBad }, 3L, 3L, 3L }, { new VariantContext[]{goodVariant, startBad, endBad, bothBad}, 2L, 3L, 2L }, }; } @Test(dataProvider = "subFilterCounts") public void testSubFilterCounts(VariantContext[] variants, long totalRejections, long startEndRejections, long nameRejections) { CountingVariantFilter badStart = new CountingVariantFilter( new VariantFilter() { private static final long serialVersionUID = 1L; @Override public boolean test(final VariantContext variant){return variant.getStart() <= 1;} } ); CountingVariantFilter badEnd = new CountingVariantFilter( new VariantFilter() { private static final long serialVersionUID = 1L; @Override public boolean test(final VariantContext variant){return variant.getEnd() > 10;} } ); CountingVariantFilter badStartAndEnd = badStart.and(badEnd); CountingVariantFilter isRay= new CountingVariantFilter( new VariantFilter() { private static final long serialVersionUID = 1L; @Override public boolean test(final VariantContext variant){return variant.getSource().equals("Ray");} } ); CountingVariantFilter isEgon = new CountingVariantFilter( new VariantFilter() { private static final long serialVersionUID = 1L; @Override public boolean test(final VariantContext variant){return variant.getSource().equals("Egon");} } ); CountingVariantFilter isRayOrEgon = isRay.or(isEgon); CountingVariantFilter compoundFilter = badStartAndEnd.or(isRayOrEgon); Arrays.asList(variants).stream().filter(compoundFilter).count(); // force the stream to be consumed Assert.assertEquals(compoundFilter.getFilteredCount(), totalRejections); Assert.assertEquals(badStartAndEnd.getFilteredCount(), startEndRejections); Assert.assertEquals(isRayOrEgon.getFilteredCount(), nameRejections); // test if reset filtered count is correctly propagated compoundFilter.resetFilteredCount(); Assert.assertEquals(compoundFilter.getFilteredCount(), 0); Assert.assertEquals(badStartAndEnd.getFilteredCount(), 0); Assert.assertEquals(isRayOrEgon.getFilteredCount(), 0); Assert.assertEquals(badStart.getFilteredCount(), 0); Assert.assertEquals(badEnd.getFilteredCount(), 0); Assert.assertEquals(isRay.getFilteredCount(), 0); Assert.assertEquals(isEgon.getFilteredCount(), 0); } @Test public void testFromListNull() { CountingVariantFilter vf = CountingVariantFilter.fromList(null); Assert.assertTrue(vf.delegateFilter == VariantFilterLibrary.ALLOW_ALL_VARIANTS); } @Test public void testFromListEmpty() { CountingVariantFilter vf = CountingVariantFilter.fromList(Collections.emptyList()); Assert.assertTrue(vf.delegateFilter == VariantFilterLibrary.ALLOW_ALL_VARIANTS); } @Test public void testFromListSingle() { final VariantFilter snpFilter = VariantContext::isSNP; List<VariantFilter> filters = new ArrayList<>(); filters.add(snpFilter); CountingVariantFilter vf = CountingVariantFilter.fromList(filters); Assert.assertTrue(vf.delegateFilter == snpFilter); } @Test public void testFromListMultiOrdered() { final VariantFilter snpFilter = VariantContext::isSNP; final VariantFilter biallelicFilter = VariantContext::isBiallelic; final VariantFilter symbolicFilter = VariantContext::isSymbolic; List<VariantFilter> filters = new ArrayList<>(); filters.add(snpFilter); filters.add(biallelicFilter); filters.add(symbolicFilter); // Since we want to ensure that order of the input is honored, we need to test the // structure of the filter rather than the result CountingVariantFilter vf = CountingVariantFilter.fromList(filters); Assert.assertTrue(vf.getClass() == CountingVariantFilter.CountingAndVariantFilter.class); CountingVariantFilter.CountingAndVariantFilter andFilter = (CountingVariantFilter.CountingAndVariantFilter) vf; // lhs is a Counting and filter; rhs is a counting filter that delegates to symbolicFilter Assert.assertTrue(andFilter.lhs.getClass() == CountingVariantFilter.CountingAndVariantFilter.class); Assert.assertTrue(andFilter.rhs.delegateFilter == symbolicFilter); andFilter = (CountingVariantFilter.CountingAndVariantFilter) andFilter.lhs; // lhs is a Counting filter that delegates to snpFilter; rhs is a // counting filter that delegates to biallelicFilter Assert.assertTrue(andFilter.lhs.getClass() == CountingVariantFilter.class); Assert.assertTrue(andFilter.lhs.delegateFilter == snpFilter); Assert.assertTrue(andFilter.rhs.getClass() == CountingVariantFilter.class); Assert.assertTrue(andFilter.rhs.delegateFilter == biallelicFilter); } }
package game; import game.GameLogic.CombinationType; import java.util.ArrayList; import java.util.Collections; import java.util.List; import model.Card; public class GameAI { private static GameAI instance = null; private GameAI() { } public static GameAI getInstance() { if(instance == null){ synchronized (GameAI.class) { if(instance == null){ instance = new GameAI(); } } } return instance; } public List<Integer> getAIPopCardsIndex(CombinationType lastType, List<Card> lastCards, List<Card> cards, List<Card> popCards) { List<Integer> indexList = new ArrayList<Integer>(); switch (lastType) { case NEWROUND: indexList = getAIPopCardsForTypeNONE(lastCards, cards, popCards); break; case NONE: indexList = getAIPopCardsForTypeNONE(lastCards, cards, popCards); break; case ONE: indexList = getAIPopCardsForTypeONE(lastCards, cards, popCards); break; case TWO: indexList = getAIPopCardsForTypeTWO(lastCards, cards, popCards); break; case THREE: indexList = getAIPopCardsForTypeTHREE(lastCards, cards, popCards); break; case FOUR: indexList = getAIPopCardsForTypeFOUR(lastCards, cards, popCards); break; case THREE_WITH_ONE: indexList = getAIPopCardsForTypeTHREEWITHONE(lastCards, cards, popCards); break; case THREE_WITH_TWO: indexList = getAIPopCardsForTypeTHREEWITHTWO(lastCards, cards, popCards); break; case FOUR_WITH_TWO: indexList = getAIPopCardsForTypeFOURWITHTWO(lastCards, cards, popCards); break; case SINGLE_STRAIGHT: indexList = getAIPopCardsForTypeSINGLESTRAIGHT(lastCards, cards, popCards); break; case DOUBLE_STRAIGHT: indexList = getAIPopCardsForTypeDOUBLESTRAIGHT(lastCards, cards, popCards); break; case KING_KILLER: break; default: break; } return indexList; } public void getAIPopCards(CombinationType lastType, List<Card> lastCards, List<Card> cards, List<Card> popCards) { getPopCardsFromIndexList(cards, popCards, getAIPopCardsIndex(lastType, lastCards, cards, popCards)); } private List<Integer> getAIPopCardsForTypeNONE(List<Card> lastCards, List<Card> cards, List<Card> popCards) { List<Integer> res = new ArrayList<Integer>(); res.add(0); return res; } private List<Integer> getAIPopCardsForTypeONE(List<Card> lastCards, List<Card> cards, List<Card> popCards) { int last = lastCards.get(0).getCardType().getValue(); int size = cards.size(); List<Integer> res = new ArrayList<Integer>(); for(int i=0;i<size;i++){ Card card = cards.get(i); if(card.getCardType().getValue() > last){ res.add(i); break; } } return res; } private List<Integer> getAIPopCardsForTypeTWO(List<Card> lastCards, List<Card> cards, List<Card> popCards) { int last = lastCards.get(0).getCardType().getValue(); int size = cards.size(); List<Card> tempCards = new ArrayList<Card>(); List<Integer> res = new ArrayList<Integer>(); for(int i=0;i<size-1;i++){ tempCards = getRangeList(cards, i, i+1); if(GameLogic.hasSameTwo(tempCards)){ if(tempCards.get(0).getCardType().getValue() > last){ res.add(i); res.add(i+1); break; } } } return res; } private List<Integer> getAIPopCardsForTypeTHREE(List<Card> lastCards, List<Card> cards, List<Card> popCards) { int last = lastCards.get(0).getCardType().getValue(); int size = cards.size(); List<Card> tempCards = new ArrayList<Card>(); List<Integer> res = new ArrayList<Integer>(); for(int i=0;i<size-2;i++){ tempCards = getRangeList(cards, i, i+2); if(GameLogic.hasSameThree(tempCards)){ if(tempCards.get(0).getCardType().getValue() > last){ res.add(i); res.add(i+1); res.add(i+2); break; } } } return res; } private List<Integer> getAIPopCardsForTypeFOUR(List<Card> lastCards, List<Card> cards, List<Card> popCards) { int last = lastCards.get(0).getCardType().getValue(); int size = cards.size(); List<Card> tempCards = new ArrayList<Card>(); List<Integer> res = new ArrayList<Integer>(); for(int i=0;i<size-3;i++){ tempCards = getRangeList(cards, i, i+3); if(GameLogic.hasSameFour(tempCards)){ if(tempCards.get(0).getCardType().getValue() > last){ res.add(i); res.add(i+1); res.add(i+2); res.add(i+3); break; } } } return res; } private List<Integer> getAIPopCardsForTypeTHREEWITHONE(List<Card> lastCards, List<Card> cards, List<Card> popCards) { int last = lastCards.get(2).getCardType().getValue(); int size = cards.size(); List<Card> tempCards = new ArrayList<Card>(); List<Integer> res = new ArrayList<Integer>(); for(int i=0;i<size-3;i++){ tempCards = getRangeList(cards, i, i+3); if(GameLogic.hasThreeWithOne(tempCards)){ if(tempCards.get(2).getCardType().getValue() > last){ res.add(i); res.add(i+1); res.add(i+2); res.add(i+3); break; } } } return res; } private List<Integer> getAIPopCardsForTypeTHREEWITHTWO(List<Card> lastCards, List<Card> cards, List<Card> popCards) { int last = lastCards.get(2).getCardType().getValue(); int size = cards.size(); List<Card> tempCards = new ArrayList<Card>(); List<Integer> res = new ArrayList<Integer>(); for(int i=0;i<size-4;i++){ tempCards = getRangeList(cards, i, i+4); if(GameLogic.hasThreeWithTwo(tempCards)){ if(tempCards.get(2).getCardType().getValue() > last){ res.add(i); res.add(i+1); res.add(i+2); res.add(i+3); res.add(i+4); break; } } } return res; } private List<Integer> getAIPopCardsForTypeFOURWITHTWO(List<Card> lastCards, List<Card> cards, List<Card> popCards) { int last = lastCards.get(2).getCardType().getValue(); int size = cards.size(); List<Card> tempCards = new ArrayList<Card>(); List<Integer> res = new ArrayList<Integer>(); for(int i=0;i<size-5;i++){ tempCards = getRangeList(cards, i, i+5); if(GameLogic.hasFourWithTwo(tempCards)){ if(tempCards.get(2).getCardType().getValue() > last){ res.add(i); res.add(i+1); res.add(i+2); res.add(i+3); res.add(i+4); res.add(i+5); break; } } } return res; } private int findTargetIndex(List<Card> cards, int target, int start) { int size = cards.size(); for(int i=start;i<size;i++){ Card card = cards.get(i); if(card.getCardType().getValue() == target){ return i; } } return -1; } private List<Integer> getAIPopCardsForTypeSINGLESTRAIGHT(List<Card> lastCards, List<Card> cards, List<Card> popCards) { int num = lastCards.size(); int prev = lastCards.get(0).getCardType().getValue(); int start = prev + 1; int end = 15 - num; Collections.sort(cards); List<Integer> res = new ArrayList<Integer>(); for(int i=start;i<=end;i++){ res.clear(); for(int j=0;j<num;j++){ int index = findTargetIndex(cards, i + j, 0); if(index == -1){ break; } else { res.add(index); } } if(res.size() < num){ res.clear(); } else { break; } } return res; } private void getPopCardsFromIndexList(List<Card> cards, List<Card> popCards, List<Integer> indexList) { int size = indexList.size(); for(int i=size-1;i>=0;i--){ popCards.add(0, cards.get(indexList.get(i))); cards.remove(indexList.get(i).intValue()); } } private List<Integer> getAIPopCardsForTypeDOUBLESTRAIGHT(List<Card> lastCards, List<Card> cards, List<Card> popCards) { int num = lastCards.size(); int prev = lastCards.get(0).getCardType().getValue(); int start = prev + 1; int end = 15 - num / 2; Collections.sort(cards); List<Integer> res = new ArrayList<Integer>(); for(int i=start;i<=end;i++){ res.clear(); for(int j=0;j<num;j++){ int index; if(j % 2 == 1){ index = findTargetIndex(cards, i + j / 2, res.get(res.size() - 1) + 1); } else { index = findTargetIndex(cards, i + j / 2, 0); } if(index == -1){ break; } else { res.add(index); } } if(res.size() < num){ res.clear(); } else { break; } } return res; } private List<Card> getRangeList(List<Card> cards, int start, int end) { List<Card> ans = new ArrayList<Card>(); for(int i=start;i<=end;i++){ ans.add(cards.get(i)); } return ans; } }
package com.zeppamobile.api.endpoint; import java.util.ArrayList; import java.util.List; import javax.annotation.Nullable; import javax.jdo.PersistenceManager; import javax.jdo.Query; import javax.jdo.Transaction; import com.google.api.server.spi.config.Api; import com.google.api.server.spi.config.ApiMethod; import com.google.api.server.spi.config.Named; import com.google.api.server.spi.response.CollectionResponse; import com.google.api.server.spi.response.UnauthorizedException; import com.google.appengine.api.datastore.Cursor; import com.google.appengine.api.oauth.OAuthRequestException; import com.google.appengine.datanucleus.query.JDOCursorHelper; import com.zeppamobile.api.Constants; import com.zeppamobile.api.PMF; import com.zeppamobile.api.datamodel.DeviceInfo; import com.zeppamobile.api.datamodel.ZeppaUser; import com.zeppamobile.api.endpoint.utils.ClientEndpointUtility; import com.zeppamobile.common.utils.Utils; @Api(name = Constants.API_NAME, version = "v1", scopes = { Constants.EMAIL_SCOPE }, audiences = { Constants.WEB_CLIENT_ID }) public class DeviceInfoEndpoint { /** * This method lists all the entities inserted in datastore. It uses HTTP * GET method and paging support. * * @return A CollectionResponse class containing the list of all entities * persisted and a cursor to the next page. * @throws UnauthorizedException * @throws OAuthRequestException */ @SuppressWarnings({ "unchecked" }) @ApiMethod(name = "listDeviceInfo",path="listDeviceInfo") public CollectionResponse<DeviceInfo> listDeviceInfo( @Nullable @Named("filter") String filterString, @Nullable @Named("cursor") String cursorString, @Nullable @Named("ordering") String orderingString, @Nullable @Named("limit") Integer limit, @Named("idToken") String tokenString) throws UnauthorizedException { // Fetch Authorized Zeppa User ZeppaUser user = ClientEndpointUtility .getAuthorizedZeppaUser(tokenString); if (user == null) { throw new UnauthorizedException( "No matching user found for this token"); } PersistenceManager mgr = null; Cursor cursor = null; List<DeviceInfo> execute = null; try { mgr = getPersistenceManager(); Query query = mgr.newQuery(DeviceInfo.class); if (Utils.isWebSafe(cursorString)) { cursor = Cursor.fromWebSafeString(cursorString); } if (Utils.isWebSafe(filterString)) { query.setFilter(filterString); } if (Utils.isWebSafe(orderingString)) { query.setOrdering(orderingString); } if (limit != null) { query.setRange(0, limit); } execute = (List<DeviceInfo>) query.execute(); cursor = JDOCursorHelper.getCursor(execute); if (cursor == null) { cursorString = null; } else { cursorString = cursor.toWebSafeString(); } /* * Devices may only be fetched by the owner Remove the bad eggs. * TODO: Flag it? */ List<DeviceInfo> badEggs = new ArrayList<DeviceInfo>(); for (DeviceInfo obj : execute) { // Make sure authed user owns this device if (obj.getOwnerId().longValue() != user.getId().longValue()) { badEggs.add(obj); } else { obj.getKey(); obj.getId(); obj.getVersion(); obj.getUpdate(); obj.getBugfix(); obj.getCreated(); obj.getUpdated(); obj.getRegistrationId(); obj.getOwnerId(); obj.getLastLogin(); } } execute.remove(badEggs); // If query only returned bad eggs, someone was being an ass hat if(execute.isEmpty() && !badEggs.isEmpty()){ throw new UnauthorizedException("Quit being an ass hat"); } } finally { mgr.close(); } return CollectionResponse.<DeviceInfo> builder().setItems(execute) .setNextPageToken(cursorString).build(); } /** * This method gets the entity having primary key id. It uses HTTP GET * method. * * @param id * the primary key of the java bean. * @return The entity with primary key id. * @throws UnauthorizedException */ @ApiMethod(name = "getDeviceInfo",path="getDeviceInfo") public DeviceInfo getDeviceInfo(@Named("id") Long id, @Named("idToken") String tokenString) throws UnauthorizedException { // Fetch Authorized Zeppa User ZeppaUser user = ClientEndpointUtility .getAuthorizedZeppaUser(tokenString); if (user == null) { throw new UnauthorizedException( "No matching user found for this token"); } PersistenceManager mgr = getPersistenceManager(); DeviceInfo deviceinfo = null; try { deviceinfo = mgr.getObjectById(DeviceInfo.class, id); if (deviceinfo.getOwnerId().longValue() != user.getId().longValue()) { throw new UnauthorizedException("You don't own this device"); } } finally { mgr.close(); } return deviceinfo; } /** * This inserts a new entity into App Engine datastore. If the entity * already exists in the datastore, an exception is thrown. It uses HTTP * POST method. * * @param deviceinfo * the entity to be inserted. * @return The inserted entity or null. * @throws UnauthorizedException */ @ApiMethod(name = "insertDeviceInfo") public DeviceInfo insertDeviceInfo(DeviceInfo deviceinfo, @Named("idToken") String tokenString) throws UnauthorizedException { // Make sure necessary items are there before inserting if (deviceinfo.getOwnerId() == null || deviceinfo.getRegistrationId() == null) { throw new NullPointerException(); } // Fetch Authorized Zeppa User ZeppaUser user = ClientEndpointUtility .getAuthorizedZeppaUser(tokenString); if (user == null) { throw new UnauthorizedException( "No matching user found for this token"); } else if (user.getId().longValue() != deviceinfo.getOwnerId().longValue()) { throw new UnauthorizedException("Can't create a device for another user, bruh"); } DeviceInfo result = null; PersistenceManager mgr = getPersistenceManager(); Transaction txn = mgr.currentTransaction(); // Try to fetch an instance of device info with a matching token and // user id try { txn.begin(); String filter = "ownerId == " + deviceinfo.getOwnerId() + " && registrationId == '" + deviceinfo.getRegistrationId() + "'"; Query q = mgr.newQuery(DeviceInfo.class, filter); // Does not check that this is a safe cast... it is. @SuppressWarnings("unchecked") List<DeviceInfo> response = (List<DeviceInfo>) q.execute(); // If there are already matching devices, update them if (response == null || response.isEmpty()) { deviceinfo.setCreated(System.currentTimeMillis()); deviceinfo.setUpdated(System.currentTimeMillis()); // Persist the object result = mgr.makePersistent(deviceinfo); } else { // get and remove the first object DeviceInfo current = response.get(0); response.remove(current); // Set version information current.setBugfix(deviceinfo.getBugfix()); current.setUpdate(deviceinfo.getUpdate()); current.setVersion(deviceinfo.getVersion()); // set login info/ set updated current.setLastLogin(deviceinfo.getLastLogin()); current.setLoggedIn(deviceinfo.getLoggedIn()); current.setUpdated(System.currentTimeMillis()); // passed device info is set to held info with updated values deviceinfo = current; // If there are more than one instances of this object, delete // the extras if (!response.isEmpty()) { mgr.deletePersistentAll(response); } } // Persist the device info txn.commit(); } catch (javax.jdo.JDOObjectNotFoundException | NullPointerException e) { e.printStackTrace(); } finally { if(txn.isActive()){ txn.rollback(); deviceinfo = null; } mgr.close(); } // Return the inserted item or null if an error occured. return result; } /** * This method is used for updating an existing entity. If the entity does * not exist in the datastore, an exception is thrown. It uses HTTP PUT * method. * * @param deviceinfo * the entity to be updated. * @return The updated entity. * @throws OAuthRequestException */ @ApiMethod(name = "updateDeviceInfo") public DeviceInfo updateDeviceInfo(DeviceInfo deviceinfo, @Named("idToken") String tokenString) throws UnauthorizedException { // Fetch Authorized Zeppa User ZeppaUser user = ClientEndpointUtility .getAuthorizedZeppaUser(tokenString); if (user == null) { throw new UnauthorizedException( "No matching user found for this token"); } deviceinfo.setUpdated(System.currentTimeMillis()); PersistenceManager mgr = getPersistenceManager(); Transaction txn = mgr.currentTransaction(); try { txn.begin(); DeviceInfo current = mgr.getObjectById(DeviceInfo.class, deviceinfo.getId()); if (user.getId().longValue() == current.getOwnerId().longValue()) { current.setBugfix(deviceinfo.getBugfix()); current.setUpdate(deviceinfo.getUpdate()); current.setVersion(deviceinfo.getVersion()); current.setLastLogin(deviceinfo.getLastLogin()); current.setLoggedIn(deviceinfo.getLoggedIn()); current.setUpdated(System.currentTimeMillis()); deviceinfo = current; txn.commit(); } else { throw new UnauthorizedException("You can't update this device"); } } finally { if(txn.isActive()){ txn.rollback(); deviceinfo = null; } mgr.close(); } return deviceinfo; } /** * This method removes the entity with primary key id. It uses HTTP DELETE * method. * * @param id * the primary key of the entity to be deleted. * @throws OAuthRequestException */ @ApiMethod(name = "removeDeviceInfo") public void removeDeviceInfo(@Named("id") Long id, @Named("idToken") String tokenString) throws UnauthorizedException { // Fetch Authorized Zeppa User ZeppaUser user = ClientEndpointUtility .getAuthorizedZeppaUser(tokenString); if (user == null) { throw new UnauthorizedException( "No matching user found for this token"); } PersistenceManager mgr = getPersistenceManager(); Transaction txn = mgr.currentTransaction(); try { DeviceInfo info = mgr.getObjectById(DeviceInfo.class, id); if (info.getOwnerId().longValue() == user.getId().longValue()) { txn.begin(); user = mgr.getObjectById(ZeppaUser.class, user.getKey()); txn.commit(); } else { throw new UnauthorizedException("You can't delete this device"); } } finally { if(txn.isActive()){ txn.rollback(); // TODO: throw an error to alert the user? } mgr.close(); } } /** * This method checks to see if device info object already exists * * @param deviceinfo * @return true if deviceinfo exists */ // private boolean containsDeviceInfo(DeviceInfo deviceinfo) { // PersistenceManager mgr = getPersistenceManager(); // boolean contains = true; // try { // mgr.getObjectById(DeviceInfo.class, deviceinfo.getKey()); // } catch (javax.jdo.JDOObjectNotFoundException ex) { // contains = false; // } finally { // mgr.close(); // } // return contains; // } private static PersistenceManager getPersistenceManager() { return PMF.get().getPersistenceManager(); } }
package com.google.bitcoin.bouncycastle.crypto.digests; import com.google.bitcoin.bouncycastle.crypto.digests.GeneralDigest; import com.google.bitcoin.bouncycastle.crypto.util.Pack; /** * SHA-224 as described in RFC 3874 * <pre> * block word digest * SHA-1 512 32 160 * SHA-224 512 32 224 * SHA-256 512 32 256 * SHA-384 1024 64 384 * SHA-512 1024 64 512 * </pre> */ public class SHA224Digest extends GeneralDigest { private static final int DIGEST_LENGTH = 28; private int H1, H2, H3, H4, H5, H6, H7, H8; private int[] X = new int[64]; private int xOff; /** * Standard constructor */ public SHA224Digest() { reset(); } /** * Copy constructor. This will copy the state of the provided * message digest. */ public SHA224Digest(SHA224Digest t) { super(t); H1 = t.H1; H2 = t.H2; H3 = t.H3; H4 = t.H4; H5 = t.H5; H6 = t.H6; H7 = t.H7; H8 = t.H8; System.arraycopy(t.X, 0, X, 0, t.X.length); xOff = t.xOff; } public String getAlgorithmName() { return "SHA-224"; } public int getDigestSize() { return DIGEST_LENGTH; } protected void processWord( byte[] in, int inOff) { // Note: Inlined for performance // X[xOff] = Pack.bigEndianToInt(in, inOff); int n = in[ inOff] << 24; n |= (in[++inOff] & 0xff) << 16; n |= (in[++inOff] & 0xff) << 8; n |= (in[++inOff] & 0xff); X[xOff] = n; if (++xOff == 16) { processBlock(); } } protected void processLength( long bitLength) { if (xOff > 14) { processBlock(); } X[14] = (int)(bitLength >>> 32); X[15] = (int)(bitLength & 0xffffffff); } public int doFinal( byte[] out, int outOff) { finish(); Pack.intToBigEndian(H1, out, outOff); Pack.intToBigEndian(H2, out, outOff + 4); Pack.intToBigEndian(H3, out, outOff + 8); Pack.intToBigEndian(H4, out, outOff + 12); Pack.intToBigEndian(H5, out, outOff + 16); Pack.intToBigEndian(H6, out, outOff + 20); Pack.intToBigEndian(H7, out, outOff + 24); reset(); return DIGEST_LENGTH; } /** * reset the chaining variables */ public void reset() { super.reset(); /* SHA-224 initial hash value */ H1 = 0xc1059ed8; H2 = 0x367cd507; H3 = 0x3070dd17; H4 = 0xf70e5939; H5 = 0xffc00b31; H6 = 0x68581511; H7 = 0x64f98fa7; H8 = 0xbefa4fa4; xOff = 0; for (int i = 0; i != X.length; i++) { X[i] = 0; } } protected void processBlock() { // // expand 16 word block into 64 word blocks. // for (int t = 16; t <= 63; t++) { X[t] = Theta1(X[t - 2]) + X[t - 7] + Theta0(X[t - 15]) + X[t - 16]; } // // set up working variables. // int a = H1; int b = H2; int c = H3; int d = H4; int e = H5; int f = H6; int g = H7; int h = H8; int t = 0; for(int i = 0; i < 8; i ++) { // t = 8 * i h += Sum1(e) + Ch(e, f, g) + K[t] + X[t]; d += h; h += Sum0(a) + Maj(a, b, c); ++t; // t = 8 * i + 1 g += Sum1(d) + Ch(d, e, f) + K[t] + X[t]; c += g; g += Sum0(h) + Maj(h, a, b); ++t; // t = 8 * i + 2 f += Sum1(c) + Ch(c, d, e) + K[t] + X[t]; b += f; f += Sum0(g) + Maj(g, h, a); ++t; // t = 8 * i + 3 e += Sum1(b) + Ch(b, c, d) + K[t] + X[t]; a += e; e += Sum0(f) + Maj(f, g, h); ++t; // t = 8 * i + 4 d += Sum1(a) + Ch(a, b, c) + K[t] + X[t]; h += d; d += Sum0(e) + Maj(e, f, g); ++t; // t = 8 * i + 5 c += Sum1(h) + Ch(h, a, b) + K[t] + X[t]; g += c; c += Sum0(d) + Maj(d, e, f); ++t; // t = 8 * i + 6 b += Sum1(g) + Ch(g, h, a) + K[t] + X[t]; f += b; b += Sum0(c) + Maj(c, d, e); ++t; // t = 8 * i + 7 a += Sum1(f) + Ch(f, g, h) + K[t] + X[t]; e += a; a += Sum0(b) + Maj(b, c, d); ++t; } H1 += a; H2 += b; H3 += c; H4 += d; H5 += e; H6 += f; H7 += g; H8 += h; // // reset the offset and clean out the word buffer. // xOff = 0; for (int i = 0; i < 16; i++) { X[i] = 0; } } /* SHA-224 functions */ private int Ch( int x, int y, int z) { return ((x & y) ^ ((~x) & z)); } private int Maj( int x, int y, int z) { return ((x & y) ^ (x & z) ^ (y & z)); } private int Sum0( int x) { return ((x >>> 2) | (x << 30)) ^ ((x >>> 13) | (x << 19)) ^ ((x >>> 22) | (x << 10)); } private int Sum1( int x) { return ((x >>> 6) | (x << 26)) ^ ((x >>> 11) | (x << 21)) ^ ((x >>> 25) | (x << 7)); } private int Theta0( int x) { return ((x >>> 7) | (x << 25)) ^ ((x >>> 18) | (x << 14)) ^ (x >>> 3); } private int Theta1( int x) { return ((x >>> 17) | (x << 15)) ^ ((x >>> 19) | (x << 13)) ^ (x >>> 10); } /* SHA-224 Constants * (represent the first 32 bits of the fractional parts of the * cube roots of the first sixty-four prime numbers) */ static final int K[] = { 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 }; }
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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.badlogic.gdx.backends.android; import java.text.NumberFormat; import java.text.ParseException; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLContext; import javax.microedition.khronos.egl.EGLDisplay; import javax.microedition.khronos.opengles.GL10; import android.opengl.GLSurfaceView; import android.opengl.GLSurfaceView.EGLConfigChooser; import android.opengl.GLSurfaceView.Renderer; import android.util.DisplayMetrics; import android.view.Display; import android.view.View; import android.view.WindowManager.LayoutParams; import com.badlogic.gdx.Application; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Graphics; import com.badlogic.gdx.LifecycleListener; import com.badlogic.gdx.backends.android.surfaceview.GLSurfaceView20; import com.badlogic.gdx.backends.android.surfaceview.GLSurfaceView20API18; import com.badlogic.gdx.backends.android.surfaceview.GLSurfaceViewAPI18; import com.badlogic.gdx.backends.android.surfaceview.GdxEglConfigChooser; import com.badlogic.gdx.backends.android.surfaceview.ResolutionStrategy; import com.badlogic.gdx.graphics.Cubemap; import com.badlogic.gdx.graphics.Cursor; import com.badlogic.gdx.graphics.Cursor.SystemCursor; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.GL30; import com.badlogic.gdx.graphics.Mesh; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.TextureArray; import com.badlogic.gdx.graphics.glutils.FrameBuffer; import com.badlogic.gdx.graphics.glutils.GLVersion; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.math.WindowedMean; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.GdxRuntimeException; import com.badlogic.gdx.utils.SnapshotArray; /** An implementation of {@link Graphics} for Android. * * @author mzechner */ public class AndroidGraphics implements Graphics, Renderer { private static final String LOG_TAG = "AndroidGraphics"; /** When {@link AndroidFragmentApplication#onPause()} or {@link AndroidApplication#onPause()} call * {@link AndroidGraphics#pause()} they <b>MUST</b> enforce continuous rendering. If not, {@link #onDrawFrame(GL10)} will not * be called in the GLThread while {@link #pause()} is sleeping in the Android UI Thread which will cause the * {@link AndroidGraphics#pause} variable never be set to false. As a result, the {@link AndroidGraphics#pause()} method will * kill the current process to avoid ANR */ static volatile boolean enforceContinuousRendering = false; final View view; int width; int height; AndroidApplicationBase app; GL20 gl20; GL30 gl30; EGLContext eglContext; GLVersion glVersion; String extensions; protected long lastFrameTime = System.nanoTime(); protected float deltaTime = 0; protected long frameStart = System.nanoTime(); protected long frameId = -1; protected int frames = 0; protected int fps; protected WindowedMean mean = new WindowedMean(5); volatile boolean created = false; volatile boolean running = false; volatile boolean pause = false; volatile boolean resume = false; volatile boolean destroy = false; private float ppiX = 0; private float ppiY = 0; private float ppcX = 0; private float ppcY = 0; private float density = 1; protected final AndroidApplicationConfiguration config; private BufferFormat bufferFormat = new BufferFormat(5, 6, 5, 0, 16, 0, 0, false); private boolean isContinuous = true; public AndroidGraphics (AndroidApplicationBase application, AndroidApplicationConfiguration config, ResolutionStrategy resolutionStrategy) { this(application, config, resolutionStrategy, true); } public AndroidGraphics (AndroidApplicationBase application, AndroidApplicationConfiguration config, ResolutionStrategy resolutionStrategy, boolean focusableView) { AndroidGL20.init(); this.config = config; this.app = application; view = createGLSurfaceView(application, resolutionStrategy); preserveEGLContextOnPause(); if (focusableView) { view.setFocusable(true); view.setFocusableInTouchMode(true); } } protected void preserveEGLContextOnPause () { int sdkVersion = android.os.Build.VERSION.SDK_INT; if ((sdkVersion >= 11 && view instanceof GLSurfaceView20) || view instanceof GLSurfaceView20API18) { try { view.getClass().getMethod("setPreserveEGLContextOnPause", boolean.class).invoke(view, true); } catch (Exception e) { Gdx.app.log(LOG_TAG, "Method GLSurfaceView.setPreserveEGLContextOnPause not found"); } } } protected View createGLSurfaceView (AndroidApplicationBase application, final ResolutionStrategy resolutionStrategy) { if (!checkGL20()) throw new GdxRuntimeException("Libgdx requires OpenGL ES 2.0"); EGLConfigChooser configChooser = getEglConfigChooser(); int sdkVersion = android.os.Build.VERSION.SDK_INT; if (sdkVersion <= 10 && config.useGLSurfaceView20API18) { GLSurfaceView20API18 view = new GLSurfaceView20API18(application.getContext(), resolutionStrategy); if (configChooser != null) view.setEGLConfigChooser(configChooser); else view.setEGLConfigChooser(config.r, config.g, config.b, config.a, config.depth, config.stencil); view.setRenderer(this); return view; } else { GLSurfaceView20 view = new GLSurfaceView20(application.getContext(), resolutionStrategy, config.useGL30 ? 3 : 2); if (configChooser != null) view.setEGLConfigChooser(configChooser); else view.setEGLConfigChooser(config.r, config.g, config.b, config.a, config.depth, config.stencil); view.setRenderer(this); return view; } } public void onPauseGLSurfaceView () { if (view != null) { if (view instanceof GLSurfaceViewAPI18) ((GLSurfaceViewAPI18)view).onPause(); if (view instanceof GLSurfaceView) ((GLSurfaceView)view).onPause(); } } public void onResumeGLSurfaceView () { if (view != null) { if (view instanceof GLSurfaceViewAPI18) ((GLSurfaceViewAPI18)view).onResume(); if (view instanceof GLSurfaceView) ((GLSurfaceView)view).onResume(); } } protected EGLConfigChooser getEglConfigChooser () { return new GdxEglConfigChooser(config.r, config.g, config.b, config.a, config.depth, config.stencil, config.numSamples); } private void updatePpi () { DisplayMetrics metrics = new DisplayMetrics(); app.getWindowManager().getDefaultDisplay().getMetrics(metrics); ppiX = metrics.xdpi; ppiY = metrics.ydpi; ppcX = metrics.xdpi / 2.54f; ppcY = metrics.ydpi / 2.54f; density = metrics.density; } protected boolean checkGL20 () { EGL10 egl = (EGL10)EGLContext.getEGL(); EGLDisplay display = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); int[] version = new int[2]; egl.eglInitialize(display, version); int EGL_OPENGL_ES2_BIT = 4; int[] configAttribs = {EGL10.EGL_RED_SIZE, 4, EGL10.EGL_GREEN_SIZE, 4, EGL10.EGL_BLUE_SIZE, 4, EGL10.EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL10.EGL_NONE}; EGLConfig[] configs = new EGLConfig[10]; int[] num_config = new int[1]; egl.eglChooseConfig(display, configAttribs, configs, 10, num_config); egl.eglTerminate(display); return num_config[0] > 0; } /** {@inheritDoc} */ @Override public GL20 getGL20 () { return gl20; } /** {@inheritDoc} */ @Override public void setGL20 (GL20 gl20) { this.gl20 = gl20; if (gl30 == null) { Gdx.gl = gl20; Gdx.gl20 = gl20; } } /** {@inheritDoc} */ @Override public boolean isGL30Available () { return gl30 != null; } /** {@inheritDoc} */ @Override public GL30 getGL30 () { return gl30; } /** {@inheritDoc} */ @Override public void setGL30 (GL30 gl30) { this.gl30 = gl30; if (gl30 != null) { this.gl20 = gl30; Gdx.gl = gl20; Gdx.gl20 = gl20; Gdx.gl30 = gl30; } } /** {@inheritDoc} */ @Override public int getHeight () { return height; } /** {@inheritDoc} */ @Override public int getWidth () { return width; } @Override public int getBackBufferWidth () { return width; } @Override public int getBackBufferHeight () { return height; } /** This instantiates the GL10, GL11 and GL20 instances. Includes the check for certain devices that pretend to support GL11 but * fuck up vertex buffer objects. This includes the pixelflinger which segfaults when buffers are deleted as well as the * Motorola CLIQ and the Samsung Behold II. * * @param gl */ private void setupGL (javax.microedition.khronos.opengles.GL10 gl) { String versionString = gl.glGetString(GL10.GL_VERSION); String vendorString = gl.glGetString(GL10.GL_VENDOR); String rendererString = gl.glGetString(GL10.GL_RENDERER); glVersion = new GLVersion(Application.ApplicationType.Android, versionString, vendorString, rendererString); if (config.useGL30 && glVersion.getMajorVersion() > 2) { if (gl30 != null) return; gl20 = gl30 = new AndroidGL30(); Gdx.gl = gl30; Gdx.gl20 = gl30; Gdx.gl30 = gl30; } else { if (gl20 != null) return; gl20 = new AndroidGL20(); Gdx.gl = gl20; Gdx.gl20 = gl20; } Gdx.app.log(LOG_TAG, "OGL renderer: " + gl.glGetString(GL10.GL_RENDERER)); Gdx.app.log(LOG_TAG, "OGL vendor: " + gl.glGetString(GL10.GL_VENDOR)); Gdx.app.log(LOG_TAG, "OGL version: " + gl.glGetString(GL10.GL_VERSION)); Gdx.app.log(LOG_TAG, "OGL extensions: " + gl.glGetString(GL10.GL_EXTENSIONS)); } @Override public void onSurfaceChanged (javax.microedition.khronos.opengles.GL10 gl, int width, int height) { this.width = width; this.height = height; updatePpi(); gl.glViewport(0, 0, this.width, this.height); if (created == false) { app.getApplicationListener().create(); created = true; synchronized (this) { running = true; } } app.getApplicationListener().resize(width, height); } @Override public void onSurfaceCreated (javax.microedition.khronos.opengles.GL10 gl, EGLConfig config) { eglContext = ((EGL10)EGLContext.getEGL()).eglGetCurrentContext(); setupGL(gl); logConfig(config); updatePpi(); Mesh.invalidateAllMeshes(app); Texture.invalidateAllTextures(app); Cubemap.invalidateAllCubemaps(app); TextureArray.invalidateAllTextureArrays(app); ShaderProgram.invalidateAllShaderPrograms(app); FrameBuffer.invalidateAllFrameBuffers(app); logManagedCachesStatus(); Display display = app.getWindowManager().getDefaultDisplay(); this.width = display.getWidth(); this.height = display.getHeight(); this.mean = new WindowedMean(5); this.lastFrameTime = System.nanoTime(); gl.glViewport(0, 0, this.width, this.height); } private void logConfig (EGLConfig config) { EGL10 egl = (EGL10)EGLContext.getEGL(); EGLDisplay display = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); int r = getAttrib(egl, display, config, EGL10.EGL_RED_SIZE, 0); int g = getAttrib(egl, display, config, EGL10.EGL_GREEN_SIZE, 0); int b = getAttrib(egl, display, config, EGL10.EGL_BLUE_SIZE, 0); int a = getAttrib(egl, display, config, EGL10.EGL_ALPHA_SIZE, 0); int d = getAttrib(egl, display, config, EGL10.EGL_DEPTH_SIZE, 0); int s = getAttrib(egl, display, config, EGL10.EGL_STENCIL_SIZE, 0); int samples = Math.max(getAttrib(egl, display, config, EGL10.EGL_SAMPLES, 0), getAttrib(egl, display, config, GdxEglConfigChooser.EGL_COVERAGE_SAMPLES_NV, 0)); boolean coverageSample = getAttrib(egl, display, config, GdxEglConfigChooser.EGL_COVERAGE_SAMPLES_NV, 0) != 0; Gdx.app.log(LOG_TAG, "framebuffer: (" + r + ", " + g + ", " + b + ", " + a + ")"); Gdx.app.log(LOG_TAG, "depthbuffer: (" + d + ")"); Gdx.app.log(LOG_TAG, "stencilbuffer: (" + s + ")"); Gdx.app.log(LOG_TAG, "samples: (" + samples + ")"); Gdx.app.log(LOG_TAG, "coverage sampling: (" + coverageSample + ")"); bufferFormat = new BufferFormat(r, g, b, a, d, s, samples, coverageSample); } int[] value = new int[1]; private int getAttrib (EGL10 egl, EGLDisplay display, EGLConfig config, int attrib, int defValue) { if (egl.eglGetConfigAttrib(display, config, attrib, value)) { return value[0]; } return defValue; } Object synch = new Object(); void resume () { synchronized (synch) { running = true; resume = true; } } void pause () { synchronized (synch) { if (!running) return; running = false; pause = true; while (pause) { try { // TODO: fix deadlock race condition with quick resume/pause. // Temporary workaround: // Android ANR time is 5 seconds, so wait up to 4 seconds before assuming // deadlock and killing process. This can easily be triggered by opening the // Recent Apps list and then double-tapping the Recent Apps button with // ~500ms between taps. synch.wait(4000); if (pause) { // pause will never go false if onDrawFrame is never called by the GLThread // when entering this method, we MUST enforce continuous rendering Gdx.app.error(LOG_TAG, "waiting for pause synchronization took too long; assuming deadlock and killing"); android.os.Process.killProcess(android.os.Process.myPid()); } } catch (InterruptedException ignored) { Gdx.app.log(LOG_TAG, "waiting for pause synchronization failed!"); } } } } void destroy () { synchronized (synch) { running = false; destroy = true; while (destroy) { try { synch.wait(); } catch (InterruptedException ex) { Gdx.app.log(LOG_TAG, "waiting for destroy synchronization failed!"); } } } } @Override public void onDrawFrame (javax.microedition.khronos.opengles.GL10 gl) { long time = System.nanoTime(); deltaTime = (time - lastFrameTime) / 1000000000.0f; lastFrameTime = time; // After pause deltaTime can have somewhat huge value that destabilizes the mean, so let's cut it off if (!resume) { mean.addValue(deltaTime); } else { deltaTime = 0; } boolean lrunning = false; boolean lpause = false; boolean ldestroy = false; boolean lresume = false; synchronized (synch) { lrunning = running; lpause = pause; ldestroy = destroy; lresume = resume; if (resume) { resume = false; } if (pause) { pause = false; synch.notifyAll(); } if (destroy) { destroy = false; synch.notifyAll(); } } if (lresume) { SnapshotArray<LifecycleListener> lifecycleListeners = app.getLifecycleListeners(); synchronized (lifecycleListeners) { LifecycleListener[] listeners = lifecycleListeners.begin(); for (int i = 0, n = lifecycleListeners.size; i < n; ++i) { listeners[i].resume(); } lifecycleListeners.end(); } app.getApplicationListener().resume(); Gdx.app.log(LOG_TAG, "resumed"); } if (lrunning) { synchronized (app.getRunnables()) { app.getExecutedRunnables().clear(); app.getExecutedRunnables().addAll(app.getRunnables()); app.getRunnables().clear(); } for (int i = 0; i < app.getExecutedRunnables().size; i++) { try { app.getExecutedRunnables().get(i).run(); } catch (Throwable t) { t.printStackTrace(); } } app.getInput().processEvents(); frameId++; app.getApplicationListener().render(); } if (lpause) { SnapshotArray<LifecycleListener> lifecycleListeners = app.getLifecycleListeners(); synchronized (lifecycleListeners) { LifecycleListener[] listeners = lifecycleListeners.begin(); for (int i = 0, n = lifecycleListeners.size; i < n; ++i) { listeners[i].pause(); } } app.getApplicationListener().pause(); Gdx.app.log(LOG_TAG, "paused"); } if (ldestroy) { SnapshotArray<LifecycleListener> lifecycleListeners = app.getLifecycleListeners(); synchronized (lifecycleListeners) { LifecycleListener[] listeners = lifecycleListeners.begin(); for (int i = 0, n = lifecycleListeners.size; i < n; ++i) { listeners[i].dispose(); } } app.getApplicationListener().dispose(); Gdx.app.log(LOG_TAG, "destroyed"); } if (time - frameStart > 1000000000) { fps = frames; frames = 0; frameStart = time; } frames++; } @Override public long getFrameId () { return frameId; } /** {@inheritDoc} */ @Override public float getDeltaTime () { return mean.getMean() == 0 ? deltaTime : mean.getMean(); } @Override public float getRawDeltaTime () { return deltaTime; } /** {@inheritDoc} */ @Override public GraphicsType getType () { return GraphicsType.AndroidGL; } /** {@inheritDoc} */ @Override public GLVersion getGLVersion () { return glVersion; } /** {@inheritDoc} */ @Override public int getFramesPerSecond () { return fps; } public void clearManagedCaches () { Mesh.clearAllMeshes(app); Texture.clearAllTextures(app); Cubemap.clearAllCubemaps(app); TextureArray.clearAllTextureArrays(app); ShaderProgram.clearAllShaderPrograms(app); FrameBuffer.clearAllFrameBuffers(app); logManagedCachesStatus(); } protected void logManagedCachesStatus () { Gdx.app.log(LOG_TAG, Mesh.getManagedStatus()); Gdx.app.log(LOG_TAG, Texture.getManagedStatus()); Gdx.app.log(LOG_TAG, Cubemap.getManagedStatus()); Gdx.app.log(LOG_TAG, ShaderProgram.getManagedStatus()); Gdx.app.log(LOG_TAG, FrameBuffer.getManagedStatus()); } public View getView () { return view; } @Override public float getPpiX () { return ppiX; } @Override public float getPpiY () { return ppiY; } @Override public float getPpcX () { return ppcX; } @Override public float getPpcY () { return ppcY; } @Override public float getDensity () { return density; } @Override public boolean supportsDisplayModeChange () { return false; } @Override public boolean setFullscreenMode (DisplayMode displayMode) { return false; } @Override public Monitor getPrimaryMonitor () { return new AndroidMonitor(0, 0, "Primary Monitor"); } @Override public Monitor getMonitor () { return getPrimaryMonitor(); } @Override public Monitor[] getMonitors () { return new Monitor[] { getPrimaryMonitor() }; } @Override public DisplayMode[] getDisplayModes (Monitor monitor) { return getDisplayModes(); } @Override public DisplayMode getDisplayMode (Monitor monitor) { return getDisplayMode(); } @Override public DisplayMode[] getDisplayModes () { return new DisplayMode[] {getDisplayMode()}; } @Override public boolean setWindowedMode (int width, int height) { return false; } @Override public void setTitle (String title) { } @Override public void setUndecorated (boolean undecorated) { final int mask = (undecorated) ? 1 : 0; app.getApplicationWindow().setFlags(LayoutParams.FLAG_FULLSCREEN, mask); } @Override public void setResizable (boolean resizable) { } @Override public DisplayMode getDisplayMode () { DisplayMetrics metrics = new DisplayMetrics(); app.getWindowManager().getDefaultDisplay().getMetrics(metrics); return new AndroidDisplayMode(metrics.widthPixels, metrics.heightPixels, 0, 0); } @Override public BufferFormat getBufferFormat () { return bufferFormat; } @Override public void setVSync (boolean vsync) { } @Override public boolean supportsExtension (String extension) { if (extensions == null) extensions = Gdx.gl.glGetString(GL10.GL_EXTENSIONS); return extensions.contains(extension); } @Override public void setContinuousRendering (boolean isContinuous) { if (view != null) { // ignore setContinuousRendering(false) while pausing this.isContinuous = enforceContinuousRendering || isContinuous; int renderMode = this.isContinuous ? GLSurfaceView.RENDERMODE_CONTINUOUSLY : GLSurfaceView.RENDERMODE_WHEN_DIRTY; if (view instanceof GLSurfaceViewAPI18) ((GLSurfaceViewAPI18)view).setRenderMode(renderMode); if (view instanceof GLSurfaceView) ((GLSurfaceView)view).setRenderMode(renderMode); mean.clear(); } } @Override public boolean isContinuousRendering () { return isContinuous; } @Override public void requestRendering () { if (view != null) { if (view instanceof GLSurfaceViewAPI18) ((GLSurfaceViewAPI18)view).requestRender(); if (view instanceof GLSurfaceView) ((GLSurfaceView)view).requestRender(); } } @Override public boolean isFullscreen () { return true; } @Override public Cursor newCursor (Pixmap pixmap, int xHotspot, int yHotspot) { return null; } @Override public void setCursor (Cursor cursor) { } @Override public void setSystemCursor (SystemCursor systemCursor) { } private class AndroidDisplayMode extends DisplayMode { protected AndroidDisplayMode (int width, int height, int refreshRate, int bitsPerPixel) { super(width, height, refreshRate, bitsPerPixel); } } private class AndroidMonitor extends Monitor { public AndroidMonitor (int virtualX, int virtualY, String name) { super(virtualX, virtualY, name); } } }
/*--- iGeo - http://igeo.jp Copyright (c) 2002-2013 Satoru Sugihara This file is part of iGeo. iGeo is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, version 3. iGeo is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with iGeo. If not, see <http://www.gnu.org/licenses/>. ---*/ package igeo; import java.awt.Color; import java.util.ArrayList; /** Class of an agent with IParticleOnPlaneGeo. @author Satoru Sugihara */ public class IParticleOnPlane extends IPointAgent implements IParticleI /*IParticleOnCurveI*/{ public IParticleOnPlaneGeo particle; /** only to refer to particle.vel and particle.frc */ public IVec vel, frc; public IParticleOnPlane(IVecI planeDir,IVecI planePt, IVecI pos, IVecI vel){ super(pos); initParticleOnPlaneAgent(planeDir, planePt, pos, vel); } public IParticleOnPlane(IVecI planeDir, IVecI planePt, IVecI pos){ super(pos); initParticleOnPlaneAgent(planeDir, planePt, pos); } public IParticleOnPlane(IParticleOnPlaneGeo p){ super(p.pos); initParticleOnPlaneAgent(p); } public IParticleOnPlane(IParticleOnPlane p){ super(p.pos.dup()); initParticleOnPlaneAgent(p.particle.planeDir, p.particle.planePt, this.pos,p.particle.vel); } public void initParticleOnPlaneAgent(IVecI planeDir,IVecI planePt, IVecI pos, IVecI vel){ particle = new IParticleOnPlaneGeo(planeDir,planePt,pos,vel); this.pos = particle.pos; vel = particle.vel; frc = particle.frc; addDynamics(particle); } public void initParticleOnPlaneAgent(IVecI planeDir,IVecI planePt, IVecI pos){ particle = new IParticleOnPlaneGeo(planeDir,planePt,pos); this.pos = particle.pos; vel = particle.vel; frc = particle.frc; addDynamics(particle); } public void initParticleOnPlaneAgent(IParticleOnPlaneGeo ptcl){ particle = ptcl; pos = particle.pos; vel = particle.vel; frc = particle.frc; addDynamics(particle); } /************************************** * IParticleI API **************************************/ synchronized public IParticleOnPlane fix(){ particle.fix(); return this; } synchronized public IParticleOnPlane unfix(){ particle.unfix(); return this; } public IParticleOnPlane skipUpdateOnce(boolean f){ particle.skipUpdateOnce(f); return this; } public boolean skipUpdateOnce(){ return particle.skipUpdateOnce(); } synchronized public boolean fixed(){ return particle.fixed(); } synchronized public double mass(){ return particle.mass(); } synchronized public IParticleOnPlane mass(double mass){ particle.mass(mass); return this; } synchronized public IVec position(){ return particle.position(); } synchronized public IParticleOnPlane position(IVecI v){ particle.position(v); return this; } synchronized public IVec pos(){ return particle.pos(); } synchronized public IParticleOnPlane pos(IVecI v){ particle.pos(v); return this; } synchronized public IVec velocity(){ return particle.velocity(); } synchronized public IParticleOnPlane velocity(IVecI v){ particle.velocity(v); return this; } synchronized public IVec vel(){ return particle.vel(); } synchronized public IParticleOnPlane vel(IVecI v){ particle.vel(v); return this; } synchronized public IVec acceleration(){ return particle.acceleration(); } //synchronized public IParticleOnPlane acceleration(IVec v){ particle.acceleration(v); return this; } synchronized public IVec acc(){ return particle.acc(); } //synchronized public IParticleOnPlane acc(IVec v){ particle.acc(v); return this; } synchronized public IVec force(){ return particle.force(); } synchronized public IParticleOnPlane force(IVecI v){ particle.force(v); return this; } synchronized public IVec frc(){ return particle.frc(); } synchronized public IParticleOnPlane frc(IVecI v){ particle.frc(v); return this; } synchronized public double friction(){ return particle.friction(); } synchronized public IParticleOnPlane friction(double friction){ particle.friction(friction); return this; } synchronized public double fric(){ return particle.fric(); } synchronized public IParticleOnPlane fric(double friction){ particle.fric(friction); return this; } /* alias of friction */ synchronized public double decay(){ return fric(); } /* alias of friction */ synchronized public IParticleOnPlane decay(double d){ return fric(d); } synchronized public IParticleOnPlane push(IVecI f){ particle.push(f); return this; } synchronized public IParticleOnPlane push(double fx, double fy, double fz){ particle.push(fx,fy,fz); return this; } synchronized public IParticleOnPlane pull(IVecI f){ particle.pull(f); return this; } synchronized public IParticleOnPlane pull(double fx, double fy, double fz){ particle.pull(fx,fy,fz); return this; } synchronized public IParticleOnPlane addForce(IVecI f){ particle.addForce(f); return this; } synchronized public IParticleOnPlane addForce(double fx, double fy, double fz){ particle.addForce(fx,fy,fz); return this; } synchronized public IParticleOnPlane reset(){ particle.reset(); return this; } synchronized public IParticleOnPlane resetForce(){ particle.resetForce(); return this; } // partial methods of IDynamics /** add terget object to be updated by this dynamic object. */ public IParticleOnPlane target(IObject targetObj){ super.target(targetObj); return this; } /** get total target number. */ public int targetNum(){ return super.targetNum(); } /** get target object. */ public IObject target(int i){ return super.target(i); } /** get all target objects. */ public ArrayList<IObject> targets(){ return super.targets(); } public IParticleOnPlane removeTarget(int i){ super.removeTarget(i); return this; } /** remove target object. */ public IParticleOnPlane removeTarget(IObject obj){ super.removeTarget(obj); return this; } /** update all terget objects (should be called when the dynamic object is updated). */ public void updateTarget(){ super.updateTarget(); } /************************************** * methods of IVecI *************************************/ public IParticleOnPlane x(double vx){ pos.x(vx); return this; } public IParticleOnPlane y(double vy){ pos.y(vy); return this; } public IParticleOnPlane z(double vz){ pos.z(vz); return this; } public IParticleOnPlane x(IDoubleI vx){ pos.x(vx); return this; } public IParticleOnPlane y(IDoubleI vy){ pos.y(vy); return this; } public IParticleOnPlane z(IDoubleI vz){ pos.z(vz); return this; } public IParticleOnPlane x(IVecI vx){ pos.x(vx); return this; } public IParticleOnPlane y(IVecI vy){ pos.y(vy); return this; } public IParticleOnPlane z(IVecI vz){ pos.z(vz); return this; } public IParticleOnPlane x(IVec2I vx){ pos.x(vx); return this; } public IParticleOnPlane y(IVec2I vy){ pos.y(vy); return this; } public IParticleOnPlane dup(){ return new IParticleOnPlane(this); } public IParticleOnPlane set(IVecI v){ pos.set(v); return this; } public IParticleOnPlane set(double x, double y, double z){ pos.set(x,y,z); return this;} public IParticleOnPlane set(IDoubleI x, IDoubleI y, IDoubleI z){ pos.set(x,y,z); return this; } public IParticleOnPlane add(double x, double y, double z){ pos.add(x,y,z); return this; } public IParticleOnPlane add(IDoubleI x, IDoubleI y, IDoubleI z){ pos.add(x,y,z); return this; } public IParticleOnPlane add(IVecI v){ pos.add(v); return this; } public IParticleOnPlane sub(double x, double y, double z){ pos.sub(x,y,z); return this; } public IParticleOnPlane sub(IDoubleI x, IDoubleI y, IDoubleI z){ pos.sub(x,y,z); return this; } public IParticleOnPlane sub(IVecI v){ pos.sub(v); return this; } public IParticleOnPlane mul(IDoubleI v){ pos.mul(v); return this; } public IParticleOnPlane mul(double v){ pos.mul(v); return this; } public IParticleOnPlane div(IDoubleI v){ pos.div(v); return this; } public IParticleOnPlane div(double v){ pos.div(v); return this; } public IParticleOnPlane neg(){ pos.neg(); return this; } public IParticleOnPlane rev(){ return neg(); } public IParticleOnPlane flip(){ return neg(); } public IParticleOnPlane zero(){ pos.zero(); return this; } public IParticleOnPlane add(IVecI v, double f){ pos.add(v,f); return this; } public IParticleOnPlane add(IVecI v, IDoubleI f){ pos.add(v,f); return this; } public IParticleOnPlane add(double f, IVecI v){ return add(v,f); } public IParticleOnPlane add(IDoubleI f, IVecI v){ return add(v,f); } public IParticleOnPlane len(IDoubleI l){ pos.len(l); return this; } public IParticleOnPlane len(double l){ pos.len(l); return this; } public IParticleOnPlane unit(){ pos.unit(); return this; } public IParticleOnPlane rot(IDoubleI angle){ pos.rot(angle); return this; } public IParticleOnPlane rot(double angle){ pos.rot(angle); return this; } public IParticleOnPlane rot(IVecI axis, IDoubleI angle){ pos.rot(axis,angle); return this; } public IParticleOnPlane rot(IVecI axis, double angle){ pos.rot(axis,angle); return this; } public IParticleOnPlane rot(double axisX, double axisY, double axisZ, double angle){ pos.rot(axisX,axisY,axisZ,angle); return this; } public IParticleOnPlane rot(IVecI center, IVecI axis, double angle){ pos.rot(center, axis,angle); return this; } public IParticleOnPlane rot(IVecI center, IVecI axis, IDoubleI angle){ pos.rot(center, axis,angle); return this; } public IParticleOnPlane rot(double centerX, double centerY, double centerZ, double axisX, double axisY, double axisZ, double angle){ pos.rot(centerX,centerY,centerZ,axisX,axisY,axisZ,angle); return this; } public IParticleOnPlane rot(IVecI axis, IVecI destDir){ pos.rot(axis,destDir); return this; } public IParticleOnPlane rot(IVecI center, IVecI axis, IVecI destPt){ pos.rot(center,axis,destPt); return this; } public IParticleOnPlane rot2(IDoubleI angle){ return rot(angle); } public IParticleOnPlane rot2(double angle){ return rot(angle); } public IParticleOnPlane rot2(IVecI center, double angle){ pos.rot2(center,angle); return this; } public IParticleOnPlane rot2(IVecI center, IDoubleI angle){ pos.rot2(center,angle); return this; } public IParticleOnPlane rot2(double centerX, double centerY, double angle){ pos.rot2(centerX,centerY,angle); return this; } public IParticleOnPlane rot2(IVecI destDir){ pos.rot2(destDir); return this; } public IParticleOnPlane rot2(IVecI center, IVecI destPt){ pos.rot2(center,destPt); return this; } public IParticleOnPlane scale(IDoubleI f){ pos.scale(f); return this; } public IParticleOnPlane scale(double f){ pos.scale(f); return this; } public IParticleOnPlane scale(IVecI center, IDoubleI f){ pos.scale(center,f); return this; } public IParticleOnPlane scale(IVecI center, double f){ pos.scale(center,f); return this; } public IParticleOnPlane scale(double centerX, double centerY, double centerZ, double f){ pos.scale(centerX,centerY,centerZ,f); return this; } /** scale only in 1 direction */ public IParticleOnPlane scale1d(IVecI axis, double f){ pos.scale1d(axis,f); return this; } public IParticleOnPlane scale1d(IVecI axis, IDoubleI f){ pos.scale1d(axis,f); return this; } public IParticleOnPlane scale1d(double axisX, double axisY, double axisZ, double f){ pos.scale1d(axisX,axisY,axisZ,f); return this; } public IParticleOnPlane scale1d(IVecI center, IVecI axis, double f){ pos.scale1d(center,axis,f); return this; } public IParticleOnPlane scale1d(IVecI center, IVecI axis, IDoubleI f){ pos.scale1d(center,axis,f); return this; } public IParticleOnPlane scale1d(double centerX, double centerY, double centerZ, double axisX, double axisY, double axisZ, double f){ pos.scale1d(centerX,centerY,centerZ,axisX,axisY,axisZ,f); return this; } public IParticleOnPlane ref(IVecI planeDir){ pos.ref(planeDir); return this; } public IParticleOnPlane ref(double planeX, double planeY, double planeZ){ pos.ref(planeX,planeY,planeZ); return this; } public IParticleOnPlane ref(IVecI center, IVecI planeDir){ pos.ref(center,planeDir); return this; } public IParticleOnPlane ref(double centerX, double centerY, double centerZ, double planeX, double planeY, double planeZ){ pos.ref(centerX,centerY,centerZ,planeX,planeY,planeZ); return this; } public IParticleOnPlane mirror(IVecI planeDir){ pos.ref(planeDir); return this; } public IParticleOnPlane mirror(double planeX, double planeY, double planeZ){ pos.ref(planeX, planeY, planeZ); return this; } public IParticleOnPlane mirror(IVecI center, IVecI planeDir){ pos.ref(center,planeDir); return this; } public IParticleOnPlane mirror(double centerX, double centerY, double centerZ, double planeX, double planeY, double planeZ){ pos.ref(centerX,centerY,centerZ,planeX,planeY,planeZ); return this; } public IParticleOnPlane shear(double sxy, double syx, double syz, double szy, double szx, double sxz){ pos.shear(sxy,syx,syz,szy,szx,sxz); return this; } public IParticleOnPlane shear(IDoubleI sxy, IDoubleI syx, IDoubleI syz, IDoubleI szy, IDoubleI szx, IDoubleI sxz){ pos.shear(sxy,syx,syz,szy,szx,sxz); return this; } public IParticleOnPlane shear(IVecI center, double sxy, double syx, double syz, double szy, double szx, double sxz){ pos.shear(center,sxy,syx,syz,szy,szx,sxz); return this; } public IParticleOnPlane shear(IVecI center, IDoubleI sxy, IDoubleI syx, IDoubleI syz, IDoubleI szy, IDoubleI szx, IDoubleI sxz){ pos.shear(center,sxy,syx,syz,szy,szx,sxz); return this; } public IParticleOnPlane shearXY(double sxy, double syx){ pos.shearXY(sxy,syx); return this; } public IParticleOnPlane shearXY(IDoubleI sxy, IDoubleI syx){ pos.shearXY(sxy,syx); return this; } public IParticleOnPlane shearXY(IVecI center, double sxy, double syx){ pos.shearXY(center,sxy,syx); return this; } public IParticleOnPlane shearXY(IVecI center, IDoubleI sxy, IDoubleI syx){ pos.shearXY(center,sxy,syx); return this; } public IParticleOnPlane shearYZ(double syz, double szy){ pos.shearYZ(syz,szy); return this; } public IParticleOnPlane shearYZ(IDoubleI syz, IDoubleI szy){ pos.shearYZ(syz,szy); return this; } public IParticleOnPlane shearYZ(IVecI center, double syz, double szy){ pos.shearYZ(center,syz,szy); return this; } public IParticleOnPlane shearYZ(IVecI center, IDoubleI syz, IDoubleI szy){ pos.shearYZ(center,syz,szy); return this; } public IParticleOnPlane shearZX(double szx, double sxz){ pos.shearZX(szx,sxz); return this; } public IParticleOnPlane shearZX(IDoubleI szx, IDoubleI sxz){ pos.shearZX(szx,sxz); return this; } public IParticleOnPlane shearZX(IVecI center, double szx, double sxz){ pos.shearZX(center,szx,sxz); return this; } public IParticleOnPlane shearZX(IVecI center, IDoubleI szx, IDoubleI sxz){ pos.shearZX(center,szx,sxz); return this; } public IParticleOnPlane translate(double x, double y, double z){ pos.translate(x,y,z); return this; } public IParticleOnPlane translate(IDoubleI x, IDoubleI y, IDoubleI z){ pos.translate(x,y,z); return this; } public IParticleOnPlane translate(IVecI v){ pos.translate(v); return this; } public IParticleOnPlane transform(IMatrix3I mat){ pos.transform(mat); return this; } public IParticleOnPlane transform(IMatrix4I mat){ pos.transform(mat); return this; } public IParticleOnPlane transform(IVecI xvec, IVecI yvec, IVecI zvec){ pos.transform(xvec,yvec,zvec); return this; } public IParticleOnPlane transform(IVecI xvec, IVecI yvec, IVecI zvec, IVecI translate){ pos.transform(xvec,yvec,zvec,translate); return this; } public IParticleOnPlane mv(double x, double y, double z){ return add(x,y,z); } public IParticleOnPlane mv(IDoubleI x, IDoubleI y, IDoubleI z){ return add(x,y,z); } public IParticleOnPlane mv(IVecI v){ return add(v); } public IParticleOnPlane cp(){ return dup(); } public IParticleOnPlane cp(double x, double y, double z){ return dup().add(x,y,z); } public IParticleOnPlane cp(IDoubleI x, IDoubleI y, IDoubleI z){ return dup().add(x,y,z); } public IParticleOnPlane cp(IVecI v){ return dup().add(v); } /************************************** * methods of IPoint *************************************/ public IParticleOnPlane setSize(double sz){ return size(sz); } public IParticleOnPlane size(double sz){ point.size(sz); return this; } /************************************** * methods of IObject *************************************/ public IParticleOnPlane name(String nm){ super.name(nm); return this; } public IParticleOnPlane layer(ILayer l){ super.layer(l); return this; } public IParticleOnPlane show(){ super.show(); return this; } public IParticleOnPlane hide(){ super.hide(); return this; } public IParticleOnPlane clr(IColor c){ super.clr(c); return this; } public IParticleOnPlane clr(IColor c, int alpha){ super.clr(c,alpha); return this; } public IParticleOnPlane clr(IColor c, float alpha){ super.clr(c,alpha); return this; } public IParticleOnPlane clr(IColor c, double alpha){ super.clr(c,alpha); return this; } public IParticleOnPlane clr(Color c){ super.clr(c); return this; } public IParticleOnPlane clr(Color c, int alpha){ super.clr(c,alpha); return this; } public IParticleOnPlane clr(Color c, float alpha){ super.clr(c,alpha); return this; } public IParticleOnPlane clr(Color c, double alpha){ super.clr(c,alpha); return this; } public IParticleOnPlane clr(int gray){ super.clr(gray); return this; } public IParticleOnPlane clr(float fgray){ super.clr(fgray); return this; } public IParticleOnPlane clr(double dgray){ super.clr(dgray); return this; } public IParticleOnPlane clr(int gray, int alpha){ super.clr(gray,alpha); return this; } public IParticleOnPlane clr(float fgray, float falpha){ super.clr(fgray,falpha); return this; } public IParticleOnPlane clr(double dgray, double dalpha){ super.clr(dgray,dalpha); return this; } public IParticleOnPlane clr(int r, int g, int b){ super.clr(r,g,b); return this; } public IParticleOnPlane clr(float fr, float fg, float fb){ super.clr(fr,fg,fb); return this; } public IParticleOnPlane clr(double dr, double dg, double db){ super.clr(dr,dg,db); return this; } public IParticleOnPlane clr(int r, int g, int b, int a){ super.clr(r,g,b,a); return this; } public IParticleOnPlane clr(float fr, float fg, float fb, float fa){ super.clr(fr,fg,fb,fa); return this; } public IParticleOnPlane clr(double dr, double dg, double db, double da){ super.clr(dr,dg,db,da); return this; } public IParticleOnPlane hsb(float h, float s, float b, float a){ super.hsb(h,s,b,a); return this; } public IParticleOnPlane hsb(double h, double s, double b, double a){ super.hsb(h,s,b,a); return this; } public IParticleOnPlane hsb(float h, float s, float b){ super.hsb(h,s,b); return this; } public IParticleOnPlane hsb(double h, double s, double b){ super.hsb(h,s,b); return this; } public IParticleOnPlane setColor(IColor c){ super.setColor(c); return this; } public IParticleOnPlane setColor(IColor c, int alpha){ super.setColor(c,alpha); return this; } public IParticleOnPlane setColor(IColor c, float alpha){ super.setColor(c,alpha); return this; } public IParticleOnPlane setColor(IColor c, double alpha){ super.setColor(c,alpha); return this; } public IParticleOnPlane setColor(Color c){ super.setColor(c); return this; } public IParticleOnPlane setColor(Color c, int alpha){ super.setColor(c,alpha); return this; } public IParticleOnPlane setColor(Color c, float alpha){ super.setColor(c,alpha); return this; } public IParticleOnPlane setColor(Color c, double alpha){ super.setColor(c,alpha); return this; } public IParticleOnPlane setColor(int gray){ super.setColor(gray); return this; } public IParticleOnPlane setColor(float fgray){ super.setColor(fgray); return this; } public IParticleOnPlane setColor(double dgray){ super.setColor(dgray); return this; } public IParticleOnPlane setColor(int gray, int alpha){ super.setColor(gray,alpha); return this; } public IParticleOnPlane setColor(float fgray, float falpha){ super.setColor(fgray,falpha); return this; } public IParticleOnPlane setColor(double dgray, double dalpha){ super.setColor(dgray,dalpha); return this; } public IParticleOnPlane setColor(int r, int g, int b){ super.setColor(r,g,b); return this; } public IParticleOnPlane setColor(float fr, float fg, float fb){ super.setColor(fr,fg,fb); return this; } public IParticleOnPlane setColor(double dr, double dg, double db){ super.setColor(dr,dg,db); return this; } public IParticleOnPlane setColor(int r, int g, int b, int a){ super.setColor(r,g,b,a); return this; } public IParticleOnPlane setColor(float fr, float fg, float fb, float fa){ super.setColor(fr,fg,fb,fa); return this; } public IParticleOnPlane setColor(double dr, double dg, double db, double da){ super.setColor(dr,dg,db,da); return this; } public IParticleOnPlane setHSBColor(float h, float s, float b, float a){ super.setHSBColor(h,s,b,a); return this; } public IParticleOnPlane setHSBColor(double h, double s, double b, double a){ super.setHSBColor(h,s,b,a); return this; } public IParticleOnPlane setHSBColor(float h, float s, float b){ super.setHSBColor(h,s,b); return this; } public IParticleOnPlane setHSBColor(double h, double s, double b){ super.setHSBColor(h,s,b); return this; } public IParticleOnPlane weight(double w){ super.weight(w); return this; } public IParticleOnPlane weight(float w){ super.weight(w); return this; } }
package org.bouncycastle.asn1.cms; import java.util.Enumeration; import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.ASN1Set; import org.bouncycastle.asn1.ASN1TaggedObject; import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.asn1.DERTaggedObject; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; /** * <a href="http://tools.ietf.org/html/rfc5652#section-5.3">RFC 5652</a>: * Signature container per Signer, see {@link SignerIdentifier}. * <pre> * PKCS#7: * * SignerInfo ::= SEQUENCE { * version Version, * sid SignerIdentifier, * digestAlgorithm DigestAlgorithmIdentifier, * authenticatedAttributes [0] IMPLICIT Attributes OPTIONAL, * digestEncryptionAlgorithm DigestEncryptionAlgorithmIdentifier, * encryptedDigest EncryptedDigest, * unauthenticatedAttributes [1] IMPLICIT Attributes OPTIONAL * } * * EncryptedDigest ::= OCTET STRING * * DigestAlgorithmIdentifier ::= AlgorithmIdentifier * * DigestEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier * * ----------------------------------------- * * RFC 5652: * * SignerInfo ::= SEQUENCE { * version CMSVersion, * sid SignerIdentifier, * digestAlgorithm DigestAlgorithmIdentifier, * signedAttrs [0] IMPLICIT SignedAttributes OPTIONAL, * signatureAlgorithm SignatureAlgorithmIdentifier, * signature SignatureValue, * unsignedAttrs [1] IMPLICIT UnsignedAttributes OPTIONAL * } * * -- {@link SignerIdentifier} referenced certificates are at containing * -- {@link SignedData} certificates element. * * SignerIdentifier ::= CHOICE { * issuerAndSerialNumber {@link IssuerAndSerialNumber}, * subjectKeyIdentifier [0] SubjectKeyIdentifier } * * -- See {@link Attributes} for generalized SET OF {@link Attribute} * * SignedAttributes ::= SET SIZE (1..MAX) OF Attribute * UnsignedAttributes ::= SET SIZE (1..MAX) OF Attribute * * {@link Attribute} ::= SEQUENCE { * attrType OBJECT IDENTIFIER, * attrValues SET OF AttributeValue } * * AttributeValue ::= ANY * * SignatureValue ::= OCTET STRING * </pre> */ public class SignerInfo extends ASN1Object { private ASN1Integer version; private SignerIdentifier sid; private AlgorithmIdentifier digAlgorithm; private ASN1Set authenticatedAttributes; private AlgorithmIdentifier digEncryptionAlgorithm; private ASN1OctetString encryptedDigest; private ASN1Set unauthenticatedAttributes; /** * Return a SignerInfo object from the given input * <p> * Accepted inputs: * <ul> * <li> null &rarr; null * <li> {@link SignerInfo} object * <li> {@link org.bouncycastle.asn1.ASN1Sequence#getInstance(java.lang.Object) ASN1Sequence} input formats with SignerInfo structure inside * </ul> * * @param o the object we want converted. * @exception IllegalArgumentException if the object cannot be converted. */ public static SignerInfo getInstance( Object o) throws IllegalArgumentException { if (o instanceof SignerInfo) { return (SignerInfo)o; } else if (o != null) { return new SignerInfo(ASN1Sequence.getInstance(o)); } return null; } /** * * @param sid * @param digAlgorithm CMS knows as 'digestAlgorithm' * @param authenticatedAttributes CMS knows as 'signedAttrs' * @param digEncryptionAlgorithm CMS knows as 'signatureAlgorithm' * @param encryptedDigest CMS knows as 'signature' * @param unauthenticatedAttributes CMS knows as 'unsignedAttrs' */ public SignerInfo( SignerIdentifier sid, AlgorithmIdentifier digAlgorithm, ASN1Set authenticatedAttributes, AlgorithmIdentifier digEncryptionAlgorithm, ASN1OctetString encryptedDigest, ASN1Set unauthenticatedAttributes) { if (sid.isTagged()) { this.version = new ASN1Integer(3); } else { this.version = new ASN1Integer(1); } this.sid = sid; this.digAlgorithm = digAlgorithm; this.authenticatedAttributes = authenticatedAttributes; this.digEncryptionAlgorithm = digEncryptionAlgorithm; this.encryptedDigest = encryptedDigest; this.unauthenticatedAttributes = unauthenticatedAttributes; } /** * * @param sid * @param digAlgorithm CMS knows as 'digestAlgorithm' * @param authenticatedAttributes CMS knows as 'signedAttrs' * @param digEncryptionAlgorithm CMS knows as 'signatureAlgorithm' * @param encryptedDigest CMS knows as 'signature' * @param unauthenticatedAttributes CMS knows as 'unsignedAttrs' */ public SignerInfo( SignerIdentifier sid, AlgorithmIdentifier digAlgorithm, Attributes authenticatedAttributes, AlgorithmIdentifier digEncryptionAlgorithm, ASN1OctetString encryptedDigest, Attributes unauthenticatedAttributes) { if (sid.isTagged()) { this.version = new ASN1Integer(3); } else { this.version = new ASN1Integer(1); } this.sid = sid; this.digAlgorithm = digAlgorithm; this.authenticatedAttributes = ASN1Set.getInstance(authenticatedAttributes); this.digEncryptionAlgorithm = digEncryptionAlgorithm; this.encryptedDigest = encryptedDigest; this.unauthenticatedAttributes = ASN1Set.getInstance(unauthenticatedAttributes); } /** * @deprecated use getInstance() method. */ public SignerInfo( ASN1Sequence seq) { Enumeration e = seq.getObjects(); version = (ASN1Integer)e.nextElement(); sid = SignerIdentifier.getInstance(e.nextElement()); digAlgorithm = AlgorithmIdentifier.getInstance(e.nextElement()); Object obj = e.nextElement(); if (obj instanceof ASN1TaggedObject) { authenticatedAttributes = ASN1Set.getInstance((ASN1TaggedObject)obj, false); digEncryptionAlgorithm = AlgorithmIdentifier.getInstance(e.nextElement()); } else { authenticatedAttributes = null; digEncryptionAlgorithm = AlgorithmIdentifier.getInstance(obj); } encryptedDigest = DEROctetString.getInstance(e.nextElement()); if (e.hasMoreElements()) { unauthenticatedAttributes = ASN1Set.getInstance((ASN1TaggedObject)e.nextElement(), false); } else { unauthenticatedAttributes = null; } } public ASN1Integer getVersion() { return version; } public SignerIdentifier getSID() { return sid; } public ASN1Set getAuthenticatedAttributes() { return authenticatedAttributes; } public AlgorithmIdentifier getDigestAlgorithm() { return digAlgorithm; } public ASN1OctetString getEncryptedDigest() { return encryptedDigest; } public AlgorithmIdentifier getDigestEncryptionAlgorithm() { return digEncryptionAlgorithm; } public ASN1Set getUnauthenticatedAttributes() { return unauthenticatedAttributes; } /** * Produce an object suitable for an ASN1OutputStream. */ public ASN1Primitive toASN1Primitive() { ASN1EncodableVector v = new ASN1EncodableVector(); v.add(version); v.add(sid); v.add(digAlgorithm); if (authenticatedAttributes != null) { v.add(new DERTaggedObject(false, 0, authenticatedAttributes)); } v.add(digEncryptionAlgorithm); v.add(encryptedDigest); if (unauthenticatedAttributes != null) { v.add(new DERTaggedObject(false, 1, unauthenticatedAttributes)); } return new DERSequence(v); } }
/* * @(#)CertificateFactory.java 1.32 06/04/21 * * Copyright 2006 Sun Microsystems, Inc. All rights reserved. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package java.security.cert; import java.io.InputStream; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.security.Provider; import java.security.Security; import java.security.AccessController; import java.security.PrivilegedAction; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import sun.security.jca.*; import sun.security.jca.GetInstance.Instance; /** * This class defines the functionality of a certificate factory, which is * used to generate certificate, certification path (<code>CertPath</code>) * and certificate revocation list (CRL) objects from their encodings. * * <p>For encodings consisting of multiple certificates, use * <code>generateCertificates</code> when you want to * parse a collection of possibly unrelated certificates. Otherwise, * use <code>generateCertPath</code> when you want to generate * a <code>CertPath</code> (a certificate chain) and subsequently * validate it with a <code>CertPathValidator</code>. * * <p>A certificate factory for X.509 must return certificates that are an * instance of <code>java.security.cert.X509Certificate</code>, and CRLs * that are an instance of <code>java.security.cert.X509CRL</code>. * * <p>The following example reads a file with Base64 encoded certificates, * which are each bounded at the beginning by -----BEGIN CERTIFICATE-----, and * bounded at the end by -----END CERTIFICATE-----. We convert the * <code>FileInputStream</code> (which does not support <code>mark</code> * and <code>reset</code>) to a <code>BufferedInputStream</code> (which * supports those methods), so that each call to * <code>generateCertificate</code> consumes only one certificate, and the * read position of the input stream is positioned to the next certificate in * the file:<p> * * <pre> * FileInputStream fis = new FileInputStream(filename); * BufferedInputStream bis = new BufferedInputStream(fis); * * CertificateFactory cf = CertificateFactory.getInstance("X.509"); * * while (bis.available() > 0) { * Certificate cert = cf.generateCertificate(bis); * System.out.println(cert.toString()); * } * </pre> * * <p>The following example parses a PKCS#7-formatted certificate reply stored * in a file and extracts all the certificates from it:<p> * * <pre> * FileInputStream fis = new FileInputStream(filename); * CertificateFactory cf = CertificateFactory.getInstance("X.509"); * Collection c = cf.generateCertificates(fis); * Iterator i = c.iterator(); * while (i.hasNext()) { * Certificate cert = (Certificate)i.next(); * System.out.println(cert); * } * </pre> * * @author Hemma Prafullchandra * @author Jan Luehe * @author Sean Mullan * * @version 1.32, 04/21/06 * * @see Certificate * @see X509Certificate * @see CertPath * @see CRL * @see X509CRL * * @since 1.2 */ public class CertificateFactory { // The certificate type private String type; // The provider private Provider provider; // The provider implementation private CertificateFactorySpi certFacSpi; /** * Creates a CertificateFactory object of the given type, and encapsulates * the given provider implementation (SPI object) in it. * * @param certFacSpi the provider implementation. * @param provider the provider. * @param type the certificate type. */ protected CertificateFactory(CertificateFactorySpi certFacSpi, Provider provider, String type) { this.certFacSpi = certFacSpi; this.provider = provider; this.type = type; } /** * Returns a certificate factory object that implements the * specified certificate type. * * <p> This method traverses the list of registered security Providers, * starting with the most preferred Provider. * A new CertificateFactory object encapsulating the * CertificateFactorySpi implementation from the first * Provider that supports the specified type is returned. * * <p> Note that the list of registered providers may be retrieved via * the {@link Security#getProviders() Security.getProviders()} method. * * @param type the name of the requested certificate type. * See Appendix A in the <a href= * "../../../../technotes/guides/security/crypto/CryptoSpec.html#AppA"> * Java Cryptography Architecture API Specification &amp; Reference </a> * for information about standard certificate types. * * @return a certificate factory object for the specified type. * * @exception CertificateException if no Provider supports a * CertificateFactorySpi implementation for the * specified type. * * @see java.security.Provider */ public static final CertificateFactory getInstance(String type) throws CertificateException { try { Instance instance = GetInstance.getInstance("CertificateFactory", CertificateFactorySpi.class, type); return new CertificateFactory((CertificateFactorySpi)instance.impl, instance.provider, type); } catch (NoSuchAlgorithmException e) { throw new CertificateException(type + " not found", e); } } /** * Returns a certificate factory object for the specified * certificate type. * * <p> A new CertificateFactory object encapsulating the * CertificateFactorySpi implementation from the specified provider * is returned. The specified provider must be registered * in the security provider list. * * <p> Note that the list of registered providers may be retrieved via * the {@link Security#getProviders() Security.getProviders()} method. * * @param type the certificate type. * See Appendix A in the <a href= * "../../../../technotes/guides/security/crypto/CryptoSpec.html#AppA"> * Java Cryptography Architecture API Specification &amp; Reference </a> * for information about standard certificate types. * * @param provider the name of the provider. * * @return a certificate factory object for the specified type. * * @exception CertificateException if a CertificateFactorySpi * implementation for the specified algorithm is not * available from the specified provider. * * @exception NoSuchProviderException if the specified provider is not * registered in the security provider list. * * @exception IllegalArgumentException if the provider name is null * or empty. * * @see java.security.Provider */ public static final CertificateFactory getInstance(String type, String provider) throws CertificateException, NoSuchProviderException { try { Instance instance = GetInstance.getInstance("CertificateFactory", CertificateFactorySpi.class, type, provider); return new CertificateFactory((CertificateFactorySpi)instance.impl, instance.provider, type); } catch (NoSuchAlgorithmException e) { throw new CertificateException(type + " not found", e); } } /** * Returns a certificate factory object for the specified * certificate type. * * <p> A new CertificateFactory object encapsulating the * CertificateFactorySpi implementation from the specified Provider * object is returned. Note that the specified Provider object * does not have to be registered in the provider list. * * @param type the certificate type. * See Appendix A in the <a href= * "../../../../technotes/guides/security/crypto/CryptoSpec.html#AppA"> * Java Cryptography Architecture API Specification &amp; Reference </a> * for information about standard certificate types. * @param provider the provider. * * @return a certificate factory object for the specified type. * * @exception CertificateException if a CertificateFactorySpi * implementation for the specified algorithm is not available * from the specified Provider object. * * @exception IllegalArgumentException if the <code>provider</code> is * null. * * @see java.security.Provider * * @since 1.4 */ public static final CertificateFactory getInstance(String type, Provider provider) throws CertificateException { try { Instance instance = GetInstance.getInstance("CertificateFactory", CertificateFactorySpi.class, type, provider); return new CertificateFactory((CertificateFactorySpi)instance.impl, instance.provider, type); } catch (NoSuchAlgorithmException e) { throw new CertificateException(type + " not found", e); } } /** * Returns the provider of this certificate factory. * * @return the provider of this certificate factory. */ public final Provider getProvider() { return this.provider; } /** * Returns the name of the certificate type associated with this * certificate factory. * * @return the name of the certificate type associated with this * certificate factory. */ public final String getType() { return this.type; } /** * Generates a certificate object and initializes it with * the data read from the input stream <code>inStream</code>. * * <p>In order to take advantage of the specialized certificate format * supported by this certificate factory, * the returned certificate object can be typecast to the corresponding * certificate class. For example, if this certificate * factory implements X.509 certificates, the returned certificate object * can be typecast to the <code>X509Certificate</code> class. * * <p>In the case of a certificate factory for X.509 certificates, the * certificate provided in <code>inStream</code> must be DER-encoded and * may be supplied in binary or printable (Base64) encoding. If the * certificate is provided in Base64 encoding, it must be bounded at * the beginning by -----BEGIN CERTIFICATE-----, and must be bounded at * the end by -----END CERTIFICATE-----. * * <p>Note that if the given input stream does not support * {@link java.io.InputStream#mark(int) mark} and * {@link java.io.InputStream#reset() reset}, this method will * consume the entire input stream. Otherwise, each call to this * method consumes one certificate and the read position of the * input stream is positioned to the next available byte after * the inherent end-of-certificate marker. If the data in the input stream * does not contain an inherent end-of-certificate marker (other * than EOF) and there is trailing data after the certificate is parsed, a * <code>CertificateException</code> is thrown. * * @param inStream an input stream with the certificate data. * * @return a certificate object initialized with the data * from the input stream. * * @exception CertificateException on parsing errors. */ public final Certificate generateCertificate(InputStream inStream) throws CertificateException { return certFacSpi.engineGenerateCertificate(inStream); } /** * Returns an iteration of the <code>CertPath</code> encodings supported * by this certificate factory, with the default encoding first. See * Appendix A in the * <a href="../../../../technotes/guides/security/certpath/CertPathProgGuide.html#AppA"> * Java Certification Path API Programmer's Guide</a> for information about * standard encoding names and their formats. * <p> * Attempts to modify the returned <code>Iterator</code> via its * <code>remove</code> method result in an * <code>UnsupportedOperationException</code>. * * @return an <code>Iterator</code> over the names of the supported * <code>CertPath</code> encodings (as <code>String</code>s) * @since 1.4 */ public final Iterator<String> getCertPathEncodings() { return(certFacSpi.engineGetCertPathEncodings()); } /** * Generates a <code>CertPath</code> object and initializes it with * the data read from the <code>InputStream</code> inStream. The data * is assumed to be in the default encoding. The name of the default * encoding is the first element of the <code>Iterator</code> returned by * the {@link #getCertPathEncodings getCertPathEncodings} method. * * @param inStream an <code>InputStream</code> containing the data * @return a <code>CertPath</code> initialized with the data from the * <code>InputStream</code> * @exception CertificateException if an exception occurs while decoding * @since 1.4 */ public final CertPath generateCertPath(InputStream inStream) throws CertificateException { return(certFacSpi.engineGenerateCertPath(inStream)); } /** * Generates a <code>CertPath</code> object and initializes it with * the data read from the <code>InputStream</code> inStream. The data * is assumed to be in the specified encoding. See Appendix A in the * <a href="../../../../technotes/guides/security/certpath/CertPathProgGuide.html#AppA"> * Java Certification Path API Programmer's Guide</a> * for information about standard encoding names and their formats. * * @param inStream an <code>InputStream</code> containing the data * @param encoding the encoding used for the data * @return a <code>CertPath</code> initialized with the data from the * <code>InputStream</code> * @exception CertificateException if an exception occurs while decoding or * the encoding requested is not supported * @since 1.4 */ public final CertPath generateCertPath(InputStream inStream, String encoding) throws CertificateException { return(certFacSpi.engineGenerateCertPath(inStream, encoding)); } /** * Generates a <code>CertPath</code> object and initializes it with * a <code>List</code> of <code>Certificate</code>s. * <p> * The certificates supplied must be of a type supported by the * <code>CertificateFactory</code>. They will be copied out of the supplied * <code>List</code> object. * * @param certificates a <code>List</code> of <code>Certificate</code>s * @return a <code>CertPath</code> initialized with the supplied list of * certificates * @exception CertificateException if an exception occurs * @since 1.4 */ public final CertPath generateCertPath(List<? extends Certificate> certificates) throws CertificateException { return(certFacSpi.engineGenerateCertPath(certificates)); } /** * Returns a (possibly empty) collection view of the certificates read * from the given input stream <code>inStream</code>. * * <p>In order to take advantage of the specialized certificate format * supported by this certificate factory, each element in * the returned collection view can be typecast to the corresponding * certificate class. For example, if this certificate * factory implements X.509 certificates, the elements in the returned * collection can be typecast to the <code>X509Certificate</code> class. * * <p>In the case of a certificate factory for X.509 certificates, * <code>inStream</code> may contain a sequence of DER-encoded certificates * in the formats described for * {@link #generateCertificate(java.io.InputStream) generateCertificate}. * In addition, <code>inStream</code> may contain a PKCS#7 certificate * chain. This is a PKCS#7 <i>SignedData</i> object, with the only * significant field being <i>certificates</i>. In particular, the * signature and the contents are ignored. This format allows multiple * certificates to be downloaded at once. If no certificates are present, * an empty collection is returned. * * <p>Note that if the given input stream does not support * {@link java.io.InputStream#mark(int) mark} and * {@link java.io.InputStream#reset() reset}, this method will * consume the entire input stream. * * @param inStream the input stream with the certificates. * * @return a (possibly empty) collection view of * java.security.cert.Certificate objects * initialized with the data from the input stream. * * @exception CertificateException on parsing errors. */ public final Collection<? extends Certificate> generateCertificates (InputStream inStream) throws CertificateException { return certFacSpi.engineGenerateCertificates(inStream); } /** * Generates a certificate revocation list (CRL) object and initializes it * with the data read from the input stream <code>inStream</code>. * * <p>In order to take advantage of the specialized CRL format * supported by this certificate factory, * the returned CRL object can be typecast to the corresponding * CRL class. For example, if this certificate * factory implements X.509 CRLs, the returned CRL object * can be typecast to the <code>X509CRL</code> class. * * <p>Note that if the given input stream does not support * {@link java.io.InputStream#mark(int) mark} and * {@link java.io.InputStream#reset() reset}, this method will * consume the entire input stream. Otherwise, each call to this * method consumes one CRL and the read position of the input stream * is positioned to the next available byte after the the inherent * end-of-CRL marker. If the data in the * input stream does not contain an inherent end-of-CRL marker (other * than EOF) and there is trailing data after the CRL is parsed, a * <code>CRLException</code> is thrown. * * @param inStream an input stream with the CRL data. * * @return a CRL object initialized with the data * from the input stream. * * @exception CRLException on parsing errors. */ public final CRL generateCRL(InputStream inStream) throws CRLException { return certFacSpi.engineGenerateCRL(inStream); } /** * Returns a (possibly empty) collection view of the CRLs read * from the given input stream <code>inStream</code>. * * <p>In order to take advantage of the specialized CRL format * supported by this certificate factory, each element in * the returned collection view can be typecast to the corresponding * CRL class. For example, if this certificate * factory implements X.509 CRLs, the elements in the returned * collection can be typecast to the <code>X509CRL</code> class. * * <p>In the case of a certificate factory for X.509 CRLs, * <code>inStream</code> may contain a sequence of DER-encoded CRLs. * In addition, <code>inStream</code> may contain a PKCS#7 CRL * set. This is a PKCS#7 <i>SignedData</i> object, with the only * significant field being <i>crls</i>. In particular, the * signature and the contents are ignored. This format allows multiple * CRLs to be downloaded at once. If no CRLs are present, * an empty collection is returned. * * <p>Note that if the given input stream does not support * {@link java.io.InputStream#mark(int) mark} and * {@link java.io.InputStream#reset() reset}, this method will * consume the entire input stream. * * @param inStream the input stream with the CRLs. * * @return a (possibly empty) collection view of * java.security.cert.CRL objects initialized with the data from the input * stream. * * @exception CRLException on parsing errors. */ public final Collection<? extends CRL> generateCRLs(InputStream inStream) throws CRLException { return certFacSpi.engineGenerateCRLs(inStream); } }
package totoro.unreality.common.driver; import li.cil.oc.api.Network; import li.cil.oc.api.driver.DeviceInfo; import li.cil.oc.api.driver.item.HostAware; import li.cil.oc.api.driver.item.Slot; import li.cil.oc.api.internal.Robot; import li.cil.oc.api.machine.Arguments; import li.cil.oc.api.machine.Callback; import li.cil.oc.api.machine.Context; import li.cil.oc.api.network.ComponentConnector; import li.cil.oc.api.network.EnvironmentHost; import li.cil.oc.api.network.Visibility; import li.cil.oc.api.prefab.ManagedEnvironment; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumFacing; import totoro.unreality.Config; import totoro.unreality.common.Tier; import totoro.unreality.common.entity.EntityPlasmaBolt; import totoro.unreality.common.item.ItemPlasmaUpgrade; import totoro.unreality.common.sounds.Sounds; import java.util.HashMap; import java.util.Map; public class DriverPlasmaUpgrade extends ManagedEnvironment implements DeviceInfo, HostAware { private static final int CALL_LIMIT = 15; private static final int FIRE_CALL_LIMIT = 1; private int color = 0xff004d; private float yaw = 0, pitch = 0; private boolean needsUpdate = false; private ComponentConnector node; private EnvironmentHost host; public DriverPlasmaUpgrade(EnvironmentHost host) { this.setNode(Network.newNode(this, Visibility.Network) .withConnector().withComponent("plasma", Visibility.Neighbors).create()); node = (ComponentConnector) this.node(); this.host = host; } @Callback(doc = "function(): string -- " + "Will return test string", direct = true, limit = CALL_LIMIT) public Object[] test(Context context, Arguments arguments) { return new Object[] { "Hello UT!" }; } @Callback(doc = "function(color: number): boolean -- " + "Sets the color of the plasma-core. Returns true on success, " + "false and an error message otherwise", direct = true) public Object[] setColor(Context context, Arguments args) { int color = args.checkInteger(0); if(color >= 0 && color <= 0xFFFFFF) { if(node.tryChangeBuffer(-Config.PLASMA_UPGRADE_COLOR_CHANGE_COST)) { setColor(color); return new Object[] { true }; } return new Object[] { false, "not enough energy" }; } return new Object[] { false, "number must be between 0 and 16777215" }; } @Callback(doc = "function(): boolean, [string] -- " + "Sets the color of the plasma-core. Returns true on success, " + "false and an error message otherwise") public Object[] fire(Context context, Arguments args) { if(node.tryChangeBuffer(-Config.PLASMA_UPGRADE_FIRE_COST)) { // Generate and position in the world new entity (plasma bolt) EnumFacing facing = ((Robot) host).facing(); float yaw = this.yaw; float mountX = 0, mountY = 0.2f, mountZ = 0; switch (facing) { case SOUTH: mountX = -0.35f; mountZ = 0; break; case NORTH: mountX = 0.35f; mountZ = 0; yaw += 180; break; case EAST: mountX = 0; mountZ = 0.35f; yaw += 90; break; case WEST: mountX = 0; mountZ = -0.35f; yaw += 270; break; } float accelX = (float) (Math.sin(Math.toRadians(yaw)) * Math.cos(Math.toRadians(pitch))); float accelY = (float) (Math.sin(Math.toRadians(pitch))); float accelZ = (float) (Math.cos(Math.toRadians(yaw)) * Math.cos(Math.toRadians(pitch))); double x = host.xPosition() + accelX + mountX; double y = host.yPosition() + accelY + mountY; double z = host.zPosition() + accelZ + mountZ; EntityPlasmaBolt bolt = new EntityPlasmaBolt(host.world(), x, y, z, accelX, accelY, accelZ); bolt.rotationYaw = yaw; bolt.rotationPitch = pitch; bolt.setColor(this.color); host.world().spawnEntityInWorld(bolt); // Play blast sound bolt.playSound(Sounds.Blast, 1.0f, 1.0f); // Cooldown context.pause(Config.PLASMA_UPGRADE_FIRE_DELAY); return new Object[] { true }; } return new Object[] { false, "not enough energy" }; } @Callback(doc = "function(yaw: number, pitch: number): boolean, [string] -- " + "Change weapon angle (yaw in [-20, 20], pitch in [-90, 90] range)", direct = true, limit = FIRE_CALL_LIMIT) public Object[] turn(Context context, Arguments arguments) { if(node.tryChangeBuffer(-Config.PLASMA_UPGRADE_ROTATION_COST)) { float yaw = (float) arguments.checkDouble(0); float pitch = (float) arguments.checkDouble(1); if (yaw < Config.PLASMA_UPGRADE_MIN_YAW || yaw > Config.PLASMA_UPGRADE_MAX_YAW) { throw new IllegalArgumentException("yaw value must be in [" + Config.PLASMA_UPGRADE_MIN_YAW + ", " + Config.PLASMA_UPGRADE_MAX_YAW + "] range"); } if (pitch < Config.PLASMA_UPGRADE_MIN_PITCH || pitch > Config.PLASMA_UPGRADE_MAX_PITCH) { throw new IllegalArgumentException("pitch value must be in [" + Config.PLASMA_UPGRADE_MIN_PITCH + ", " + Config.PLASMA_UPGRADE_MAX_PITCH + "] range"); } this.setYaw(yaw); this.setPitch(pitch); return new Object[] { true }; } return new Object[] { false, "not enough energy" }; } public int getColor() { return color; } public void setColor(int color) { if(this.color != color) { this.color = color; needsUpdate = true; } } public float getYaw() { return yaw; } public void setYaw(float yaw) { if (this.yaw != yaw) { this.yaw = yaw; needsUpdate = true; } } public float getPitch() { return pitch; } public void setPitch(float pitch) { if (this.pitch != pitch) { this.pitch = pitch; needsUpdate = true; } } protected void updateClient() { try { if(host instanceof Robot) { Robot robot = (Robot) host; robot.synchronizeSlot(robot.componentSlot(node.address())); } } catch(NullPointerException e) { // NO-OP } } @Override public boolean canUpdate() { return true; } @Override public void update() { if(needsUpdate) { updateClient(); needsUpdate = false; } } @Override public void load(NBTTagCompound nbt) { super.load(nbt); if (nbt.hasKey("unreality:color")) { setColor(nbt.getInteger("unreality:color")); } if (nbt.hasKey("unreality:yaw")) { setYaw(nbt.getFloat("unreality:yaw")); } if (nbt.hasKey("unreality:pitch")) { setPitch(nbt.getFloat("unreality:pitch")); } this.needsUpdate = true; } @Override public void save(NBTTagCompound nbt) { super.save(nbt); nbt.setInteger("unreality:color", this.getColor()); nbt.setFloat("unreality:yaw", this.getYaw()); nbt.setFloat("unreality:pitch", this.getPitch()); } private Map<String, String> deviceInfo; @Override public Map<String, String> getDeviceInfo() { if(deviceInfo == null) { deviceInfo = new HashMap<String, String>() {{ put(DeviceAttribute.Class, DeviceClass.Generic); put(DeviceAttribute.Description, "Weapon upgrade for UT2: Deathmatch event"); put(DeviceAttribute.Vendor, "Totoro Corp."); }}; } return deviceInfo; } public boolean worksWith(ItemStack stack, Class<? extends EnvironmentHost> host) { return worksWith(stack) && Robot.class.isAssignableFrom(host); } @Override public boolean worksWith(ItemStack stack) { return stack.getItem() instanceof ItemPlasmaUpgrade; } @Override public li.cil.oc.api.network.ManagedEnvironment createEnvironment(ItemStack stack, EnvironmentHost host) { return new DriverPlasmaUpgrade(host); } @Override public String slot(ItemStack stack) { return Slot.Upgrade; } @Override public int tier(ItemStack stack) { return Tier.One; } @Override public NBTTagCompound dataTag(ItemStack stack) { return null; } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.resourcemover.implementation; import com.azure.core.annotation.ExpectedResponses; import com.azure.core.annotation.Get; import com.azure.core.annotation.HeaderParam; import com.azure.core.annotation.Headers; import com.azure.core.annotation.Host; import com.azure.core.annotation.HostParam; import com.azure.core.annotation.PathParam; import com.azure.core.annotation.QueryParam; import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceInterface; import com.azure.core.annotation.ServiceMethod; import com.azure.core.annotation.UnexpectedResponseExceptionType; import com.azure.core.http.rest.PagedFlux; import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.PagedResponse; import com.azure.core.http.rest.PagedResponseBase; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.RestProxy; import com.azure.core.management.exception.ManagementException; import com.azure.core.util.Context; import com.azure.core.util.FluxUtil; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.resourcemover.fluent.UnresolvedDependenciesClient; import com.azure.resourcemanager.resourcemover.fluent.models.UnresolvedDependencyInner; import com.azure.resourcemanager.resourcemover.models.DependencyLevel; import com.azure.resourcemanager.resourcemover.models.UnresolvedDependencyCollection; import reactor.core.publisher.Mono; /** An instance of this class provides access to all the operations defined in UnresolvedDependenciesClient. */ public final class UnresolvedDependenciesClientImpl implements UnresolvedDependenciesClient { private final ClientLogger logger = new ClientLogger(UnresolvedDependenciesClientImpl.class); /** The proxy service used to perform REST calls. */ private final UnresolvedDependenciesService service; /** The service client containing this operation class. */ private final ResourceMoverServiceApiImpl client; /** * Initializes an instance of UnresolvedDependenciesClientImpl. * * @param client the instance of the service client containing this operation class. */ UnresolvedDependenciesClientImpl(ResourceMoverServiceApiImpl client) { this.service = RestProxy .create(UnresolvedDependenciesService.class, client.getHttpPipeline(), client.getSerializerAdapter()); this.client = client; } /** * The interface defining all the services for ResourceMoverServiceApiUnresolvedDependencies to be used by the proxy * service to perform REST calls. */ @Host("{$host}") @ServiceInterface(name = "ResourceMoverService") private interface UnresolvedDependenciesService { @Headers({"Content-Type: application/json"}) @Get( "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate" + "/moveCollections/{moveCollectionName}/unresolvedDependencies") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(ManagementException.class) Mono<Response<UnresolvedDependencyCollection>> get( @HostParam("$host") String endpoint, @PathParam("subscriptionId") String subscriptionId, @PathParam("resourceGroupName") String resourceGroupName, @PathParam("moveCollectionName") String moveCollectionName, @QueryParam("dependencyLevel") DependencyLevel dependencyLevel, @QueryParam("$orderby") String orderby, @QueryParam("api-version") String apiVersion, @QueryParam("$filter") String filter, @HeaderParam("Accept") String accept, Context context); @Headers({"Content-Type: application/json"}) @Get("{nextLink}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(ManagementException.class) Mono<Response<UnresolvedDependencyCollection>> getNext( @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, @HeaderParam("Accept") String accept, Context context); } /** * Gets a list of unresolved dependencies. * * @param resourceGroupName The Resource Group Name. * @param moveCollectionName The Move Collection Name. * @param dependencyLevel Defines the dependency level. * @param orderby OData order by query option. For example, you can use $orderby=Count desc. * @param filter The filter to apply on the operation. For example, $apply=filter(count eq 2). * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a list of unresolved dependencies. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<UnresolvedDependencyInner>> getSinglePageAsync( String resourceGroupName, String moveCollectionName, DependencyLevel dependencyLevel, String orderby, String filter) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (this.client.getSubscriptionId() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getSubscriptionId() is required and cannot be null.")); } if (resourceGroupName == null) { return Mono .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); } if (moveCollectionName == null) { return Mono .error(new IllegalArgumentException("Parameter moveCollectionName is required and cannot be null.")); } final String accept = "application/json"; return FluxUtil .withContext( context -> service .get( this.client.getEndpoint(), this.client.getSubscriptionId(), resourceGroupName, moveCollectionName, dependencyLevel, orderby, this.client.getApiVersion(), filter, accept, context)) .<PagedResponse<UnresolvedDependencyInner>>map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** * Gets a list of unresolved dependencies. * * @param resourceGroupName The Resource Group Name. * @param moveCollectionName The Move Collection Name. * @param dependencyLevel Defines the dependency level. * @param orderby OData order by query option. For example, you can use $orderby=Count desc. * @param filter The filter to apply on the operation. For example, $apply=filter(count eq 2). * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a list of unresolved dependencies. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<UnresolvedDependencyInner>> getSinglePageAsync( String resourceGroupName, String moveCollectionName, DependencyLevel dependencyLevel, String orderby, String filter, Context context) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (this.client.getSubscriptionId() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getSubscriptionId() is required and cannot be null.")); } if (resourceGroupName == null) { return Mono .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); } if (moveCollectionName == null) { return Mono .error(new IllegalArgumentException("Parameter moveCollectionName is required and cannot be null.")); } final String accept = "application/json"; context = this.client.mergeContext(context); return service .get( this.client.getEndpoint(), this.client.getSubscriptionId(), resourceGroupName, moveCollectionName, dependencyLevel, orderby, this.client.getApiVersion(), filter, accept, context) .map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)); } /** * Gets a list of unresolved dependencies. * * @param resourceGroupName The Resource Group Name. * @param moveCollectionName The Move Collection Name. * @param dependencyLevel Defines the dependency level. * @param orderby OData order by query option. For example, you can use $orderby=Count desc. * @param filter The filter to apply on the operation. For example, $apply=filter(count eq 2). * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a list of unresolved dependencies. */ @ServiceMethod(returns = ReturnType.COLLECTION) private PagedFlux<UnresolvedDependencyInner> getAsync( String resourceGroupName, String moveCollectionName, DependencyLevel dependencyLevel, String orderby, String filter) { return new PagedFlux<>( () -> getSinglePageAsync(resourceGroupName, moveCollectionName, dependencyLevel, orderby, filter), nextLink -> getNextSinglePageAsync(nextLink)); } /** * Gets a list of unresolved dependencies. * * @param resourceGroupName The Resource Group Name. * @param moveCollectionName The Move Collection Name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a list of unresolved dependencies. */ @ServiceMethod(returns = ReturnType.COLLECTION) private PagedFlux<UnresolvedDependencyInner> getAsync(String resourceGroupName, String moveCollectionName) { final DependencyLevel dependencyLevel = null; final String orderby = null; final String filter = null; return new PagedFlux<>( () -> getSinglePageAsync(resourceGroupName, moveCollectionName, dependencyLevel, orderby, filter), nextLink -> getNextSinglePageAsync(nextLink)); } /** * Gets a list of unresolved dependencies. * * @param resourceGroupName The Resource Group Name. * @param moveCollectionName The Move Collection Name. * @param dependencyLevel Defines the dependency level. * @param orderby OData order by query option. For example, you can use $orderby=Count desc. * @param filter The filter to apply on the operation. For example, $apply=filter(count eq 2). * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a list of unresolved dependencies. */ @ServiceMethod(returns = ReturnType.COLLECTION) private PagedFlux<UnresolvedDependencyInner> getAsync( String resourceGroupName, String moveCollectionName, DependencyLevel dependencyLevel, String orderby, String filter, Context context) { return new PagedFlux<>( () -> getSinglePageAsync(resourceGroupName, moveCollectionName, dependencyLevel, orderby, filter, context), nextLink -> getNextSinglePageAsync(nextLink, context)); } /** * Gets a list of unresolved dependencies. * * @param resourceGroupName The Resource Group Name. * @param moveCollectionName The Move Collection Name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a list of unresolved dependencies. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<UnresolvedDependencyInner> get(String resourceGroupName, String moveCollectionName) { final DependencyLevel dependencyLevel = null; final String orderby = null; final String filter = null; return new PagedIterable<>(getAsync(resourceGroupName, moveCollectionName, dependencyLevel, orderby, filter)); } /** * Gets a list of unresolved dependencies. * * @param resourceGroupName The Resource Group Name. * @param moveCollectionName The Move Collection Name. * @param dependencyLevel Defines the dependency level. * @param orderby OData order by query option. For example, you can use $orderby=Count desc. * @param filter The filter to apply on the operation. For example, $apply=filter(count eq 2). * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a list of unresolved dependencies. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<UnresolvedDependencyInner> get( String resourceGroupName, String moveCollectionName, DependencyLevel dependencyLevel, String orderby, String filter, Context context) { return new PagedIterable<>( getAsync(resourceGroupName, moveCollectionName, dependencyLevel, orderby, filter, context)); } /** * Get the next page of items. * * @param nextLink The nextLink parameter. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return unresolved dependency collection. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<UnresolvedDependencyInner>> getNextSinglePageAsync(String nextLink) { if (nextLink == null) { return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); } if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } final String accept = "application/json"; return FluxUtil .withContext(context -> service.getNext(nextLink, this.client.getEndpoint(), accept, context)) .<PagedResponse<UnresolvedDependencyInner>>map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** * Get the next page of items. * * @param nextLink The nextLink parameter. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return unresolved dependency collection. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<UnresolvedDependencyInner>> getNextSinglePageAsync(String nextLink, Context context) { if (nextLink == null) { return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); } if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } final String accept = "application/json"; context = this.client.mergeContext(context); return service .getNext(nextLink, this.client.getEndpoint(), accept, context) .map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)); } }
/* * Copyright 2011 Red Hat inc. and third party contributors as noted * by the author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.redhat.ceylon.cmr.api; import java.io.Serializable; import com.redhat.ceylon.cmr.spi.ContentOptions; import com.redhat.ceylon.cmr.spi.Node; import com.redhat.ceylon.cmr.spi.OpenNode; /** * Artifact lookup context. * * @author <a href="mailto:[email protected]">Ales Justin</a> */ public class ArtifactContext implements Serializable, ContentOptions { public static final String CAR = ".car"; public static final String JAR = ".jar"; public static final String JS = ".js"; public static final String ZIP = ".zip"; public static final String SRC = ".src"; public static final String MAVEN_SRC = "-sources.jar"; public static final String DOCS = "module-doc"; public static final String DOCS_ZIPPED = ".doc.zip"; public static final String MODULE_PROPERTIES = "module.properties"; public static final String MODULE_XML = "module.xml"; public static final String SHA1 = ".sha1"; public static final String INFO = ".info"; // These contain only user supplied suffixes, not ones that get generated by the system like INFO public static final String[] userSuffixes = { CAR, CAR + SHA1, JAR, JAR + SHA1, JS, JS + SHA1, ZIP, ZIP + SHA1, SRC, SRC + SHA1, DOCS_ZIPPED, DOCS_ZIPPED + SHA1, MODULE_PROPERTIES, MODULE_XML }; private String name; private String version; private String[] suffixes = {CAR}; private boolean localOnly; private boolean ignoreSHA; private boolean ignoreCache; private boolean throwErrorIfMissing; private boolean forceOperation; private boolean forceDescriptorCheck; private boolean fetchSingleArtifact; private ArtifactCallback callback; public ArtifactContext(String name, String version) { this.name = name; this.version = version; } public ArtifactContext(String name, String version, String... suffixes) { this(name, version); this.suffixes = suffixes; } public ArtifactContext() { } public ArtifactContext getSha1Context() { String[] sha1Suffixes = new String[suffixes.length]; for (int i = 0; i < sha1Suffixes.length; i++) { sha1Suffixes[i] = suffixes[i] + SHA1; } return new ArtifactContext(name, version, sha1Suffixes); } public ArtifactContext getDocsContext() { return new ArtifactContext(name, version, new String[]{DOCS}); } public ArtifactContext getModuleProperties() { return new ArtifactContext(name, version, new String[]{MODULE_PROPERTIES}); } public ArtifactContext getModuleXml() { return new ArtifactContext(name, version, new String[]{MODULE_XML}); } public void toNode(Node node) { if (node instanceof OpenNode) { final OpenNode on = (OpenNode) node; on.addNode(INFO, this); } } public static ArtifactContext fromNode(Node node) { final Node ac = (node instanceof OpenNode) ? ((OpenNode) node).peekChild(INFO) : node.getChild(INFO); return ac != null ? ac.getValue(ArtifactContext.class) : null; } public static void removeNode(Node node) { if (node instanceof OpenNode) { final OpenNode on = (OpenNode) node; if (on.peekChild(INFO) != null) { on.removeNode(INFO); } } } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String[] getSuffixes() { return suffixes; } public void setSuffixes(String... suffixes) { this.suffixes = suffixes; } public String getSingleSuffix() { if (suffixes.length != 1) { throw new RepositoryException("ArtifactContext should have a single suffix"); } return suffixes[0]; } public static String getSuffixFromNode(Node node) { String fileName = node.getLabel(); return getSuffixFromFilename(fileName); } public static String getSuffixFromFilename(String fileName) { if (fileName.endsWith(CAR)) { return CAR; } else if (fileName.endsWith(JAR)) { return JAR; } else if (fileName.endsWith(JS)) { return JS; } else if (fileName.endsWith(ZIP)) { return ZIP; } else if (fileName.endsWith(SRC)) { return SRC; } else { throw new RepositoryException("Unknown suffix in " + fileName); } } public boolean isLocalOnly() { return localOnly; } public void setLocalOnly(boolean localOnly) { this.localOnly = localOnly; } public boolean isIgnoreSHA() { return ignoreSHA; } public void setIgnoreSHA(boolean ignoreSHA) { this.ignoreSHA = ignoreSHA; } public boolean isIgnoreCache() { return ignoreCache; } public void setIgnoreCache(boolean ignoreCache) { this.ignoreCache = ignoreCache; } public boolean isThrowErrorIfMissing() { return throwErrorIfMissing; } public void setThrowErrorIfMissing(boolean throwErrorIfMissing) { this.throwErrorIfMissing = throwErrorIfMissing; } public boolean isForceOperation() { return forceOperation; } public void setForceOperation(boolean forceOperation) { this.forceOperation = forceOperation; } public boolean isForceDescriptorCheck() { return forceDescriptorCheck; } public void setForceDescriptorCheck(boolean forceDescriptorCheck) { this.forceDescriptorCheck = forceDescriptorCheck; } public boolean isFetchSingleArtifact() { return fetchSingleArtifact; } public void setFetchSingleArtifact(boolean fetchSingleArtifact) { this.fetchSingleArtifact = fetchSingleArtifact; } public ArtifactCallback getCallback() { return callback; } public void setCallback(ArtifactCallback callback) { this.callback = callback; } @Override public String toString() { StringBuilder str = new StringBuilder(); str.append(getName()).append("-").append(getVersion()); if (suffixes.length == 1) { str.append(suffixes[0]); } else { str.append("("); boolean first = true; for (String s : suffixes) { if (!first) { str.append("|"); } str.append(s); first = false; } str.append(")"); } return str.toString(); } public boolean forceOperation() { return isForceOperation(); } public boolean forceDescriptorCheck() { return isForceDescriptorCheck(); } }
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered.org <http://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.mod.mixin.plugin.entityactivation; import net.minecraft.entity.Entity; import net.minecraft.entity.EnumCreatureType; import net.minecraft.entity.IRangedAttackMob; import net.minecraft.entity.boss.EntityDragon; import net.minecraft.entity.boss.EntityDragonPart; import net.minecraft.entity.boss.EntityWither; import net.minecraft.entity.effect.EntityWeatherEffect; import net.minecraft.entity.item.EntityEnderCrystal; import net.minecraft.entity.item.EntityFireworkRocket; import net.minecraft.entity.item.EntityTNTPrimed; import net.minecraft.entity.monster.EntityMob; import net.minecraft.entity.monster.IMob; import net.minecraft.entity.passive.EntityAmbientCreature; import net.minecraft.entity.passive.EntityAnimal; import net.minecraft.entity.passive.EntityWaterMob; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.projectile.EntityFireball; import net.minecraft.entity.projectile.EntityThrowable; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.BlockPos; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import net.minecraft.world.chunk.Chunk; import net.minecraftforge.common.util.FakePlayer; import org.spongepowered.mod.configuration.SpongeConfig; import org.spongepowered.mod.entity.SpongeEntityType; import org.spongepowered.mod.interfaces.IMixinEntity; import org.spongepowered.mod.interfaces.IMixinWorld; import org.spongepowered.mod.interfaces.IMixinWorldProvider; import org.spongepowered.mod.mixin.plugin.CoreMixinPlugin; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class ActivationRange { static AxisAlignedBB maxBB = AxisAlignedBB.fromBounds(0, 0, 0, 0, 0, 0); static AxisAlignedBB miscBB = AxisAlignedBB.fromBounds(0, 0, 0, 0, 0, 0); static AxisAlignedBB creatureBB = AxisAlignedBB.fromBounds(0, 0, 0, 0, 0, 0); static AxisAlignedBB monsterBB = AxisAlignedBB.fromBounds(0, 0, 0, 0, 0, 0); static AxisAlignedBB aquaticBB = AxisAlignedBB.fromBounds(0, 0, 0, 0, 0, 0); static AxisAlignedBB ambientBB = AxisAlignedBB.fromBounds(0, 0, 0, 0, 0, 0); /** * Initializes an entities type on construction to specify what group this * entity is in for activation ranges. * * @param entity Entity to get type for * @return group id */ public static byte initializeEntityActivationType(Entity entity) { // account for entities that dont extend EntityMob, EntityAmbientCreature, EntityCreature if (((IMob.class.isAssignableFrom(entity.getClass()) || IRangedAttackMob.class.isAssignableFrom(entity.getClass())) && (entity.getClass() != EntityMob.class)) || entity.isCreatureType(EnumCreatureType.MONSTER, false)) { return 1; // Monster } else if (((EntityAnimal.class.isAssignableFrom(entity.getClass()) && !entity.isCreatureType(EnumCreatureType.AMBIENT, false)) || entity .isCreatureType(EnumCreatureType.CREATURE, false))) { return 2; // Creature } else if (EntityWaterMob.class.isAssignableFrom(entity.getClass()) || entity.isCreatureType(EnumCreatureType.WATER_CREATURE, true)) { return 3; // Aquatic } else if (EntityAmbientCreature.class.isAssignableFrom(entity.getClass()) || entity.isCreatureType(EnumCreatureType.AMBIENT, false)) { return 4; // Ambient } else { return 5; // Misc } } public boolean isFlowerPot() { return false; } /** * These entities are excluded from Activation range checks. * * @param entity Entity to check * @return boolean If it should always tick. */ public static boolean initializeEntityActivationState(Entity entity) { if (entity.worldObj.isRemote) { return true; } SpongeConfig.EntityActivationRangeCategory config = getActiveConfig(entity.worldObj).getConfig().getEntityActivationRange(); if ((((IMixinEntity) entity).getActivationType() == 5 && config.getMiscActivationRange() == 0) || (((IMixinEntity) entity).getActivationType() == 4 && config.getAmbientActivationRange() == 0) || (((IMixinEntity) entity).getActivationType() == 3 && config.getAquaticActivationRange() == 0) || (((IMixinEntity) entity).getActivationType() == 2 && config.getCreatureActivationRange() == 0) || (((IMixinEntity) entity).getActivationType() == 1 && config.getMonsterActivationRange() == 0) || (entity instanceof EntityPlayer && !(entity instanceof FakePlayer)) || entity instanceof EntityThrowable || entity instanceof EntityDragon || entity instanceof EntityDragonPart || entity instanceof EntityWither || entity instanceof EntityFireball || entity instanceof EntityWeatherEffect || entity instanceof EntityTNTPrimed || entity instanceof EntityEnderCrystal || entity instanceof EntityFireworkRocket) { return true; } return false; } /** * Utility method to grow an AABB without creating a new AABB or touching * the pool, so we can re-use ones we have. * * @param target The AABB to modify * @param source The AABB to get initial coordinates from * @param x The x value to expand by * @param y The y value to expand by * @param z The z value to expand by */ public static void growBb(AxisAlignedBB target, AxisAlignedBB source, int x, int y, int z) { target.minX = source.minX - x; target.minY = source.minY - y; target.minZ = source.minZ - z; target.maxX = source.maxX + x; target.maxY = source.maxY + y; target.maxZ = source.maxZ + z; } /** * Find what entities are in range of the players in the world and set * active if in range. * * @param world The world to perform activation checks in */ public static void activateEntities(World world) { SpongeConfig.EntityActivationRangeCategory config = getActiveConfig(world).getConfig().getEntityActivationRange(); final int miscActivationRange = config.getMiscActivationRange(); final int creatureActivationRange = config.getCreatureActivationRange(); final int monsterActivationRange = config.getMonsterActivationRange(); final int aquaticActivationRange = config.getAquaticActivationRange(); final int ambientActivationRange = config.getAmbientActivationRange(); int[] ranges = {miscActivationRange, creatureActivationRange, monsterActivationRange, aquaticActivationRange, ambientActivationRange}; int maxRange = 0; for (int range : ranges) { if (range > maxRange) { maxRange = range; } } maxRange = Math.max(maxRange, miscActivationRange); maxRange = Math.min((6 << 4) - 8, maxRange); for (Object entity : world.playerEntities) { Entity player = (Entity) entity; ((IMixinEntity) player).setActivatedTick(world.getWorldInfo().getWorldTotalTime()); growBb(maxBB, player.getEntityBoundingBox(), maxRange, 256, maxRange); growBb(miscBB, player.getEntityBoundingBox(), miscActivationRange, 256, miscActivationRange); growBb(creatureBB, player.getEntityBoundingBox(), creatureActivationRange, 256, creatureActivationRange); growBb(monsterBB, player.getEntityBoundingBox(), monsterActivationRange, 256, monsterActivationRange); growBb(aquaticBB, player.getEntityBoundingBox(), aquaticActivationRange, 256, aquaticActivationRange); growBb(ambientBB, player.getEntityBoundingBox(), ambientActivationRange, 256, ambientActivationRange); int i = MathHelper.floor_double(maxBB.minX / 16.0D); int j = MathHelper.floor_double(maxBB.maxX / 16.0D); int k = MathHelper.floor_double(maxBB.minZ / 16.0D); int l = MathHelper.floor_double(maxBB.maxZ / 16.0D); for (int i1 = i; i1 <= j; ++i1) { for (int j1 = k; j1 <= l; ++j1) { WorldServer worldserver = (WorldServer) world; if (worldserver.theChunkProviderServer.chunkExists(i1, j1)) { activateChunkEntities(world.getChunkFromChunkCoords(i1, j1)); } } } } } /** * Checks for the activation state of all entities in this chunk. * * @param chunk Chunk to check for activation */ @SuppressWarnings("rawtypes") private static void activateChunkEntities(Chunk chunk) { for (int i = 0; i < chunk.getEntityLists().length; ++i) { for (Object o : chunk.getEntityLists()[i]) { Entity entity = (Entity) o; SpongeConfig<?> config = getActiveConfig(entity.worldObj); SpongeEntityType type = (SpongeEntityType) ((org.spongepowered.api.entity.Entity) entity).getType(); if (entity.worldObj.getWorldInfo().getWorldTotalTime() > ((IMixinEntity) entity).getActivatedTick()) { if (((IMixinEntity) entity).getDefaultActivationState()) { ((IMixinEntity) entity).setActivatedTick(entity.worldObj.getWorldInfo().getWorldTotalTime()); continue; } if (!config.getRootNode().getNode(SpongeConfig.MODULE_ENTITY_ACTIVATION_RANGE, type.getModId(), "enabled").getBoolean() || !config.getRootNode() .getNode(SpongeConfig.MODULE_ENTITY_ACTIVATION_RANGE, type.getModId(), "entities", type.getEntityName()) .getBoolean()) { continue; } switch (((IMixinEntity) entity).getActivationType()) { case 1: if (monsterBB.intersectsWith(entity.getEntityBoundingBox())) { ((IMixinEntity) entity).setActivatedTick(entity.worldObj.getWorldInfo().getWorldTotalTime()); } break; case 2: if (creatureBB.intersectsWith(entity.getEntityBoundingBox())) { ((IMixinEntity) entity).setActivatedTick(entity.worldObj.getWorldInfo().getWorldTotalTime()); } break; case 3: if (aquaticBB.intersectsWith(entity.getEntityBoundingBox())) { ((IMixinEntity) entity).setActivatedTick(entity.worldObj.getWorldInfo().getWorldTotalTime()); } break; case 4: if (ambientBB.intersectsWith(entity.getEntityBoundingBox())) { ((IMixinEntity) entity).setActivatedTick(entity.worldObj.getWorldInfo().getWorldTotalTime()); } break; case 5: default: if (miscBB.intersectsWith(entity.getEntityBoundingBox())) { ((IMixinEntity) entity).setActivatedTick(entity.worldObj.getWorldInfo().getWorldTotalTime()); } } } } } } /** * If an entity is not in range, do some more checks to see if we should * give it a shot. * * @param entity Entity to check * @return Whether entity should still be maintained active */ public static boolean checkEntityImmunities(Entity entity) { return false; } /** * Checks if the entity is active for this tick. * * @param entity The entity to check for activity * @return Whether the given entity should be active */ public static boolean checkIfActive(Entity entity) { if (entity.worldObj.isRemote) { return true; } IMixinEntity spongeEntity = (IMixinEntity) entity; boolean isActive = spongeEntity.getActivatedTick() >= entity.worldObj.getWorldInfo().getWorldTotalTime() || spongeEntity.getDefaultActivationState(); // Should this entity tick? if (!isActive) { if ((entity.worldObj.getWorldInfo().getWorldTotalTime() - spongeEntity.getActivatedTick() - 1) % 20 == 0) { // Check immunities every 20 ticks. if (checkEntityImmunities(entity)) { // Triggered some sort of immunity, give 20 full ticks before we check again. spongeEntity.setActivatedTick(entity.worldObj.getWorldInfo().getWorldTotalTime() + 20); } isActive = true; } // Add a little performance juice to active entities. Skip 1/4 if not immune. } else if (!spongeEntity.getDefaultActivationState() && entity.ticksExisted % 4 == 0 && !checkEntityImmunities(entity)) { isActive = false; } // Make sure not on edge of unloaded chunk int x = net.minecraft.util.MathHelper.floor_double(entity.posX); int z = net.minecraft.util.MathHelper.floor_double(entity.posZ); if (isActive && !entity.worldObj.isAreaLoaded(new BlockPos(x, 0, z), 16)) { isActive = false; } return isActive; } public static void addEntityToConfig(World world, SpongeEntityType type, byte activationType) { List<SpongeConfig<?>> configs = new ArrayList<SpongeConfig<?>>(); configs.add(CoreMixinPlugin.getGlobalConfig()); configs.add(((IMixinWorldProvider) world.provider).getDimensionConfig()); configs.add(((IMixinWorld) world).getWorldConfig()); String entityType = "misc"; if (activationType == 1) { entityType = "monster"; } else if (activationType == 2) { entityType = "creature"; } else if (activationType == 3) { entityType = "aquatic"; } else if (activationType == 4) { entityType = "ambient"; } for (SpongeConfig<?> config : configs) { if (config.getRootNode().getNode(SpongeConfig.MODULE_ENTITY_ACTIVATION_RANGE, type.getModId()).isVirtual()) { config.getRootNode().getNode(SpongeConfig.MODULE_ENTITY_ACTIVATION_RANGE, type.getModId(), "enabled").setValue(true); } if (config.getRootNode().getNode(SpongeConfig.MODULE_ENTITY_ACTIVATION_RANGE, type.getModId(), entityType, type.getEntityName()) .isVirtual()) { config.getRootNode().getNode(SpongeConfig.MODULE_ENTITY_ACTIVATION_RANGE, type.getModId(), entityType, type.getEntityName()) .setValue(true); config.save(); } } } public static SpongeConfig<?> getActiveConfig(World world) { SpongeConfig<?> config = ((IMixinWorld) world).getWorldConfig(); if (config.getConfig().isConfigEnabled()) { return config; } else if (((IMixinWorldProvider) world.provider).getDimensionConfig() != null && ((IMixinWorldProvider) world.provider) .getDimensionConfig().getConfig().isConfigEnabled()) { return ((IMixinWorldProvider) world.provider).getDimensionConfig(); } else { return CoreMixinPlugin.getGlobalConfig(); } } }
/* ### * IP: GHIDRA * * 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 ghidra.app.merge.listing; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.util.ArrayList; import java.util.Iterator; import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.SwingConstants; import javax.swing.border.Border; import javax.swing.border.TitledBorder; import javax.swing.event.ChangeListener; import docking.widgets.button.GRadioButton; import docking.widgets.checkbox.GCheckBox; import docking.widgets.label.GDHtmlLabel; import docking.widgets.label.GLabel; import ghidra.app.merge.util.ConflictUtility; import ghidra.util.HTMLUtilities; import ghidra.util.layout.MaximizeSpecificColumnGridLayout; /** * <code>VariousChoicesPanel</code> provides a table type of format for resolving * multiple conflicts in one panel. Each row that has choices represents the * choices for a single conflict. * So each row can have multiple radio buttons or multiple check boxes. * At least one choice must be made in each row that provides choices before * this panel will indicate that all choices are resolved. */ public class VariousChoicesPanel extends ConflictPanel { private final static long serialVersionUID = 1; private static final Border UNDERLINE_BORDER = BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK); private JPanel rowPanel; private GDHtmlLabel headerLabel; private ArrayList<ChoiceRow> rows; private Border radioButtonBorder; private Border checkBoxBorder; private int columnCount = 1; private MaximizeSpecificColumnGridLayout layout; private int indent; /** * Constructor for a various choices panel. */ public VariousChoicesPanel() { super(); init(); } /** * Constructor for a various choices panel. * @param isDoubleBuffered */ public VariousChoicesPanel(boolean isDoubleBuffered) { super(isDoubleBuffered); init(); } private void init() { setBorder(BorderFactory.createTitledBorder("Resolve Conflict")); rows = new ArrayList<>(); layout = new MaximizeSpecificColumnGridLayout(5, 5, columnCount); rowPanel = new JPanel(layout); rowPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); setLayout(new BorderLayout()); headerLabel = new GDHtmlLabel(" "); headerLabel.setHorizontalAlignment(SwingConstants.CENTER); add(headerLabel, BorderLayout.NORTH); setHeader(null); MyRadioButton rb = new MyRadioButton("W"); MyCheckBox cb = new MyCheckBox("W"); MyLabel lbl = new MyLabel("W"); indent = Math.max(rb.getPreferredSize().width, cb.getPreferredSize().width); int radioButtonOffset = (rb.getPreferredSize().height - lbl.getPreferredSize().height) / 2; int checkBoxOffset = (cb.getPreferredSize().height - lbl.getPreferredSize().height) / 2; radioButtonBorder = BorderFactory.createEmptyBorder( (radioButtonOffset > 0 ? radioButtonOffset : 0), 0, 0, 0); checkBoxBorder = BorderFactory.createEmptyBorder((checkBoxOffset > 0 ? checkBoxOffset : 0), 0, 0, 0); add(createUseForAllCheckBox(), BorderLayout.SOUTH); adjustUseForAllEnablement(); } /** * This sets the text that appears as the border title of this panel. * @param conflictType the type of conflict being resolved. */ void setTitle(String conflictType) { ((TitledBorder) getBorder()).setTitle("Resolve " + conflictType + " Conflict"); } /** * This sets the header text that appears above the table. * @param text the text */ void setHeader(String text) { if (text != null && text.length() != 0) { headerLabel.setText(ConflictUtility.wrapAsHTML(text)); add(headerLabel, BorderLayout.NORTH); } else { headerLabel.setText(""); remove(headerLabel); } validate(); invalidate(); } private void adjustColumnCount(int numberOfColumns) { if (numberOfColumns <= 0) { numberOfColumns = 1; } if (columnCount != numberOfColumns) { columnCount = numberOfColumns; layout = new MaximizeSpecificColumnGridLayout(5, 5, columnCount); rowPanel.setLayout(layout); } } /** * Adds a row to the table that doesn't provide any choices. * Instead this row just provides information. * * @param title title the is placed at the beginning of the row * @param info the text for each table column in the row * @param underline true indicates each info string should be underlined * when it appears. (Underlining is done on the header row (row 0) of the table. */ void addInfoRow(final String title, final String[] info, boolean underline) { adjustColumnCount(info.length); MyLabel titleComp = new MyLabel(title); if (underline) { titleComp.setBorder(UNDERLINE_BORDER); } MyLabel[] labels = new MyLabel[info.length]; for (int i = 0; i < info.length; i++) { labels[i] = new MyLabel(info[i]); if (underline) { labels[i].setBorder(UNDERLINE_BORDER); } } ChoiceRow noChoiceRow = new ChoiceRow(titleComp, labels); addRow(noChoiceRow); rowPanel.validate(); validate(); invalidate(); adjustUseForAllEnablement(); } /** * Adds radiobutton choices as a row of the table. * Radiobuttons allow you to select only one choice in the row. * * @param title title the is placed at the beginning of the row * @param choices the text for each choice in the row * @param listener listener that gets notified whenever the state of * one of the radiobuttons in this row changes. */ void addSingleChoice(final String title, final String[] choices, final ChangeListener listener) { adjustColumnCount(choices.length + 1); for (int i = 0; i < choices.length; i++) { if (choices[i] == null) { choices[i] = "-- none --"; } else if (choices[i].length() == 0) { choices[i] = "-- empty --"; } } MyLabel titleComp = new MyLabel(title); MyRadioButton[] rb = new MyRadioButton[choices.length]; final int row = rows.size(); final ChoiceRow choiceRow = new ChoiceRow(titleComp, rb); ItemListener itemListener = new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { adjustUseForAllEnablement(); if (listener != null) { Object source = e.getSource(); if (((MyRadioButton) source).isSelected()) { ResolveConflictChangeEvent re = new ResolveConflictChangeEvent(source, row, choiceRow.getChoice()); listener.stateChanged(re); } } } }; ButtonGroup group = new ButtonGroup(); for (int i = 0; i < choices.length; i++) { rb[i] = new MyRadioButton(choices[i]); rb[i].setName("ChoiceComponentRow" + row + "Col" + (i + 1)); group.add(rb[i]); rb[i].addItemListener(itemListener); } if (choices.length > 0) { titleComp.setBorder(radioButtonBorder); } addRow(choiceRow); rowPanel.validate(); validate(); invalidate(); adjustUseForAllEnablement(); } /** * Adds checkbox choices as a row of the table. * Check boxes allow you to select one or more choices in the row. * * @param title title the is placed at the beginning of the row * @param choices the text for each choice in the row * @param listener listener that gets notified whenever the state of * one of the checkboxes in this row changes. */ void addMultipleChoice(final String title, final String[] choices, final ChangeListener listener) { adjustColumnCount(choices.length + 1); MyLabel titleComp = new MyLabel(title); MyCheckBox[] cb = new MyCheckBox[choices.length]; final int row = rows.size(); final ChoiceRow choiceRow = new ChoiceRow(titleComp, cb); ItemListener itemListener = new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { adjustUseForAllEnablement(); if (listener != null) { ResolveConflictChangeEvent re = new ResolveConflictChangeEvent(e.getSource(), row, choiceRow.getChoice()); listener.stateChanged(re); } } }; for (int i = 0; i < choices.length; i++) { cb[i] = new MyCheckBox(choices[i]); cb[i].setName(getComponentName(row, (i + 1))); cb[i].addItemListener(itemListener); } if (choices.length > 0) { titleComp.setBorder(checkBoxBorder); } addRow(choiceRow); rowPanel.validate(); validate(); invalidate(); adjustUseForAllEnablement(); } /** * Gets a generic name for a component in the table. * @param row the row of the table * @param column the column of the table * @return the default name of the indicated component in the table. */ String getComponentName(int row, int column) { return "ChoiceComponentRow" + row + "Col" + column; } /** * @param choiceRow */ private void addRow(ChoiceRow choiceRow) { int row = rows.size(); rows.add(choiceRow); rowPanel.add(choiceRow.titleLabel); for (int i = 0; i < choiceRow.rb.length; i++) { rowPanel.add(choiceRow.rb[i]); } if (row == 0) { add(rowPanel, BorderLayout.CENTER); } } private void removeRow(int rowNum) { ChoiceRow cr = rows.get(rowNum); rowPanel.remove(cr.titleLabel); JComponent[] comps = cr.rb; for (int i = 0; i < comps.length; i++) { rowPanel.remove(comps[i]); } rows.remove(rowNum); } @Override public int getUseForAllChoice() { if (rows == null || rows.isEmpty()) { return 0; } int firstChoice = -1; Iterator<ChoiceRow> iter = rows.iterator(); while (iter.hasNext()) { ChoiceRow cr = iter.next(); int currentChoice = cr.getChoice(); if (cr.hasChoices()) { if (currentChoice == 0) { return 0; } if (firstChoice == -1) { firstChoice = currentChoice; } else if (currentChoice != firstChoice) { return 0; } } } return (firstChoice != -1) ? firstChoice : 0; } /** * Returns true if the user made a selection for every conflict in the table. */ @Override public boolean allChoicesAreResolved() { Iterator<ChoiceRow> iter = rows.iterator(); while (iter.hasNext()) { ChoiceRow cr = iter.next(); if (cr.hasChoices() && cr.getChoice() == 0) { return false; } } return true; } /** * Returns true if the user made a selection for every conflict in the table and * made the same choice for every row. */ @Override public boolean allChoicesAreSame() { if (rows == null || rows.isEmpty()) { return false; } int firstChoice = -1; Iterator<ChoiceRow> iter = rows.iterator(); while (iter.hasNext()) { ChoiceRow cr = iter.next(); int currentChoice = cr.getChoice(); if (cr.hasChoices()) { if (currentChoice == 0) { return false; } if (firstChoice == -1) { firstChoice = currentChoice; } else if (currentChoice != firstChoice) { return false; } } } return (firstChoice != -1); } /* (non-Javadoc) * @see ghidra.app.merge.listing.ChoiceComponent#getNumConflictsResolved() */ @Override public int getNumConflictsResolved() { int count = 0; Iterator<ChoiceRow> iter = rows.iterator(); while (iter.hasNext()) { ChoiceRow cr = iter.next(); if (cr.getChoice() != 0) { count++; } } return count; } @Override public void removeAllListeners() { Iterator<ChoiceRow> iter = rows.iterator(); while (iter.hasNext()) { ChoiceRow cr = iter.next(); removeListeners(cr); } } private void removeListeners(ChoiceRow cr) { for (int i = 0; i < cr.rb.length; i++) { JComponent comp = cr.rb[i]; if (comp instanceof MyRadioButton) { MyRadioButton rb = (MyRadioButton) comp; ItemListener[] listeners = rb.getItemListeners(); for (int j = listeners.length - 1; j >= 0; j--) { rb.removeItemListener(listeners[j]); } } if (comp instanceof MyCheckBox) { MyCheckBox cb = (MyCheckBox) comp; ItemListener[] listeners = cb.getItemListeners(); for (int j = listeners.length - 1; j >= 0; j--) { cb.removeItemListener(listeners[j]); } } } } /** * Removes header text for this panel and all table/row information. */ @Override public void clear() { removeAllListeners(); int numRows = rows.size(); for (int i = numRows - 1; i >= 0; i--) { removeRow(i); } setHeader(null); columnCount = 1; rowPanel.validate(); validate(); invalidate(); adjustUseForAllEnablement(); } /** * Adjusts the enablement of the Use For All checkbox based on whether choices have been made * for all the conflicts currently on the screen and whether the same choice was made for all * conflicts on the screen. */ public void adjustUseForAllEnablement() { boolean enable = allChoicesAreSame(); if (!enable) { setUseForAll(false); } useForAllCB.setEnabled(enable); } class ChoiceRow { MyLabel titleLabel; JComponent[] rb; ChoiceRow(MyLabel titleLabel, JComponent[] rb) { this.titleLabel = titleLabel; this.rb = rb; } int[] getWidths() { int[] widths = new int[rb.length + 1]; widths[0] = titleLabel.getWidth(); for (int i = 0; i < rb.length; i++) { widths[i + 1] = rb[i].getWidth(); } return widths; } int getHeight() { int height = titleLabel.getHeight(); return height; } int getChoice() { int choice = 0; for (int i = 0; i < rb.length; i++) { if (rb[i] instanceof MyRadioButton) { if (((MyRadioButton) rb[i]).isSelected()) { choice |= 1 << i; } } if (rb[i] instanceof MyCheckBox) { if (((MyCheckBox) rb[i]).isSelected()) { choice |= 1 << i; } } } return choice; } boolean hasChoices() { for (int i = 0; i < rb.length; i++) { if ((rb[i] instanceof MyRadioButton) || (rb[i] instanceof MyCheckBox)) { return true; } } return false; } } /* (non-Javadoc) * @see ghidra.app.merge.listing.ConflictPanel#hasChoice() */ @Override public boolean hasChoice() { return rows.size() > 0; } private class MyLabel extends GLabel { /** * @param text the text of this label. */ public MyLabel(String text) { super(text); addComponentListener(new ComponentListener() { @Override public void componentResized(ComponentEvent e) { // Set a tooltip if we can't see all the text. String displayedText = getText(); if (displayedText == null) { setToolTipText(null); return; } int displayedWidth = getWidth(); Font displayedFont = getFont(); FontMetrics fontMetrics = (displayedFont != null) ? getFontMetrics(displayedFont) : null; int stringWidth = (fontMetrics != null) ? fontMetrics.stringWidth(displayedText) : 0; setToolTipText( (stringWidth > displayedWidth) ? "<html>" + HTMLUtilities.escapeHTML(text) : null); } @Override public void componentMoved(ComponentEvent e) { // Do nothing. } @Override public void componentShown(ComponentEvent e) { // Do nothing. } @Override public void componentHidden(ComponentEvent e) { // Do nothing. } }); } } private class MyRadioButton extends GRadioButton { private final static long serialVersionUID = 1; /** * @param text the text for this radio button */ public MyRadioButton(final String text) { super(text); addComponentListener(new ComponentListener() { @Override public void componentResized(ComponentEvent e) { // Set a tooltip if we can't see all the text. String displayedText = getText(); if (displayedText == null) { setToolTipText(null); return; } int displayedWidth = getWidth() - indent; Font displayedFont = getFont(); FontMetrics fontMetrics = (displayedFont != null) ? getFontMetrics(displayedFont) : null; int stringWidth = (fontMetrics != null) ? fontMetrics.stringWidth(displayedText) : 0; setToolTipText((stringWidth > displayedWidth) ? displayedText : null); } @Override public void componentMoved(ComponentEvent e) { // Do nothing. } @Override public void componentShown(ComponentEvent e) { // Do nothing. } @Override public void componentHidden(ComponentEvent e) { // Do nothing. } }); } } private class MyCheckBox extends GCheckBox { private final static long serialVersionUID = 1; /** * @param text the text for this check box */ public MyCheckBox(String text) { super(text); addComponentListener(new ComponentListener() { @Override public void componentResized(ComponentEvent e) { // Set a tooltip if we can't see all the text. String displayedText = getText(); if (displayedText == null) { setToolTipText(null); return; } int displayedWidth = getWidth() - indent; Font displayedFont = getFont(); FontMetrics fontMetrics = (displayedFont != null) ? getFontMetrics(displayedFont) : null; int stringWidth = (fontMetrics != null) ? fontMetrics.stringWidth(displayedText) : 0; setToolTipText((stringWidth > displayedWidth) ? displayedText : null); } @Override public void componentMoved(ComponentEvent e) { // Do nothing. } @Override public void componentShown(ComponentEvent e) { // Do nothing. } @Override public void componentHidden(ComponentEvent e) { // Do nothing. } }); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.internal.lang; import java.util.Optional; /** * The SystemPropertyHelper class is an helper class for accessing system properties used in geode. * The method name to get the system property should be the same as the system property name. * * @since Geode 1.4.0 */ public class SystemPropertyHelper { public static final String GEODE_PREFIX = "geode."; public static final String GEMFIRE_PREFIX = "gemfire."; /** * When set to "true" enables asynchronous eviction algorithm (defaults to true). For more details * see {@link org.apache.geode.internal.cache.eviction.LRUListWithAsyncSorting}. * * @since Geode 1.4.0 */ public static final String EVICTION_SCAN_ASYNC = "EvictionScanAsync"; /** * This property allows the maximum number of threads used for asynchronous eviction scanning to * be configured. It defaults to "Math.max((Runtime.getRuntime().availableProcessors() / 4), 1)". * For more details see {@link org.apache.geode.internal.cache.eviction.LRUListWithAsyncSorting}. * * @since Geode 1.4.0 */ public static final String EVICTION_SCAN_MAX_THREADS = "EvictionScanMaxThreads"; /** * This property allows configuration of the threshold percentage at which an asynchronous scan is * started. If the number of entries that have been recently used since the previous scan divided * by total number of entries exceeds the threshold then a scan is started. The default threshold * is 25. If the threshold is less than 0 or greater than 100 then the default threshold is used. * For more details see {@link org.apache.geode.internal.cache.eviction.LRUListWithAsyncSorting}. * * @since Geode 1.4.0 */ public static final String EVICTION_SCAN_THRESHOLD_PERCENT = "EvictionScanThresholdPercent"; public static final String EVICTION_SEARCH_MAX_ENTRIES = "lru.maxSearchEntries"; public static final String EARLY_ENTRY_EVENT_SERIALIZATION = "earlyEntryEventSerialization"; public static final String DEFAULT_DISK_DIRS_PROPERTY = "defaultDiskDirs"; public static final String HA_REGION_QUEUE_EXPIRY_TIME_PROPERTY = "MessageTimeToLive"; public static final String THREAD_ID_EXPIRY_TIME_PROPERTY = "threadIdExpiryTime"; public static final String PERSISTENT_VIEW_RETRY_TIMEOUT_SECONDS = "PERSISTENT_VIEW_RETRY_TIMEOUT_SECONDS"; public static final String USE_HTTP_SYSTEM_PROPERTY = "useHTTP"; /** * This property allows users to enable retrying when client application encounters * PdxSerializationException. The default setting is false, and PdxSerializationException will not * be retried. It will cause client application to throw ServerOperationException. When the * property is set to true, the client application will automatically retry the operation to * another server if encountered PdxSerializationException. * * @since Geode 1.15.0 */ public static final String ENABLE_QUERY_RETRY_ON_PDX_SERIALIZATION_EXCEPTION = "enableQueryRetryOnPdxSerializationException"; /** * a comma separated string to list out the packages to scan. If not specified, the entire * classpath is scanned. * This is used by the FastPathScanner to scan for: * 1. XSDRootElement annotation * * @since Geode 1.7.0 */ public static final String PACKAGES_TO_SCAN = "packagesToScan"; /** * This property turns on/off parallel disk store recovery during cluster restart. * By default, the value is True, which allows parallel disk store recovery by multiple threads. */ public static final String PARALLEL_DISK_STORE_RECOVERY = "parallelDiskStoreRecovery"; /** * Milliseconds to wait before retrying to get events for a transaction from the * gateway sender queue when group-transaction-events is true. */ public static final String GET_TRANSACTION_EVENTS_FROM_QUEUE_WAIT_TIME_MS = "get-transaction-events-from-queue-wait-time-ms"; /** * Milliseconds to wait for the client to re-authenticate back before unregister this client * proxy. If client re-authenticate back successfully within this period, messages will continue * to be delivered to the client */ public static final String RE_AUTHENTICATE_WAIT_TIME = "reauthenticate.wait.time"; /** * This method will try to look up "geode." and "gemfire." versions of the system property. It * will check and prefer "geode." setting first, then try to check "gemfire." setting. * * @param name system property name set in Geode * @return an Optional containing the Boolean value of the system property */ public static Optional<Boolean> getProductBooleanProperty(String name) { String property = getProperty(name); return property != null ? Optional.of(Boolean.parseBoolean(property)) : Optional.empty(); } /** * This method will try to look up "geode." and "gemfire." versions of the system property. It * will check and prefer "geode." setting first, then try to check "gemfire." setting. * * @param name system property name set in Geode * @return an Optional containing the Integer value of the system property */ public static Optional<Integer> getProductIntegerProperty(String name) { Integer propertyValue = Integer.getInteger(GEODE_PREFIX + name); if (propertyValue == null) { propertyValue = Integer.getInteger(GEMFIRE_PREFIX + name); } if (propertyValue != null) { return Optional.of(propertyValue); } else { return Optional.empty(); } } /** * This method will try to look up "geode." and "gemfire." versions of the system property. It * will check and prefer "geode." setting first, then try to check "gemfire." setting. * * @param name system property name set in Geode * @return an Optional containing the Long value of the system property */ public static Optional<Long> getProductLongProperty(String name) { Long propertyValue = Long.getLong(GEODE_PREFIX + name); if (propertyValue == null) { propertyValue = Long.getLong(GEMFIRE_PREFIX + name); } if (propertyValue != null) { return Optional.of(propertyValue); } else { return Optional.empty(); } } /** * This method will try to look up "geode." and "gemfire." versions of the system property. It * will check and prefer "geode." setting first, then try to check "gemfire." setting. * * @param name system property name set in Geode * @return the integer value of the system property if exits or the default value */ public static Integer getProductIntegerProperty(String name, int defaultValue) { return getProductIntegerProperty(name).orElse(defaultValue); } public static Long getProductLongProperty(String name, long defaultValue) { return getProductLongProperty(name).orElse(defaultValue); } /** * This method will try to look up "geode." and "gemfire." versions of the system property. It * will check and prefer "geode." setting first, then try to check "gemfire." setting. * * @param name system property name set in Geode * @return an Optional containing the String value of the system property */ public static Optional<String> getProductStringProperty(String name) { String property = getProperty(name); return property != null ? Optional.of(property) : Optional.empty(); } public static String getProperty(String name) { String property = getGeodeProperty(name); return property != null ? property : getGemfireProperty(name); } private static String getGeodeProperty(String name) { return System.getProperty(GEODE_PREFIX + name); } private static String getGemfireProperty(String name) { return System.getProperty(GEMFIRE_PREFIX + name); } /** * As of Geode 1.4.0, a region set operation will be in a transaction even if it is the first * operation in the transaction. * * In previous releases, a region set operation is not in a transaction if it is the first * operation of the transaction. * * Setting this system property to true will restore the previous behavior. * * @since Geode 1.4.0 */ public static boolean restoreSetOperationTransactionBehavior() { return getProductBooleanProperty("restoreSetOperationTransactionBehavior").orElse(false); } /** * As of Geode 1.4.0, idle expiration on a replicate or partitioned region will now do a * distributed check for a more recent last access time on one of the other copies of the region. * * This system property can be set to true to turn off this new check and restore the previous * behavior of only using the local last access time as the basis for expiration. * * @since Geode 1.4.0 */ public static boolean restoreIdleExpirationBehavior() { return getProductBooleanProperty("restoreIdleExpirationBehavior").orElse(false); } }
/* * 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. */ /* $Id$ */ package org.apache.fop.afp.modca; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.util.List; import org.apache.fop.afp.AFPLineDataInfo; import org.apache.fop.afp.AFPTextDataInfo; import org.apache.fop.afp.ptoca.LineDataInfoProducer; import org.apache.fop.afp.ptoca.PtocaBuilder; import org.apache.fop.afp.ptoca.PtocaProducer; import org.apache.fop.afp.ptoca.TextDataInfoProducer; /** * The Presentation Text object is the data object used in document processing * environments for representing text which has been prepared for presentation. * Text, as used here, means an ordered string of characters, such as graphic * symbols, numbers, and letters, that are suitable for the specific purpose of * representing coherent information. Text which has been prepared for * presentation has been reduced to a primitive form through explicit * specification of the characters and their placement in the presentation * space. Control sequences which designate specific control functions may be * embedded within the text. These functions extend the primitive form by * applying specific characteristics to the text when it is presented. The * collection of the graphic characters and control codes is called Presentation * Text, and the object that contains the Presentation Text is called the * PresentationText object. * <p> * The content for this object can be created using {@link PtocaBuilder}. */ public class PresentationTextObject extends AbstractNamedAFPObject { /** * The current presentation text data */ private PresentationTextData currentPresentationTextData; /** * The presentation text data list */ private List/*<PresentationTextData>*/ presentationTextDataList; private PtocaBuilder builder = new DefaultBuilder(); /** * Construct a new PresentationTextObject for the specified name argument, * the name should be an 8 character identifier. * * @param name the name of this presentation object */ public PresentationTextObject(String name) { super(name); } /** * Create the presentation text data for the byte array of data. * * @param textDataInfo * The afp text data * @throws UnsupportedEncodingException thrown if character encoding is not supported */ public void createTextData(AFPTextDataInfo textDataInfo) throws UnsupportedEncodingException { createControlSequences(new TextDataInfoProducer(textDataInfo)); } /** * Creates a chain of control sequences using a producer. * @param producer the producer * @throws UnsupportedEncodingException thrown if character encoding is not supported */ public void createControlSequences(PtocaProducer producer) throws UnsupportedEncodingException { if (currentPresentationTextData == null) { startPresentationTextData(); } try { producer.produce(builder); } catch (UnsupportedEncodingException e) { endPresentationTextData(); throw e; } catch (IOException ioe) { endPresentationTextData(); handleUnexpectedIOError(ioe); } } private class DefaultBuilder extends PtocaBuilder { protected OutputStream getOutputStreamForControlSequence(int length) { if (length > currentPresentationTextData.getBytesAvailable()) { endPresentationTextData(); startPresentationTextData(); } return currentPresentationTextData.getOutputStream(); } } /** * Drawing of lines using the starting and ending coordinates, thickness and * orientation arguments. * * @param lineDataInfo the line data information. */ public void createLineData(AFPLineDataInfo lineDataInfo) { try { createControlSequences(new LineDataInfoProducer(lineDataInfo)); } catch (UnsupportedEncodingException e) { handleUnexpectedIOError(e); //Won't happen for lines } } /** * Helper method to mark the start of the presentation text data */ private void startPresentationTextData() { if (presentationTextDataList == null) { presentationTextDataList = new java.util.ArrayList/*<PresentationTextData>*/(); } if (presentationTextDataList.size() == 0) { currentPresentationTextData = new PresentationTextData(true); } else { currentPresentationTextData = new PresentationTextData(); } presentationTextDataList.add(currentPresentationTextData); } /** * Helper method to mark the end of the presentation text data */ private void endPresentationTextData() { this.currentPresentationTextData = null; } /** {@inheritDoc} */ protected void writeStart(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.BEGIN, Category.PRESENTATION_TEXT); os.write(data); } /** {@inheritDoc} */ protected void writeContent(OutputStream os) throws IOException { writeObjects(this.presentationTextDataList, os); } /** {@inheritDoc} */ protected void writeEnd(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.END, Category.PRESENTATION_TEXT); os.write(data); } /** * A control sequence is a sequence of bytes that specifies a control * function. A control sequence consists of a control sequence introducer * and zero or more parameters. The control sequence can extend multiple * presentation text data objects, but must eventually be terminated. This * method terminates the control sequence. */ public void endControlSequence() { if (currentPresentationTextData == null) { startPresentationTextData(); } try { builder.endChainedControlSequence(); } catch (IOException ioe) { endPresentationTextData(); handleUnexpectedIOError(ioe); //Should not occur since we're writing to byte arrays } } private void handleUnexpectedIOError(IOException ioe) { //"Unexpected" since we're currently dealing with ByteArrayOutputStreams here. throw new RuntimeException("Unexpected I/O error: " + ioe.getMessage(), ioe); } /** {@inheritDoc} */ public String toString() { if (presentationTextDataList != null) { return presentationTextDataList.toString(); } return super.toString(); } }
/* * Copyright 2014 Netflix, 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.reactivex.netty.protocol.http.server; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.DecoderResult; import io.netty.handler.codec.http.Cookie; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.DefaultHttpHeaders; import io.netty.handler.codec.http.DefaultHttpResponse; import io.netty.handler.codec.http.DefaultLastHttpContent; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpChunkedInput; import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.codec.http.ServerCookieEncoder; import io.reactivex.netty.channel.DefaultChannelWriter; import io.reactivex.netty.metrics.MetricEventsSubject; import io.reactivex.netty.server.ServerChannelMetricEventProvider; import io.reactivex.netty.server.ServerMetricsEvent; import rx.Observable; import java.util.concurrent.atomic.AtomicBoolean; /** * @author Nitesh Kant */ public class HttpServerResponse<T> extends DefaultChannelWriter<T> { private final HttpResponseHeaders headers; private final HttpResponse nettyResponse; private final AtomicBoolean headerWritten = new AtomicBoolean(); private volatile boolean fullResponseWritten; private ChannelFuture headerWriteFuture; private volatile boolean flushOnlyOnReadComplete; protected HttpServerResponse(Channel nettyChannel, MetricEventsSubject<? extends ServerMetricsEvent<?>> eventsSubject) { this(nettyChannel, HttpVersion.HTTP_1_1, eventsSubject); } protected HttpServerResponse(Channel nettyChannel, HttpVersion httpVersion, MetricEventsSubject<? extends ServerMetricsEvent<?>> eventsSubject) { this(nettyChannel, new DefaultHttpResponse(httpVersion, HttpResponseStatus.OK), eventsSubject); } /*Visible for testing */ HttpServerResponse(Channel nettyChannel, HttpResponse nettyResponse, MetricEventsSubject<? extends ServerMetricsEvent<?>> eventsSubject) { super(nettyChannel, eventsSubject, ServerChannelMetricEventProvider.INSTANCE); this.nettyResponse = nettyResponse; headers = new HttpResponseHeaders(nettyResponse); } public HttpResponseHeaders getHeaders() { return headers; } public void addCookie(Cookie cookie) { headers.add(HttpHeaders.Names.SET_COOKIE, ServerCookieEncoder.encode(cookie)); } public void setStatus(HttpResponseStatus status) { nettyResponse.setStatus(status); } public HttpResponseStatus getStatus() { return nettyResponse.getStatus(); } @Override public Observable<Void> close() { return close(true); } /** * Closes this response with optionally flushing the writes. <br/> * * <b>Unless it is required by the usecase, it is generally more optimal to leave the decision of when to flush to * the framework as that enables a gathering write on the underlying socket, which is more optimal.</b> * * @param flush If this close should also flush the writes. * * @return Observable representing the close result. */ @Override public Observable<Void> close(boolean flush) { return super.close(flush); } @Override public Observable<Void> _close(boolean flush) { writeHeadersIfNotWritten(); if (!fullResponseWritten && (headers.isTransferEncodingChunked() || headers.isKeepAlive())) { writeOnChannel(new DefaultLastHttpContent()); // This indicates end of response for netty. If this is not // sent for keep-alive connections, netty's HTTP codec will not know that the response has ended and hence // will ignore the subsequent HTTP header writes. See issue: https://github.com/Netflix/RxNetty/issues/130 } return flush ? flush() : Observable.<Void>empty(); } public void writeChunkedInput(HttpChunkedInput httpChunkedInput) { writeOnChannel(httpChunkedInput); } /** * Flush semantics of a response are as follows: * <ul> <li>Flush immediately if {@link HttpServerResponse#flush()} is called.</li> <li>Flush at the completion of {@link Observable} returned by {@link RequestHandler#handle(HttpServerRequest, HttpServerResponse)} if and only if {@link #flushOnlyOnChannelReadComplete(boolean)} is set to false (default is false).</li> <li>Flush when {@link ChannelHandlerContext#fireChannelReadComplete()} event is fired by netty. This is done unconditionally and is a no-op if there is nothing to flush.</li> </ul> */ public void flushOnlyOnChannelReadComplete(boolean flushOnlyOnReadComplete) { this.flushOnlyOnReadComplete = flushOnlyOnReadComplete; } public boolean isFlushOnlyOnReadComplete() { return flushOnlyOnReadComplete; } HttpResponse getNettyResponse() { return nettyResponse; } boolean isHeaderWritten() { return null != headerWriteFuture && headerWriteFuture.isSuccess(); } @Override protected ChannelFuture writeOnChannel(Object msg) { /** * The following code either sends a single FullHttpResponse or assures that the headers are written before * writing any content. * * A single FullHttpResponse will be written, if and only if, * -- The passed object (to be written) is a ByteBuf instance and it's readable bytes are equal to the * content-length header value set. * -- There is no content ever to be written (content length header is set to zero). * * We resort to writing a FullHttpResponse in above scenarios to reduce the overhead of write (executing * netty's pipeline) */ if (!HttpServerResponse.class.isAssignableFrom(msg.getClass())) { if (msg instanceof ByteBuf) { ByteBuf content = (ByteBuf) msg; long contentLength = headers.getContentLength(-1); if (-1 != contentLength && contentLength == content.readableBytes()) { if (headerWritten.compareAndSet(false, true)) { // The passed object (to be written) is a ByteBuf instance and it's readable bytes are equal to the // content-length header value set. // So write full response instead of header, content & last HTTP content. return writeFullResponse((ByteBuf) msg); } } } writeHeadersIfNotWritten(); } else { long contentLength = headers.getContentLength(-1); if (0 == contentLength) { if (headerWritten.compareAndSet(false, true)) { // There is no content ever to be written (content length header is set to zero). // So write full response instead of header & last HTTP content. return writeFullResponse((ByteBuf) msg); } } // There is no reason to call writeHeadersIfNotWritten() as this is the call to actually write the headers. } return super.writeOnChannel(msg); // Write the message as is if we did not write FullHttpResponse. } private ChannelFuture writeFullResponse(ByteBuf content) { fullResponseWritten = true; FullHttpResponse fhr = new DelegatingFullHttpResponse(nettyResponse, content); return super.writeOnChannel(fhr); } protected void writeHeadersIfNotWritten() { if (headerWritten.compareAndSet(false, true)) { /** * This assertion whether the transfer encoding should be chunked or not, should be done here and not * anywhere in the netty's pipeline. The reason is that in close() method we determine whether to write * the LastHttpContent based on whether the transfer encoding is chunked or not. * Now, if we do this determination & updation of transfer encoding in a handler in the pipeline, it may be * that the handler is invoked asynchronously (i.e. when this method is not invoked from the server's * eventloop). In such a scenario there will be a race-condition between close() asserting that the transfer * encoding is chunked and the handler adding the same and thus in some cases, the LastHttpContent will not * be written with transfer-encoding chunked and the response will never finish. */ if (!headers.contains(HttpHeaders.Names.CONTENT_LENGTH)) { // If there is no content length we need to specify the transfer encoding as chunked as we always send // data in multiple HttpContent. // On the other hand, if someone wants to not have chunked encoding, adding content-length will work // as expected. headers.add(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED); } headerWriteFuture = super.writeOnChannel(this); } } /** * An implementation of {@link FullHttpResponse} which can be composed of already created headers and content * separately. The implementation provided by netty does not provide a way to do this. */ private static class DelegatingFullHttpResponse implements FullHttpResponse { private final HttpResponse headers; private final ByteBuf content; private final HttpHeaders trailingHeaders; public DelegatingFullHttpResponse(HttpResponse headers, ByteBuf content) { this.headers = headers; this.content = content; trailingHeaders = new DefaultHttpHeaders(false); } public static FullHttpResponse newWithNoContent(HttpResponse headers, ByteBufAllocator allocator) { headers.headers().set(HttpHeaders.Names.CONTENT_LENGTH, 0); return new DelegatingFullHttpResponse(headers, allocator.buffer(0)); } @Override public FullHttpResponse copy() { DefaultFullHttpResponse copy = new DefaultFullHttpResponse(getProtocolVersion(), getStatus(), content.copy()); copy.headers().set(headers()); copy.trailingHeaders().set(trailingHeaders()); return copy; } @Override public HttpContent duplicate() { DefaultFullHttpResponse dup = new DefaultFullHttpResponse(getProtocolVersion(), getStatus(), content.duplicate()); dup.headers().set(headers()); dup.trailingHeaders().set(trailingHeaders()); return dup; } @Override public FullHttpResponse retain(int increment) { content.retain(increment); return this; } @Override public FullHttpResponse retain() { content.retain(); return this; } @Override public FullHttpResponse setProtocolVersion(HttpVersion version) { headers.setProtocolVersion(version); return this; } @Override public FullHttpResponse setStatus(HttpResponseStatus status) { headers.setStatus(status); return this; } @Override public ByteBuf content() { return content; } @Override public HttpResponseStatus getStatus() { return headers.getStatus(); } @Override public HttpVersion getProtocolVersion() { return headers.getProtocolVersion(); } @Override public HttpHeaders headers() { return headers.headers(); } @Override public HttpHeaders trailingHeaders() { return trailingHeaders; } @Override public DecoderResult getDecoderResult() { return DecoderResult.SUCCESS; } @Override public void setDecoderResult(DecoderResult result) { // No op as we use this only for write. } @Override public int refCnt() { return content.refCnt(); } @Override public boolean release() { return content.release(); } @Override public boolean release(int decrement) { return content.release(decrement); } } }
/* * Copyright (c) 2001-2005 Sun Microsystems, Inc. All rights reserved. * * The Sun Project JXTA(TM) Software License * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The end-user documentation included with the redistribution, if any, must * include the following acknowledgment: "This product includes software * developed by Sun Microsystems, Inc. for JXTA(TM) technology." * Alternately, this acknowledgment may appear in the software itself, if * and wherever such third-party acknowledgments normally appear. * * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must * not be used to endorse or promote products derived from this software * without prior written permission. For written permission, please contact * Project JXTA at http://www.jxta.org. * * 5. Products derived from this software may not be called "JXTA", nor may * "JXTA" appear in their name, without prior written permission of Sun. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * JXTA is a registered trademark of Sun Microsystems, Inc. in the United * States and other countries. * * Please see the license information page at : * <http://www.jxta.org/project/www/license.html> for instructions on use of * the license in source files. * * ==================================================================== * * This software consists of voluntary contributions made by many individuals * on behalf of Project JXTA. For more information on Project JXTA, please see * http://www.jxta.org. * * This license is based on the BSD license adopted by the Apache Foundation. */ package tutorial.psesample.old; import net.jxta.credential.AuthenticationCredential; import net.jxta.document.MimeMediaType; import net.jxta.document.StructuredDocumentFactory; import net.jxta.document.XMLDocument; import net.jxta.exception.PeerGroupException; import net.jxta.exception.ProtocolNotSupportedException; import net.jxta.id.ID; import net.jxta.id.IDFactory; import net.jxta.impl.membership.pse.PSECredential; import net.jxta.impl.membership.pse.PSEMembershipService; import net.jxta.impl.membership.pse.PSEUtils; import net.jxta.impl.membership.pse.StringAuthenticator; import net.jxta.impl.protocol.Certificate; import net.jxta.peergroup.PeerGroup; import net.jxta.protocol.ModuleImplAdvertisement; import net.jxta.protocol.PeerGroupAdvertisement; import org.bouncycastle.asn1.DERSet; import org.bouncycastle.jce.PKCS10CertificationRequest; import org.bouncycastle.jce.X509Principal; import org.bouncycastle.jce.X509V3CertificateGenerator; import javax.crypto.EncryptedPrivateKeyInfo; import javax.swing.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.ByteArrayInputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.lang.reflect.UndeclaredThrowableException; import java.math.BigInteger; import java.security.*; import java.security.cert.CertificateEncodingException; import java.security.cert.X509Certificate; import java.util.*; /** * Main User Interface for the PSE Sample Peer Group application. * <p/> * <p/>Provides access to a wide variety of fun and interesting PSE operations. * <p/> * <p/>This user interface is appropriate for this sample application but is * not appropriate for real applications. The major difference is the strategy * used for dynamically updating buttons and panels. After some experimentation * and feedback it was decided that this application would not dynamically * enable and disable most buttons. By leaving all buttons enabled, but * including status messages when unavailable options are attempted developers * can better experiment and understand why the application behaves as it does. * <p/> * <p/>Real applications should not present users with unavailable options. */ public class SwingUI extends javax.swing.JFrame { /** * The peer group which is the parent for our PSE peer group. Normally this * will be the Net Peer Group, but it is a bad idea to assume that it * always will be the Net Peer Group. * <p/> * <p/>The PSE peer group is instantiated into the parent peer group. The * parent peer group is also used for publishing our peer group * advertisement and the module implementation advertisement for the PSE * peer group. */ final PeerGroup parentgroup; /** * Our peer group object, the PSE Peer Group. */ final PeerGroup group; /** * The Membership service of the PSE Peer Group. */ final PSEMembershipService membership; /** * Credential which is created when the user successfully authenticates * for the invitation certificate. This requires that they know the * password used to encrypt the private key. */ PSECredential invitationCredential = null; /** * Authenticator which is used for generating the invitation credential. */ StringAuthenticator invitationAuthenticator = null; /** * Credential which is created when the user successfully authenticates * for the member certificate. This requires that they know the password * used to encrypt the private key. */ PSECredential memberCredential = null; /** * Authenticator which is used for generating the invitation credential. */ StringAuthenticator memberAuthenticator = null; /** * Credential which is created when the user successfully authenticates * for the owner certificate. This requires that they know the password * used to encrypt the private key. */ PSECredential ownerCredential = null; /** * Authenticator which is used for generating the invitation credential. */ StringAuthenticator ownerAuthenticator = null; /** * Creates new form SwingUI */ public SwingUI(PeerGroup parent, PeerGroupAdvertisement pse_pga) { parentgroup = parent; try { group = parentgroup.newGroup(pse_pga); } catch (PeerGroupException failed) { JOptionPane.showMessageDialog(null, failed.getMessage(), "Couldn't create PSE Peer Group", JOptionPane.ERROR_MESSAGE); throw new IllegalStateException("Can't continue without being able to create a peergroup."); } membership = (PSEMembershipService) group.getMembershipService(); initComponents(); membership.addPropertyChangeListener("defaultCredential", new PropertyChangeListener() { public void propertyChange(final PropertyChangeEvent evt) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() {// FIXME 20050624 bondolo how do I tell the swing UI???? } }); } }); } /** * This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; javax.swing.JLabel invitationDescriptionText; javax.swing.JLabel invitationPasswordLabel; javax.swing.JLabel memberPasswordLabel; memberTab = new javax.swing.JPanel(); memberPasswordLabel = new javax.swing.JLabel(); memberPasswordField = new javax.swing.JPasswordField(); generateMemberCertButton = new javax.swing.JButton(); memberAuthenticateButton = new javax.swing.JButton(); memberGenerateCSRButton = new javax.swing.JButton(); memberImportCertButton = new javax.swing.JButton(); memberResignButton = new javax.swing.JButton(); adminTab = new javax.swing.JPanel(); adminSignCSRButton = new javax.swing.JButton(); adminInviteButton = new javax.swing.JButton(); adminInvitationPasswordLabel = new javax.swing.JLabel(); adminInvitationPasswordField = new javax.swing.JPasswordField(); ownerTab = new javax.swing.JPanel(); ownerSignCSRButton = new javax.swing.JButton(); ownerPasswordLabel = new javax.swing.JLabel(); ownerPasswordField = new javax.swing.JPasswordField(); ownerAuthenticateButton = new javax.swing.JButton(); ownerResignButton = new javax.swing.JButton(); invitationTab = new javax.swing.JPanel(); invitationDescriptionText = new javax.swing.JLabel(); invitationPasswordLabel = new javax.swing.JLabel(); invitationPasswordField = new javax.swing.JPasswordField(); invitationConfirmButton = new javax.swing.JButton(); keyStorePasswordLabel = new javax.swing.JLabel(); keyStorePasswordField = new javax.swing.JPasswordField(); tabs = new javax.swing.JTabbedPane(); authenticationStatus = new javax.swing.JTextField(); memberTab.setLayout(new java.awt.GridBagLayout()); memberTab.setToolTipText("Actions for Peer Group Members"); memberTab.setName("Member"); memberTab.setNextFocusableComponent(adminTab); if (membership.getPSEConfig().isInitialized()) { tabs.add(memberTab); } memberPasswordLabel.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); memberPasswordLabel.setLabelFor(memberPasswordField); memberPasswordLabel.setText("Member Password"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(3, 0, 0, 3); memberTab.add(memberPasswordLabel, gridBagConstraints); memberPasswordField.setColumns(16); memberPasswordField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { memberPasswordFieldActionPerformed(evt); } }); memberPasswordField.addKeyListener(new java.awt.event.KeyAdapter() { @Override public void keyReleased(java.awt.event.KeyEvent evt) { memberPasswordFieldKeyReleasedHandler(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.RELATIVE; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(4, 2, 2, 4); memberTab.add(memberPasswordField, gridBagConstraints); generateMemberCertButton.setText("Generate Certificate "); generateMemberCertButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { generateMemberCertButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2); memberTab.add(generateMemberCertButton, gridBagConstraints); memberAuthenticateButton.setText("Authenticate"); memberAuthenticateButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { memberAuthenticateButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2); memberTab.add(memberAuthenticateButton, gridBagConstraints); memberGenerateCSRButton.setText("Generate CSR..."); memberGenerateCSRButton.setEnabled(false); memberGenerateCSRButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { memberGenerateCSRButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2); memberTab.add(memberGenerateCSRButton, gridBagConstraints); memberImportCertButton.setText("Import Signed Certificate..."); memberImportCertButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { memberImportCertButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2); memberTab.add(memberImportCertButton, gridBagConstraints); memberResignButton.setText("Resign"); memberResignButton.setEnabled(false); memberResignButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { memberResignButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2); memberTab.add(memberResignButton, gridBagConstraints); adminTab.setLayout(new java.awt.GridBagLayout()); adminTab.setToolTipText("Actions for Peer Group Administrators"); adminTab.setName("Administrator"); adminTab.setNextFocusableComponent(ownerTab); adminSignCSRButton.setText("Sign CSR..."); adminSignCSRButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { adminSignCSRButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.LAST_LINE_START; gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2); adminTab.add(adminSignCSRButton, gridBagConstraints); adminInviteButton.setText("Generate Invitation..."); adminInviteButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { adminInviteButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2); adminTab.add(adminInviteButton, gridBagConstraints); adminInvitationPasswordLabel.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); adminInvitationPasswordLabel.setLabelFor(adminInvitationPasswordField); adminInvitationPasswordLabel.setText("Invitation Password"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; gridBagConstraints.insets = new java.awt.Insets(3, 0, 0, 3); adminTab.add(adminInvitationPasswordLabel, gridBagConstraints); adminInvitationPasswordField.setColumns(16); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; gridBagConstraints.insets = new java.awt.Insets(4, 2, 2, 4); adminTab.add(adminInvitationPasswordField, gridBagConstraints); ownerTab.setLayout(new java.awt.GridBagLayout()); ownerTab.setToolTipText("Actions for Peer Group Owner"); ownerTab.setName("Owner"); ownerTab.setNextFocusableComponent(keyStorePasswordField); ownerSignCSRButton.setText("Sign CSR..."); ownerSignCSRButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ownerSignCSRButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.LAST_LINE_START; gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2); ownerTab.add(ownerSignCSRButton, gridBagConstraints); ownerPasswordLabel.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); ownerPasswordLabel.setLabelFor(ownerPasswordField); ownerPasswordLabel.setText("Owner Password"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; gridBagConstraints.insets = new java.awt.Insets(3, 0, 0, 3); ownerTab.add(ownerPasswordLabel, gridBagConstraints); ownerPasswordField.setColumns(16); ownerPasswordField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ownerPasswordFieldActionPerformed(evt); } }); ownerPasswordField.addKeyListener(new java.awt.event.KeyAdapter() { @Override public void keyReleased(java.awt.event.KeyEvent evt) { ownerPasswordFieldKeyReleasedHandler(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_END; gridBagConstraints.insets = new java.awt.Insets(4, 2, 2, 4); ownerTab.add(ownerPasswordField, gridBagConstraints); ownerAuthenticateButton.setText("Authencticate"); ownerAuthenticateButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ownerAuthenticateButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2); ownerTab.add(ownerAuthenticateButton, gridBagConstraints); ownerResignButton.setText("Resign"); ownerResignButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ownerResignButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2); ownerTab.add(ownerResignButton, gridBagConstraints); invitationTab.setLayout(new java.awt.GridBagLayout()); invitationTab.setToolTipText("Actions for Confirming a Peer Group Invitation"); invitationTab.setFocusable(false); invitationTab.setName("Invitation"); invitationTab.setNextFocusableComponent(keyStorePasswordField); if (!membership.getPSEConfig().isInitialized()) { tabs.add(invitationTab); } invitationDescriptionText.setFont(new java.awt.Font("Dialog", 0, 12)); invitationDescriptionText.setText("Confirm the invitation \"%1\" from \"%2\" to join the JXTA Peer Group \"%3\"."); invitationDescriptionText.setHorizontalTextPosition(javax.swing.SwingConstants.LEADING); if (!membership.getPSEConfig().isInitialized()) { try { AuthenticationCredential application = new AuthenticationCredential(group, "StringAuthentication", null); invitationAuthenticator = (StringAuthenticator) membership.apply(application); } catch (ProtocolNotSupportedException noAuthenticator) { throw new UndeclaredThrowableException(noAuthenticator, "String authenticator not available!"); } // The invitation authenticator allows us to get the invitation // certificate even if we don't have a keystore password. The certificate // will be requestable via the local peer's peer id. X509Certificate invitationCert = invitationAuthenticator.getCertificate(new char[0], group.getPeerID()); StringBuilder description = new StringBuilder(invitationDescriptionText.getText()); String subjectName = PSEUtils.getCertSubjectCName(invitationCert); int replaceIdx = description.indexOf("%1"); if ((-1 != replaceIdx) && (null != subjectName)) { description.replace(replaceIdx, replaceIdx + 2, subjectName); } String issuerName = PSEUtils.getCertIssuerCName(invitationCert); replaceIdx = description.indexOf("%2"); if ((-1 != replaceIdx) && (null != issuerName)) { description.replace(replaceIdx, replaceIdx + 2, issuerName); } replaceIdx = description.indexOf("%3"); if (-1 != replaceIdx) { String groupName = group.getPeerGroupName(); if (null == groupName) { groupName = "ID " + group.getPeerGroupID().toString(); } description.replace(replaceIdx, replaceIdx + 2, groupName); } invitationDescriptionText.setText(description.toString()); } gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.gridheight = java.awt.GridBagConstraints.RELATIVE; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; invitationTab.add(invitationDescriptionText, gridBagConstraints); invitationPasswordLabel.setLabelFor(invitationPasswordField); invitationPasswordLabel.setText("Invitation Password"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(3, 0, 0, 3); invitationTab.add(invitationPasswordLabel, gridBagConstraints); invitationPasswordField.setColumns(16); invitationPasswordField.setToolTipText("Enter the password for the invitation"); invitationPasswordField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { invitationPasswordFieldActionPerformed(evt); } }); invitationPasswordField.addKeyListener(new java.awt.event.KeyAdapter() { @Override public void keyReleased(java.awt.event.KeyEvent evt) { invitationPasswordFieldKeyReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(4, 2, 2, 4); invitationTab.add(invitationPasswordField, gridBagConstraints); invitationConfirmButton.setEnabled(!invitationTab.isEnabled()); invitationConfirmButton.setText("Confirm"); invitationConfirmButton.setToolTipText("Click to confirm the peer group invitation."); invitationConfirmButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { invitationConfirmButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 1; gridBagConstraints.ipady = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2); invitationTab.add(invitationConfirmButton, gridBagConstraints); getContentPane().setLayout(new java.awt.GridBagLayout()); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("PSE Peer Group Sample"); addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosed(java.awt.event.WindowEvent evt) { swingUIClosed(evt); } }); keyStorePasswordLabel.setLabelFor(keyStorePasswordField); keyStorePasswordLabel.setText("Key Store Password"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.ipadx = 3; gridBagConstraints.ipady = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; gridBagConstraints.insets = new java.awt.Insets(5, 3, 1, 0); getContentPane().add(keyStorePasswordLabel, gridBagConstraints); keyStorePasswordField.setColumns(16); keyStorePasswordField.setNextFocusableComponent(invitationTab); keyStorePasswordField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { keyStorePasswordFieldActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_END; gridBagConstraints.insets = new java.awt.Insets(4, 0, 1, 2); getContentPane().add(keyStorePasswordField, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.ipadx = 3; gridBagConstraints.ipady = 3; gridBagConstraints.insets = new java.awt.Insets(1, 0, 1, 0); getContentPane().add(tabs, gridBagConstraints); authenticationStatus.setColumns(32); authenticationStatus.setEditable(false); authenticationStatus.setFont(new java.awt.Font("Dialog", 0, 10)); authenticationStatus.setBorder(new javax.swing.border.BevelBorder(javax.swing.border.BevelBorder.LOWERED)); authenticationStatus.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { authenticationStatusActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.ipady = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.LAST_LINE_END; gridBagConstraints.insets = new java.awt.Insets(1, 0, 4, 0); getContentPane().add(authenticationStatus, gridBagConstraints); pack(); } // </editor-fold>//GEN-END:initComponents private void memberPasswordFieldKeyReleasedHandler(java.awt.event.KeyEvent evt) { // GEN-FIRST:event_memberPasswordFieldKeyReleasedHandler if (null == memberAuthenticator) { try { AuthenticationCredential application = new AuthenticationCredential(group, "StringAuthentication", null); memberAuthenticator = (StringAuthenticator) membership.apply(application); } catch (ProtocolNotSupportedException noAuthenticator) { authenticationStatus.setText("Could not create authenticator: " + noAuthenticator.getMessage()); return; } memberAuthenticator.setAuth1_KeyStorePassword(keyStorePasswordField.getPassword()); memberAuthenticator.setAuth2Identity(group.getPeerID()); } memberAuthenticator.setAuth3_IdentityPassword(memberPasswordField.getPassword()); memberAuthenticateButton.setEnabled(memberAuthenticator.isReadyForJoin()); }// GEN-LAST:event_memberPasswordFieldKeyReleasedHandler private void memberPasswordFieldActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_memberPasswordFieldActionPerformed // TODO add your handling code here: }// GEN-LAST:event_memberPasswordFieldActionPerformed private void ownerPasswordFieldActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_ownerPasswordFieldActionPerformed // TODO add your handling code here: }// GEN-LAST:event_ownerPasswordFieldActionPerformed private void ownerPasswordFieldKeyReleasedHandler(java.awt.event.KeyEvent evt) { // GEN-FIRST:event_ownerPasswordFieldKeyReleasedHandler if (null == ownerAuthenticator) { try { AuthenticationCredential application = new AuthenticationCredential(group, "StringAuthentication", null); ownerAuthenticator = (StringAuthenticator) membership.apply(application); } catch (ProtocolNotSupportedException noAuthenticator) { authenticationStatus.setText("Could not create authenticator: " + noAuthenticator.getMessage()); return; } ownerAuthenticator.setAuth1_KeyStorePassword(keyStorePasswordField.getPassword()); ownerAuthenticator.setAuth2Identity(group.getPeerGroupID()); } ownerAuthenticator.setAuth3_IdentityPassword(ownerPasswordField.getPassword()); ownerAuthenticateButton.setEnabled(ownerAuthenticator.isReadyForJoin()); }// GEN-LAST:event_ownerPasswordFieldKeyReleasedHandler private void adminInviteButtonActionPerformed(java.awt.event.ActionEvent evt) { // GEN-FIRST:event_adminInviteButtonActionPerformed if (null == memberCredential) { authenticationStatus.setText("Not authenticated -- cannot create invitation."); return; } X509Certificate[] issuerChain = memberCredential.getCertificateChain(); PrivateKey issuerKey = null; try { issuerKey = memberCredential.getPrivateKey(); } catch (IllegalStateException notLocal) { ; } if (null == issuerKey) { authenticationStatus.setText("Member credential is not a local login credential."); return; } if (issuerChain.length < 2) { authenticationStatus.setText("Member credential is not certified as a Peer Group Administrator."); return; } if (!issuerChain[1].getPublicKey().equals(Main.PSE_SAMPLE_GROUP_ROOT_CERT.getPublicKey())) { authenticationStatus.setText("Member credential is not certified as a Peer Group Administrator."); return; } // Build the Module Impl Advertisemet we will use for our group. ModuleImplAdvertisement pseImpl = Main.build_psegroup_impl_adv(parentgroup); // Publish the Module Impl Advertisement to the group where the // peergroup will be advertised. This should be done in every peer // group in which the Peer Group is also advertised. // We use the same expiration and lifetime that the Peer Group Adv // will use (the default). try { parentgroup.getDiscoveryService().publish(pseImpl, PeerGroup.DEFAULT_LIFETIME, PeerGroup.DEFAULT_EXPIRATION); } catch (IOException failed) { ; } PeerGroupAdvertisement pse_pga = null; PSEUtils.IssuerInfo issuer = new PSEUtils.IssuerInfo(); issuer.cert = issuerChain[0]; issuer.subjectPkey = issuerKey; PSEUtils.IssuerInfo newcert = PSEUtils.genCert("Invitation", issuer); List<X509Certificate> chain = new ArrayList<X509Certificate>(); chain.add(newcert.cert); chain.addAll(Arrays.asList(issuerChain)); EncryptedPrivateKeyInfo encryptedInvitationKey = PSEUtils.pkcs5_Encrypt_pbePrivateKey( adminInvitationPasswordField.getPassword(), newcert.subjectPkey, 10000); // Create the invitation. pse_pga = Main.build_psegroup_adv(pseImpl, (X509Certificate[]) chain.toArray(new X509Certificate[chain.size()]) , encryptedInvitationKey); XMLDocument asXML = (XMLDocument) pse_pga.getDocument(MimeMediaType.XMLUTF8); try { JFileChooser fc = new JFileChooser(); // In response to a button click: int returnVal = fc.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { FileWriter invitation_file = new FileWriter(fc.getSelectedFile()); asXML.sendToWriter(invitation_file); invitation_file.close(); authenticationStatus.setText("Invitation created as file : " + fc.getSelectedFile().getAbsolutePath()); } else { authenticationStatus.setText("Invitation creation cancelled."); } } catch (IOException failed) { authenticationStatus.setText("Failed invitation creation : " + failed); } }// GEN-LAST:event_adminInviteButtonActionPerformed private void ownerSignCSRButtonActionPerformed(java.awt.event.ActionEvent evt) { // GEN-FIRST:event_ownerSignCSRButtonActionPerformed if (null == ownerCredential) { authenticationStatus.setText("Not authenticated -- cannot sign certificates."); return; } PSEUtils.IssuerInfo issuer = null; X509Certificate[] issuerChain = null; issuerChain = ownerCredential.getCertificateChain(); PrivateKey issuerKey = null; try { issuerKey = ownerCredential.getPrivateKey(); } catch (IllegalStateException notLocal) { ; } if (null == issuerKey) { authenticationStatus.setText("Owner credential is not a local login credential."); return; } issuer = new PSEUtils.IssuerInfo(); issuer.cert = issuerChain[0]; issuer.subjectPkey = issuerKey; org.bouncycastle.jce.PKCS10CertificationRequest csr; try { JFileChooser fc = new JFileChooser(); // In response to a button click: int returnVal = fc.showOpenDialog(this); XMLDocument csr_doc = null; if (returnVal == JFileChooser.APPROVE_OPTION) { FileReader csr_file = new FileReader(fc.getSelectedFile()); csr_doc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, csr_file); csr_file.close(); } else { authenticationStatus.setText("Certificate signing cancelled."); return; } net.jxta.impl.protocol.CertificateSigningRequest csr_msg = new net.jxta.impl.protocol.CertificateSigningRequest( csr_doc); csr = csr_msg.getCSR(); } catch (IOException failed) { authenticationStatus.setText("Failed to read certificate signing request: " + failed); return; } // set validity 10 years from today Date today = new Date(); Calendar cal = Calendar.getInstance(); cal.setTime(today); cal.add(Calendar.DATE, 10 * 365); Date until = cal.getTime(); // generate cert try { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setIssuerDN(new X509Principal(true, issuer.cert.getSubjectX500Principal().getName())); certGen.setSubjectDN(csr.getCertificationRequestInfo().getSubject()); certGen.setNotBefore(today); certGen.setNotAfter(until); certGen.setPublicKey(csr.getPublicKey()); // certGen.setSignatureAlgorithm("SHA1withDSA"); certGen.setSignatureAlgorithm("SHA1withRSA"); // FIXME bondolo 20040317 needs fixing. certGen.setSerialNumber(BigInteger.valueOf(1)); // return issuer info for generating service cert // the cert X509Certificate newCert = certGen.generateX509Certificate(issuer.subjectPkey); net.jxta.impl.protocol.Certificate cert_msg = new net.jxta.impl.protocol.Certificate(); List<X509Certificate> newChain = new ArrayList<X509Certificate>(Arrays.asList(issuerChain)); newChain.add(0, newCert); cert_msg.setCertificates(newChain); XMLDocument asXML = (XMLDocument) cert_msg.getDocument(MimeMediaType.XMLUTF8); JFileChooser fc = new JFileChooser(); // In response to a button click: int returnVal = fc.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { FileWriter csr_file = new FileWriter(fc.getSelectedFile()); asXML.sendToWriter(csr_file); csr_file.close(); authenticationStatus.setText("Signed admin certificate saved."); } else { authenticationStatus.setText("Save admin certificate cancelled."); } } catch (NoSuchAlgorithmException failed) { authenticationStatus.setText("Certificate signing failed:" + failed.getMessage()); } catch (NoSuchProviderException failed) { authenticationStatus.setText("Certificate signing failed:" + failed.getMessage()); } catch (InvalidKeyException failed) { authenticationStatus.setText("Certificate signing failed:" + failed.getMessage()); } catch (SignatureException failed) { authenticationStatus.setText("Certificate signing failed:" + failed.getMessage()); } catch (IOException failed) { authenticationStatus.setText("Certificate signing failed:" + failed.getMessage()); } }// GEN-LAST:event_ownerSignCSRButtonActionPerformed private void ownerResignButtonActionPerformed(java.awt.event.ActionEvent evt) { // GEN-FIRST:event_ownerResignButtonActionPerformed if (null == ownerCredential) { authenticationStatus.setText("Already resigned."); return; } ownerCredential = null; }// GEN-LAST:event_ownerResignButtonActionPerformed private void ownerAuthenticateButtonActionPerformed(java.awt.event.ActionEvent evt) { // GEN-FIRST:event_ownerAuthenticateButtonActionPerformed if (null == membership.getDefaultCredential()) { // if the keychain hasn't been unlocked then set the keystore password. membership.getPSEConfig().setKeyStorePassword(keyStorePasswordField.getPassword()); } StringAuthenticator ownerAuthenticator = null; try { AuthenticationCredential application = new AuthenticationCredential(group, "StringAuthentication", null); ownerAuthenticator = (StringAuthenticator) membership.apply(application); } catch (ProtocolNotSupportedException noAuthenticator) { authenticationStatus.setText("Could not create authenticator: " + noAuthenticator.getMessage()); return; } ownerAuthenticator.setAuth1_KeyStorePassword(keyStorePasswordField.getPassword()); ownerAuthenticator.setAuth2Identity(group.getPeerGroupID()); ownerAuthenticator.setAuth3_IdentityPassword(ownerPasswordField.getPassword()); // clear the password ownerPasswordField.setText(""); try { ownerCredential = (PSECredential) membership.join(ownerAuthenticator); authenticationStatus.setText("Owner authentication successful."); } catch (PeerGroupException failed) { authenticationStatus.setText("Owner authentication failed: " + failed.getMessage()); } }// GEN-LAST:event_ownerAuthenticateButtonActionPerformed private void memberResignButtonActionPerformed(java.awt.event.ActionEvent evt) { // GEN-FIRST:event_memberResignButtonActionPerformed if (null == memberCredential) { authenticationStatus.setText("Already resigned."); return; } memberGenerateCSRButton.setEnabled(false); memberResignButton.setEnabled(false); memberCredential = null; }// GEN-LAST:event_memberResignButtonActionPerformed private void memberImportCertButtonActionPerformed(java.awt.event.ActionEvent evt) { // GEN-FIRST:event_memberImportCertButtonActionPerformed if (null == memberCredential) { authenticationStatus.setText("Not authenticated -- cannot import certificates."); return; } JFileChooser fc = new JFileChooser(); // In response to a button click: int returnVal = fc.showOpenDialog(this); XMLDocument certs_doc = null; try { if (returnVal == JFileChooser.APPROVE_OPTION) { FileReader certs_file = new FileReader(fc.getSelectedFile()); certs_doc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, certs_file); certs_file.close(); } else { authenticationStatus.setText("Certificate import cancelled."); return; } } catch (IOException failed) { authenticationStatus.setText("Certificate import failed: " + failed.getMessage()); } Certificate cert_msg = new Certificate(certs_doc); try { Iterator<X509Certificate> sourceChain = Arrays.asList(cert_msg.getCertificates()).iterator(); int imported = 0; X509Certificate aCert = sourceChain.next(); ID createid = group.getPeerGroupID(); do { if (null != membership.getPSEConfig().getTrustedCertificateID(aCert)) { break; } membership.getPSEConfig().erase(createid); membership.getPSEConfig().setTrustedCertificate(createid, aCert); imported++; // create a codat id for the next certificate in the chain. aCert = null; if (sourceChain.hasNext()) { aCert = sourceChain.next(); if (null != membership.getPSEConfig().getTrustedCertificateID(aCert)) { // it's already in the pse, time to bail! break; } byte[] der = aCert.getEncoded(); createid = IDFactory.newCodatID(group.getPeerGroupID(), new ByteArrayInputStream(der)); } } while (null != aCert); authenticationStatus.setText(" Imported " + imported + " certificates. "); } catch (CertificateEncodingException failure) { authenticationStatus.setText("Bad certificate: " + failure); } catch (KeyStoreException failure) { authenticationStatus.setText("KeyStore failure while importing certificate: " + failure); } catch (IOException failure) { authenticationStatus.setText("IO failure while importing certificate: " + failure); } }// GEN-LAST:event_memberImportCertButtonActionPerformed private void adminSignCSRButtonActionPerformed(java.awt.event.ActionEvent evt) { // GEN-FIRST:event_adminSignCSRButtonActionPerformed if (null == memberCredential) { authenticationStatus.setText("Not authenticated -- cannot sign certificates."); return; } PSEUtils.IssuerInfo issuer = null; X509Certificate[] issuerChain = null; issuerChain = memberCredential.getCertificateChain(); PrivateKey issuerKey = null; try { issuerKey = memberCredential.getPrivateKey(); } catch (IllegalStateException notLocal) { ; } if (null == issuerKey) { authenticationStatus.setText("Credential is not a local login credential."); return; } issuer = new PSEUtils.IssuerInfo(); issuer.cert = issuerChain[0]; issuer.subjectPkey = issuerKey; org.bouncycastle.jce.PKCS10CertificationRequest csr; try { JFileChooser fc = new JFileChooser(); // In response to a button click: int returnVal = fc.showOpenDialog(this); XMLDocument csr_doc = null; if (returnVal == JFileChooser.APPROVE_OPTION) { FileReader csr_file = new FileReader(fc.getSelectedFile()); csr_doc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, csr_file); csr_file.close(); } else { authenticationStatus.setText("Certificate Signing cancelled."); return; } net.jxta.impl.protocol.CertificateSigningRequest csr_msg = new net.jxta.impl.protocol.CertificateSigningRequest( csr_doc); csr = csr_msg.getCSR(); } catch (IOException failed) { authenticationStatus.setText("Failed to read certificate signing request: " + failed); return; } // set validity 10 years from today Date today = new Date(); Calendar cal = Calendar.getInstance(); cal.setTime(today); cal.add(Calendar.DATE, 10 * 365); Date until = cal.getTime(); // generate cert try { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setIssuerDN(new X509Principal(true, issuer.cert.getSubjectX500Principal().getName())); certGen.setSubjectDN(csr.getCertificationRequestInfo().getSubject()); certGen.setNotBefore(today); certGen.setNotAfter(until); certGen.setPublicKey(csr.getPublicKey()); // certGen.setSignatureAlgorithm("SHA1withDSA"); certGen.setSignatureAlgorithm("SHA1withRSA"); // FIXME bondolo 20040317 needs fixing. certGen.setSerialNumber(BigInteger.valueOf(1)); // return issuer info for generating service cert // the cert X509Certificate newCert = certGen.generateX509Certificate(issuer.subjectPkey); net.jxta.impl.protocol.Certificate cert_msg = new net.jxta.impl.protocol.Certificate(); List<X509Certificate> newChain = new ArrayList<X509Certificate>(Arrays.asList(issuerChain)); newChain.add(0, newCert); cert_msg.setCertificates(newChain); XMLDocument asXML = (XMLDocument) cert_msg.getDocument(MimeMediaType.XMLUTF8); JFileChooser fc = new JFileChooser(); // In response to a button click: int returnVal = fc.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { FileWriter csr_file = new FileWriter(fc.getSelectedFile()); asXML.sendToWriter(csr_file); csr_file.close(); authenticationStatus.setText("Signed certificate saved."); } else { authenticationStatus.setText("Save certificate cancelled."); } } catch (NoSuchAlgorithmException failed) { authenticationStatus.setText("Certificate signing failed:" + failed.getMessage()); } catch (NoSuchProviderException failed) { authenticationStatus.setText("Certificate signing failed:" + failed.getMessage()); } catch (InvalidKeyException failed) { authenticationStatus.setText("Certificate signing failed:" + failed.getMessage()); } catch (SignatureException failed) { authenticationStatus.setText("Certificate signing failed:" + failed.getMessage()); } catch (IOException failed) { authenticationStatus.setText("Certificate signing failed:" + failed.getMessage()); } }// GEN-LAST:event_adminSignCSRButtonActionPerformed private void memberGenerateCSRButtonActionPerformed(java.awt.event.ActionEvent evt) { // GEN-FIRST:event_memberGenerateCSRButtonActionPerformed if (null == memberCredential) { authenticationStatus.setText("Not authenticated -- cannot generate Certificate Signing Request."); return; } X509Certificate cert = memberCredential.getCertificate(); PrivateKey key = null; try { key = memberCredential.getPrivateKey(); } catch (IllegalStateException notLocal) { ; } if (null == key) { authenticationStatus.setText("Credential is not a local login credential."); return; } try { PKCS10CertificationRequest csr = new PKCS10CertificationRequest("SHA1withRSA" , new X509Principal(cert.getSubjectX500Principal().getEncoded()), cert.getPublicKey(), new DERSet(), key); net.jxta.impl.protocol.CertificateSigningRequest csr_msg = new net.jxta.impl.protocol.CertificateSigningRequest(); csr_msg.setCSR(csr); XMLDocument asXML = (XMLDocument) csr_msg.getDocument(MimeMediaType.XMLUTF8); JFileChooser fc = new JFileChooser(); // In response to a button click: int returnVal = fc.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { FileWriter csr_file = new FileWriter(fc.getSelectedFile()); asXML.sendToWriter(csr_file); csr_file.close(); authenticationStatus.setText( "Certificate Signing Request saved as file: " + fc.getSelectedFile().getCanonicalPath()); } else { authenticationStatus.setText("Certificate Signing Request not saved."); } } catch (NoSuchAlgorithmException failed) { authenticationStatus.setText("Certificate Signing Request generation failed:" + failed.getMessage()); } catch (NoSuchProviderException failed) { authenticationStatus.setText("Certificate Signing Request generation failed:" + failed.getMessage()); } catch (InvalidKeyException failed) { authenticationStatus.setText("Certificate Signing Request generation failed:" + failed.getMessage()); } catch (SignatureException failed) { authenticationStatus.setText("Certificate Signing Request generation failed:" + failed.getMessage()); } catch (IOException failed) { authenticationStatus.setText("Certificate Signing Request generation failed:" + failed.getMessage()); } }// GEN-LAST:event_memberGenerateCSRButtonActionPerformed private void memberAuthenticateButtonActionPerformed(java.awt.event.ActionEvent evt) { // GEN-FIRST:event_memberAuthenticateButtonActionPerformed if (null != memberCredential) { authenticationStatus.setText("Already authenticated."); return; } StringAuthenticator memberAuthenticator = null; try { AuthenticationCredential application = new AuthenticationCredential(group, "StringAuthentication", null); memberAuthenticator = (StringAuthenticator) membership.apply(application); } catch (ProtocolNotSupportedException noAuthenticator) { authenticationStatus.setText("Could not create authenticator: " + noAuthenticator.getMessage()); return; } memberAuthenticator.setAuth1_KeyStorePassword(keyStorePasswordField.getPassword()); memberAuthenticator.setAuth2Identity(group.getPeerID()); memberAuthenticator.setAuth3_IdentityPassword(memberPasswordField.getPassword()); // clear the password memberPasswordField.setText(""); try { memberCredential = (PSECredential) membership.join(memberAuthenticator); authenticationStatus.setText("Member authentication successful."); } catch (PeerGroupException failed) { authenticationStatus.setText("Member authentication failed: " + failed.getMessage()); return; } X509Certificate[] chain = memberCredential.getCertificateChain(); memberGenerateCSRButton.setEnabled(true); memberResignButton.setEnabled(true); if (chain.length > 1) { // If there's a certificate chain then perhaps admin and owner // be should enabled. if (chain[1].getPublicKey().equals(Main.PSE_SAMPLE_GROUP_ROOT_CERT.getPublicKey())) { // Signed by the root? That makes us an admin and maybe an owner tabs.add(adminTab); tabs.add(ownerTab); } } }// GEN-LAST:event_memberAuthenticateButtonActionPerformed private void swingUIClosed(java.awt.event.WindowEvent evt) { // GEN-FIRST:event_swingUIClosed // Shutdown the pse peer group. group.stopApp(); // group.unref(); // Un-reference the parent peer group. // parentgroup.unref(); }// GEN-LAST:event_swingUIClosed private void invitationPasswordFieldKeyReleased(java.awt.event.KeyEvent evt) { // GEN-FIRST:event_invitationPasswordFieldKeyReleased invitationAuthenticator.setAuth3_IdentityPassword(invitationPasswordField.getPassword()); invitationConfirmButton.setEnabled(invitationAuthenticator.isReadyForJoin()); }// GEN-LAST:event_invitationPasswordFieldKeyReleased private void invitationConfirmButtonActionPerformed(java.awt.event.ActionEvent evt) { // GEN-FIRST:event_invitationConfirmButtonActionPerformed boolean ownerInvite = invitationAuthenticator.getCertificate(null, group.getPeerID()).getPublicKey().equals( Main.PSE_SAMPLE_GROUP_ROOT_CERT.getPublicKey()); invitationAuthenticator.setAuth1_KeyStorePassword(keyStorePasswordField.getPassword()); if (ownerInvite) { // If the invitation is for the owner identity then store it under the peer group id. invitationAuthenticator.setAuth2Identity(group.getPeerGroupID()); } else { // Otherwise store it under another random key. invitationAuthenticator.setAuth2Identity(IDFactory.newCodatID(group.getPeerGroupID())); } invitationAuthenticator.setAuth3_IdentityPassword(invitationPasswordField.getPassword()); // clear the password invitationPasswordField.setText(""); try { invitationCredential = (PSECredential) membership.join(invitationAuthenticator); tabs.remove(invitationTab); tabs.add(memberTab); if (ownerInvite) { tabs.add(ownerTab); } authenticationStatus.setText("Invitation confirmed."); } catch (PeerGroupException failed) { authenticationStatus.setText("Invitation confirmation failed: " + failed.getMessage()); } }// GEN-LAST:event_invitationConfirmButtonActionPerformed private void invitationPasswordFieldActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_invitationPasswordFieldActionPerformed // TODO add your handling code here: }// GEN-LAST:event_invitationPasswordFieldActionPerformed private void keyStorePasswordFieldActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_keyStorePasswordFieldActionPerformed // TODO add your handling code here: }// GEN-LAST:event_keyStorePasswordFieldActionPerformed private void generateMemberCertButtonActionPerformed(java.awt.event.ActionEvent evt) { // GEN-FIRST:event_generateMemberCertButtonActionPerformed try { X509Certificate checkCert = membership.getPSEConfig().getTrustedCertificate(group.getPeerID()); if (null != checkCert) { authenticationStatus.setText("Member certificate already present."); } PSEUtils.IssuerInfo issuer = null; if (null != invitationCredential) { issuer = new PSEUtils.IssuerInfo(); issuer.cert = invitationCredential.getCertificate(); issuer.subjectPkey = invitationCredential.getPrivateKey(); } PSEUtils.IssuerInfo certs = PSEUtils.genCert(group.getPeerName(), issuer); X509Certificate chain[]; if (null != issuer) { chain = new X509Certificate[] { certs.cert, certs.issuer}; } else { chain = new X509Certificate[] { certs.cert}; } if (null == membership.getDefaultCredential()) { // if the keychain hasn't been unlocked then set the keystore password. membership.getPSEConfig().setKeyStorePassword(keyStorePasswordField.getPassword()); } // Save our new certificate into the keystore. membership.getPSEConfig().setKey(group.getPeerID(), chain, certs.subjectPkey, memberPasswordField.getPassword()); authenticationStatus.setText("New member certificate generated."); memberAuthenticateButton.setEnabled(true); } catch (KeyStoreException failed) { authenticationStatus.setText("Certificate generation failed: " + failed.getMessage()); } catch (IOException failed) { authenticationStatus.setText("Certificate generation failed: " + failed.getMessage()); } }// GEN-LAST:event_generateMemberCertButtonActionPerformed private void authenticationStatusActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_authenticationStatusActionPerformed // TODO add your handling code here: }// GEN-LAST:event_authenticationStatusActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPasswordField adminInvitationPasswordField; private javax.swing.JLabel adminInvitationPasswordLabel; private javax.swing.JButton adminInviteButton; private javax.swing.JButton adminSignCSRButton; private javax.swing.JPanel adminTab; private javax.swing.JTextField authenticationStatus; private javax.swing.JButton generateMemberCertButton; private javax.swing.JButton invitationConfirmButton; private javax.swing.JPasswordField invitationPasswordField; private javax.swing.JPanel invitationTab; private javax.swing.JPasswordField keyStorePasswordField; private javax.swing.JLabel keyStorePasswordLabel; private javax.swing.JButton memberAuthenticateButton; private javax.swing.JButton memberGenerateCSRButton; private javax.swing.JButton memberImportCertButton; private javax.swing.JPasswordField memberPasswordField; private javax.swing.JButton memberResignButton; private javax.swing.JPanel memberTab; private javax.swing.JButton ownerAuthenticateButton; private javax.swing.JPasswordField ownerPasswordField; private javax.swing.JLabel ownerPasswordLabel; private javax.swing.JButton ownerResignButton; private javax.swing.JButton ownerSignCSRButton; private javax.swing.JPanel ownerTab; private javax.swing.JTabbedPane tabs; // End of variables declaration//GEN-END:variables }
package org.apache.velocity.runtime.parser.node; /* * 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. */ import java.lang.reflect.InvocationTargetException; import org.apache.commons.lang3.StringUtils; import org.apache.velocity.app.event.EventHandlerUtil; import org.apache.velocity.context.InternalContextAdapter; import org.apache.velocity.exception.MethodInvocationException; import org.apache.velocity.exception.TemplateInitException; import org.apache.velocity.exception.VelocityException; import org.apache.velocity.runtime.RuntimeConstants; import org.apache.velocity.runtime.directive.StopCommand; import org.apache.velocity.runtime.parser.Parser; import org.apache.velocity.util.ClassUtils; import org.apache.velocity.util.introspection.Info; import org.apache.velocity.util.introspection.VelMethod; /** * ASTMethod.java * * Method support for references : $foo.method() * * NOTE : * * introspection is now done at render time. * * Please look at the Parser.jjt file which is * what controls the generation of this class. * * @author <a href="mailto:[email protected]">Jason van Zyl</a> * @author <a href="mailto:[email protected]">Geir Magnusson Jr.</a> * @version $Id: ASTMethod.java 1043077 2010-12-07 15:01:25Z apetrelli $ */ public class ASTMethod extends SimpleNode { /** * An empty immutable <code>Class</code> array. */ private static final Class<?>[] EMPTY_CLASS_ARRAY = new Class<?>[0]; private String methodName = ""; private int paramCount = 0; protected Info uberInfo; /** * Indicates if we are running in strict reference mode. */ protected boolean strictRef = false; /** * @param id */ public ASTMethod(int id) { super(id); } /** * @param p * @param id */ public ASTMethod(Parser p, int id) { super(p, id); } /** * @see org.apache.velocity.runtime.parser.node.SimpleNode#jjtAccept(org.apache.velocity.runtime.parser.node.ParserVisitor, java.lang.Object) */ public Object jjtAccept(ParserVisitor visitor, Object data) { return visitor.visit(this, data); } /** * simple init - init our subtree and get what we can from * the AST * @param context * @param data * @return The init result * @throws TemplateInitException */ public Object init( InternalContextAdapter context, Object data) throws TemplateInitException { super.init( context, data ); /* * make an uberinfo - saves new's later on */ uberInfo = new Info(getTemplateName(), getLine(),getColumn()); /* * this is about all we can do */ methodName = getFirstToken().image; paramCount = jjtGetNumChildren() - 1; strictRef = rsvc.getBoolean(RuntimeConstants.RUNTIME_REFERENCES_STRICT, false); return data; } /** * invokes the method. Returns null if a problem, the * actual return if the method returns something, or * an empty string "" if the method returns void * @param o * @param context * @return Result or null. * @throws MethodInvocationException */ public Object execute(Object o, InternalContextAdapter context) throws MethodInvocationException { /* * new strategy (strategery!) for introspection. Since we want * to be thread- as well as context-safe, we *must* do it now, * at execution time. There can be no in-node caching, * but if we are careful, we can do it in the context. */ Object [] params = new Object[paramCount]; /* * sadly, we do need recalc the values of the args, as this can * change from visit to visit */ final Class[] paramClasses = paramCount > 0 ? new Class[paramCount] : EMPTY_CLASS_ARRAY; for (int j = 0; j < paramCount; j++) { params[j] = jjtGetChild(j + 1).value(context); if (params[j] != null) { paramClasses[j] = params[j].getClass(); } } VelMethod method = ClassUtils.getMethod(methodName, params, paramClasses, o, context, this, strictRef); if (method == null) return null; try { /* * get the returned object. It may be null, and that is * valid for something declared with a void return type. * Since the caller is expecting something to be returned, * as long as things are peachy, we can return an empty * String so ASTReference() correctly figures out that * all is well. */ Object obj = method.invoke(o, params); if (obj == null) { if( method.getReturnType() == Void.TYPE) { return ""; } } return obj; } catch( InvocationTargetException ite ) { return handleInvocationException(o, context, ite.getTargetException()); } /** Can also be thrown by method invocation **/ catch( IllegalArgumentException t ) { return handleInvocationException(o, context, t); } /** * pass through application level runtime exceptions */ catch( RuntimeException e ) { throw e; } catch( Exception e ) { String msg = "ASTMethod.execute() : exception invoking method '" + methodName + "' in " + o.getClass(); log.error(msg, e); throw new VelocityException(msg, e); } } private Object handleInvocationException(Object o, InternalContextAdapter context, Throwable t) { /* * We let StopCommands go up to the directive they are for/from */ if (t instanceof StopCommand) { throw (StopCommand)t; } /* * In the event that the invocation of the method * itself throws an exception, we want to catch that * wrap it, and throw. We don't log here as we want to figure * out which reference threw the exception, so do that * above */ else if (t instanceof Exception) { try { return EventHandlerUtil.methodException( rsvc, context, o.getClass(), methodName, (Exception) t ); } /** * If the event handler throws an exception, then wrap it * in a MethodInvocationException. Don't pass through RuntimeExceptions like other * similar catchall code blocks. */ catch( Exception e ) { throw new MethodInvocationException( "Invocation of method '" + methodName + "' in " + o.getClass() + " threw exception " + e.toString(), e, methodName, getTemplateName(), this.getLine(), this.getColumn()); } } /* * let non-Exception Throwables go... */ else { /* * no event cartridge to override. Just throw */ throw new MethodInvocationException( "Invocation of method '" + methodName + "' in " + o.getClass() + " threw exception " + t.toString(), t, methodName, getTemplateName(), this.getLine(), this.getColumn()); } } /** * Internal class used as key for method cache. Combines * ASTMethod fields with array of parameter classes. Has * public access (and complete constructor) for unit test * purposes. * @since 1.5 */ public static class MethodCacheKey { private final String methodName; private final Class[] params; public MethodCacheKey(String methodName, Class[] params) { /** * Should never be initialized with nulls, but to be safe we refuse * to accept them. */ this.methodName = (methodName != null) ? methodName : StringUtils.EMPTY; this.params = (params != null) ? params : EMPTY_CLASS_ARRAY; } /** * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object o) { /** * note we skip the null test for methodName and params * due to the earlier test in the constructor */ if (o instanceof MethodCacheKey) { final MethodCacheKey other = (MethodCacheKey) o; if (params.length == other.params.length && methodName.equals(other.methodName)) { for (int i = 0; i < params.length; ++i) { if (params[i] == null) { if (params[i] != other.params[i]) { return false; } } else if (!params[i].equals(other.params[i])) { return false; } } return true; } } return false; } /** * @see java.lang.Object#hashCode() */ public int hashCode() { int result = 17; /** * note we skip the null test for methodName and params * due to the earlier test in the constructor */ for (int i = 0; i < params.length; ++i) { final Class param = params[i]; if (param != null) { result = result * 37 + param.hashCode(); } } result = result * 37 + methodName.hashCode(); return result; } } /** * @return Returns the methodName. * @since 1.5 */ public String getMethodName() { return methodName; } }
/* * Copyright (c) 2012 Google 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.google.api.client.http; import com.google.api.client.util.Preconditions; import java.nio.charset.Charset; import java.util.Collections; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.SortedMap; import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * HTTP Media-type as specified in the HTTP RFC ( {@link * "http://tools.ietf.org/html/rfc2616#section-3.7"}). * * <p>Implementation is not thread-safe. * * @author Matthias Linder (mlinder) * @since 1.10 */ public final class HttpMediaType { /** Matches a valid media type or '*' (examples: "text" or "*"). */ private static final Pattern TYPE_REGEX; /** Matches a valid token which might be used as a type, key parameter or key value. */ private static final Pattern TOKEN_REGEX; /** The pattern matching the full HTTP media type string. */ private static final Pattern FULL_MEDIA_TYPE_REGEX; /** The pattern matching a single parameter (key, value) at a time. */ private static final Pattern PARAMETER_REGEX; /** The main type of the media type, for example {@code "text"}. */ private String type = "application"; /** The sub type of the media type, for example {@code "plain"}. */ private String subType = "octet-stream"; /** Additional parameters to the media type, for example {@code "charset=utf-8"}. */ private final SortedMap<String, String> parameters = new TreeMap<String, String>(); /** The last build result or {@code null}. */ private String cachedBuildResult; /** Initialize all Patterns used for parsing. */ static { // TYPE_REGEX: Very restrictive regex accepting valid types and '*' for e.g. "text/*". // http://tools.ietf.org/html/rfc4288#section-4.2 TYPE_REGEX = Pattern.compile("[\\w!#$&.+\\-\\^_]+|[*]"); // TOKEN_REGEX: Restrictive (but less than TYPE_REGEX) regex accepting valid tokens. // http://tools.ietf.org/html/rfc2045#section-5.1 TOKEN_REGEX = Pattern.compile("[\\p{ASCII}&&[^\\p{Cntrl} ;/=\\[\\]\\(\\)\\<\\>\\@\\,\\:\\\"\\?\\=]]+"); // FULL_MEDIA_TYPE_REGEX: Unrestrictive regex matching the general structure of the media type. // Used to split a Content-Type string into different parts. Unrestrictive so that invalid char // detection can be done on a per-type/parameter basis. String typeOrKey = "[^\\s/=;\"]+"; // only disallow separators String wholeParameterSection = ";.*"; FULL_MEDIA_TYPE_REGEX = Pattern.compile( "\\s*(" + typeOrKey + ")/(" + typeOrKey + ")" + // main type (G1)/sub type (G2) "\\s*(" + wholeParameterSection + ")?", Pattern.DOTALL); // parameters (G3) or null // PARAMETER_REGEX: Semi-restrictive regex matching each parameter in the parameter section. // We also allow multipart values here (http://www.w3.org/Protocols/rfc1341/7_2_Multipart.html) // although those do not fully conform to the HTTP spec. String quotedParameterValue = "\"([^\"]*)\""; String unquotedParameterValue = "[^\\s;\"]*"; String parameterValue = quotedParameterValue + "|" + unquotedParameterValue; PARAMETER_REGEX = Pattern.compile( "\\s*;\\s*(" + typeOrKey + ")" + // parameter key (G1) "=(" + parameterValue + ")"); // G2 (if quoted) and else G3 } /** * Initializes the {@link HttpMediaType} by setting the specified media type. * * @param type main media type, for example {@code "text"} * @param subType sub media type, for example {@code "plain"} */ public HttpMediaType(String type, String subType) { setType(type); setSubType(subType); } /** * Creates a {@link HttpMediaType} by parsing the specified media type string. * * @param mediaType full media type string, for example {@code "text/plain; charset=utf-8"} */ public HttpMediaType(String mediaType) { fromString(mediaType); } /** * Sets the (main) media type, for example {@code "text"}. * * @param type main/major media type */ public HttpMediaType setType(String type) { Preconditions.checkArgument( TYPE_REGEX.matcher(type).matches(), "Type contains reserved characters"); this.type = type; cachedBuildResult = null; return this; } /** Returns the main media type, for example {@code "text"}, or {@code null} for '*'. */ public String getType() { return type; } /** * Sets the sub media type, for example {@code "plain"} when using {@code "text"}. * * @param subType sub media type */ public HttpMediaType setSubType(String subType) { Preconditions.checkArgument( TYPE_REGEX.matcher(subType).matches(), "Subtype contains reserved characters"); this.subType = subType; cachedBuildResult = null; return this; } /** Returns the sub media type, for example {@code "plain"} when using {@code "text"}. */ public String getSubType() { return subType; } /** * Sets the full media type by parsing a full content-type string, for example {@code "text/plain; * foo=bar"}. * * <p>This method will not clear existing parameters. Use {@link #clearParameters()} if this * behavior is required. * * @param combinedType full media type in the {@code "maintype/subtype; key=value"} format. */ private HttpMediaType fromString(String combinedType) { Matcher matcher = FULL_MEDIA_TYPE_REGEX.matcher(combinedType); Preconditions.checkArgument( matcher.matches(), "Type must be in the 'maintype/subtype; parameter=value' format"); setType(matcher.group(1)); setSubType(matcher.group(2)); String params = matcher.group(3); if (params != null) { matcher = PARAMETER_REGEX.matcher(params); while (matcher.find()) { // 1=key, 2=valueWithQuotes, 3=valueWithoutQuotes String key = matcher.group(1); String value = matcher.group(3); if (value == null) { value = matcher.group(2); } setParameter(key, value); } } return this; } /** * Sets the media parameter to the specified value. * * @param name case-insensitive name of the parameter * @param value value of the parameter or {@code null} to remove */ public HttpMediaType setParameter(String name, String value) { if (value == null) { removeParameter(name); return this; } Preconditions.checkArgument( TOKEN_REGEX.matcher(name).matches(), "Name contains reserved characters"); cachedBuildResult = null; parameters.put(name.toLowerCase(Locale.US), value); return this; } /** * Returns the value of the specified parameter or {@code null} if not found. * * @param name name of the parameter */ public String getParameter(String name) { return parameters.get(name.toLowerCase(Locale.US)); } /** * Removes the specified media parameter. * * @param name parameter to remove */ public HttpMediaType removeParameter(String name) { cachedBuildResult = null; parameters.remove(name.toLowerCase(Locale.US)); return this; } /** Removes all set parameters from this media type. */ public void clearParameters() { cachedBuildResult = null; parameters.clear(); } /** * Returns an unmodifiable map of all specified parameters. Parameter names will be stored in * lower-case in this map. */ public Map<String, String> getParameters() { return Collections.unmodifiableMap(parameters); } /** * Returns whether the given value matches the regular expression for "token" as specified in <a * href="http://tools.ietf.org/html/rfc2616#section-2.2">RFC 2616 section 2.2</a>. */ static boolean matchesToken(String value) { return TOKEN_REGEX.matcher(value).matches(); } private static String quoteString(String unquotedString) { String escapedString = unquotedString.replace("\\", "\\\\"); // change \ to \\ escapedString = escapedString.replace("\"", "\\\""); // change " to \" return "\"" + escapedString + "\""; } /** Builds the full media type string which can be passed in the Content-Type header. */ public String build() { if (cachedBuildResult != null) { return cachedBuildResult; } StringBuilder str = new StringBuilder(); str.append(type); str.append('/'); str.append(subType); if (parameters != null) { for (Entry<String, String> entry : parameters.entrySet()) { String value = entry.getValue(); str.append("; "); str.append(entry.getKey()); str.append("="); str.append(!matchesToken(value) ? quoteString(value) : value); } } cachedBuildResult = str.toString(); return cachedBuildResult; } @Override public String toString() { return build(); } /** * Returns {@code true} if the specified media type has both the same type and subtype, or {@code * false} if they don't match or the media type is {@code null}. */ public boolean equalsIgnoreParameters(HttpMediaType mediaType) { return mediaType != null && getType().equalsIgnoreCase(mediaType.getType()) && getSubType().equalsIgnoreCase(mediaType.getSubType()); } /** * Returns {@code true} if the two specified media types have the same type and subtype, or if * both types are {@code null}. */ public static boolean equalsIgnoreParameters(String mediaTypeA, String mediaTypeB) { // TODO(mlinder): Make the HttpMediaType.isSameType implementation more performant. return (mediaTypeA == null && mediaTypeB == null) || mediaTypeA != null && mediaTypeB != null && new HttpMediaType(mediaTypeA).equalsIgnoreParameters(new HttpMediaType(mediaTypeB)); } /** * Sets the charset parameter of the media type. * * @param charset new value for the charset parameter or {@code null} to remove */ public HttpMediaType setCharsetParameter(Charset charset) { setParameter("charset", charset == null ? null : charset.name()); return this; } /** Returns the specified charset or {@code null} if unset. */ public Charset getCharsetParameter() { String value = getParameter("charset"); return value == null ? null : Charset.forName(value); } @Override public int hashCode() { return build().hashCode(); } @Override public boolean equals(Object obj) { if (!(obj instanceof HttpMediaType)) { return false; } HttpMediaType otherType = (HttpMediaType) obj; return equalsIgnoreParameters(otherType) && parameters.equals(otherType.parameters); } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.mapred; import java.io.DataOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Random; import java.util.zip.CRC32; import java.util.zip.CheckedOutputStream; import org.apache.hadoop.fs.ChecksumException; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.mapreduce.server.tasktracker.TTConfig; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class TestIndexCache { private JobConf conf; private FileSystem fs; private Path p; @Before public void setUp() throws IOException { conf = new JobConf(); fs = FileSystem.getLocal(conf).getRaw(); p = new Path(System.getProperty("test.build.data", "/tmp"), "cache").makeQualified(fs.getUri(), fs.getWorkingDirectory()); } @Test public void testLRCPolicy() throws Exception { Random r = new Random(); long seed = r.nextLong(); r.setSeed(seed); System.out.println("seed: " + seed); fs.delete(p, true); conf.setInt(TTConfig.TT_INDEX_CACHE, 1); final int partsPerMap = 1000; final int bytesPerFile = partsPerMap * 24; IndexCache cache = new IndexCache(conf); // fill cache int totalsize = bytesPerFile; for (; totalsize < 1024 * 1024; totalsize += bytesPerFile) { Path f = new Path(p, Integer.toString(totalsize, 36)); writeFile(fs, f, totalsize, partsPerMap); IndexRecord rec = cache.getIndexInformation( Integer.toString(totalsize, 36), r.nextInt(partsPerMap), f, UserGroupInformation.getCurrentUser().getShortUserName()); checkRecord(rec, totalsize); } // delete files, ensure cache retains all elem for (FileStatus stat : fs.listStatus(p)) { fs.delete(stat.getPath(),true); } for (int i = bytesPerFile; i < 1024 * 1024; i += bytesPerFile) { Path f = new Path(p, Integer.toString(i, 36)); IndexRecord rec = cache.getIndexInformation(Integer.toString(i, 36), r.nextInt(partsPerMap), f, UserGroupInformation.getCurrentUser().getShortUserName()); checkRecord(rec, i); } // push oldest (bytesPerFile) out of cache Path f = new Path(p, Integer.toString(totalsize, 36)); writeFile(fs, f, totalsize, partsPerMap); cache.getIndexInformation(Integer.toString(totalsize, 36), r.nextInt(partsPerMap), f, UserGroupInformation.getCurrentUser().getShortUserName()); fs.delete(f, false); // oldest fails to read, or error boolean fnf = false; try { cache.getIndexInformation(Integer.toString(bytesPerFile, 36), r.nextInt(partsPerMap), new Path(p, Integer.toString(bytesPerFile)), UserGroupInformation.getCurrentUser().getShortUserName()); } catch (IOException e) { if (e.getCause() == null || !(e.getCause() instanceof FileNotFoundException)) { throw e; } else { fnf = true; } } if (!fnf) fail("Failed to push out last entry"); // should find all the other entries for (int i = bytesPerFile << 1; i < 1024 * 1024; i += bytesPerFile) { IndexRecord rec = cache.getIndexInformation(Integer.toString(i, 36), r.nextInt(partsPerMap), new Path(p, Integer.toString(i, 36)), UserGroupInformation.getCurrentUser().getShortUserName()); checkRecord(rec, i); } IndexRecord rec = cache.getIndexInformation(Integer.toString(totalsize, 36), r.nextInt(partsPerMap), f, UserGroupInformation.getCurrentUser().getShortUserName()); checkRecord(rec, totalsize); } @Test public void testBadIndex() throws Exception { final int parts = 30; fs.delete(p, true); conf.setInt(TTConfig.TT_INDEX_CACHE, 1); IndexCache cache = new IndexCache(conf); Path f = new Path(p, "badindex"); FSDataOutputStream out = fs.create(f, false); CheckedOutputStream iout = new CheckedOutputStream(out, new CRC32()); DataOutputStream dout = new DataOutputStream(iout); for (int i = 0; i < parts; ++i) { for (int j = 0; j < MapTask.MAP_OUTPUT_INDEX_RECORD_LENGTH / 8; ++j) { if (0 == (i % 3)) { dout.writeLong(i); } else { out.writeLong(i); } } } out.writeLong(iout.getChecksum().getValue()); dout.close(); try { cache.getIndexInformation("badindex", 7, f, UserGroupInformation.getCurrentUser().getShortUserName()); fail("Did not detect bad checksum"); } catch (IOException e) { if (!(e.getCause() instanceof ChecksumException)) { throw e; } } } @Test public void testInvalidReduceNumberOrLength() throws Exception { fs.delete(p, true); conf.setInt(TTConfig.TT_INDEX_CACHE, 1); final int partsPerMap = 1000; final int bytesPerFile = partsPerMap * 24; IndexCache cache = new IndexCache(conf); // fill cache Path feq = new Path(p, "invalidReduceOrPartsPerMap"); writeFile(fs, feq, bytesPerFile, partsPerMap); // Number of reducers should always be less than partsPerMap as reducer // numbers start from 0 and there cannot be more reducer than parts try { // Number of reducers equal to partsPerMap cache.getIndexInformation("reduceEqualPartsPerMap", partsPerMap, // reduce number == partsPerMap feq, UserGroupInformation.getCurrentUser().getShortUserName()); fail("Number of reducers equal to partsPerMap did not fail"); } catch (Exception e) { if (!(e instanceof IOException)) { throw e; } } try { // Number of reducers more than partsPerMap cache.getIndexInformation( "reduceMorePartsPerMap", partsPerMap + 1, // reduce number > partsPerMap feq, UserGroupInformation.getCurrentUser().getShortUserName()); fail("Number of reducers more than partsPerMap did not fail"); } catch (Exception e) { if (!(e instanceof IOException)) { throw e; } } } @Test public void testRemoveMap() throws Exception { // This test case use two thread to call getIndexInformation and // removeMap concurrently, in order to construct race condition. // This test case may not repeatable. But on my macbook this test // fails with probability of 100% on code before MAPREDUCE-2541, // so it is repeatable in practice. fs.delete(p, true); conf.setInt(TTConfig.TT_INDEX_CACHE, 10); // Make a big file so removeMapThread almost surely runs faster than // getInfoThread final int partsPerMap = 100000; final int bytesPerFile = partsPerMap * 24; final IndexCache cache = new IndexCache(conf); final Path big = new Path(p, "bigIndex"); final String user = UserGroupInformation.getCurrentUser().getShortUserName(); writeFile(fs, big, bytesPerFile, partsPerMap); // run multiple times for (int i = 0; i < 20; ++i) { Thread getInfoThread = new Thread() { @Override public void run() { try { cache.getIndexInformation("bigIndex", partsPerMap, big, user); } catch (Exception e) { // should not be here } } }; Thread removeMapThread = new Thread() { @Override public void run() { cache.removeMap("bigIndex"); } }; if (i%2==0) { getInfoThread.start(); removeMapThread.start(); } else { removeMapThread.start(); getInfoThread.start(); } getInfoThread.join(); removeMapThread.join(); assertEquals(true, cache.checkTotalMemoryUsed()); } } @Test public void testCreateRace() throws Exception { fs.delete(p, true); conf.setInt(TTConfig.TT_INDEX_CACHE, 1); final int partsPerMap = 1000; final int bytesPerFile = partsPerMap * 24; final IndexCache cache = new IndexCache(conf); final Path racy = new Path(p, "racyIndex"); final String user = UserGroupInformation.getCurrentUser().getShortUserName(); writeFile(fs, racy, bytesPerFile, partsPerMap); // run multiple instances Thread[] getInfoThreads = new Thread[50]; for (int i = 0; i < 50; i++) { getInfoThreads[i] = new Thread() { @Override public void run() { try { cache.getIndexInformation("racyIndex", partsPerMap, racy, user); cache.removeMap("racyIndex"); } catch (Exception e) { // should not be here } } }; } for (int i = 0; i < 50; i++) { getInfoThreads[i].start(); } final Thread mainTestThread = Thread.currentThread(); Thread timeoutThread = new Thread() { @Override public void run() { try { Thread.sleep(15000); mainTestThread.interrupt(); } catch (InterruptedException ie) { // we are done; } } }; for (int i = 0; i < 50; i++) { try { getInfoThreads[i].join(); } catch (InterruptedException ie) { // we haven't finished in time. Potential deadlock/race. fail("Unexpectedly long delay during concurrent cache entry creations"); } } // stop the timeoutThread. If we get interrupted before stopping, there // must be something wrong, although it wasn't a deadlock. No need to // catch and swallow. timeoutThread.interrupt(); } private static void checkRecord(IndexRecord rec, long fill) { assertEquals(fill, rec.startOffset); assertEquals(fill, rec.rawLength); assertEquals(fill, rec.partLength); } private static void writeFile(FileSystem fs, Path f, long fill, int parts) throws IOException { FSDataOutputStream out = fs.create(f, false); CheckedOutputStream iout = new CheckedOutputStream(out, new CRC32()); DataOutputStream dout = new DataOutputStream(iout); for (int i = 0; i < parts; ++i) { for (int j = 0; j < MapTask.MAP_OUTPUT_INDEX_RECORD_LENGTH / 8; ++j) { dout.writeLong(fill); } } out.writeLong(iout.getChecksum().getValue()); dout.close(); } }
/* ==================================================================== 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.poifs.storage; import static org.junit.Assert.assertEquals; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.poi.poifs.common.POIFSConstants; import org.apache.poi.poifs.property.Property; import org.junit.Test; /** * Class to test PropertyBlock functionality */ public final class TestPropertyBlock { @Test public void testCreatePropertyBlocks() throws Exception { // test with 0 properties List<Property> properties = new ArrayList<Property>(); BlockWritable[] blocks = PropertyBlock.createPropertyBlockArray(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS,properties); assertEquals(0, blocks.length); // test with 1 property properties.add(new LocalProperty("Root Entry")); blocks = PropertyBlock.createPropertyBlockArray(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS,properties); assertEquals(1, blocks.length); byte[] testblock = new byte[ 512 ]; for (int j = 0; j < 4; j++) { setDefaultBlock(testblock, j); } testblock[ 0x0000 ] = ( byte ) 'R'; testblock[ 0x0002 ] = ( byte ) 'o'; testblock[ 0x0004 ] = ( byte ) 'o'; testblock[ 0x0006 ] = ( byte ) 't'; testblock[ 0x0008 ] = ( byte ) ' '; testblock[ 0x000A ] = ( byte ) 'E'; testblock[ 0x000C ] = ( byte ) 'n'; testblock[ 0x000E ] = ( byte ) 't'; testblock[ 0x0010 ] = ( byte ) 'r'; testblock[ 0x0012 ] = ( byte ) 'y'; testblock[ 0x0040 ] = ( byte ) 22; verifyCorrect(blocks, testblock); // test with 3 properties properties.add(new LocalProperty("workbook")); properties.add(new LocalProperty("summary")); blocks = PropertyBlock.createPropertyBlockArray(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS,properties); assertEquals(1, blocks.length); testblock[ 0x0080 ] = ( byte ) 'w'; testblock[ 0x0082 ] = ( byte ) 'o'; testblock[ 0x0084 ] = ( byte ) 'r'; testblock[ 0x0086 ] = ( byte ) 'k'; testblock[ 0x0088 ] = ( byte ) 'b'; testblock[ 0x008A ] = ( byte ) 'o'; testblock[ 0x008C ] = ( byte ) 'o'; testblock[ 0x008E ] = ( byte ) 'k'; testblock[ 0x00C0 ] = ( byte ) 18; testblock[ 0x0100 ] = ( byte ) 's'; testblock[ 0x0102 ] = ( byte ) 'u'; testblock[ 0x0104 ] = ( byte ) 'm'; testblock[ 0x0106 ] = ( byte ) 'm'; testblock[ 0x0108 ] = ( byte ) 'a'; testblock[ 0x010A ] = ( byte ) 'r'; testblock[ 0x010C ] = ( byte ) 'y'; testblock[ 0x0140 ] = ( byte ) 16; verifyCorrect(blocks, testblock); // test with 4 properties properties.add(new LocalProperty("wintery")); blocks = PropertyBlock.createPropertyBlockArray(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS,properties); assertEquals(1, blocks.length); testblock[ 0x0180 ] = ( byte ) 'w'; testblock[ 0x0182 ] = ( byte ) 'i'; testblock[ 0x0184 ] = ( byte ) 'n'; testblock[ 0x0186 ] = ( byte ) 't'; testblock[ 0x0188 ] = ( byte ) 'e'; testblock[ 0x018A ] = ( byte ) 'r'; testblock[ 0x018C ] = ( byte ) 'y'; testblock[ 0x01C0 ] = ( byte ) 16; verifyCorrect(blocks, testblock); // test with 5 properties properties.add(new LocalProperty("foo")); blocks = PropertyBlock.createPropertyBlockArray(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS,properties); assertEquals(2, blocks.length); testblock = new byte[ 1024 ]; for (int j = 0; j < 8; j++) { setDefaultBlock(testblock, j); } testblock[ 0x0000 ] = ( byte ) 'R'; testblock[ 0x0002 ] = ( byte ) 'o'; testblock[ 0x0004 ] = ( byte ) 'o'; testblock[ 0x0006 ] = ( byte ) 't'; testblock[ 0x0008 ] = ( byte ) ' '; testblock[ 0x000A ] = ( byte ) 'E'; testblock[ 0x000C ] = ( byte ) 'n'; testblock[ 0x000E ] = ( byte ) 't'; testblock[ 0x0010 ] = ( byte ) 'r'; testblock[ 0x0012 ] = ( byte ) 'y'; testblock[ 0x0040 ] = ( byte ) 22; testblock[ 0x0080 ] = ( byte ) 'w'; testblock[ 0x0082 ] = ( byte ) 'o'; testblock[ 0x0084 ] = ( byte ) 'r'; testblock[ 0x0086 ] = ( byte ) 'k'; testblock[ 0x0088 ] = ( byte ) 'b'; testblock[ 0x008A ] = ( byte ) 'o'; testblock[ 0x008C ] = ( byte ) 'o'; testblock[ 0x008E ] = ( byte ) 'k'; testblock[ 0x00C0 ] = ( byte ) 18; testblock[ 0x0100 ] = ( byte ) 's'; testblock[ 0x0102 ] = ( byte ) 'u'; testblock[ 0x0104 ] = ( byte ) 'm'; testblock[ 0x0106 ] = ( byte ) 'm'; testblock[ 0x0108 ] = ( byte ) 'a'; testblock[ 0x010A ] = ( byte ) 'r'; testblock[ 0x010C ] = ( byte ) 'y'; testblock[ 0x0140 ] = ( byte ) 16; testblock[ 0x0180 ] = ( byte ) 'w'; testblock[ 0x0182 ] = ( byte ) 'i'; testblock[ 0x0184 ] = ( byte ) 'n'; testblock[ 0x0186 ] = ( byte ) 't'; testblock[ 0x0188 ] = ( byte ) 'e'; testblock[ 0x018A ] = ( byte ) 'r'; testblock[ 0x018C ] = ( byte ) 'y'; testblock[ 0x01C0 ] = ( byte ) 16; testblock[ 0x0200 ] = ( byte ) 'f'; testblock[ 0x0202 ] = ( byte ) 'o'; testblock[ 0x0204 ] = ( byte ) 'o'; testblock[ 0x0240 ] = ( byte ) 8; verifyCorrect(blocks, testblock); } private static void setDefaultBlock(byte [] testblock, int j) { int base = j * 128; int index = 0; for (; index < 0x40; index++) { testblock[ base++ ] = ( byte ) 0; } testblock[ base++ ] = ( byte ) 2; testblock[ base++ ] = ( byte ) 0; index += 2; for (; index < 0x44; index++) { testblock[ base++ ] = ( byte ) 0; } for (; index < 0x50; index++) { testblock[ base++ ] = ( byte ) 0xff; } for (; index < 0x80; index++) { testblock[ base++ ] = ( byte ) 0; } } private static void verifyCorrect(BlockWritable[] blocks, byte[] testblock) throws IOException { ByteArrayOutputStream stream = new ByteArrayOutputStream(512 * blocks.length); for (BlockWritable b : blocks) { b.writeBlocks(stream); } byte[] output = stream.toByteArray(); assertEquals(testblock.length, output.length); for (int j = 0; j < testblock.length; j++) { assertEquals("mismatch at offset " + j, testblock[ j ], output[ j ]); } } }