index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src
Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/AiNode.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team 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 the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. 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 jassimp; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * A node in the imported hierarchy.<p> * * Each node has name, a parent node (except for the root node), * a transformation relative to its parent and possibly several child nodes. * Simple file formats don't support hierarchical structures - for these formats * the imported scene consists of only a single root node without children. */ public final class AiNode { /** * Parent node. */ private final AiNode m_parent; /** * Mesh references. */ private final int[] m_meshReferences; /** * List of children. */ private final List<AiNode> m_children = new ArrayList<AiNode>(); /** * List of metadata entries. */ private final Map<String, AiMetadataEntry> m_metaData = new HashMap<String, AiMetadataEntry>(); /** * Buffer for transformation matrix. */ private final Object m_transformationMatrix; /** * Constructor. * * @param parent the parent node, may be null * @param transform the transform matrix * @param meshReferences array of mesh references * @param name the name of the node */ AiNode(AiNode parent, Object transform, int[] meshReferences, String name) { m_parent = parent; m_transformationMatrix = transform; m_meshReferences = meshReferences; m_name = name; if (null != m_parent) { m_parent.addChild(this); } } /** * Returns the name of this node. * * @return the name */ public String getName() { return m_name; } /** * Returns the number of child nodes.<p> * * This method exists for compatibility reasons with the native assimp API. * The returned value is identical to <code>getChildren().size()</code> * * @return the number of child nodes */ public int getNumChildren() { return getChildren().size(); } /** * Returns a 4x4 matrix that specifies the transformation relative to * the parent node.<p> * * This method is part of the wrapped API (see {@link AiWrapperProvider} * for details on wrappers).<p> * * The built in behavior is to return an {@link AiMatrix4f}. * * @param wrapperProvider the wrapper provider (used for type inference) * * @return a matrix */ @SuppressWarnings("unchecked") public <V3, M4, C, N, Q> M4 getTransform(AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) { return (M4) m_transformationMatrix; } /** * Returns the children of this node. * * @return the children, or an empty list if the node has no children */ public List<AiNode> getChildren() { return m_children; } /** * Returns the parent node. * * @return the parent, or null of the node has no parent */ public AiNode getParent() { return m_parent; } /** * Searches the node hierarchy below (and including) this node for a node * with the specified name. * * @param name the name to look for * @return the first node with the given name, or null if no such node * exists */ public AiNode findNode(String name) { /* classic recursive depth first search */ if (m_name.equals(name)) { return this; } for (AiNode child : m_children) { if (null != child.findNode(name)) { return child; } } return null; } /** * Returns the number of meshes references by this node.<p> * * This method exists for compatibility with the native assimp API. * The returned value is identical to <code>getMeshes().length</code> * * @return the number of references */ public int getNumMeshes() { return m_meshReferences.length; } /** * Returns the meshes referenced by this node.<p> * * Each entry is an index into the mesh list stored in {@link AiScene}. * * @return an array of indices */ public int[] getMeshes() { return m_meshReferences; } /** * Returns the metadata entries for this node.<p> * * Consult the original Doxygen for importer_notes to * see which formats have metadata and what to expect. * * @return A map of metadata names to entries. */ public Map<String, AiMetadataEntry> getMetadata() { return m_metaData; } /** * Adds a child node. * * @param child the child to add */ void addChild(AiNode child) { m_children.add(child); } /** * Name. */ private final String m_name; }
8,900
0
Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src
Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/AiNodeAnim.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team 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 the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. 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 jassimp; import java.nio.ByteBuffer; import java.nio.ByteOrder; /** * Describes the animation of a single node.<p> * * The node name ({@link #getNodeName()} specifies the bone/node which is * affected by this animation channel. The keyframes are given in three * separate series of values, one each for position, rotation and scaling. * The transformation matrix computed from these values replaces the node's * original transformation matrix at a specific time.<p> * * This means all keys are absolute and not relative to the bone default pose. * The order in which the transformations are applied is - as usual - * scaling, rotation, translation.<p> * * <b>Note:</b> All keys are returned in their correct, chronological order. * Duplicate keys don't pass the validation step. Most likely there * will be no negative time values, but they are not forbidden also (so * implementations need to cope with them!)<p> * * Like {@link AiMesh}, the animation related classes offer a Buffer API, a * Direct API and a wrapped API. Please consult the documentation of * {@link AiMesh} for a description and comparison of these APIs. */ public final class AiNodeAnim { /** * Size of one position key entry. */ private final int POS_KEY_SIZE = Jassimp.NATIVE_AIVEKTORKEY_SIZE; /** * Size of one rotation key entry. */ private final int ROT_KEY_SIZE = Jassimp.NATIVE_AIQUATKEY_SIZE; /** * Size of one scaling key entry. */ private final int SCALE_KEY_SIZE = Jassimp.NATIVE_AIVEKTORKEY_SIZE; /** * Constructor. * * @param nodeName name of corresponding scene graph node * @param numPosKeys number of position keys * @param numRotKeys number of rotation keys * @param numScaleKeys number of scaling keys * @param preBehavior behavior before animation start * @param postBehavior behavior after animation end */ AiNodeAnim(String nodeName, int numPosKeys, int numRotKeys, int numScaleKeys, int preBehavior, int postBehavior) { m_nodeName = nodeName; m_numPosKeys = numPosKeys; m_numRotKeys = numRotKeys; m_numScaleKeys = numScaleKeys; m_preState = AiAnimBehavior.fromRawValue(preBehavior); m_postState = AiAnimBehavior.fromRawValue(postBehavior); m_posKeys = ByteBuffer.allocateDirect(numPosKeys * POS_KEY_SIZE); m_posKeys.order(ByteOrder.nativeOrder()); m_rotKeys = ByteBuffer.allocateDirect(numRotKeys * ROT_KEY_SIZE); m_rotKeys.order(ByteOrder.nativeOrder()); m_scaleKeys = ByteBuffer.allocateDirect(numScaleKeys * SCALE_KEY_SIZE); m_scaleKeys.order(ByteOrder.nativeOrder()); } /** * Returns the name of the scene graph node affected by this animation.<p> * * The node must exist and it must be unique. * * @return the name of the affected node */ public String getNodeName() { return m_nodeName; } /** * Returns the number of position keys. * * @return the number of position keys */ public int getNumPosKeys() { return m_numPosKeys; } /** * Returns the buffer with position keys of this animation channel.<p> * * Position keys consist of a time value (double) and a position (3D vector * of floats), resulting in a total of 20 bytes per entry. * The buffer contains {@link #getNumPosKeys()} of these entries.<p> * * If there are position keys, there will also be at least one * scaling and one rotation key.<p> * * @return a native order, direct ByteBuffer */ public ByteBuffer getPosKeyBuffer() { ByteBuffer buf = m_posKeys.duplicate(); buf.order(ByteOrder.nativeOrder()); return buf; } /** * Returns the time component of the specified position key. * * @param keyIndex the index of the position key * @return the time component */ public double getPosKeyTime(int keyIndex) { return m_posKeys.getDouble(POS_KEY_SIZE * keyIndex); } /** * Returns the position x component of the specified position key. * * @param keyIndex the index of the position key * @return the x component */ public float getPosKeyX(int keyIndex) { return m_posKeys.getFloat(POS_KEY_SIZE * keyIndex + 8); } /** * Returns the position y component of the specified position key. * * @param keyIndex the index of the position key * @return the y component */ public float getPosKeyY(int keyIndex) { return m_posKeys.getFloat(POS_KEY_SIZE * keyIndex + 12); } /** * Returns the position z component of the specified position key. * * @param keyIndex the index of the position key * @return the z component */ public float getPosKeyZ(int keyIndex) { return m_posKeys.getFloat(POS_KEY_SIZE * keyIndex + 16); } /** * Returns the position as vector.<p> * * This method is part of the wrapped API (see {@link AiWrapperProvider} * for details on wrappers).<p> * * The built in behavior is to return an {@link AiVector}. * * @param wrapperProvider the wrapper provider (used for type inference) * * @return the position as vector */ public <V3, M4, C, N, Q> V3 getPosKeyVector(int keyIndex, AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) { return wrapperProvider.wrapVector3f(m_posKeys, POS_KEY_SIZE * keyIndex + 8, 3); } /** * Returns the number of rotation keys. * * @return the number of rotation keys */ public int getNumRotKeys() { return m_numRotKeys; } /** * Returns the buffer with rotation keys of this animation channel.<p> * * Rotation keys consist of a time value (double) and a quaternion (4D * vector of floats), resulting in a total of 24 bytes per entry. The * buffer contains {@link #getNumRotKeys()} of these entries.<p> * * If there are rotation keys, there will also be at least one * scaling and one position key. * * @return a native order, direct ByteBuffer */ public ByteBuffer getRotKeyBuffer() { ByteBuffer buf = m_rotKeys.duplicate(); buf.order(ByteOrder.nativeOrder()); return buf; } /** * Returns the time component of the specified rotation key. * * @param keyIndex the index of the position key * @return the time component */ public double getRotKeyTime(int keyIndex) { return m_rotKeys.getDouble(ROT_KEY_SIZE * keyIndex); } /** * Returns the rotation w component of the specified rotation key. * * @param keyIndex the index of the position key * @return the w component */ public float getRotKeyW(int keyIndex) { return m_rotKeys.getFloat(ROT_KEY_SIZE * keyIndex + 8); } /** * Returns the rotation x component of the specified rotation key. * * @param keyIndex the index of the position key * @return the x component */ public float getRotKeyX(int keyIndex) { return m_rotKeys.getFloat(ROT_KEY_SIZE * keyIndex + 12); } /** * Returns the rotation y component of the specified rotation key. * * @param keyIndex the index of the position key * @return the y component */ public float getRotKeyY(int keyIndex) { return m_rotKeys.getFloat(ROT_KEY_SIZE * keyIndex + 16); } /** * Returns the rotation z component of the specified rotation key. * * @param keyIndex the index of the position key * @return the z component */ public float getRotKeyZ(int keyIndex) { return m_rotKeys.getFloat(ROT_KEY_SIZE * keyIndex + 20); } /** * Returns the rotation as quaternion.<p> * * This method is part of the wrapped API (see {@link AiWrapperProvider} * for details on wrappers).<p> * * The built in behavior is to return an {@link AiQuaternion}. * * @param wrapperProvider the wrapper provider (used for type inference) * * @return the rotation as quaternion */ public <V3, M4, C, N, Q> Q getRotKeyQuaternion(int keyIndex, AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) { return wrapperProvider.wrapQuaternion(m_rotKeys, ROT_KEY_SIZE * keyIndex + 8); } /** * Returns the number of scaling keys. * * @return the number of scaling keys */ public int getNumScaleKeys() { return m_numScaleKeys; } /** * Returns the buffer with scaling keys of this animation channel.<p> * * Scaling keys consist of a time value (double) and a 3D vector of floats, * resulting in a total of 20 bytes per entry. The buffer * contains {@link #getNumScaleKeys()} of these entries.<p> * * If there are scaling keys, there will also be at least one * position and one rotation key. * * @return a native order, direct ByteBuffer */ public ByteBuffer getScaleKeyBuffer() { ByteBuffer buf = m_scaleKeys.duplicate(); buf.order(ByteOrder.nativeOrder()); return buf; } /** * Returns the time component of the specified scaling key. * * @param keyIndex the index of the position key * @return the time component */ public double getScaleKeyTime(int keyIndex) { return m_scaleKeys.getDouble(SCALE_KEY_SIZE * keyIndex); } /** * Returns the scaling x component of the specified scaling key. * * @param keyIndex the index of the position key * @return the x component */ public float getScaleKeyX(int keyIndex) { return m_scaleKeys.getFloat(SCALE_KEY_SIZE * keyIndex + 8); } /** * Returns the scaling y component of the specified scaling key. * * @param keyIndex the index of the position key * @return the y component */ public float getScaleKeyY(int keyIndex) { return m_scaleKeys.getFloat(SCALE_KEY_SIZE * keyIndex + 12); } /** * Returns the scaling z component of the specified scaling key. * * @param keyIndex the index of the position key * @return the z component */ public float getScaleKeyZ(int keyIndex) { return m_scaleKeys.getFloat(SCALE_KEY_SIZE * keyIndex + 16); } /** * Returns the scaling factor as vector.<p> * * This method is part of the wrapped API (see {@link AiWrapperProvider} * for details on wrappers).<p> * * The built in behavior is to return an {@link AiVector}. * * @param wrapperProvider the wrapper provider (used for type inference) * * @return the scaling factor as vector */ public <V3, M4, C, N, Q> V3 getScaleKeyVector(int keyIndex, AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) { return wrapperProvider.wrapVector3f(m_scaleKeys, SCALE_KEY_SIZE * keyIndex + 8, 3); } /** * Defines how the animation behaves before the first key is encountered. * <p> * * The default value is {@link AiAnimBehavior#DEFAULT} (the original * transformation matrix of the affected node is used). * * @return the animation behavior before the first key */ public AiAnimBehavior getPreState() { return m_preState; } /** * Defines how the animation behaves after the last key was processed.<p> * * The default value is {@link AiAnimBehavior#DEFAULT} (the original * transformation matrix of the affected node is taken). * * @return the animation behavior before after the last key */ public AiAnimBehavior getPostState() { return m_postState; } /** * Node name. */ private final String m_nodeName; /** * Number of position keys. */ private final int m_numPosKeys; /** * Buffer with position keys. */ private ByteBuffer m_posKeys; /** * Number of rotation keys. */ private final int m_numRotKeys; /** * Buffer for rotation keys. */ private ByteBuffer m_rotKeys; /** * Number of scaling keys. */ private final int m_numScaleKeys; /** * Buffer for scaling keys. */ private ByteBuffer m_scaleKeys; /** * Pre animation behavior. */ private final AiAnimBehavior m_preState; /** * Post animation behavior. */ private final AiAnimBehavior m_postState; }
8,901
0
Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src
Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/AiCamera.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team 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 the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. 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 jassimp; /** * Helper structure to describe a virtual camera.<p> * * Cameras have a representation in the node graph and can be animated. * An important aspect is that the camera itself is also part of the * scenegraph. This means, any values such as the look-at vector are not * *absolute*, they're <b>relative</b> to the coordinate system defined * by the node which corresponds to the camera. This allows for camera * animations. For static cameras parameters like the 'look-at' or 'up' vectors * are usually specified directly in aiCamera, but beware, they could also * be encoded in the node transformation. The following (pseudo)code sample * shows how to do it: <p> * <code><pre> * // Get the camera matrix for a camera at a specific time * // if the node hierarchy for the camera does not contain * // at least one animated node this is a static computation * get-camera-matrix (node sceneRoot, camera cam) : matrix * { * node cnd = find-node-for-camera(cam) * matrix cmt = identity() * * // as usual - get the absolute camera transformation for this frame * for each node nd in hierarchy from sceneRoot to cnd * matrix cur * if (is-animated(nd)) * cur = eval-animation(nd) * else cur = nd->mTransformation; * cmt = mult-matrices( cmt, cur ) * end for * * // now multiply with the camera's own local transform * cam = mult-matrices (cam, get-camera-matrix(cmt) ) * } * </pre></code> * * <b>Note:</b> some file formats (such as 3DS, ASE) export a "target point" - * the point the camera is looking at (it can even be animated). Assimp * writes the target point as a subnode of the camera's main node, * called "<camName>.Target". However this is just additional information * then the transformation tracks of the camera main node make the * camera already look in the right direction. */ public final class AiCamera { /** * Constructor. * * @param name name * @param position position * @param up up vector * @param lookAt look-at vector * @param horizontalFOV field of view * @param clipNear near clip plane * @param clipFar far clip plane * @param aspect aspect ratio */ AiCamera(String name, Object position, Object up, Object lookAt, float horizontalFOV, float clipNear, float clipFar, float aspect) { m_name = name; m_position = position; m_up = up; m_lookAt = lookAt; m_horizontalFOV = horizontalFOV; m_clipNear = clipNear; m_clipFar = clipFar; m_aspect = aspect; } /** * Returns the name of the camera.<p> * * There must be a node in the scenegraph with the same name. * This node specifies the position of the camera in the scene * hierarchy and can be animated. */ public String getName() { return m_name; } /** * Returns the position of the camera.<p> * * The returned position is relative to the coordinate space defined by the * corresponding node.<p> * * The default value is 0|0|0.<p> * * This method is part of the wrapped API (see {@link AiWrapperProvider} * for details on wrappers).<p> * * The built-in behavior is to return a {@link AiVector}. * * @param wrapperProvider the wrapper provider (used for type inference) * @return the position vector */ @SuppressWarnings("unchecked") public <V3, M4, C, N, Q> V3 getPosition(AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) { return (V3) m_position; } /** * Returns the 'Up' - vector of the camera coordinate system. * * The returned vector is relative to the coordinate space defined by the * corresponding node.<p> * * The 'right' vector of the camera coordinate system is the cross product * of the up and lookAt vectors. The default value is 0|1|0. The vector * may be normalized, but it needn't.<p> * * This method is part of the wrapped API (see {@link AiWrapperProvider} * for details on wrappers).<p> * * The built-in behavior is to return a {@link AiVector}. * * @param wrapperProvider the wrapper provider (used for type inference) * @return the 'Up' vector */ @SuppressWarnings("unchecked") public <V3, M4, C, N, Q> V3 getUp(AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) { return (V3) m_up; } /** * Returns the 'LookAt' - vector of the camera coordinate system.<p> * * The returned vector is relative to the coordinate space defined by the * corresponding node.<p> * * This is the viewing direction of the user. The default value is 0|0|1. * The vector may be normalized, but it needn't.<p> * * This method is part of the wrapped API (see {@link AiWrapperProvider} * for details on wrappers).<p> * * The built-in behavior is to return a {@link AiVector}. * * @param wrapperProvider the wrapper provider (used for type inference) * @return the 'LookAt' vector */ @SuppressWarnings("unchecked") public <V3, M4, C, N, Q> V3 getLookAt(AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) { return (V3) m_lookAt; } /** * Returns the half horizontal field of view angle, in radians.<p> * * The field of view angle is the angle between the center line of the * screen and the left or right border. The default value is 1/4PI. * * @return the half horizontal field of view angle */ public float getHorizontalFOV() { return m_horizontalFOV; } /** * Returns the distance of the near clipping plane from the camera.<p> * * The value may not be 0.f (for arithmetic reasons to prevent a division * through zero). The default value is 0.1f. * * @return the distance of the near clipping plane */ public float getClipPlaneNear() { return m_clipNear; } /** * Returns the distance of the far clipping plane from the camera.<p> * * The far clipping plane must, of course, be further away than the * near clipping plane. The default value is 1000.0f. The ratio * between the near and the far plane should not be too * large (between 1000-10000 should be ok) to avoid floating-point * inaccuracies which could lead to z-fighting. * * @return the distance of the far clipping plane */ public float getClipPlaneFar() { return m_clipFar; } /** * Returns the screen aspect ratio.<p> * * This is the ration between the width and the height of the * screen. Typical values are 4/3, 1/2 or 1/1. This value is * 0 if the aspect ratio is not defined in the source file. * 0 is also the default value. * * @return the screen aspect ratio */ public float getAspect() { return m_aspect; } /** * Name. */ private final String m_name; /** * Position. */ private final Object m_position; /** * Up vector. */ private final Object m_up; /** * Look-At vector. */ private final Object m_lookAt; /** * FOV. */ private final float m_horizontalFOV; /** * Near clipping plane. */ private final float m_clipNear; /** * Far clipping plane. */ private final float m_clipFar; /** * Aspect ratio. */ private final float m_aspect; }
8,902
0
Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src
Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/AiScene.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team 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 the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. 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 jassimp; import java.util.ArrayList; import java.util.List; /** * The root structure of the imported data.<p> * * Everything that was imported from the given file can be accessed from here. * <p> * Jassimp copies all data into "java memory" during import and frees * resources allocated by native code after scene loading is completed. No * special care has to be taken for freeing resources, unreferenced jassimp * objects (including the scene itself) are eligible to garbage collection like * any other java object. */ public final class AiScene { /** * Constructor. */ AiScene() { /* nothing to do */ } /** * Returns the number of meshes contained in the scene.<p> * * This method is provided for completeness reasons. It will return the * same value as <code>getMeshes().size()</code> * * @return the number of meshes */ public int getNumMeshes() { return m_meshes.size(); } /** * Returns the meshes contained in the scene.<p> * * If there are no meshes in the scene, an empty collection is returned * * @return the list of meshes */ public List<AiMesh> getMeshes() { return m_meshes; } /** * Returns the number of materials in the scene.<p> * * This method is provided for completeness reasons. It will return the * same value as <code>getMaterials().size()</code> * * @return the number of materials */ public int getNumMaterials() { return m_materials.size(); } /** * Returns the list of materials.<p> * * Use the index given in each aiMesh structure to access this * array. If the {@link AiSceneFlag#INCOMPLETE} flag is not set there will * always be at least ONE material. * * @return the list of materials */ public List<AiMaterial> getMaterials() { return m_materials; } /** * Returns the number of animations in the scene.<p> * * This method is provided for completeness reasons. It will return the * same value as <code>getAnimations().size()</code> * * @return the number of materials */ public int getNumAnimations() { return m_animations.size(); } /** * Returns the list of animations. * * @return the list of animations */ public List<AiAnimation> getAnimations() { return m_animations; } /** * Returns the number of light sources in the scene.<p> * * This method is provided for completeness reasons. It will return the * same value as <code>getLights().size()</code> * * @return the number of lights */ public int getNumLights() { return m_lights.size(); } /** * Returns the list of light sources.<p> * * Light sources are fully optional, the returned list may be empty * * @return a possibly empty list of lights */ public List<AiLight> getLights() { return m_lights; } /** * Returns the number of cameras in the scene.<p> * * This method is provided for completeness reasons. It will return the * same value as <code>getCameras().size()</code> * * @return the number of cameras */ public int getNumCameras() { return m_cameras.size(); } /** * Returns the list of cameras.<p> * * Cameras are fully optional, the returned list may be empty * * @return a possibly empty list of cameras */ public List<AiCamera> getCameras() { return m_cameras; } /** * Returns the scene graph root. * * This method is part of the wrapped API (see {@link AiWrapperProvider} * for details on wrappers).<p> * * The built-in behavior is to return a {@link AiVector}. * * @param wrapperProvider the wrapper provider (used for type inference) * @return the scene graph root */ @SuppressWarnings("unchecked") public <V3, M4, C, N, Q> N getSceneRoot(AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) { return (N) m_sceneRoot; } @Override public String toString() { return "AiScene (" + m_meshes.size() + " mesh/es)"; } /** * Meshes. */ private final List<AiMesh> m_meshes = new ArrayList<AiMesh>(); /** * Materials. */ private final List<AiMaterial> m_materials = new ArrayList<AiMaterial>(); /** * Animations. */ private final List<AiAnimation> m_animations = new ArrayList<AiAnimation>(); /** * Lights. */ private final List<AiLight> m_lights = new ArrayList<AiLight>(); /** * Cameras. */ private final List<AiCamera> m_cameras = new ArrayList<AiCamera>(); /** * Scene graph root. */ private Object m_sceneRoot; }
8,903
0
Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src
Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/AiPostProcessSteps.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team 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 the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. 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 jassimp; import java.util.Set; /** * Enumerates the post processing steps supported by assimp. */ public enum AiPostProcessSteps { /** * Calculates the tangents and bitangents for the imported meshes. * <p> * * Does nothing if a mesh does not have normals. You might want this post * processing step to be executed if you plan to use tangent space * calculations such as normal mapping applied to the meshes. There's a * config setting, <tt>#AI_CONFIG_PP_CT_MAX_SMOOTHING_ANGLE</tt>, which * allows you to specify a maximum smoothing angle for the algorithm. * However, usually you'll want to leave it at the default value. */ CALC_TANGENT_SPACE(0x1), /** * Identifies and joins identical vertex data sets within all imported * meshes.<p> * * After this step is run, each mesh contains unique vertices, so a vertex * may be used by multiple faces. You usually want to use this post * processing step. If your application deals with indexed geometry, this * step is compulsory or you'll just waste rendering time. <b>If this flag * is not specified</b>, no vertices are referenced by more than one face * and <b>no index buffer is required</b> for rendering. */ JOIN_IDENTICAL_VERTICES(0x2), /** * Converts all the imported data to a left-handed coordinate space.<p> * * By default the data is returned in a right-handed coordinate space (which * OpenGL prefers). In this space, +X points to the right, +Z points towards * the viewer, and +Y points upwards. In the DirectX coordinate space +X * points to the right, +Y points upwards, and +Z points away from the * viewer.<p> * * You'll probably want to consider this flag if you use Direct3D for * rendering. The #ConvertToLeftHanded flag supersedes this * setting and bundles all conversions typically required for D3D-based * applications. */ MAKE_LEFT_HANDED(0x4), /** * Triangulates all faces of all meshes.<p> * * By default the imported mesh data might contain faces with more than 3 * indices. For rendering you'll usually want all faces to be triangles. * This post processing step splits up faces with more than 3 indices into * triangles. Line and point primitives are *not* modified! If you want * 'triangles only' with no other kinds of primitives, try the following * solution: * <ul> * <li>Specify both #Triangulate and #SortByPType * <li>Ignore all point and line meshes when you process assimp's output * </ul> */ TRIANGULATE(0x8), /** * Removes some parts of the data structure (animations, materials, light * sources, cameras, textures, vertex components).<p> * * The components to be removed are specified in a separate configuration * option, <tt>#AI_CONFIG_PP_RVC_FLAGS</tt>. This is quite useful if you * don't need all parts of the output structure. Vertex colors are rarely * used today for example... Calling this step to remove unneeded data from * the pipeline as early as possible results in increased performance and a * more optimized output data structure. This step is also useful if you * want to force Assimp to recompute normals or tangents. The corresponding * steps don't recompute them if they're already there (loaded from the * source asset). By using this step you can make sure they are NOT there. * <p> * * This flag is a poor one, mainly because its purpose is usually * misunderstood. Consider the following case: a 3D model has been exported * from a CAD app, and it has per-face vertex colors. Vertex positions can't * be shared, thus the #JoinIdenticalVertices step fails to * optimize the data because of these nasty little vertex colors. Most apps * don't even process them, so it's all for nothing. By using this step, * unneeded components are excluded as early as possible thus opening more * room for internal optimizations. */ REMOVE_COMPONENT(0x10), /** * Generates normals for all faces of all meshes.<p> * * This is ignored if normals are already there at the time this flag is * evaluated. Model importers try to load them from the source file, so * they're usually already there. Face normals are shared between all points * of a single face, so a single point can have multiple normals, which * forces the library to duplicate vertices in some cases. * #JoinIdenticalVertices is *senseless* then.<p> * * This flag may not be specified together with {@link #GEN_SMOOTH_NORMALS}. */ GEN_NORMALS(0x20), /** * Generates smooth normals for all vertices in the mesh.<p> * * This is ignored if normals are already there at the time this flag is * evaluated. Model importers try to load them from the source file, so * they're usually already there.<p> * * This flag may not be specified together with {@link #GEN_NORMALS} * There's a configuration option, * <tt>#AI_CONFIG_PP_GSN_MAX_SMOOTHING_ANGLE</tt> which allows you to * specify an angle maximum for the normal smoothing algorithm. Normals * exceeding this limit are not smoothed, resulting in a 'hard' seam between * two faces. Using a decent angle here (e.g. 80 degrees) results in very * good visual appearance. */ GEN_SMOOTH_NORMALS(0x40), /** * Splits large meshes into smaller sub-meshes.<p> * * This is quite useful for real-time rendering, where the number of * triangles which can be maximally processed in a single draw-call is * limited by the video driver/hardware. The maximum vertex buffer is * usually limited too. Both requirements can be met with this step: you may * specify both a triangle and vertex limit for a single mesh.<p> * * The split limits can (and should!) be set through the * <tt>#AI_CONFIG_PP_SLM_VERTEX_LIMIT</tt> and * <tt>#AI_CONFIG_PP_SLM_TRIANGLE_LIMIT</tt> settings. The default values * are <tt>#AI_SLM_DEFAULT_MAX_VERTICES</tt> and * <tt>#AI_SLM_DEFAULT_MAX_TRIANGLES</tt>.<p> * * Note that splitting is generally a time-consuming task, but only if * there's something to split. The use of this step is recommended for most * users. */ SPLIT_LARGE_MESHES(0x80), /** * Removes the node graph and pre-transforms all vertices with the local * transformation matrices of their nodes.<p> * * The output scene still contains nodes, however there is only a root node * with children, each one referencing only one mesh, and each mesh * referencing one material. For rendering, you can simply render all meshes * in order - you don't need to pay attention to local transformations and * the node hierarchy. Animations are removed during this step. This step is * intended for applications without a scenegraph. The step CAN cause some * problems: if e.g. a mesh of the asset contains normals and another, using * the same material index, does not, they will be brought together, but the * first meshes's part of the normal list is zeroed. However, these * artifacts are rare.<p> * * <b>Note:</b> The <tt>#AI_CONFIG_PP_PTV_NORMALIZE</tt> configuration * property can be set to normalize the scene's spatial dimension to the * -1...1 range. */ PRE_TRANSFORM_VERTICES(0x100), /** * Limits the number of bones simultaneously affecting a single vertex to a * maximum value.<p> * * If any vertex is affected by more than the maximum number of bones, the * least important vertex weights are removed and the remaining vertex * weights are renormalized so that the weights still sum up to 1. The * default bone weight limit is 4 (defined as <tt>#AI_LMW_MAX_WEIGHTS</tt> * in config.h), but you can use the <tt>#AI_CONFIG_PP_LBW_MAX_WEIGHTS</tt> * setting to supply your own limit to the post processing step.<p> * * If you intend to perform the skinning in hardware, this post processing * step might be of interest to you. */ LIMIT_BONE_WEIGHTS(0x200), /** * Validates the imported scene data structure. This makes sure that all * indices are valid, all animations and bones are linked correctly, all * material references are correct .. etc.<p> * * It is recommended that you capture Assimp's log output if you use this * flag, so you can easily find out what's wrong if a file fails the * validation. The validator is quite strict and will find *all* * inconsistencies in the data structure... It is recommended that plugin * developers use it to debug their loaders. There are two types of * validation failures: * <ul> * <li>Error: There's something wrong with the imported data. Further * postprocessing is not possible and the data is not usable at all. The * import fails. #Importer::GetErrorString() or #aiGetErrorString() carry * the error message around.</li> * <li>Warning: There are some minor issues (e.g. 1000000 animation * keyframes with the same time), but further postprocessing and use of the * data structure is still safe. Warning details are written to the log * file, <tt>#AI_SCENE_FLAGS_VALIDATION_WARNING</tt> is set in * #aiScene::mFlags</li> * </ul> * * This post-processing step is not time-consuming. Its use is not * compulsory, but recommended. */ VALIDATE_DATA_STRUCTURE(0x400), /** * Reorders triangles for better vertex cache locality.<p> * * The step tries to improve the ACMR (average post-transform vertex cache * miss ratio) for all meshes. The implementation runs in O(n) and is * roughly based on the 'tipsify' algorithm (see <a href=" * http://www.cs.princeton.edu/gfx/pubs/Sander_2007_%3ETR/tipsy.pdf">this * paper</a>).<p> * * If you intend to render huge models in hardware, this step might be of * interest to you. The <tt>#AI_CONFIG_PP_ICL_PTCACHE_SIZE</tt>config * setting can be used to fine-tune the cache optimization. */ IMPROVE_CACHE_LOCALITY(0x800), /** * Searches for redundant/unreferenced materials and removes them.<p> * * This is especially useful in combination with the * #PretransformVertices and #OptimizeMeshes flags. Both * join small meshes with equal characteristics, but they can't do their * work if two meshes have different materials. Because several material * settings are lost during Assimp's import filters, (and because many * exporters don't check for redundant materials), huge models often have * materials which are are defined several times with exactly the same * settings.<p> * * Several material settings not contributing to the final appearance of a * surface are ignored in all comparisons (e.g. the material name). So, if * you're passing additional information through the content pipeline * (probably using *magic* material names), don't specify this flag. * Alternatively take a look at the <tt>#AI_CONFIG_PP_RRM_EXCLUDE_LIST</tt> * setting. */ REMOVE_REDUNDANT_MATERIALS(0x1000), /** * This step tries to determine which meshes have normal vectors that are * facing inwards and inverts them.<p> * * The algorithm is simple but effective: the bounding box of all vertices + * their normals is compared against the volume of the bounding box of all * vertices without their normals. This works well for most objects, * problems might occur with planar surfaces. However, the step tries to * filter such cases. The step inverts all in-facing normals. Generally it * is recommended to enable this step, although the result is not always * correct. */ FIX_INFACING_NORMALS(0x2000), /** * This step splits meshes with more than one primitive type in homogeneous * sub-meshes.<p> * * The step is executed after the triangulation step. After the step * returns, just one bit is set in aiMesh::mPrimitiveTypes. This is * especially useful for real-time rendering where point and line primitives * are often ignored or rendered separately. You can use the * <tt>#AI_CONFIG_PP_SBP_REMOVE</tt> option to specify which primitive types * you need. This can be used to easily exclude lines and points, which are * rarely used, from the import. */ SORT_BY_PTYPE(0x8000), /** * This step searches all meshes for degenerate primitives and converts them * to proper lines or points.<p> * * A face is 'degenerate' if one or more of its points are identical. To * have the degenerate stuff not only detected and collapsed but removed, * try one of the following procedures: <br> * <b>1.</b> (if you support lines and points for rendering but don't want * the degenerates)</br> * <ul> * <li>Specify the #FindDegenerates flag.</li> * <li>Set the <tt>AI_CONFIG_PP_FD_REMOVE</tt> option to 1. This will cause * the step to remove degenerate triangles from the import as soon as * they're detected. They won't pass any further pipeline steps.</li> * </ul> * <br> * <b>2.</b>(if you don't support lines and points at all)</br> * <ul> * <li>Specify the #FindDegenerates flag. * <li>Specify the #SortByPType flag. This moves line and point * primitives to separate meshes. * <li>Set the <tt>AI_CONFIG_PP_SBP_REMOVE</tt> option to * <code>aiPrimitiveType_POINTS | aiPrimitiveType_LINES</code> * to cause SortByPType to reject point and line meshes from the * scene. * </ul> * <b>Note:</b> Degenerated polygons are not necessarily evil and that's * why they're not removed by default. There are several file formats * which don't support lines or points, and some exporters bypass the * format specification and write them as degenerate triangles instead. */ FIND_DEGENERATES(0x10000), /** * This step searches all meshes for invalid data, such as zeroed normal * vectors or invalid UV coords and removes/fixes them. This is intended to * get rid of some common exporter errors.<p> * * This is especially useful for normals. If they are invalid, and the step * recognizes this, they will be removed and can later be recomputed, i.e. * by the {@link #GEN_SMOOTH_NORMALS} flag.<p> * * The step will also remove meshes that are infinitely small and reduce * animation tracks consisting of hundreds if redundant keys to a single * key. The <tt>AI_CONFIG_PP_FID_ANIM_ACCURACY</tt> config property decides * the accuracy of the check for duplicate animation tracks. */ FIND_INVALID_DATA(0x20000), /** * This step converts non-UV mappings (such as spherical or cylindrical * mapping) to proper texture coordinate channels.<p> * * Most applications will support UV mapping only, so you will probably want * to specify this step in every case. Note that Assimp is not always able * to match the original mapping implementation of the 3D app which produced * a model perfectly. It's always better to let the modelling app compute * the UV channels - 3ds max, Maya, Blender, LightWave, and Modo do this for * example.<p> * * <b>Note:</b> If this step is not requested, you'll need to process the * <tt>MATKEY_MAPPING</tt> material property in order to display all * assets properly. */ GEN_UV_COORDS(0x40000), /** * This step applies per-texture UV transformations and bakes them into * stand-alone vtexture coordinate channels.<p> * * UV transformations are specified per-texture - see the * <tt>MATKEY_UVTRANSFORM</tt> material key for more information. This * step processes all textures with transformed input UV coordinates and * generates a new (pre-transformed) UV channel which replaces the old * channel. Most applications won't support UV transformations, so you will * probably want to specify this step.<p> * * <b>Note:</b> UV transformations are usually implemented in real-time * apps by transforming texture coordinates at vertex shader stage with a * 3x3 (homogenous) transformation matrix. */ TRANSFORM_UV_COORDS(0x80000), /** * This step searches for duplicate meshes and replaces them with references * to the first mesh.<p> * * This step takes a while, so don't use it if speed is a concern. Its main * purpose is to workaround the fact that many export file formats don't * support instanced meshes, so exporters need to duplicate meshes. This * step removes the duplicates again. Please note that Assimp does not * currently support per-node material assignment to meshes, which means * that identical meshes with different materials are currently *not* * joined, although this is planned for future versions. */ FIND_INSTANCES(0x100000), /** * A postprocessing step to reduce the number of meshes.<p> * * This will, in fact, reduce the number of draw calls.<p> * * This is a very effective optimization and is recommended to be used * together with #OptimizeGraph, if possible. The flag is fully * compatible with both {@link #SPLIT_LARGE_MESHES} and * {@link #SORT_BY_PTYPE}. */ OPTIMIZE_MESHES(0x200000), /** * A postprocessing step to optimize the scene hierarchy.<p> * * Nodes without animations, bones, lights or cameras assigned are collapsed * and joined.<p> * * Node names can be lost during this step. If you use special 'tag nodes' * to pass additional information through your content pipeline, use the * <tt>#AI_CONFIG_PP_OG_EXCLUDE_LIST</tt> setting to specify a list of node * names you want to be kept. Nodes matching one of the names in this list * won't be touched or modified.<p> * * Use this flag with caution. Most simple files will be collapsed to a * single node, so complex hierarchies are usually completely lost. This is * not useful for editor environments, but probably a very effective * optimization if you just want to get the model data, convert it to your * own format, and render it as fast as possible.<p> * * This flag is designed to be used with #OptimizeMeshes for best * results.<p> * * <b>Note:</b> 'Crappy' scenes with thousands of extremely small meshes * packed in deeply nested nodes exist for almost all file formats. * {@link #OPTIMIZE_MESHES} in combination with {@link #OPTIMIZE_GRAPH} * usually fixes them all and makes them renderable. */ OPTIMIZE_GRAPH(0x400000), /** * This step flips all UV coordinates along the y-axis and adjusts material * settings and bitangents accordingly.<p> * * <b>Output UV coordinate system:</b><br> * <code><pre> * 0y|0y ---------- 1x|0y * | | * | | * | | * 0x|1y ---------- 1x|1y * </pre></code> * <p> * * You'll probably want to consider this flag if you use Direct3D for * rendering. The {@link #MAKE_LEFT_HANDED} flag supersedes this setting * and bundles all conversions typically required for D3D-based * applications. */ FLIP_UVS(0x800000), /** * This step adjusts the output face winding order to be CW.<p> * * The default face winding order is counter clockwise (CCW). * * <b>Output face order:</b> * * <code><pre> * x2 * * x0 * x1 * </pre></code> */ FLIP_WINDING_ORDER(0x1000000), /** * This step splits meshes with many bones into sub-meshes so that each * sub-mesh has fewer or as many bones as a given limit.<p> */ SPLIT_BY_BONE_COUNT(0x2000000), /** * This step removes bones losslessly or according to some threshold.<p> * * In some cases (i.e. formats that require it) exporters are forced to * assign dummy bone weights to otherwise static meshes assigned to animated * meshes. Full, weight-based skinning is expensive while animating nodes is * extremely cheap, so this step is offered to clean up the data in that * regard.<p> * * Use <tt>#AI_CONFIG_PP_DB_THRESHOLD</tt> to control this. Use * <tt>#AI_CONFIG_PP_DB_ALL_OR_NONE</tt> if you want bones removed if and * only if all bones within the scene qualify for removal. */ DEBONE(0x4000000); /** * Utility method for converting to c/c++ based integer enums from java * enums.<p> * * This method is intended to be used from JNI and my change based on * implementation needs. * * @param set the set to convert * @return an integer based enum value (as defined by assimp) */ static long toRawValue(Set<AiPostProcessSteps> set) { long rawValue = 0L; for (AiPostProcessSteps step : set) { rawValue |= step.m_rawValue; } return rawValue; } /** * Constructor. * * @param rawValue maps java enum to c/c++ integer enum values */ private AiPostProcessSteps(long rawValue) { m_rawValue = rawValue; } /** * The mapped c/c++ integer enum value. */ private final long m_rawValue; }
8,904
0
Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src
Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/AiIOStream.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team 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 the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. 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 jassimp; import java.nio.ByteBuffer; /** * Interface to allow custom resource loaders for jassimp.<p> * * The design is based on passing the file wholly in memory, * because Java inputstreams do not have to support seek. <p> * * Writing files from Java is unsupported. * * * @author Jesper Smith * */ public interface AiIOStream { /** * Read all data into buffer. <p> * * The whole stream should be read into the buffer. * No support is provided for partial reads. * * @param buffer Target buffer for the model data * * @return true if successful, false if an error occurred. */ boolean read(ByteBuffer buffer); /** * The total size of this stream. <p> * * @return total size of this stream */ int getFileSize(); }
8,905
0
Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src
Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/AiTextureMapMode.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team 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 the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. 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 jassimp; /** * Defines how UV coordinates outside the [0...1] range are handled.<p> * * Commonly referred to as 'wrapping mode'. */ public enum AiTextureMapMode { /** * A texture coordinate u|v is translated to u%1|v%1. */ WRAP(0x0), /** * Texture coordinates outside [0...1] are clamped to the nearest * valid value. */ CLAMP(0x1), /** * A texture coordinate u|v becomes u%1|v%1 if (u-(u%1))%2 is zero and * 1-(u%1)|1-(v%1) otherwise. */ MIRROR(0x2), /** * If the texture coordinates for a pixel are outside [0...1] the texture * is not applied to that pixel. */ DECAL(0x3); /** * Utility method for converting from c/c++ based integer enums to java * enums.<p> * * This method is intended to be used from JNI and my change based on * implementation needs. * * @param rawValue an integer based enum value (as defined by assimp) * @return the enum value corresponding to rawValue */ static AiTextureMapMode fromRawValue(int rawValue) { for (AiTextureMapMode type : AiTextureMapMode.values()) { if (type.m_rawValue == rawValue) { return type; } } throw new IllegalArgumentException("unexptected raw value: " + rawValue); } /** * Constructor. * * @param rawValue maps java enum to c/c++ integer enum values */ private AiTextureMapMode(int rawValue) { m_rawValue = rawValue; } /** * The mapped c/c++ integer enum value. */ private final int m_rawValue; }
8,906
0
Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src
Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/package-info.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team 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 the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. 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. --------------------------------------------------------------------------- */ /** * Java binding for the Open Asset Import Library. */ package jassimp;
8,907
0
Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src
Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/AiInputStreamIOStream.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team 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 the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. 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 jassimp; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.net.URL; import java.nio.ByteBuffer; /** * Implementation of AiIOStream reading from a InputStream * * @author Jesper Smith * */ public class AiInputStreamIOStream implements AiIOStream { private final ByteArrayOutputStream os = new ByteArrayOutputStream(); public AiInputStreamIOStream(URI uri) throws IOException { this(uri.toURL()); } public AiInputStreamIOStream(URL url) throws IOException { this(url.openStream()); } public AiInputStreamIOStream(InputStream is) throws IOException { int read; byte[] data = new byte[1024]; while((read = is.read(data, 0, data.length)) != -1) { os.write(data, 0, read); } os.flush(); is.close(); } @Override public int getFileSize() { return os.size(); } @Override public boolean read(ByteBuffer buffer) { ByteBufferOutputStream bos = new ByteBufferOutputStream(buffer); try { os.writeTo(bos); } catch (IOException e) { e.printStackTrace(); return false; } return true; } /** * Internal helper class to copy the contents of an OutputStream * into a ByteBuffer. This avoids a copy. * */ private static class ByteBufferOutputStream extends OutputStream { private final ByteBuffer buffer; public ByteBufferOutputStream(ByteBuffer buffer) { this.buffer = buffer; } @Override public void write(int b) throws IOException { buffer.put((byte) b); } @Override public void write(byte b[], int off, int len) throws IOException { buffer.put(b, off, len); } } }
8,908
0
Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src
Create_ds/lumberyard/dev/Gems/Blast/3rdParty/assimp/port/jassimp/jassimp/src/jassimp/AiBone.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team 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 the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. 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 jassimp; import java.util.ArrayList; import java.util.List; /** * A single bone of a mesh.<p> * * A bone has a name by which it can be found in the frame hierarchy and by * which it can be addressed by animations. In addition it has a number of * influences on vertices.<p> * * This class is designed to be mutable, i.e., the returned collections are * writable and may be modified. */ public final class AiBone { /** * Name of the bone. */ private String m_name; /** * Bone weights. */ private final List<AiBoneWeight> m_boneWeights = new ArrayList<AiBoneWeight>(); /** * Offset matrix. */ private Object m_offsetMatrix; /** * Constructor. */ AiBone() { /* nothing to do */ } /** * Returns the name of the bone. * * @return the name */ public String getName() { return m_name; } /** * Returns the number of bone weights.<p> * * This method exists for compatibility with the native assimp API. * The returned value is identical to <code>getBoneWeights().size()</code> * * @return the number of weights */ public int getNumWeights() { return m_boneWeights.size(); } /** * Returns a list of bone weights. * * @return the bone weights */ public List<AiBoneWeight> getBoneWeights() { return m_boneWeights; } /** * Returns the offset matrix.<p> * * The offset matrix is a 4x4 matrix that transforms from mesh space to * bone space in bind pose.<p> * * This method is part of the wrapped API (see {@link AiWrapperProvider} * for details on wrappers). * * @param wrapperProvider the wrapper provider (used for type inference) * * @return the offset matrix */ @SuppressWarnings("unchecked") public <V3, M4, C, N, Q> M4 getOffsetMatrix( AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) { return (M4) m_offsetMatrix; } }
8,909
0
Create_ds/amazon-freertos/vendors/ti/SimpleLink_CC32xx/v2_10_00_04/source/ti/drivers
Create_ds/amazon-freertos/vendors/ti/SimpleLink_CC32xx/v2_10_00_04/source/ti/drivers/package/ti_drivers.java
/* * Do not modify this file; it is automatically * generated and any modifications will be overwritten. * * @(#) xdc-D28 */ import java.util.*; import org.mozilla.javascript.*; import xdc.services.intern.xsr.*; import xdc.services.spec.Session; public class ti_drivers { static final String VERS = "@(#) xdc-D28\n"; static final Proto.Elm $$T_Bool = Proto.Elm.newBool(); static final Proto.Elm $$T_Num = Proto.Elm.newNum(); static final Proto.Elm $$T_Str = Proto.Elm.newStr(); static final Proto.Elm $$T_Obj = Proto.Elm.newObj(); static final Proto.Fxn $$T_Met = new Proto.Fxn(null, null, 0, -1, false); static final Proto.Map $$T_Map = new Proto.Map($$T_Obj); static final Proto.Arr $$T_Vec = new Proto.Arr($$T_Obj); static final XScriptO $$DEFAULT = Value.DEFAULT; static final Object $$UNDEF = Undefined.instance; static final Proto.Obj $$Package = (Proto.Obj)Global.get("$$Package"); static final Proto.Obj $$Module = (Proto.Obj)Global.get("$$Module"); static final Proto.Obj $$Instance = (Proto.Obj)Global.get("$$Instance"); static final Proto.Obj $$Params = (Proto.Obj)Global.get("$$Params"); static final Object $$objFldGet = Global.get("$$objFldGet"); static final Object $$objFldSet = Global.get("$$objFldSet"); static final Object $$proxyGet = Global.get("$$proxyGet"); static final Object $$proxySet = Global.get("$$proxySet"); static final Object $$delegGet = Global.get("$$delegGet"); static final Object $$delegSet = Global.get("$$delegSet"); Scriptable xdcO; Session ses; Value.Obj om; boolean isROV; boolean isCFG; Proto.Obj pkgP; Value.Obj pkgV; ArrayList<Object> imports = new ArrayList<Object>(); ArrayList<Object> loggables = new ArrayList<Object>(); ArrayList<Object> mcfgs = new ArrayList<Object>(); ArrayList<Object> icfgs = new ArrayList<Object>(); ArrayList<String> inherits = new ArrayList<String>(); ArrayList<Object> proxies = new ArrayList<Object>(); ArrayList<Object> sizes = new ArrayList<Object>(); ArrayList<Object> tdefs = new ArrayList<Object>(); void $$IMPORTS() { Global.callFxn("loadPackage", xdcO, "ti.sysbios"); Global.callFxn("loadPackage", xdcO, "ti.dpl"); Global.callFxn("loadPackage", xdcO, "xdc"); Global.callFxn("loadPackage", xdcO, "xdc.corevers"); Global.callFxn("loadPackage", xdcO, "xdc.runtime"); } void $$OBJECTS() { pkgP = (Proto.Obj)om.bind("ti.drivers.Package", new Proto.Obj()); pkgV = (Value.Obj)om.bind("ti.drivers", new Value.Obj("ti.drivers", pkgP)); } void Config$$OBJECTS() { Proto.Obj po, spo; Value.Obj vo; po = (Proto.Obj)om.bind("ti.drivers.Config.Module", new Proto.Obj()); vo = (Value.Obj)om.bind("ti.drivers.Config", new Value.Obj("ti.drivers.Config", po)); pkgV.bind("Config", vo); // decls om.bind("ti.drivers.Config.LibType", new Proto.Enm("ti.drivers.Config.LibType")); om.bind("ti.drivers.Config.RFDriverMode", new Proto.Enm("ti.drivers.Config.RFDriverMode")); } void Power$$OBJECTS() { Proto.Obj po, spo; Value.Obj vo; po = (Proto.Obj)om.bind("ti.drivers.Power.Module", new Proto.Obj()); vo = (Value.Obj)om.bind("ti.drivers.Power", new Value.Obj("ti.drivers.Power", po)); pkgV.bind("Power", vo); // decls } void Config$$CONSTS() { // module Config om.bind("ti.drivers.Config.LibType_Instrumented", xdc.services.intern.xsr.Enum.make((Proto.Enm)om.findStrict("ti.drivers.Config.LibType", "ti.drivers"), "ti.drivers.Config.LibType_Instrumented", 0)); om.bind("ti.drivers.Config.LibType_NonInstrumented", xdc.services.intern.xsr.Enum.make((Proto.Enm)om.findStrict("ti.drivers.Config.LibType", "ti.drivers"), "ti.drivers.Config.LibType_NonInstrumented", 1)); om.bind("ti.drivers.Config.RF_MultiMode", xdc.services.intern.xsr.Enum.make((Proto.Enm)om.findStrict("ti.drivers.Config.RFDriverMode", "ti.drivers"), "ti.drivers.Config.RF_MultiMode", 0)); om.bind("ti.drivers.Config.RF_SingleMode", xdc.services.intern.xsr.Enum.make((Proto.Enm)om.findStrict("ti.drivers.Config.RFDriverMode", "ti.drivers"), "ti.drivers.Config.RF_SingleMode", 1)); } void Power$$CONSTS() { // module Power } void Config$$CREATES() { Proto.Fxn fxn; StringBuilder sb; } void Power$$CREATES() { Proto.Fxn fxn; StringBuilder sb; } void Config$$FUNCTIONS() { Proto.Fxn fxn; } void Power$$FUNCTIONS() { Proto.Fxn fxn; } void Config$$SIZES() { } void Power$$SIZES() { Proto.Str so; Object fxn; } void Config$$TYPES() { Scriptable cap; Proto.Obj po; Proto.Str ps; Proto.Typedef pt; Object fxn; cap = (Scriptable)Global.callFxn("loadCapsule", xdcO, "ti/drivers/Config.xs"); om.bind("ti.drivers.Config$$capsule", cap); po = (Proto.Obj)om.findStrict("ti.drivers.Config.Module", "ti.drivers"); po.init("ti.drivers.Config.Module", $$Module); po.addFld("$hostonly", $$T_Num, 1, "r"); po.addFld("libType", (Proto)om.findStrict("ti.drivers.Config.LibType", "ti.drivers"), om.find("ti.drivers.Config.LibType_NonInstrumented"), "wh"); po.addFld("rfDriverMode", (Proto)om.findStrict("ti.drivers.Config.RFDriverMode", "ti.drivers"), om.find("ti.drivers.Config.RF_SingleMode"), "wh"); po.addFld("supportsRFDriver", $$T_Bool, false, "wh"); fxn = Global.get(cap, "module$use"); if (fxn != null) om.bind("ti.drivers.Config$$module$use", true); if (fxn != null) po.addFxn("module$use", $$T_Met, fxn); fxn = Global.get(cap, "module$meta$init"); if (fxn != null) om.bind("ti.drivers.Config$$module$meta$init", true); if (fxn != null) po.addFxn("module$meta$init", $$T_Met, fxn); fxn = Global.get(cap, "module$validate"); if (fxn != null) om.bind("ti.drivers.Config$$module$validate", true); if (fxn != null) po.addFxn("module$validate", $$T_Met, fxn); } void Power$$TYPES() { Scriptable cap; Proto.Obj po; Proto.Str ps; Proto.Typedef pt; Object fxn; cap = (Scriptable)Global.callFxn("loadCapsule", xdcO, "ti/drivers/Power.xs"); om.bind("ti.drivers.Power$$capsule", cap); po = (Proto.Obj)om.findStrict("ti.drivers.Power.Module", "ti.drivers"); po.init("ti.drivers.Power.Module", om.findStrict("xdc.runtime.IModule.Module", "ti.drivers")); po.addFld("$hostonly", $$T_Num, 0, "r"); if (isCFG) { }//isCFG fxn = Global.get(cap, "module$use"); if (fxn != null) om.bind("ti.drivers.Power$$module$use", true); if (fxn != null) po.addFxn("module$use", $$T_Met, fxn); fxn = Global.get(cap, "module$meta$init"); if (fxn != null) om.bind("ti.drivers.Power$$module$meta$init", true); if (fxn != null) po.addFxn("module$meta$init", $$T_Met, fxn); fxn = Global.get(cap, "module$static$init"); if (fxn != null) om.bind("ti.drivers.Power$$module$static$init", true); if (fxn != null) po.addFxn("module$static$init", $$T_Met, fxn); fxn = Global.get(cap, "module$validate"); if (fxn != null) om.bind("ti.drivers.Power$$module$validate", true); if (fxn != null) po.addFxn("module$validate", $$T_Met, fxn); } void Config$$ROV() { } void Power$$ROV() { Proto.Obj po; Value.Obj vo; vo = (Value.Obj)om.findStrict("ti.drivers.Power", "ti.drivers"); } void $$SINGLETONS() { pkgP.init("ti.drivers.Package", (Proto.Obj)om.findStrict("xdc.IPackage.Module", "ti.drivers")); Scriptable cap = (Scriptable)Global.callFxn("loadCapsule", xdcO, "ti/drivers/package.xs"); om.bind("xdc.IPackage$$capsule", cap); Object fxn; fxn = Global.get(cap, "init"); if (fxn != null) pkgP.addFxn("init", (Proto.Fxn)om.findStrict("xdc.IPackage$$init", "ti.drivers"), fxn); fxn = Global.get(cap, "close"); if (fxn != null) pkgP.addFxn("close", (Proto.Fxn)om.findStrict("xdc.IPackage$$close", "ti.drivers"), fxn); fxn = Global.get(cap, "validate"); if (fxn != null) pkgP.addFxn("validate", (Proto.Fxn)om.findStrict("xdc.IPackage$$validate", "ti.drivers"), fxn); fxn = Global.get(cap, "exit"); if (fxn != null) pkgP.addFxn("exit", (Proto.Fxn)om.findStrict("xdc.IPackage$$exit", "ti.drivers"), fxn); fxn = Global.get(cap, "getLibs"); if (fxn != null) pkgP.addFxn("getLibs", (Proto.Fxn)om.findStrict("xdc.IPackage$$getLibs", "ti.drivers"), fxn); fxn = Global.get(cap, "getSects"); if (fxn != null) pkgP.addFxn("getSects", (Proto.Fxn)om.findStrict("xdc.IPackage$$getSects", "ti.drivers"), fxn); pkgP.bind("$capsule", cap); pkgV.init2(pkgP, "ti.drivers", Value.DEFAULT, false); pkgV.bind("$name", "ti.drivers"); pkgV.bind("$category", "Package"); pkgV.bind("$$qn", "ti.drivers."); pkgV.bind("$vers", Global.newArray(1, 0, 0)); Value.Map atmap = (Value.Map)pkgV.getv("$attr"); atmap.seal("length"); imports.clear(); imports.add(Global.newArray("ti.sysbios", Global.newArray())); imports.add(Global.newArray("ti.dpl", Global.newArray())); pkgV.bind("$imports", imports); StringBuilder sb = new StringBuilder(); sb.append("var pkg = xdc.om['ti.drivers'];\n"); sb.append("if (pkg.$vers.length >= 3) {\n"); sb.append("pkg.$vers.push(Packages.xdc.services.global.Vers.getDate(xdc.csd() + '/..'));\n"); sb.append("}\n"); sb.append("if ('ti.drivers$$stat$base' in xdc.om) {\n"); sb.append("pkg.packageBase = xdc.om['ti.drivers$$stat$base'];\n"); sb.append("pkg.packageRepository = xdc.om['ti.drivers$$stat$root'];\n"); sb.append("}\n"); sb.append("pkg.build.libraries = [\n"); sb.append("'lib/drivers_cc32xx.aem4',\n"); sb.append("'lib/drivers_cc32xx.am4g',\n"); sb.append("'lib/drivers_cc32xx.arm4',\n"); sb.append("];\n"); sb.append("pkg.build.libDesc = [\n"); sb.append("['lib/drivers_cc32xx.aem4', {target: 'ti.targets.arm.elf.M4', suffix: 'em4'}],\n"); sb.append("['lib/drivers_cc32xx.am4g', {target: 'gnu.targets.arm.M4', suffix: 'm4g'}],\n"); sb.append("['lib/drivers_cc32xx.arm4', {target: 'iar.targets.arm.M4', suffix: 'rm4'}],\n"); sb.append("];\n"); Global.eval(sb.toString()); } void Config$$SINGLETONS() { Proto.Obj po; Value.Obj vo; vo = (Value.Obj)om.findStrict("ti.drivers.Config", "ti.drivers"); po = (Proto.Obj)om.findStrict("ti.drivers.Config.Module", "ti.drivers"); vo.init2(po, "ti.drivers.Config", $$DEFAULT, false); vo.bind("Module", po); vo.bind("$category", "Module"); vo.bind("$capsule", om.findStrict("ti.drivers.Config$$capsule", "ti.drivers")); vo.bind("$package", om.findStrict("ti.drivers", "ti.drivers")); tdefs.clear(); proxies.clear(); mcfgs.clear(); icfgs.clear(); inherits.clear(); vo.bind("LibType", om.findStrict("ti.drivers.Config.LibType", "ti.drivers")); vo.bind("RFDriverMode", om.findStrict("ti.drivers.Config.RFDriverMode", "ti.drivers")); vo.bind("LibType_Instrumented", om.findStrict("ti.drivers.Config.LibType_Instrumented", "ti.drivers")); vo.bind("LibType_NonInstrumented", om.findStrict("ti.drivers.Config.LibType_NonInstrumented", "ti.drivers")); vo.bind("RF_MultiMode", om.findStrict("ti.drivers.Config.RF_MultiMode", "ti.drivers")); vo.bind("RF_SingleMode", om.findStrict("ti.drivers.Config.RF_SingleMode", "ti.drivers")); vo.bind("$$tdefs", Global.newArray(tdefs.toArray())); vo.bind("$$proxies", Global.newArray(proxies.toArray())); vo.bind("$$mcfgs", Global.newArray(mcfgs.toArray())); vo.bind("$$icfgs", Global.newArray(icfgs.toArray())); vo.bind("$$inherits", Global.newArray(inherits.toArray())); ((Value.Arr)pkgV.getv("$modules")).add(vo); ((Value.Arr)om.findStrict("$modules", "ti.drivers")).add(vo); vo.bind("$$instflag", 0); vo.bind("$$iobjflag", 1); vo.bind("$$sizeflag", 1); vo.bind("$$dlgflag", 0); vo.bind("$$iflag", 0); vo.bind("$$romcfgs", "|"); vo.bind("$$nortsflag", 0); Proto.Str ps = (Proto.Str)vo.find("Module_State"); if (ps != null) vo.bind("$object", ps.newInstance()); vo.bind("$$meta_iobj", om.has("ti.drivers.Config$$instance$static$init", null) ? 1 : 0); vo.bind("$$fxntab", Global.newArray()); vo.bind("$$logEvtCfgs", Global.newArray()); vo.bind("$$errorDescCfgs", Global.newArray()); vo.bind("$$assertDescCfgs", Global.newArray()); Value.Map atmap = (Value.Map)vo.getv("$attr"); atmap.seal("length"); pkgV.bind("Config", vo); ((Value.Arr)pkgV.getv("$unitNames")).add("Config"); } void Power$$SINGLETONS() { Proto.Obj po; Value.Obj vo; vo = (Value.Obj)om.findStrict("ti.drivers.Power", "ti.drivers"); po = (Proto.Obj)om.findStrict("ti.drivers.Power.Module", "ti.drivers"); vo.init2(po, "ti.drivers.Power", $$DEFAULT, false); vo.bind("Module", po); vo.bind("$category", "Module"); vo.bind("$capsule", om.findStrict("ti.drivers.Power$$capsule", "ti.drivers")); vo.bind("$package", om.findStrict("ti.drivers", "ti.drivers")); tdefs.clear(); proxies.clear(); mcfgs.clear(); icfgs.clear(); inherits.clear(); mcfgs.add("Module__diagsEnabled"); icfgs.add("Module__diagsEnabled"); mcfgs.add("Module__diagsIncluded"); icfgs.add("Module__diagsIncluded"); mcfgs.add("Module__diagsMask"); icfgs.add("Module__diagsMask"); mcfgs.add("Module__gateObj"); icfgs.add("Module__gateObj"); mcfgs.add("Module__gatePrms"); icfgs.add("Module__gatePrms"); mcfgs.add("Module__id"); icfgs.add("Module__id"); mcfgs.add("Module__loggerDefined"); icfgs.add("Module__loggerDefined"); mcfgs.add("Module__loggerObj"); icfgs.add("Module__loggerObj"); mcfgs.add("Module__loggerFxn0"); icfgs.add("Module__loggerFxn0"); mcfgs.add("Module__loggerFxn1"); icfgs.add("Module__loggerFxn1"); mcfgs.add("Module__loggerFxn2"); icfgs.add("Module__loggerFxn2"); mcfgs.add("Module__loggerFxn4"); icfgs.add("Module__loggerFxn4"); mcfgs.add("Module__loggerFxn8"); icfgs.add("Module__loggerFxn8"); mcfgs.add("Object__count"); icfgs.add("Object__count"); mcfgs.add("Object__heap"); icfgs.add("Object__heap"); mcfgs.add("Object__sizeof"); icfgs.add("Object__sizeof"); mcfgs.add("Object__table"); icfgs.add("Object__table"); vo.bind("$$tdefs", Global.newArray(tdefs.toArray())); vo.bind("$$proxies", Global.newArray(proxies.toArray())); vo.bind("$$mcfgs", Global.newArray(mcfgs.toArray())); vo.bind("$$icfgs", Global.newArray(icfgs.toArray())); inherits.add("xdc.runtime"); vo.bind("$$inherits", Global.newArray(inherits.toArray())); ((Value.Arr)pkgV.getv("$modules")).add(vo); ((Value.Arr)om.findStrict("$modules", "ti.drivers")).add(vo); vo.bind("$$instflag", 0); vo.bind("$$iobjflag", 0); vo.bind("$$sizeflag", 1); vo.bind("$$dlgflag", 0); vo.bind("$$iflag", 0); vo.bind("$$romcfgs", "|"); vo.bind("$$nortsflag", 1); if (isCFG) { Proto.Str ps = (Proto.Str)vo.find("Module_State"); if (ps != null) vo.bind("$object", ps.newInstance()); vo.bind("$$meta_iobj", 1); }//isCFG vo.bind("$$fxntab", Global.newArray("ti_drivers_Power_Module__startupDone__E")); vo.bind("$$logEvtCfgs", Global.newArray()); vo.bind("$$errorDescCfgs", Global.newArray()); vo.bind("$$assertDescCfgs", Global.newArray()); Value.Map atmap = (Value.Map)vo.getv("$attr"); atmap.setElem("", true); atmap.setElem("", ""); atmap.seal("length"); if (isCFG) { vo.put("common$", vo, Global.get((Proto.Obj)om.find("xdc.runtime.Defaults.Module"), "noRuntimeCommon$")); ((Value.Obj)vo.geto("common$")).seal(null); }//isCFG vo.bind("MODULE_STARTUP$", 0); vo.bind("PROXY$", 0); loggables.clear(); vo.bind("$$loggables", loggables.toArray()); pkgV.bind("Power", vo); ((Value.Arr)pkgV.getv("$unitNames")).add("Power"); } void $$INITIALIZATION() { Value.Obj vo; if (isCFG) { }//isCFG Global.callFxn("module$meta$init", (Scriptable)om.findStrict("ti.drivers.Config", "ti.drivers")); Global.callFxn("module$meta$init", (Scriptable)om.findStrict("ti.drivers.Power", "ti.drivers")); Global.callFxn("init", pkgV); ((Value.Obj)om.getv("ti.drivers.Config")).bless(); ((Value.Obj)om.getv("ti.drivers.Power")).bless(); ((Value.Arr)om.findStrict("$packages", "ti.drivers")).add(pkgV); } public void exec( Scriptable xdcO, Session ses ) { this.xdcO = xdcO; this.ses = ses; om = (Value.Obj)xdcO.get("om", null); Object o = om.geto("$name"); String s = o instanceof String ? (String)o : null; isCFG = s != null && s.equals("cfg"); isROV = s != null && s.equals("rov"); $$IMPORTS(); $$OBJECTS(); Config$$OBJECTS(); Power$$OBJECTS(); Config$$CONSTS(); Power$$CONSTS(); Config$$CREATES(); Power$$CREATES(); Config$$FUNCTIONS(); Power$$FUNCTIONS(); Config$$SIZES(); Power$$SIZES(); Config$$TYPES(); Power$$TYPES(); if (isROV) { Config$$ROV(); Power$$ROV(); }//isROV $$SINGLETONS(); Config$$SINGLETONS(); Power$$SINGLETONS(); $$INITIALIZATION(); } }
8,910
0
Create_ds/amazon-freertos/vendors/ti/SimpleLink_CC32xx/v2_10_00_04/source/ti/display
Create_ds/amazon-freertos/vendors/ti/SimpleLink_CC32xx/v2_10_00_04/source/ti/display/package/ti_display.java
/* * Do not modify this file; it is automatically * generated and any modifications will be overwritten. * * @(#) xdc-D28 */ import java.util.*; import org.mozilla.javascript.*; import xdc.services.intern.xsr.*; import xdc.services.spec.Session; public class ti_display { static final String VERS = "@(#) xdc-D28\n"; static final Proto.Elm $$T_Bool = Proto.Elm.newBool(); static final Proto.Elm $$T_Num = Proto.Elm.newNum(); static final Proto.Elm $$T_Str = Proto.Elm.newStr(); static final Proto.Elm $$T_Obj = Proto.Elm.newObj(); static final Proto.Fxn $$T_Met = new Proto.Fxn(null, null, 0, -1, false); static final Proto.Map $$T_Map = new Proto.Map($$T_Obj); static final Proto.Arr $$T_Vec = new Proto.Arr($$T_Obj); static final XScriptO $$DEFAULT = Value.DEFAULT; static final Object $$UNDEF = Undefined.instance; static final Proto.Obj $$Package = (Proto.Obj)Global.get("$$Package"); static final Proto.Obj $$Module = (Proto.Obj)Global.get("$$Module"); static final Proto.Obj $$Instance = (Proto.Obj)Global.get("$$Instance"); static final Proto.Obj $$Params = (Proto.Obj)Global.get("$$Params"); static final Object $$objFldGet = Global.get("$$objFldGet"); static final Object $$objFldSet = Global.get("$$objFldSet"); static final Object $$proxyGet = Global.get("$$proxyGet"); static final Object $$proxySet = Global.get("$$proxySet"); static final Object $$delegGet = Global.get("$$delegGet"); static final Object $$delegSet = Global.get("$$delegSet"); Scriptable xdcO; Session ses; Value.Obj om; boolean isROV; boolean isCFG; Proto.Obj pkgP; Value.Obj pkgV; ArrayList<Object> imports = new ArrayList<Object>(); ArrayList<Object> loggables = new ArrayList<Object>(); ArrayList<Object> mcfgs = new ArrayList<Object>(); ArrayList<Object> icfgs = new ArrayList<Object>(); ArrayList<String> inherits = new ArrayList<String>(); ArrayList<Object> proxies = new ArrayList<Object>(); ArrayList<Object> sizes = new ArrayList<Object>(); ArrayList<Object> tdefs = new ArrayList<Object>(); void $$IMPORTS() { Global.callFxn("loadPackage", xdcO, "ti.drivers"); Global.callFxn("loadPackage", xdcO, "xdc"); Global.callFxn("loadPackage", xdcO, "xdc.corevers"); } void $$OBJECTS() { pkgP = (Proto.Obj)om.bind("ti.display.Package", new Proto.Obj()); pkgV = (Value.Obj)om.bind("ti.display", new Value.Obj("ti.display", pkgP)); } void $$SINGLETONS() { pkgP.init("ti.display.Package", (Proto.Obj)om.findStrict("xdc.IPackage.Module", "ti.display")); Scriptable cap = (Scriptable)Global.callFxn("loadCapsule", xdcO, "ti/display/package.xs"); om.bind("xdc.IPackage$$capsule", cap); Object fxn; fxn = Global.get(cap, "init"); if (fxn != null) pkgP.addFxn("init", (Proto.Fxn)om.findStrict("xdc.IPackage$$init", "ti.display"), fxn); fxn = Global.get(cap, "close"); if (fxn != null) pkgP.addFxn("close", (Proto.Fxn)om.findStrict("xdc.IPackage$$close", "ti.display"), fxn); fxn = Global.get(cap, "validate"); if (fxn != null) pkgP.addFxn("validate", (Proto.Fxn)om.findStrict("xdc.IPackage$$validate", "ti.display"), fxn); fxn = Global.get(cap, "exit"); if (fxn != null) pkgP.addFxn("exit", (Proto.Fxn)om.findStrict("xdc.IPackage$$exit", "ti.display"), fxn); fxn = Global.get(cap, "getLibs"); if (fxn != null) pkgP.addFxn("getLibs", (Proto.Fxn)om.findStrict("xdc.IPackage$$getLibs", "ti.display"), fxn); fxn = Global.get(cap, "getSects"); if (fxn != null) pkgP.addFxn("getSects", (Proto.Fxn)om.findStrict("xdc.IPackage$$getSects", "ti.display"), fxn); pkgP.bind("$capsule", cap); pkgV.init2(pkgP, "ti.display", Value.DEFAULT, false); pkgV.bind("$name", "ti.display"); pkgV.bind("$category", "Package"); pkgV.bind("$$qn", "ti.display."); pkgV.bind("$vers", Global.newArray()); Value.Map atmap = (Value.Map)pkgV.getv("$attr"); atmap.seal("length"); imports.clear(); imports.add(Global.newArray("ti.drivers", Global.newArray())); pkgV.bind("$imports", imports); StringBuilder sb = new StringBuilder(); sb.append("var pkg = xdc.om['ti.display'];\n"); sb.append("if (pkg.$vers.length >= 3) {\n"); sb.append("pkg.$vers.push(Packages.xdc.services.global.Vers.getDate(xdc.csd() + '/..'));\n"); sb.append("}\n"); sb.append("if ('ti.display$$stat$base' in xdc.om) {\n"); sb.append("pkg.packageBase = xdc.om['ti.display$$stat$base'];\n"); sb.append("pkg.packageRepository = xdc.om['ti.display$$stat$root'];\n"); sb.append("}\n"); sb.append("pkg.build.libraries = [\n"); sb.append("'lib/display.aem4',\n"); sb.append("'lib/display.am4g',\n"); sb.append("'lib/display.arm4',\n"); sb.append("];\n"); sb.append("pkg.build.libDesc = [\n"); sb.append("['lib/display.aem4', {target: 'ti.targets.arm.elf.M4', suffix: 'em4'}],\n"); sb.append("['lib/display.am4g', {target: 'gnu.targets.arm.M4', suffix: 'm4g'}],\n"); sb.append("['lib/display.arm4', {target: 'iar.targets.arm.M4', suffix: 'rm4'}],\n"); sb.append("];\n"); Global.eval(sb.toString()); } void $$INITIALIZATION() { Value.Obj vo; if (isCFG) { }//isCFG Global.callFxn("init", pkgV); ((Value.Arr)om.findStrict("$packages", "ti.display")).add(pkgV); } public void exec( Scriptable xdcO, Session ses ) { this.xdcO = xdcO; this.ses = ses; om = (Value.Obj)xdcO.get("om", null); Object o = om.geto("$name"); String s = o instanceof String ? (String)o : null; isCFG = s != null && s.equals("cfg"); isROV = s != null && s.equals("rov"); $$IMPORTS(); $$OBJECTS(); if (isROV) { }//isROV $$SINGLETONS(); $$INITIALIZATION(); } }
8,911
0
Create_ds/s2n-quic/netbench/cdk/src/test/java/com
Create_ds/s2n-quic/netbench/cdk/src/test/java/com/aws/VpcStackTest.java
package com.aws; import software.amazon.awscdk.App; import software.amazon.awscdk.assertions.Template; import java.io.IOException; import org.junit.jupiter.api.Test; import java.util.HashMap; import software.amazon.awscdk.Environment; import java.util.List; import java.util.Map; /* Unit testing for VpcStack, tests for key properties * in the cloudformation output of the stack. * Some empty maps and lists can be found to match * any value for fields in the Cloudformation output with * unimportant information. * More extensive tests are performed through deployments * of various scenarios and verifying outputs. */ public class VpcStackTest { private String cidr; private String region; private Template template; private VpcStack vpcStack; public VpcStackTest() { App app = new App(); cidr = "11.0.0.0/16"; region = "us-west-2"; vpcStack = new VpcStack(app, "VpcStack", VpcStackProps.builder() .env(makeEnv(System.getenv("CDK_DEFAULT_ACCOUNT"), region)) .cidr(cidr) .build()); template = Template.fromStack(vpcStack); } @Test public void testStack() throws IOException { //Check Vpc template.hasResourceProperties("AWS::EC2::VPC", new HashMap<String, Object>() {{ put("CidrBlock", cidr); put("EnableDnsHostnames", true); put("EnableDnsSupport", true); }}); //Check private VPC subnet template.hasResourceProperties("AWS::EC2::Subnet", new HashMap<String, Object>() {{ put("Tags", List.of( Map.of("Key", "aws-cdk:subnet-name", "Value", "Private"), Map.of(), Map.of() )); }}); //Check S3 Endpoint template.hasResourceProperties("AWS::EC2::VPCEndpoint", new HashMap<String, Object>() {{ put("ServiceName", Map.of("Fn::Join", List.of("", List.of("com.amazonaws.", Map.of("Ref", "AWS::Region"), ".s3")))); put("VpcEndpointType", "Gateway"); }}); //Check security group template.hasResourceProperties("AWS::EC2::SecurityGroupIngress", new HashMap<String, Object>() {{ put("CidrIp", "0.0.0.0/0"); }}); //Check S3 bucket template.hasResource("AWS::S3::Bucket", new HashMap<String, Object>() {{ put("DeletionPolicy", "Retain"); }}); } static Environment makeEnv(String account, String region) { return Environment.builder() .account(account) .region(region) .build(); } }
8,912
0
Create_ds/s2n-quic/netbench/cdk/src/test/java/com
Create_ds/s2n-quic/netbench/cdk/src/test/java/com/aws/ServerEcsStackTest.java
package com.aws; import software.amazon.awscdk.App; import software.amazon.awscdk.assertions.Template; import java.io.IOException; import org.junit.jupiter.api.Test; import java.util.HashMap; import software.amazon.awscdk.Environment; import java.util.List; import java.util.Map; /* Unit testing for ServerEcsStack, tests for key properties * in the cloudformation output of the stack. * Some empty maps and lists can be found to match * any value for fields in the Cloudformation output with * unimportant information. * More extensive tests are performed through deployments * of various scenarios and verifying outputs. */ public class ServerEcsStackTest { private String cidr; private String region; private String instanceType; private String ecrUri; private String scenarioFile; private Template serverTemplate; private Template vpcTemplate; private EcsStack serverEcsStack; private VpcStack vpcStack; private String arm; public ServerEcsStackTest() { App app = new App(); cidr = "11.0.0.0/16"; region = "us-west-2"; instanceType = "t4g.xlarge"; ecrUri = "public.ecr.aws/d2r9y8c2/s2n-quic-collector-server-scenario"; scenarioFile = "/usr/bin/request_response.json"; arm = "true"; vpcStack = new VpcStack(app, "VpcStack", VpcStackProps.builder() .env(makeEnv(System.getenv("CDK_DEFAULT_ACCOUNT"), region)) .cidr(cidr) .build()); serverEcsStack = new EcsStack(app, "ServerEcsStack", EcsStackProps.builder() .env(makeEnv(System.getenv("CDK_DEFAULT_ACCOUNT"), region)) .bucket(vpcStack.getBucket()) .stackType("server") .vpc(vpcStack.getVpc()) .instanceType(instanceType) .ecrUri(ecrUri) .scenario(scenarioFile) .serverRegion(region) .arm(arm) .build()); serverTemplate = Template.fromStack(serverEcsStack); vpcTemplate = Template.fromStack(vpcStack); } @Test public void testServerStack() throws IOException { //Security Group serverTemplate.hasResourceProperties("AWS::EC2::SecurityGroup", new HashMap<String, Object>() {{ put("SecurityGroupEgress", List.of(Map.of("CidrIp", "0.0.0.0/0", "Description", "Allow all outbound traffic by default","IpProtocol", "-1"))); put("SecurityGroupIngress", List.of(Map.of("CidrIp", "0.0.0.0/0", "Description", "from 0.0.0.0/0:ALL TRAFFIC","IpProtocol", "-1"))); }}); //Cluster serverTemplate.hasResource("AWS::ECS::Cluster", new HashMap<String, Object>() {{ put("DeletionPolicy", "Delete"); }}); //Launch config serverTemplate.hasResourceProperties("AWS::AutoScaling::LaunchConfiguration", new HashMap<String, Object>() {{ put("InstanceType", instanceType); }}); //Autoscaling group serverTemplate.hasResourceProperties("AWS::AutoScaling::AutoScalingGroup", new HashMap<String, Object>() {{ put("DesiredCapacity", "1"); put("MinSize", "0"); }}); //Asg Provider serverTemplate.hasResourceProperties("AWS::ECS::CapacityProvider", new HashMap<String, Object>() {{ put("AutoScalingGroupProvider", Map.of("ManagedTerminationProtection","DISABLED")); }}); //Task Definition serverTemplate.hasResourceProperties("AWS::ECS::TaskDefinition", new HashMap<String, Object>() {{ put("ContainerDefinitions", List.of(Map.of( "Environment", List.of(Map.of("Name", "PORT", "Value", "3000"), Map.of("Name", "SCENARIO", "Value", scenarioFile)), "PortMappings", List.of(Map.of("ContainerPort", 3000, "HostPort", 3000, "Protocol", "udp")), "Image", ecrUri, "LogConfiguration", Map.of("LogDriver", "awslogs", "Options", Map.of( "awslogs-stream-prefix", "server-ecs-task"))) )); put("NetworkMode", "awsvpc"); }}); //Server task policy to access metrics s3 bucket serverTemplate.hasResourceProperties("AWS::IAM::Policy", new HashMap<String, Object>() {{ put("PolicyDocument", Map.of("Statement", List.of(Map.of("Action", List.of( "s3:DeleteObject*", "s3:PutObject", "s3:PutObjectLegalHold", "s3:PutObjectRetention", "s3:PutObjectTagging", "s3:PutObjectVersionTagging", "s3:Abort*"), "Effect", "Allow", "Resource", List.of(Map.of(), Map.of()))), "Version", "2012-10-17")); }}); //Server task policy can send logs to Cloudwatch serverTemplate.hasResourceProperties("AWS::IAM::Policy", new HashMap<String, Object>() {{ put("PolicyDocument", Map.of("Statement", List.of(Map.of("Action", List.of( "logs:CreateLogStream", "logs:PutLogEvents"), "Effect", "Allow", "Resource", Map.of())))); }}); //Namespace serverTemplate.hasResourceProperties("AWS::ServiceDiscovery::PrivateDnsNamespace", new HashMap<String, Object>() {{ put("Name", "serverecs.com"); }}); //LogGroup serverTemplate.hasResource("AWS::Logs::LogGroup", new HashMap<String, Object>() {{ put("Properties", Map.of("RetentionInDays", 1)); }}); //Export lambda function serverTemplate.hasResourceProperties("AWS::Lambda::Function", new HashMap<String, Object>() {{ put("Handler", "exportS3.handler"); put("Runtime", "nodejs14.x"); }}); //Export lambda policy permissions serverTemplate.hasResourceProperties("AWS::IAM::Policy", new HashMap<String, Object>() {{ put("PolicyDocument", Map.of("Statement", List.of( Map.of("Action", "logs:CreateExportTask", "Effect", "Allow"), Map.of("Action", List.of("s3:GetObject*", "s3:GetBucket*", "s3:List*", "s3:DeleteObject*", "s3:PutObject", "s3:PutObjectLegalHold", "s3:PutObjectRetention", "s3:PutObjectTagging", "s3:PutObjectVersionTagging", "s3:Abort*"), "Effect", "Allow") ))); }}); //Log Retention serverTemplate.hasResourceProperties("Custom::LogRetention", new HashMap<String, Object>() {{ put("RetentionInDays", 1); }}); //ECS Service serverTemplate.hasResourceProperties("AWS::ECS::Service", new HashMap<String, Object>() {{ put("CapacityProviderStrategy", List.of(Map.of("CapacityProvider", Map.of()))); put("DesiredCount", 1); put("NetworkConfiguration", Map.of("AwsvpcConfiguration", Map.of())); }}); //Service Discovery serverTemplate.hasResourceProperties("AWS::ServiceDiscovery::Service", new HashMap<String, Object>() {{ put("DnsConfig", Map.of("DnsRecords", List.of(Map.of("TTL", 60, "Type", "A")))); put ("Name", "ec2serviceserverCloudmapSrv-UEyneXTpp1nx"); }}); //Check bucket policy changed by export lambda vpcTemplate.hasResourceProperties("AWS::S3::BucketPolicy", new HashMap<String, Object>() {{ put("PolicyDocument", Map.of( "Statement", List.of( Map.of("Action", List.of( "s3:PutObject","s3:PutObjectLegalHold", "s3:PutObjectRetention","s3:PutObjectTagging", "s3:PutObjectVersionTagging","s3:Abort*"), "Effect", "Allow", "Principal", Map.of("Service", "logs.us-west-2.amazonaws.com")), Map.of("Action", "s3:GetBucketAcl", "Effect", "Allow", "Principal", Map.of("Service", "logs.us-west-2.amazonaws.com")) ))); }}); } static Environment makeEnv(String account, String region) { return Environment.builder() .account(account) .region(region) .build(); } }
8,913
0
Create_ds/s2n-quic/netbench/cdk/src/test/java/com
Create_ds/s2n-quic/netbench/cdk/src/test/java/com/aws/StateMachineStackTest.java
package com.aws; import software.amazon.awscdk.App; import software.amazon.awscdk.assertions.Template; import java.io.IOException; import org.junit.jupiter.api.Test; import java.util.HashMap; import software.amazon.awscdk.Environment; import java.util.List; import java.util.Map; /* Unit testing for StateMachineStack, tests for key properties * in the cloudformation output of the stack. * Some empty maps and lists can be found to match * any value for fields in the Cloudformation output with * unimportant information. * More extensive tests are performed through deployments * of various scenarios and verifying outputs. */ public class StateMachineStackTest { private String cidr; private String region; private String instanceType; private String serverEcrUri; private String clientEcrUri; private String scenarioFile; private Template smTemplate; private EcsStack clientEcsStack; private EcsStack serverEcsStack; private VpcStack vpcStack; private StateMachineStack stateMachineStack; private String protocol; private String arm; public StateMachineStackTest() { App app = new App(); protocol = "s2n-quic"; cidr = "11.0.0.0/16"; region = "us-west-2"; instanceType = "t4g.xlarge"; serverEcrUri = "public.ecr.aws/d2r9y8c2/s2n-quic-collector-server-scenario"; clientEcrUri = "public.ecr.aws/d2r9y8c2/s2n-quic-collector-client-scenario"; scenarioFile = "/usr/bin/request_response.json"; arm = "arm"; vpcStack = new VpcStack(app, "VpcStack", VpcStackProps.builder() .env(makeEnv(System.getenv("CDK_DEFAULT_ACCOUNT"), region)) .cidr(cidr) .build()); serverEcsStack = new EcsStack(app, "ServerEcsStack", EcsStackProps.builder() .env(makeEnv(System.getenv("CDK_DEFAULT_ACCOUNT"), region)) .bucket(vpcStack.getBucket()) .stackType("server") .vpc(vpcStack.getVpc()) .instanceType(instanceType) .ecrUri(serverEcrUri) .scenario(scenarioFile) .serverRegion(region) .arm(arm) .build()); clientEcsStack = new EcsStack(app, "ClientEcsStack", EcsStackProps.builder() .env(makeEnv(System.getenv("CDK_DEFAULT_ACCOUNT"), region)) .bucket(vpcStack.getBucket()) .stackType("client") .vpc(vpcStack.getVpc()) .instanceType(instanceType) .serverRegion(region) .dnsAddress(serverEcsStack.getDnsAddress()) .ecrUri(clientEcrUri) .scenario(scenarioFile) .arm(arm) .build()); stateMachineStack = new StateMachineStack(app, "StateMachineStack", StateMachineStackProps.builder() .env(makeEnv(System.getenv("CDK_DEFAULT_ACCOUNT"), region)) .clientTask(clientEcsStack.getEcsTask()) .bucket(vpcStack.getBucket()) .logsLambda(serverEcsStack.getLogsLambda()) .cluster(clientEcsStack.getCluster()) .protocol(protocol) .build()); smTemplate = Template.fromStack(stateMachineStack); } @Test public void testStack() throws IOException { //Timestamp function smTemplate.hasResourceProperties("AWS::Lambda::Function", new HashMap<String, Object>() {{ put("Handler", "timestamp.handler"); put("Runtime", "nodejs14.x"); }}); //Log retention for timestamp function smTemplate.hasResourceProperties("Custom::LogRetention", new HashMap<String, Object>() {{ put("RetentionInDays", 1); }}); //Report Generation Task smTemplate.hasResourceProperties("AWS::ECS::TaskDefinition", new HashMap<String, Object>() {{ put("ContainerDefinitions", List.of(Map.of( "Environment", List.of(Map.of(), Map.of("Name", "PROTOCOL", "Value", "s2n-quic")), "Name", "report-generation" ))); }}); //Report Generation Task Policy smTemplate.hasResourceProperties("AWS::IAM::Policy", new HashMap<String, Object>() {{ put("PolicyDocument", Map.of("Statement", List.of( Map.of("Action", "logs:DescribeExportTasks", "Effect", "Allow", "Resource", "*"), Map.of("Action", List.of("s3:GetObject*", "s3:GetBucket*", "s3:List*", "s3:DeleteObject*", "s3:PutObject", "s3:PutObjectLegalHold", "s3:PutObjectRetention", "s3:PutObjectTagging", "s3:PutObjectVersionTagging", "s3:Abort*"), "Effect", "Allow") ))); }}); //State Machine smTemplate.hasResourceProperties("AWS::StepFunctions::StateMachine", new HashMap<String, Object>() {{}}); } static Environment makeEnv(String account, String region) { return Environment.builder() .account(account) .region(region) .build(); } }
8,914
0
Create_ds/s2n-quic/netbench/cdk/src/test/java/com
Create_ds/s2n-quic/netbench/cdk/src/test/java/com/aws/ClientEcsStackTest.java
package com.aws; import software.amazon.awscdk.App; import software.amazon.awscdk.assertions.Template; import java.io.IOException; import org.junit.jupiter.api.Test; import java.util.HashMap; import software.amazon.awscdk.Environment; import java.util.List; import java.util.Map; /* Unit testing for ClientEcsStack, tests for key properties * in the cloudformation output of the stack. * Some empty maps and lists can be found to match * any value for fields in the Cloudformation output with * unimportant information. * More extensive tests are performed through deployments * of various scenarios and verifying outputs. */ public class ClientEcsStackTest { private String cidr; private String region; private String instanceType; private String serverEcrUri; private String clientEcrUri; private String scenarioFile; private Template clientTemplate; private EcsStack clientEcsStack; private EcsStack serverEcsStack; private VpcStack vpcStack; private String arm; public ClientEcsStackTest() { App app = new App(); cidr = "11.0.0.0/16"; region = "us-west-2"; instanceType = "t4g.xlarge"; serverEcrUri = "public.ecr.aws/d2r9y8c2/s2n-quic-collector-server-scenario"; clientEcrUri = "public.ecr.aws/d2r9y8c2/s2n-quic-collector-client-scenario"; scenarioFile = "/usr/bin/request_response.json"; arm = "true"; vpcStack = new VpcStack(app, "VpcStack", VpcStackProps.builder() .env(makeEnv(System.getenv("CDK_DEFAULT_ACCOUNT"), region)) .cidr(cidr) .build()); serverEcsStack = new EcsStack(app, "ServerEcsStack", EcsStackProps.builder() .env(makeEnv(System.getenv("CDK_DEFAULT_ACCOUNT"), region)) .bucket(vpcStack.getBucket()) .stackType("server") .vpc(vpcStack.getVpc()) .instanceType(instanceType) .ecrUri(serverEcrUri) .scenario(scenarioFile) .serverRegion(region) .arm(arm) .build()); clientEcsStack = new EcsStack(app, "ClientEcsStack", EcsStackProps.builder() .env(makeEnv(System.getenv("CDK_DEFAULT_ACCOUNT"), region)) .bucket(vpcStack.getBucket()) .stackType("client") .vpc(vpcStack.getVpc()) .instanceType(instanceType) .serverRegion(region) .dnsAddress(serverEcsStack.getDnsAddress()) .ecrUri(clientEcrUri) .scenario(scenarioFile) .arm(arm) .build()); clientTemplate = Template.fromStack(clientEcsStack); } @Test public void testStack() throws IOException { //Security Group clientTemplate.hasResourceProperties("AWS::EC2::SecurityGroup", new HashMap<String, Object>() {{ put("SecurityGroupEgress", List.of(Map.of("CidrIp", "0.0.0.0/0", "Description", "Allow all outbound traffic by default","IpProtocol", "-1"))); put("SecurityGroupIngress", List.of(Map.of("CidrIp", "0.0.0.0/0", "Description", "from 0.0.0.0/0:ALL TRAFFIC","IpProtocol", "-1"))); }}); //Cluster clientTemplate.hasResource("AWS::ECS::Cluster", new HashMap<String, Object>() {{ put("DeletionPolicy", "Delete"); }}); //Autoscaling group clientTemplate.hasResourceProperties("AWS::AutoScaling::AutoScalingGroup", new HashMap<String, Object>() {{ put("DesiredCapacity", "1"); put("MinSize", "0"); }}); //Asg Provider clientTemplate.hasResourceProperties("AWS::ECS::CapacityProvider", new HashMap<String, Object>() {{ put("AutoScalingGroupProvider", Map.of("ManagedTerminationProtection","DISABLED")); }}); //Launch Configuration clientTemplate.hasResourceProperties("AWS::AutoScaling::LaunchConfiguration", new HashMap<String, Object>() {{ put("InstanceType", instanceType); }}); //Task Definition clientTemplate.hasResourceProperties("AWS::ECS::TaskDefinition", new HashMap<String, Object>() {{ put("ContainerDefinitions", List.of(Map.of( "Environment", List.of(Map.of("Name", "SERVER_PORT", "Value", "3000"), Map.of("Name", "S3_BUCKET", "Value", Map.of()), Map.of("Name", "PORT", "Value", "3000"), Map.of("Name", "LOCAL_IP", "Value", "0.0.0.0"), Map.of("Name", "SCENARIO", "Value", "/usr/bin/request_response.json"), Map.of("Name", "DNS_ADDRESS", "Value", "ec2serviceserverCloudmapSrv-UEyneXTpp1nx.serverecs.com")), "PortMappings", List.of(Map.of("ContainerPort", 3000, "HostPort", 3000, "Protocol", "udp")), "LogConfiguration", Map.of("LogDriver", "awslogs")) )); put("NetworkMode", "awsvpc"); }}); //Client task policy to access metrics s3 bucket clientTemplate.hasResourceProperties("AWS::IAM::Policy", new HashMap<String, Object>() {{ put("PolicyDocument", Map.of("Statement", List.of(Map.of("Action", List.of( "s3:DeleteObject*", "s3:PutObject", "s3:PutObjectLegalHold", "s3:PutObjectRetention", "s3:PutObjectTagging", "s3:PutObjectVersionTagging", "s3:Abort*"), "Effect", "Allow", "Resource", List.of(Map.of(), Map.of()))), "Version", "2012-10-17")); }}); //Client task policy can send logs to Cloudwatch clientTemplate.hasResourceProperties("AWS::IAM::Policy", new HashMap<String, Object>() {{ put("PolicyDocument", Map.of("Statement", List.of(Map.of("Action", List.of( "logs:CreateLogStream", "logs:PutLogEvents"), "Effect", "Allow", "Resource", Map.of())))); }}); //LogGroup clientTemplate.hasResourceProperties("AWS::Logs::LogGroup", new HashMap<String, Object>() {{ put("RetentionInDays", 1); }}); } static Environment makeEnv(String account, String region) { return Environment.builder() .account(account) .region(region) .build(); } }
8,915
0
Create_ds/s2n-quic/netbench/cdk/src/main/java/com
Create_ds/s2n-quic/netbench/cdk/src/main/java/com/aws/StateMachineStackProps.java
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.aws; import software.amazon.awscdk.StackProps; import software.amazon.awscdk.Environment; import software.amazon.awscdk.services.stepfunctions.tasks.EcsRunTask; import software.amazon.awscdk.services.s3.Bucket; import software.amazon.awscdk.services.lambda.Function; import software.amazon.awscdk.services.ecs.Cluster; public interface StateMachineStackProps extends StackProps { public static Builder builder() { return new Builder(); } EcsRunTask getClientTask(); Bucket getBucket(); Function getLogsLambda(); Cluster getCluster(); String getProtocol(); public static class Builder { private EcsRunTask clientTask; private Environment env; private Bucket bucket; private Function logsLambda; private Cluster cluster; private String protocol; public Builder clientTask(EcsRunTask clientTask) { this.clientTask = clientTask; return this; } public Builder env(Environment env) { this.env = env; return this; } public Builder bucket(Bucket bucket) { this.bucket = bucket; return this; } public Builder logsLambda(Function logsLambda) { this.logsLambda = logsLambda; return this; } public Builder cluster(Cluster cluster) { this.cluster = cluster; return this; } public Builder protocol(String protocol) { this.protocol = protocol; return this; } public StateMachineStackProps build() { return new StateMachineStackProps() { @Override public EcsRunTask getClientTask() { return clientTask; } @Override public Environment getEnv() { return env; } @Override public Bucket getBucket() { return bucket; } @Override public Function getLogsLambda() { return logsLambda; } @Override public Cluster getCluster() { return cluster; } @Override public String getProtocol() { return protocol; } }; } } }
8,916
0
Create_ds/s2n-quic/netbench/cdk/src/main/java/com
Create_ds/s2n-quic/netbench/cdk/src/main/java/com/aws/PeeringStackProps.java
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.aws; import software.amazon.awscdk.StackProps; import software.amazon.awscdk.Environment; import software.amazon.awscdk.services.ec2.Vpc; public interface PeeringStackProps extends StackProps { static Builder builder() { return new Builder(); } Vpc getVpcClient(); Vpc getVpcServer(); String getStackType(); String getRef(); String getCidr(); String getRegion(); class Builder { private Vpc vpcClient; private Vpc vpcServer; private Environment env; private String stackType; private String ref; private String cidr; private String region; public Builder VpcClient(Vpc vpcClient) { this.vpcClient = vpcClient; return this; } public Builder VpcServer(Vpc vpcServer) { this.vpcServer = vpcServer; return this; } public Builder env(Environment env) { this.env = env; return this; } public Builder stackType(String stackType) { this.stackType = stackType; return this; } public Builder ref(String ref) { this.ref = ref; return this; } public Builder cidr(String cidr) { this.cidr = cidr; return this; } public Builder region(String region) { this.region = region; return this; } public PeeringStackProps build() { return new PeeringStackProps() { @Override public Vpc getVpcClient() { return vpcClient; } @Override public Vpc getVpcServer() { return vpcServer; } @Override public Environment getEnv() { return env; } @Override public String getStackType() { return stackType; } @Override public String getRef() { return ref; } @Override public String getCidr() { return cidr; } @Override public String getRegion() { return region; } }; } } }
8,917
0
Create_ds/s2n-quic/netbench/cdk/src/main/java/com
Create_ds/s2n-quic/netbench/cdk/src/main/java/com/aws/PeeringConnectionStack.java
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.aws; import software.amazon.awscdk.Stack; import software.amazon.awscdk.services.ec2.CfnRoute; import software.amazon.awscdk.services.ec2.CfnVPCPeeringConnection; import software.amazon.awscdk.services.ec2.ISubnet; import software.amazon.awscdk.services.ssm.StringParameter; import software.constructs.Construct; class PeeringConnectionStack extends Stack { private String ref; public PeeringConnectionStack(final Construct parent, final String id, final PeeringStackProps props) { super(parent, id, props); String stackType = props.getStackType(); int counter = 1; if (stackType.equals("server")) { String serverVpcId = StringParameter.fromStringParameterName(this, "server-vpc-id", "server-vpc-id").getStringValue(); String clientVpcId = new SSMParameterReader(this, "client-vpc-id-reader", SSMParameterReaderProps.builder() .sdkCall("client-vpc-id", props.getRegion()) .policy() .build()) .getParameterValue(); String cidr = new SSMParameterReader(this, "client-cidr-reader", SSMParameterReaderProps.builder() .sdkCall("client-cidr", props.getRegion()) .policy() .build()) .getParameterValue(); //Vpc peering connection between client-server vpc's CfnVPCPeeringConnection conn = CfnVPCPeeringConnection.Builder .create(this, "vpc-peering-connection") .vpcId(serverVpcId) .peerVpcId(clientVpcId) .peerRegion(props.getRegion()) .build(); //Establishing server-to-client connections between private subnets for (ISubnet subnet: props.getVpcServer().getPrivateSubnets()) { CfnRoute.Builder.create(this, "server-to-client" + Integer.toString(counter)) .destinationCidrBlock(cidr) .routeTableId(subnet.getRouteTable().getRouteTableId()) .vpcPeeringConnectionId(conn.getRef()) .build(); counter++; } StringParameter.Builder.create(this, "conn-ref") .parameterName("conn-ref") .stringValue(conn.getRef()) .build(); } else { String cidr = new SSMParameterReader(this, "server-cidr-reader", SSMParameterReaderProps.builder() .sdkCall("server-cidr", props.getRegion()) .policy() .build()) .getParameterValue(); String connRef = new SSMParameterReader(this, "conn-ref-reader", SSMParameterReaderProps.builder() .sdkCall("conn-ref", props.getRegion()) .policy() .build()) .getParameterValue(); //Establishing client-to-server connections between private subnets for (ISubnet subnet: props.getVpcClient().getPrivateSubnets()) { CfnRoute.Builder.create(this, "client-to-server" + Integer.toString(counter)) .destinationCidrBlock(cidr) .routeTableId(subnet.getRouteTable().getRouteTableId()) .vpcPeeringConnectionId(connRef) .build(); counter++; } } } public String getRef() { return this.ref; } }
8,918
0
Create_ds/s2n-quic/netbench/cdk/src/main/java/com
Create_ds/s2n-quic/netbench/cdk/src/main/java/com/aws/VpcStack.java
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.aws; import software.constructs.Construct; import software.amazon.awscdk.PhysicalName; import software.amazon.awscdk.RemovalPolicy; import software.amazon.awscdk.Stack; import software.amazon.awscdk.services.ec2.Vpc; import software.amazon.awscdk.services.ec2.GatewayVpcEndpoint; import software.amazon.awscdk.services.ec2.GatewayVpcEndpointAwsService; import software.amazon.awscdk.services.ec2.GatewayVpcEndpointOptions; import software.amazon.awscdk.services.ec2.Peer; import software.amazon.awscdk.services.ec2.Port; import software.amazon.awscdk.services.ec2.SecurityGroup; import software.amazon.awscdk.services.s3.Bucket; public class VpcStack extends Stack { private final Vpc vpc; private Bucket metricsBucket; public VpcStack(final Construct parent, final String id, final VpcStackProps props) { super(parent, id, props); String cidr = props.getCidr(); //All construct names are for descriptive purposes only this.vpc = Vpc.Builder.create(this, "client-server-vpc") .maxAzs(1) .enableDnsSupport(true) .enableDnsHostnames(true) .cidr(cidr) .build(); SecurityGroup.fromSecurityGroupId(this, "vpc-sec-group", this.vpc.getVpcDefaultSecurityGroup()) .addIngressRule(Peer.anyIpv4(), Port.allTraffic()); GatewayVpcEndpoint s3Endpoint = this.vpc.addGatewayEndpoint("s3-endpoint", GatewayVpcEndpointOptions.builder() .service(GatewayVpcEndpointAwsService.S3) .build()); metricsBucket = Bucket.Builder.create(this, "MetricsReportBucket") .bucketName(PhysicalName.GENERATE_IF_NEEDED) .removalPolicy(RemovalPolicy.RETAIN) .build(); } public Vpc getVpc() { return this.vpc; } public Bucket getBucket() { return metricsBucket; } }
8,919
0
Create_ds/s2n-quic/netbench/cdk/src/main/java/com
Create_ds/s2n-quic/netbench/cdk/src/main/java/com/aws/NetbenchAutoApp.java
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.aws; import software.amazon.awscdk.App; import software.amazon.awscdk.Environment; import software.amazon.awscdk.regioninfo.Fact; import java.lang.IllegalArgumentException; import java.util.HashSet; import java.util.Set; public class NetbenchAutoApp { // Helper method to build an environment static Environment makeEnv(String account, String region) { return Environment.builder() .account(account) .region(region) .build(); } public static void main(final String[] args) { App app = new App(); Set<String> awsRegions = new HashSet<>(Fact.getRegions()); // Context variable default values and validation String protocol = (String)app.getNode().tryGetContext("protocol"); protocol = (protocol == null) ? "s2n-quic" : protocol.toLowerCase(); if (!protocol.equals("s2n-quic")) { throw new IllegalArgumentException("Invalid protocol, only s2n-quic is currently supported."); } String awsAccount = (String)app.getNode().tryGetContext("aws-account"); awsAccount = (awsAccount == null) ? System.getenv("CDK_DEFAULT_ACCOUNT") : awsAccount; String clientRegion = (String)app.getNode().tryGetContext("client-region"); clientRegion = (clientRegion == null) ? System.getenv("CDK_DEFAULT_REGION") : clientRegion.toLowerCase(); if (!awsRegions.contains(clientRegion)) { throw new IllegalArgumentException("Invalid client region."); } String serverRegion = (String)app.getNode().tryGetContext("server-region"); serverRegion = (serverRegion == null) ? System.getenv("CDK_DEFAULT_REGION") : serverRegion.toLowerCase(); if (!awsRegions.contains(serverRegion)) { throw new IllegalArgumentException("Invalid server region."); } String ec2InstanceType = (String)app.getNode().tryGetContext("instance-type"); ec2InstanceType = (ec2InstanceType == null) ? "t4g.xlarge" : ec2InstanceType.toLowerCase(); String serverEcrUri = (String)app.getNode().tryGetContext("server-ecr-uri"); serverEcrUri = (serverEcrUri == null) ? "public.ecr.aws/d2r9y8c2/s2n-quic-collector-server-scenario:latest" : serverEcrUri; String clientEcrUri = (String)app.getNode().tryGetContext("client-ecr-uri"); clientEcrUri = (clientEcrUri == null) ? "public.ecr.aws/d2r9y8c2/s2n-quic-collector-client-scenario:latest" : clientEcrUri; String scenarioFile = (String)app.getNode().tryGetContext("scenario"); scenarioFile = (scenarioFile == null) ? "/usr/bin/request_response.json" : scenarioFile; String arm = (String)app.getNode().tryGetContext("arm"); arm = (arm == null) ? "true" : arm.toLowerCase(); if (!arm.equals("true") && !arm.equals("false")) { throw new IllegalArgumentException("arm must be true or false."); } // Stack instantiation VpcStack vpcStack = new VpcStack(app, "VpcStack", VpcStackProps.builder() .env(makeEnv(awsAccount, serverRegion)) .cidr("11.0.0.0/16") .build()); EcsStack serverEcsStack = new EcsStack(app, "ServerEcsStack", EcsStackProps.builder() .env(makeEnv(awsAccount, serverRegion)) .bucket(vpcStack.getBucket()) .stackType("server") .vpc(vpcStack.getVpc()) .instanceType(ec2InstanceType) .ecrUri(serverEcrUri) .scenario(scenarioFile) .serverRegion(serverRegion) .arm(arm) .build()); serverEcsStack.addDependency(vpcStack); EcsStack clientEcsStack = new EcsStack(app, "ClientEcsStack", EcsStackProps.builder() .env(makeEnv(awsAccount, clientRegion)) .bucket(vpcStack.getBucket()) .stackType("client") .vpc(vpcStack.getVpc()) .instanceType(ec2InstanceType) .serverRegion(serverRegion) .dnsAddress(serverEcsStack.getDnsAddress()) .ecrUri(clientEcrUri) .scenario(scenarioFile) .arm(arm) .build()); clientEcsStack.addDependency(serverEcsStack); StateMachineStack stateMachineStack = new StateMachineStack(app, "StateMachineStack", StateMachineStackProps.builder() .env(makeEnv(awsAccount, clientRegion)) .clientTask(clientEcsStack.getEcsTask()) .bucket(vpcStack.getBucket()) .logsLambda(serverEcsStack.getLogsLambda()) .cluster(clientEcsStack.getCluster()) .protocol(protocol) .build()); stateMachineStack.addDependency(clientEcsStack); app.synth(); } }
8,920
0
Create_ds/s2n-quic/netbench/cdk/src/main/java/com
Create_ds/s2n-quic/netbench/cdk/src/main/java/com/aws/EcsStack.java
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.aws; import software.constructs.Construct; import software.amazon.awscdk.RemovalPolicy; import software.amazon.awscdk.Stack; import software.amazon.awscdk.services.s3.Bucket; import software.amazon.awscdk.services.autoscaling.AutoScalingGroup; import software.amazon.awscdk.services.servicediscovery.DnsRecordType; import software.amazon.awscdk.services.servicediscovery.PrivateDnsNamespace; import software.amazon.awscdk.services.ecs.Cluster; import software.amazon.awscdk.services.ecs.ContainerImage; import software.amazon.awscdk.services.ecs.EcsOptimizedImage; import software.amazon.awscdk.services.ecs.AsgCapacityProvider; import software.amazon.awscdk.services.ecs.Ec2TaskDefinition; import software.amazon.awscdk.services.ecs.ContainerDefinitionOptions; import software.amazon.awscdk.services.ecs.Ec2Service; import software.amazon.awscdk.services.ecs.CapacityProviderStrategy; import software.amazon.awscdk.services.ecs.NetworkMode; import software.amazon.awscdk.services.ecs.PortMapping; import software.amazon.awscdk.services.ecs.AmiHardwareType; import software.amazon.awscdk.services.ecs.CloudMapOptions; import software.amazon.awscdk.services.ecs.AwsLogDriverProps; import software.amazon.awscdk.services.ecs.LogDriver; import software.amazon.awscdk.services.ecs.ContainerDefinition; import software.amazon.awscdk.services.logs.LogGroup; import software.amazon.awscdk.services.logs.RetentionDays; import software.amazon.awscdk.services.lambda.Function; import software.amazon.awscdk.services.lambda.Runtime; import software.amazon.awscdk.services.lambda.Code; import software.amazon.awscdk.services.stepfunctions.tasks.EcsRunTask; import software.amazon.awscdk.services.stepfunctions.IntegrationPattern; import software.amazon.awscdk.services.stepfunctions.tasks.EcsEc2LaunchTarget; import software.amazon.awscdk.services.stepfunctions.tasks.ContainerOverride; import software.amazon.awscdk.services.iam.PolicyStatement; import software.amazon.awscdk.services.iam.Effect; import software.amazon.awscdk.services.iam.ServicePrincipal; import software.amazon.awscdk.services.iam.ArnPrincipal; import software.amazon.awscdk.services.stepfunctions.tasks.TaskEnvironmentVariable; import software.amazon.awscdk.services.stepfunctions.JsonPath; import software.amazon.awscdk.services.ec2.Vpc; import software.amazon.awscdk.services.ec2.InstanceType; import software.amazon.awscdk.services.ec2.SecurityGroup; import software.amazon.awscdk.services.ec2.Peer; import software.amazon.awscdk.services.ec2.Port; import java.util.HashMap; import java.util.Map; import java.util.List; import java.util.Date; import java.text.SimpleDateFormat; class EcsStack extends Stack { private String dnsAddress; private EcsRunTask ecsTask; private Function exportLogsLambda; private Cluster cluster; private static final String bucketName = "BUCKET_NAME"; private static final String logGroupName = "LOG_GROUP_NAME"; public EcsStack(final Construct parent, final String id, final EcsStackProps props) { super(parent, id, props); String stackType = props.getStackType(); String instanceType = props.getInstanceType(); Vpc vpc = props.getVpc(); Bucket bucket = props.getBucket(); SecurityGroup sg = SecurityGroup.Builder.create(this, stackType + "ecs-service-sg") .vpc(vpc) .build(); sg.addIngressRule(Peer.anyIpv4(), Port.allTraffic()); cluster = Cluster.Builder.create(this, stackType + "-cluster") .vpc(vpc) .build(); EcsOptimizedImage ecsMachineImage; if (props.getArm().equals("true")) { ecsMachineImage = EcsOptimizedImage.amazonLinux2(AmiHardwareType.ARM); } else { ecsMachineImage = EcsOptimizedImage.amazonLinux2(); } AutoScalingGroup asg = AutoScalingGroup.Builder.create(this, stackType + "-asg") .vpc(vpc) .instanceType(new InstanceType(instanceType)) .machineImage(ecsMachineImage) .minCapacity(0) .desiredCapacity(1) .securityGroup(sg) .build(); AsgCapacityProvider asgProvider = AsgCapacityProvider.Builder.create(this, stackType + "-asg-provider") .autoScalingGroup(asg) .enableManagedTerminationProtection(false) .enableManagedScaling(false) .build(); cluster.addAsgCapacityProvider(asgProvider); cluster.applyRemovalPolicy(RemovalPolicy.DESTROY); Ec2TaskDefinition task = Ec2TaskDefinition.Builder .create(this, stackType + "-task") .networkMode(NetworkMode.AWS_VPC) .build(); Map<String, String> ecrEnv = new HashMap<>(); ecrEnv.put("SCENARIO", props.getScenario()); ecrEnv.put("PORT", "3000"); //Arbitrary port if (stackType.equals("server")) { PrivateDnsNamespace ecsNameSpace = PrivateDnsNamespace.Builder.create(this, stackType + "-namespace") .name(stackType + "ecs.com") //Arbitrary name .vpc(vpc) .build(); LogGroup serviceLogGroup = LogGroup.Builder.create(this, "server-log-group") .retention(RetentionDays.ONE_DAY) .logGroupName("server-logs" + new SimpleDateFormat("MM-dd-yyyy-HH-mm-ss").format(new Date()).toString()) .removalPolicy(RemovalPolicy.DESTROY) .build(); bucket.grantPut(new ServicePrincipal("logs." + props.getServerRegion() + ".amazonaws.com")); bucket.addToResourcePolicy(PolicyStatement.Builder.create() .effect(Effect.ALLOW) .actions(List.of("s3:GetBucketAcl")) .principals(List.of(new ServicePrincipal("logs." + props.getServerRegion() + ".amazonaws.com"))) .resources(List.of(bucket.getBucketArn())) .build()); Map<String, String> exportLambdaLogsEnv = new HashMap<>(); exportLambdaLogsEnv.put(bucketName, bucket.getBucketName()); exportLambdaLogsEnv.put(logGroupName, serviceLogGroup.getLogGroupName()); exportLogsLambda = Function.Builder.create(this, "export-logs-lambda") .runtime(Runtime.NODEJS_14_X) .handler("exportS3.handler") .code(Code.fromAsset("lambda")) .environment(exportLambdaLogsEnv) .logRetention(RetentionDays.ONE_DAY) //One day to prevent reaching log limit, can be adjusted accordingly .build(); exportLogsLambda.addToRolePolicy(PolicyStatement.Builder.create() .actions(List.of("logs:CreateExportTask")) .effect(Effect.ALLOW) .resources(List.of(serviceLogGroup.getLogGroupArn())) .build()); bucket.grantReadWrite(exportLogsLambda.getRole()); serviceLogGroup.addToResourcePolicy(PolicyStatement.Builder.create() .actions(List.of("logs:CreateExportTask")) .effect(Effect.ALLOW) .principals(List.of(new ArnPrincipal(exportLogsLambda.getRole().getRoleArn()))) .build()); task.addContainer(stackType + "-driver", ContainerDefinitionOptions.builder() .image(ContainerImage.fromRegistry(props.getEcrUri())) .environment(ecrEnv) .memoryLimitMiB(2048) .logging(LogDriver.awsLogs(AwsLogDriverProps.builder().logGroup(serviceLogGroup).streamPrefix(stackType + "-ecs-task").build())) .portMappings(List.of(PortMapping.builder().containerPort(3000).hostPort(3000) .protocol(software.amazon.awscdk.services.ecs.Protocol.UDP).build())) .build()); bucket.grantWrite(task.getTaskRole()); CloudMapOptions ecsServiceDiscovery = CloudMapOptions.builder() .dnsRecordType(DnsRecordType.A) .cloudMapNamespace(ecsNameSpace) .name("ec2serviceserverCloudmapSrv-UEyneXTpp1nx") //Arbitrary hard-coded value to make DNS resolution easier .build(); dnsAddress = ecsServiceDiscovery.getName(); Ec2Service service = Ec2Service.Builder.create(this, "ec2service-" + stackType) .cluster(cluster) .taskDefinition(task) .cloudMapOptions(ecsServiceDiscovery) .capacityProviderStrategies(List.of(CapacityProviderStrategy.builder() .capacityProvider(asgProvider.getCapacityProviderName()) .weight(1) .build())) .desiredCount(1) .securityGroups(List.of(sg)) .build(); } else { ecrEnv.put("DNS_ADDRESS", props.getDnsAddress() + ".serverecs.com"); ecrEnv.put("SERVER_PORT", "3000"); ecrEnv.put("S3_BUCKET", bucket.getBucketName()); ecrEnv.put("LOCAL_IP", "0.0.0.0"); ContainerDefinition clientContainer = task.addContainer(stackType + "-driver", ContainerDefinitionOptions.builder() .image(ContainerImage.fromRegistry(props.getEcrUri())) .environment(ecrEnv) .memoryLimitMiB(2048) .logging(LogDriver.awsLogs(AwsLogDriverProps.builder().logRetention(RetentionDays.ONE_DAY).streamPrefix(stackType + "-ecs-task").build())) .portMappings(List.of(PortMapping.builder().containerPort(3000).hostPort(3000) .protocol(software.amazon.awscdk.services.ecs.Protocol.UDP).build())) .build()); bucket.grantWrite(task.getTaskRole()); ecsTask = EcsRunTask.Builder.create(this, "client-run-task") .integrationPattern(IntegrationPattern.RUN_JOB) .cluster(cluster) .taskDefinition(task) .launchTarget(EcsEc2LaunchTarget.Builder.create().build()) .inputPath("$.Payload") .resultPath("$.client_result") .containerOverrides(List.of(ContainerOverride.builder() .containerDefinition(clientContainer) .environment(List.of(TaskEnvironmentVariable.builder() .name("TIMESTAMP") .value(JsonPath.stringAt("$.timestamp")) .build())) .build())) .build(); } } public String getDnsAddress() { return dnsAddress; } public EcsRunTask getEcsTask() { return ecsTask; } public Function getLogsLambda() { return exportLogsLambda; } public Cluster getCluster() { return cluster; } }
8,921
0
Create_ds/s2n-quic/netbench/cdk/src/main/java/com
Create_ds/s2n-quic/netbench/cdk/src/main/java/com/aws/SSMParameterReader.java
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.aws; import software.amazon.awscdk.customresources.AwsCustomResource; import software.constructs.Construct; class SSMParameterReader extends AwsCustomResource { public SSMParameterReader(final Construct scope, final String id, final SSMParameterReaderProps props) { super(scope, id, props); } public String getParameterValue() { return this.getResponseField("Parameter.Value").toString(); } }
8,922
0
Create_ds/s2n-quic/netbench/cdk/src/main/java/com
Create_ds/s2n-quic/netbench/cdk/src/main/java/com/aws/SSMParameterReaderProps.java
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.aws; import java.util.HashMap; import software.amazon.awscdk.customresources.AwsCustomResourcePolicy; import software.amazon.awscdk.customresources.AwsCustomResourceProps; import software.amazon.awscdk.customresources.AwsSdkCall; import software.amazon.awscdk.customresources.PhysicalResourceId; import software.amazon.awscdk.customresources.SdkCallsPolicyOptions; public interface SSMParameterReaderProps extends AwsCustomResourceProps { public static Builder builder() { return new Builder(); } public static class Builder { private AwsSdkCall sdkCall; private AwsCustomResourcePolicy policy; public Builder sdkCall(String name, String region) { HashMap<String, String> sdkParameters = new HashMap<>(); sdkParameters.put("Name", name); this.sdkCall = AwsSdkCall.builder() .service("SSM") .action("getParameter") .parameters(sdkParameters) .region(region) .physicalResourceId(PhysicalResourceId.of(name + region + "reader")) .build(); return this; } public Builder policy() { this.policy = AwsCustomResourcePolicy.fromSdkCalls(SdkCallsPolicyOptions.builder() .resources(AwsCustomResourcePolicy.ANY_RESOURCE) .build()); return this; } public SSMParameterReaderProps build() { return new SSMParameterReaderProps() { @Override public AwsSdkCall getOnUpdate() { return sdkCall; } @Override public AwsCustomResourcePolicy getPolicy() { return policy; } }; } } }
8,923
0
Create_ds/s2n-quic/netbench/cdk/src/main/java/com
Create_ds/s2n-quic/netbench/cdk/src/main/java/com/aws/StateMachineStack.java
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.aws; import software.constructs.Construct; import software.amazon.awscdk.Stack; import software.amazon.awscdk.services.stepfunctions.tasks.EcsRunTask; import software.amazon.awscdk.services.stepfunctions.StateMachine; import software.amazon.awscdk.services.s3.Bucket; import software.amazon.awscdk.services.logs.RetentionDays; import software.amazon.awscdk.Duration; import software.amazon.awscdk.services.stepfunctions.tasks.LambdaInvoke; import software.amazon.awscdk.services.stepfunctions.tasks.LambdaInvocationType; import software.amazon.awscdk.services.stepfunctions.tasks.ContainerOverride; import software.amazon.awscdk.services.stepfunctions.tasks.TaskEnvironmentVariable; import software.amazon.awscdk.services.stepfunctions.JsonPath; import software.amazon.awscdk.services.stepfunctions.IntegrationPattern; import software.amazon.awscdk.services.stepfunctions.tasks.EcsEc2LaunchTarget; import software.amazon.awscdk.services.stepfunctions.Wait; import software.amazon.awscdk.services.stepfunctions.WaitTime; import software.amazon.awscdk.services.lambda.Function; import software.amazon.awscdk.services.lambda.Runtime; import software.amazon.awscdk.services.lambda.Code; import software.amazon.awscdk.services.ecs.ContainerDefinition; import software.amazon.awscdk.services.ecs.ContainerDefinitionOptions; import software.amazon.awscdk.services.ecs.Ec2TaskDefinition; import software.amazon.awscdk.services.ecs.ContainerImage; import software.amazon.awscdk.services.ecs.AwsLogDriverProps; import software.amazon.awscdk.services.ecs.LogDriver; import software.amazon.awscdk.services.iam.PolicyStatement; import software.amazon.awscdk.services.iam.Effect; import java.util.HashMap; import java.util.Map; import java.util.List; public class StateMachineStack extends Stack { public StateMachineStack(final Construct parent, final String id, final StateMachineStackProps props) { super(parent, id, props); Bucket bucket = props.getBucket(); Function timestampFunction = Function.Builder.create(this, "timestamp-function") .runtime(Runtime.NODEJS_14_X) .handler("timestamp.handler") .code(Code.fromAsset("lambda")) .logRetention(RetentionDays.ONE_DAY) //One day to prevent reaching log limit, can be adjusted accordingly .build(); LambdaInvoke timestampLambdaInvoke = LambdaInvoke.Builder.create(this, "timestamp-task") .lambdaFunction(timestampFunction) .build(); EcsRunTask clientTask = props.getClientTask(); Wait waitTask = Wait.Builder.create(this, "wait-step") .time(WaitTime.duration(Duration.seconds(60))) .build(); LambdaInvoke exportServerLogsLambdaInvoke = LambdaInvoke.Builder.create(this, "export-server-logs-task") .lambdaFunction(props.getLogsLambda()) .resultPath("$.Payload.body") .invocationType(LambdaInvocationType.REQUEST_RESPONSE) .build(); Ec2TaskDefinition reportGenerationTask = Ec2TaskDefinition.Builder .create(this, "report-generation-task") .build(); reportGenerationTask.addToTaskRolePolicy(PolicyStatement.Builder.create() .actions(List.of("logs:DescribeExportTasks")) .effect(Effect.ALLOW) .resources(List.of("*")) .build()); Map<String, String> reportGenerationEnv = new HashMap<>(); reportGenerationEnv.put("S3_BUCKET", bucket.getBucketName()); reportGenerationEnv.put("PROTOCOL", props.getProtocol()); ContainerDefinition reportGenerationContainer = reportGenerationTask.addContainer("report-generation", ContainerDefinitionOptions.builder() .image(ContainerImage.fromRegistry("public.ecr.aws/d2r9y8c2/netbench-cli")) .environment(reportGenerationEnv) .memoryLimitMiB(2048) .logging(LogDriver.awsLogs(AwsLogDriverProps.builder().logRetention(RetentionDays.ONE_DAY).streamPrefix("report-generation").build())) .build()); bucket.grantReadWrite(reportGenerationTask.getTaskRole()); EcsRunTask reportGenerationStep = EcsRunTask.Builder.create(this, "report-generation-step") .integrationPattern(IntegrationPattern.RUN_JOB) .cluster(props.getCluster()) .taskDefinition(reportGenerationTask) .launchTarget(EcsEc2LaunchTarget.Builder.create().build()) .inputPath("$.Payload") .containerOverrides(List.of(ContainerOverride.builder() .containerDefinition(reportGenerationContainer) .environment(List.of(TaskEnvironmentVariable.builder() .name("EXPORT_TASK_ID") .value(JsonPath.stringAt("$.body.Payload.taskId")) .build(), TaskEnvironmentVariable.builder() .name("TIMESTAMP") .value(JsonPath.stringAt("$.timestamp")) .build())) .build())) .build(); timestampLambdaInvoke.next(clientTask); clientTask.next(waitTask); waitTask.next(exportServerLogsLambdaInvoke); exportServerLogsLambdaInvoke.next(reportGenerationStep); StateMachine stateMachine = StateMachine.Builder.create(this, "ecs-state-machine") .definition(timestampLambdaInvoke) .build(); } }
8,924
0
Create_ds/s2n-quic/netbench/cdk/src/main/java/com
Create_ds/s2n-quic/netbench/cdk/src/main/java/com/aws/EcsStackProps.java
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.aws; import software.amazon.awscdk.StackProps; import software.amazon.awscdk.services.s3.Bucket; import software.amazon.awscdk.Environment; import software.amazon.awscdk.services.ec2.Vpc; public interface EcsStackProps extends StackProps { public static Builder builder() { return new Builder(); } Bucket getBucket(); String getInstanceType(); String getStackType(); String getProtocol(); Vpc getVpc(); String getServerRegion(); String getDnsAddress(); String getEcrUri(); String getScenario(); String getArm(); public static class Builder { private Bucket bucket; private String instanceType; private Environment env; private String stackType; private String protocol; private Vpc vpc; private String serverRegion; private String dnsAddress; private String ecrUri; private String scenario; private String arm; public Builder bucket(Bucket bucket) { this.bucket = bucket; return this; } public Builder instanceType(String instanceType) { this.instanceType = instanceType; return this; } public Builder env(Environment env) { this.env = env; return this; } public Builder stackType(String stackType) { this.stackType = stackType; return this; } public Builder protocol(String protocol) { this.protocol = protocol; return this; } public Builder vpc(Vpc vpc) { this.vpc = vpc; return this; } public Builder serverRegion(String serverRegion) { this.serverRegion = serverRegion; return this; } public Builder dnsAddress(String dnsAddress) { this.dnsAddress = dnsAddress; return this; } public Builder ecrUri(String ecrUri) { this.ecrUri = ecrUri; return this; } public Builder scenario(String scenario) { this.scenario = scenario; return this; } public Builder arm(String arm) { this.arm = arm; return this; } public EcsStackProps build() { return new EcsStackProps() { @Override public Bucket getBucket() { return bucket; } @Override public String getInstanceType() { return instanceType; } @Override public String getStackType() { return stackType; } @Override public Environment getEnv() { return env; } @Override public String getProtocol() { return protocol; } @Override public Vpc getVpc() { return vpc; } @Override public String getServerRegion() { return serverRegion; } @Override public String getDnsAddress() { return dnsAddress; } @Override public String getEcrUri() { return ecrUri; } @Override public String getScenario() { return scenario; } @Override public String getArm() { return arm; } }; } } }
8,925
0
Create_ds/s2n-quic/netbench/cdk/src/main/java/com
Create_ds/s2n-quic/netbench/cdk/src/main/java/com/aws/VpcStackProps.java
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.aws; import software.amazon.awscdk.StackProps; import software.amazon.awscdk.Environment; public interface VpcStackProps extends StackProps { public static Builder builder() { return new Builder(); } String getCidr(); public static class Builder { private Environment env; private String cidr; public Builder cidr(String cidr) { this.cidr = cidr; return this; } public Builder env(Environment env) { this.env = env; return this; } public VpcStackProps build() { return new VpcStackProps() { @Override public String getCidr() { return cidr; } @Override public Environment getEnv() { return env; } }; } } }
8,926
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/test/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/test/java/software/amazon/smithy/go/codegen/IntEnumShapeGeneratorTest.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen; import java.util.logging.Logger; import org.junit.jupiter.api.Test; import software.amazon.smithy.build.MockManifest; import software.amazon.smithy.build.PluginContext; import software.amazon.smithy.go.codegen.GoCodegenPlugin; import software.amazon.smithy.model.Model; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static software.amazon.smithy.go.codegen.TestUtils.buildMockPluginContext; import static software.amazon.smithy.go.codegen.TestUtils.loadSmithyModelFromResource; import static software.amazon.smithy.go.codegen.TestUtils.loadExpectedFileStringFromResource; public class IntEnumShapeGeneratorTest { private static final Logger LOGGER = Logger.getLogger(IntEnumShapeGeneratorTest.class.getName()); @Test public void testIntEnumShapeTest() { // Arrange Model model = loadSmithyModelFromResource("int-enum-shape-test"); MockManifest manifest = new MockManifest(); PluginContext context = buildMockPluginContext(model, manifest, "smithy.example#Example"); // Act (new GoCodegenPlugin()).execute(context); // Assert String actualEnumShapeCode = manifest.getFileString("types/enums.go").get(); String expectedEnumShapeCode = loadExpectedFileStringFromResource("int-enum-shape-test", "types/enums.go"); assertThat("intEnum shape actual generated code is equal to the expected generated code", actualEnumShapeCode, is(expectedEnumShapeCode)); String actualChangeCardOperationCode = manifest.getFileString("api_op_ChangeCard.go").get(); String expectedChangeCardInputCode = loadExpectedFileStringFromResource("int-enum-shape-test", "changeCardInput.go.struct"); assertThat("intEnum shape properly referenced in generated input structure code", actualChangeCardOperationCode, containsString(expectedChangeCardInputCode)); String expectedChangeCardOutputCode = loadExpectedFileStringFromResource("int-enum-shape-test", "changeCardOutput.go.struct"); assertThat("intEnum shape properly referenced in generated output structure code", actualChangeCardOperationCode, containsString(expectedChangeCardOutputCode)); } }
8,927
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/test/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/test/java/software/amazon/smithy/go/codegen/TestUtils.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen; import static software.amazon.smithy.go.codegen.testutils.ExecuteCommand.execute; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import software.amazon.smithy.build.FileManifest; import software.amazon.smithy.build.PluginContext; import software.amazon.smithy.go.codegen.testutils.ExecuteCommand; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.node.Node; import software.amazon.smithy.model.node.ObjectNode; public class TestUtils { public static final String SMITHY_TESTS_PREFIX = "smithy-tests"; public static final String SMITHY_TESTS_EXPECTED_PREFIX = "expected"; public static Model loadSmithyModelFromResource(String testPath) { String resourcePath = SMITHY_TESTS_PREFIX + "/" + testPath + "/" + testPath + ".smithy"; return Model.assembler() .addImport(TestUtils.class.getResource(resourcePath)) .discoverModels() .assemble() .unwrap(); } public static String loadExpectedFileStringFromResource(String testPath, String filePath) { String resourcePath = SMITHY_TESTS_PREFIX + "/" + testPath + "/" + SMITHY_TESTS_EXPECTED_PREFIX + "/" + filePath; return getResourceAsString(resourcePath); } public static String getResourceAsString(String resourcePath) { try { return Files.readString( Paths.get(TestUtils.class.getResource(resourcePath).toURI()), Charset.forName("utf-8")); } catch (Exception e) { return null; } } public static PluginContext buildMockPluginContext( Model model, FileManifest manifest, String serviceShapeId ) { return buildPluginContext( model, manifest, serviceShapeId, "example", "0.0.1", false); } public static PluginContext buildPluginContext( Model model, FileManifest manifest, String serviceShapeId, String moduleName, String moduleVersion, Boolean generateGoMod ) { return PluginContext.builder() .model(model) .fileManifest(manifest) .settings(getSettingsNode( serviceShapeId, moduleName, moduleVersion, generateGoMod, "Example")) .build(); } public static ObjectNode getSettingsNode( String serviceShapeId, String moduleName, String moduleVersion, Boolean generateGoMod, String sdkId ) { return Node.objectNodeBuilder() .withMember("service", Node.from(serviceShapeId)) .withMember("module", Node.from(moduleName)) .withMember("moduleVersion", Node.from(moduleVersion)) .withMember("generateGoMod", Node.from(generateGoMod)) .withMember("homepage", Node.from("https://docs.amplify.aws/")) .withMember("sdkId", Node.from(sdkId)) .withMember("author", Node.from("Amazon Web Services")) .withMember("gitRepo", Node.from("https://github.com/aws-amplify/amplify-codegen.git")) .withMember("swiftVersion", Node.from("5.5.0")) .build(); } /** * Returns the path for the repository's root relative to the smithy-go-codegen module. * @return repo root. */ public static Path getRepoRootDir() { return Path.of(System.getProperty("user.dir")) .resolve("..") .resolve("..") .toAbsolutePath(); } /** * Returns true if the go command can be executed. * @return go command can be executed. */ public static boolean hasGoInstalled() { try{ ExecuteCommand.builder() .addCommand("go", "version") .build() .execute(); } catch (Exception e) { return false; } return true; } public static void makeGoModule(Path path) throws Exception { var repoRoot = getRepoRootDir(); execute(repoRoot.toFile(), "go", "run", "github.com/awslabs/aws-go-multi-module-repository-tools/cmd/gomodgen@latest", "--build", path.resolve("..").toAbsolutePath().toString(), "--plugin-dir", path.getFileName().toString(), "--copy-artifact=false", "--prepare-target-dir=false" ); execute(path.toFile(), "go", "mod", "edit", "--replace", "github.com/aws/smithy-go="+repoRoot); execute(path.toFile(), "go", "mod", "tidy"); execute(path.toFile(), "gofmt", "-w", "-s", "."); } public static void testGoModule(Path path) throws Exception { execute(path.toFile(), "go", "test", "-v", "./..."); } }
8,928
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/test/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/test/java/software/amazon/smithy/go/codegen/GenerateStandaloneGoModuleTest.java
package software.amazon.smithy.go.codegen; import static software.amazon.smithy.go.codegen.GoWriter.goBlockTemplate; import static software.amazon.smithy.go.codegen.TestUtils.hasGoInstalled; import static software.amazon.smithy.go.codegen.TestUtils.makeGoModule; import static software.amazon.smithy.go.codegen.TestUtils.testGoModule; import java.nio.file.Files; import java.util.Map; import java.util.logging.Logger; import org.junit.jupiter.api.Test; import software.amazon.smithy.build.FileManifest; import software.amazon.smithy.utils.MapUtils; public class GenerateStandaloneGoModuleTest { private static final Logger LOGGER = Logger.getLogger(GenerateStandaloneGoModuleTest.class.getName()); @Test public void testGenerateGoModule() throws Exception { if (!hasGoInstalled()) { LOGGER.warning("Skipping testGenerateGoModule, go command cannot be executed."); return; } var testPath = Files.createTempDirectory(getClass().getName()); LOGGER.warning("generating test suites into " + testPath); var fileManifest = FileManifest.create(testPath); var writers = new GoWriterDelegator(fileManifest); writers.useFileWriter("test-directory/package-name/gofile.go", "github.com/aws/smithy-go/internal/testmodule/packagename", (w) -> { w.writeGoTemplate(""" type $name:L struct { Bar $barType:T Baz *$bazType:T } $somethingElse:W """, MapUtils.of( "name", "Foo", "barType", SymbolUtils.createValueSymbolBuilder("string").build(), "bazType", SymbolUtils.createValueSymbolBuilder("Request", SmithyGoDependency.SMITHY_HTTP_TRANSPORT).build(), "somethingElse", generateSomethingElse() )); }); writers.useFileWriter("test-directory/package-name/gofile_test.go", "github.com/aws/smithy-go/internal/testmodule/packagename", (w) -> { Map<String, Object> commonArgs = MapUtils.of( "testingT", SymbolUtils.createValueSymbolBuilder("T", SmithyGoDependency.TESTING).build() ); w.writeGoTemplate(""" func Test$name:L(t *$testingT:T) { v := $name:L{} v.Baz = nil } """, commonArgs, MapUtils.of( "name", "Foo" )); w.writeGoBlockTemplate("func TestBar(t *$testingT:T) {", "}", commonArgs, (ww) -> { ww.write("t.Skip(\"not relevant\")"); }); }); var dependencies = writers.getDependencies(); writers.flushWriters(); var goModuleInfo = new GoModuleInfo.Builder() .goDirective(GoModuleInfo.DEFAULT_GO_DIRECTIVE) .dependencies(dependencies) .build(); ManifestWriter.builder() .moduleName("github.com/aws/smithy-go/internal/testmodule") .fileManifest(fileManifest) .goModuleInfo(goModuleInfo) .build() .writeManifest(); makeGoModule(testPath); testGoModule(testPath); } private GoWriter.Writable generateSomethingElse() { return goBlockTemplate("func (s *$name:L) $funcName:L(i int) string {", "}", MapUtils.of("funcName", "SomethingElse"), MapUtils.of( "name", "Foo" ), (w) -> { w.write("return \"hello!\""); }); } }
8,929
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/test/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/test/java/software/amazon/smithy/go/codegen/GoDependencyTest.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen; import static org.hamcrest.MatcherAssert.assertThat; import java.util.List; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; import software.amazon.smithy.codegen.core.SymbolDependency; public class GoDependencyTest { @Test public void testStandardLibraryDependency() { GoDependency dependency = GoDependency.builder() .type(GoDependency.Type.STANDARD_LIBRARY) .importPath("net/http") .version("1.14") .build(); List<SymbolDependency> symbolDependencies = dependency.getDependencies(); assertThat(symbolDependencies.size(), Matchers.equalTo(1)); SymbolDependency symbolDependency = symbolDependencies.get(0); assertThat(symbolDependency.getDependencyType(), Matchers.equalTo("stdlib")); assertThat(symbolDependency.getPackageName(), Matchers.equalTo("")); assertThat(symbolDependency.getVersion(), Matchers.equalTo("1.14")); } @Test public void testSingleDependency() { GoDependency dependency = GoDependency.builder() .type(GoDependency.Type.DEPENDENCY) .sourcePath("github.com/aws/smithy-go") .importPath("github.com/aws/smithy-go/middleware") .version("1.2.3") .build(); List<SymbolDependency> symbolDependencies = dependency.getDependencies(); assertThat(symbolDependencies.size(), Matchers.equalTo(1)); SymbolDependency symbolDependency = symbolDependencies.get(0); assertThat(symbolDependency.getDependencyType(), Matchers.equalTo("dependency")); assertThat(symbolDependency.getPackageName(), Matchers.equalTo("github.com/aws/smithy-go")); assertThat(symbolDependency.getVersion(), Matchers.equalTo("1.2.3")); } @Test public void testDependencyWithDependencies() { GoDependency dependency = GoDependency.builder() .type(GoDependency.Type.DEPENDENCY) .sourcePath("github.com/aws/aws-sdk-go-v2") .importPath("github.com/aws/aws-sdk-go-v2/aws/middleware") .version("1.2.3") .addDependency(GoDependency.builder() .type(GoDependency.Type.DEPENDENCY) .sourcePath("github.com/aws/smithy-go") .importPath("github.com/aws/smithy-go/middleware") .version("3.4.5") .build()) .build(); List<SymbolDependency> symbolDependencies = dependency.getDependencies(); assertThat(symbolDependencies.size(), Matchers.equalTo(2)); assertThat(symbolDependencies, Matchers.containsInAnyOrder( Matchers.equalTo(SymbolDependency.builder() .dependencyType("dependency") .packageName("github.com/aws/aws-sdk-go-v2") .version("1.2.3") .build()), Matchers.equalTo(SymbolDependency.builder() .dependencyType("dependency") .packageName("github.com/aws/smithy-go") .version("3.4.5") .build()) )); } @Test public void testDependencyWithNestedDependencies() { GoDependency dependency = GoDependency.builder() .type(GoDependency.Type.DEPENDENCY) .sourcePath("github.com/aws/aws-sdk-go-v2") .importPath("github.com/aws/aws-sdk-go-v2/aws/middleware") .version("1.2.3") .addDependency(GoDependency.builder() .type(GoDependency.Type.DEPENDENCY) .sourcePath("github.com/aws/smithy-go") .importPath("github.com/aws/smithy-go/middleware") .version("3.4.5") .addDependency(GoDependency.builder() .type(GoDependency.Type.DEPENDENCY) .sourcePath("github.com/awslabs/smithy-go-extensions") .importPath("github.com/awslabs/smithy-go-extensions/foobar") .version("6.7.8") .addDependency(GoDependency.builder() .type(GoDependency.Type.STANDARD_LIBRARY) .importPath("net/http") .version("1.14") .build()) .addDependency(GoDependency.builder() .type(GoDependency.Type.STANDARD_LIBRARY) .importPath("time") .version("1.14") .build()) .build()) .build()) .build(); List<SymbolDependency> symbolDependencies = dependency.getDependencies(); assertThat(symbolDependencies.size(), Matchers.equalTo(4)); assertThat(symbolDependencies, Matchers.containsInAnyOrder( Matchers.equalTo(SymbolDependency.builder() .dependencyType("dependency") .packageName("github.com/aws/aws-sdk-go-v2") .version("1.2.3") .build()), Matchers.equalTo(SymbolDependency.builder() .dependencyType("dependency") .packageName("github.com/aws/smithy-go") .version("3.4.5") .build()), Matchers.equalTo(SymbolDependency.builder() .dependencyType("dependency") .packageName("github.com/awslabs/smithy-go-extensions") .version("6.7.8") .build()), Matchers.equalTo(SymbolDependency.builder() .dependencyType("stdlib") .packageName("") .version("1.14") .build()) )); } }
8,930
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/test/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/test/java/software/amazon/smithy/go/codegen/GoStackStepMiddlewareGeneratorTest.java
package software.amazon.smithy.go.codegen; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import org.junit.jupiter.api.Test; public class GoStackStepMiddlewareGeneratorTest { @Test public void generatesSerializeMiddlewareDefinition() { GoWriter writer = new GoWriter("middlewaregentest"); GoStackStepMiddlewareGenerator.createSerializeStepMiddleware("someMiddleware", MiddlewareIdentifier.string("some id")) .writeMiddleware(writer, (m, w) -> { w.openBlock("return next.$L(ctx, in)", m.getHandleMethodName()); }); String generated = writer.toString(); System.out.println(generated); assertThat(generated, containsString("type someMiddleware struct {")); assertThat(generated, containsString("func (*someMiddleware) ID() string {")); assertThat(generated, containsString("return \"some id\"")); assertThat(generated, containsString("func (m *someMiddleware) HandleSerialize(" + "ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) (")); assertThat(generated, containsString("out middleware.SerializeOutput, metadata middleware.Metadata, err error,")); assertThat(generated, containsString("return next.HandleSerialize(ctx, in)")); } }
8,931
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/test/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/test/java/software/amazon/smithy/go/codegen/MixinCodegenTest.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen; import java.util.logging.Logger; import org.junit.jupiter.api.Test; import software.amazon.smithy.build.MockManifest; import software.amazon.smithy.build.PluginContext; import software.amazon.smithy.go.codegen.GoCodegenPlugin; import software.amazon.smithy.model.Model; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; import static software.amazon.smithy.go.codegen.TestUtils.buildMockPluginContext; import static software.amazon.smithy.go.codegen.TestUtils.loadSmithyModelFromResource; import static software.amazon.smithy.go.codegen.TestUtils.loadExpectedFileStringFromResource; public class MixinCodegenTest { private static final Logger LOGGER = Logger.getLogger(MixinCodegenTest.class.getName()); @Test public void testMixinCodegen() { // Arrange Model model = loadSmithyModelFromResource("mixin-test"); MockManifest manifest = new MockManifest(); PluginContext context = buildMockPluginContext(model, manifest, "smithy.example#Example"); // Act (new GoCodegenPlugin()).execute(context); // Assert String actualChangeCardOperationCode = manifest.getFileString("api_op_ChangeCard.go").get(); String expectedInputMixinCode = loadExpectedFileStringFromResource("mixin-test", "changeCardInput.go.mixin"); assertThat("mixins are properly applied in the input structure", actualChangeCardOperationCode, containsString(expectedInputMixinCode)); String expectedOutputMixinCode = loadExpectedFileStringFromResource("mixin-test", "changeCardOutput.go.mixin"); assertThat("mixins are properly applied in the output structure", actualChangeCardOperationCode, containsString(expectedOutputMixinCode)); } }
8,932
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/test/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/test/java/software/amazon/smithy/go/codegen/AddOperationShapesTest.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; import software.amazon.smithy.model.shapes.StringShape; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.utils.ListUtils; import java.util.Optional; import java.util.logging.Logger; public class AddOperationShapesTest { private static final Logger LOGGER = Logger.getLogger(AddOperationShapesTest.class.getName()); private static final String NAMESPACE = "go.codege.test"; private static final ServiceShape SERVICE = ServiceShape.builder() .id(ShapeId.fromParts(NAMESPACE, "TestService")) .version("1.0") .build(); @Test public void testOperationWithoutInputOutput() { GoSettings settings = new GoSettings(); settings.setService(SERVICE.toShapeId()); OperationShape op = OperationShape.builder() .id(ShapeId.fromParts(NAMESPACE, "TestOperation")) .build(); ServiceShape service = SERVICE.toBuilder() .addOperation(op.getId()) .build(); Model model = Model.builder() .addShapes(service, op) .build(); Model processedModel = AddOperationShapes.execute(model, service.getId()); ListUtils.of( ShapeId.fromParts(CodegenUtils.getSyntheticTypeNamespace(), "TestOperationInput"), ShapeId.fromParts(CodegenUtils.getSyntheticTypeNamespace(), "TestOperationOutput") ).forEach(shapeId -> { Optional<Shape> shape = processedModel.getShape(shapeId); MatcherAssert.assertThat(shapeId + " shape must be present in model", shape.isPresent(), Matchers.is(true)); MatcherAssert.assertThat(shapeId + " shape must have no members", shape.get().members().size(), Matchers.equalTo(0)); Optional<Synthetic> opSynth = shape.get().getTrait(Synthetic.class); if (opSynth.isPresent()) { Synthetic synth = opSynth.get(); MatcherAssert.assertThat(shapeId + " shape must not have archetype", synth.getArchetype().isPresent(), Matchers.equalTo(false)); } else { MatcherAssert.assertThat(shapeId + " shape must be synthetic clone", false); } }); } @Test public void testOperationWithExistingInputOutput() { GoSettings settings = new GoSettings(); settings.setService(SERVICE.toShapeId()); StringShape stringShape = StringShape.builder().id(ShapeId.fromParts(NAMESPACE, "String")).build(); StructureShape inputShape = StructureShape.builder() .id(ShapeId.fromParts(NAMESPACE, "TestOperationRequest")) .addMember("foo", stringShape.getId()) .build(); StructureShape outputShape = StructureShape.builder() .id(ShapeId.fromParts(NAMESPACE, "TestOperationResponse")) .addMember("foo", stringShape.getId()) .build(); OperationShape op = OperationShape.builder() .id(ShapeId.fromParts(NAMESPACE, "TestOperation")) .input(inputShape) .output(outputShape) .build(); ServiceShape service = SERVICE.toBuilder() .addOperation(op.getId()) .build(); Model model = Model.builder() .addShapes(stringShape, inputShape, outputShape, op, service) .build(); Model processedModel = AddOperationShapes.execute(model, service.getId()); ListUtils.of( ShapeId.fromParts(CodegenUtils.getSyntheticTypeNamespace(), "TestOperationInput"), ShapeId.fromParts(CodegenUtils.getSyntheticTypeNamespace(), "TestOperationOutput") ).forEach(shapeId -> { Optional<Shape> shape = processedModel.getShape(shapeId); MatcherAssert.assertThat(shapeId + " shape must be present in model", shape.isPresent(), Matchers.is(true)); StructureShape structureShape = shape.get().asStructureShape().get(); Optional<MemberShape> fooMember = structureShape.getMember("foo"); MatcherAssert.assertThat("foo member present", fooMember.isPresent(), Matchers.is(true)); ShapeId id = fooMember.get().getId(); MatcherAssert.assertThat("foo is correct namespace", id.getNamespace(), Matchers.equalTo(shapeId.getNamespace())); MatcherAssert.assertThat("foo is correct parent", id.getName(service), Matchers.equalTo(shapeId.getName(service))); Optional<Synthetic> synthetic = shape.get().getTrait(Synthetic.class); if (!synthetic.isPresent()) { MatcherAssert.assertThat(shapeId + " shape must be marked as synthetic clone", false); } else { MatcherAssert.assertThat(synthetic.get().getArchetype().get().toString(), Matchers.is(Matchers.oneOf(NAMESPACE + "#TestOperationRequest", NAMESPACE + "#TestOperationResponse"))); } }); } @Test public void testOperationWithExistingInputOutputWithConflitcs() { GoSettings settings = new GoSettings(); settings.setService(SERVICE.toShapeId()); StructureShape inputConflict = StructureShape.builder() .id(ShapeId.fromParts(NAMESPACE, "TestOperationInput")) .build(); StructureShape outputConflict = StructureShape.builder() .id(ShapeId.fromParts(NAMESPACE, "TestOperationOutput")) .build(); OperationShape op = OperationShape.builder() .id(ShapeId.fromParts(NAMESPACE, "TestOperation")) .build(); ServiceShape service = SERVICE.toBuilder() .addOperation(op.getId()) .build(); Model model = Model.builder() .addShapes(inputConflict, outputConflict, op, service) .build(); Model processedModel = AddOperationShapes.execute(model, service.getId()); ShapeId expInputRename = ShapeId.fromParts(CodegenUtils.getSyntheticTypeNamespace(), "TestOperationInput"); ShapeId expOutputRename = ShapeId.fromParts(CodegenUtils.getSyntheticTypeNamespace(), "TestOperationOutput"); ListUtils.of(inputConflict.getId(), outputConflict.getId()) .forEach(shapeId -> { Optional<Shape> shape = processedModel.getShape(shapeId); MatcherAssert.assertThat(shapeId + " shape must be present in model", shape.isPresent(), Matchers.is(true)); if (shape.get().getTrait(Synthetic.class).isPresent()) { MatcherAssert.assertThat("shape must not be marked as synthetic clone", false); } }); ListUtils.of(expInputRename, expOutputRename) .forEach(shapeId -> { Optional<Shape> shape = processedModel.getShape(shapeId); MatcherAssert.assertThat(shapeId + " shape must be present in model", shape.isPresent(), Matchers.is(true)); Optional<Synthetic> opSynth = shape.get().getTrait(Synthetic.class); if (opSynth.isPresent()) { Synthetic synth = opSynth.get(); MatcherAssert.assertThat(shapeId + " shape must not have archetype", synth.getArchetype().isPresent(), Matchers.equalTo(false)); } else { MatcherAssert.assertThat(shapeId + " shape must be synthetic clone", false); } }); } }
8,933
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/test/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/test/java/software/amazon/smithy/go/codegen/SemanticVersionTest.java
/* * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen; import static org.hamcrest.MatcherAssert.assertThat; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; public class SemanticVersionTest { @Test public void testSemanticVersion() { SemanticVersion version = SemanticVersion.parseVersion("1.2.3"); assertThat(version.toString(), Matchers.equalTo("1.2.3")); } @Test public void testSemanticVersionWithPrefix() { SemanticVersion version = SemanticVersion.parseVersion("v1.2.3"); assertThat(version.toString(), Matchers.equalTo("v1.2.3")); } @Test public void testSemanticVersionWithPreRelease() { SemanticVersion version = SemanticVersion.parseVersion("1.2.3-alpha"); assertThat(version.toString(), Matchers.equalTo("1.2.3-alpha")); } @Test public void testSemanticVersionWithBuild() { SemanticVersion version = SemanticVersion.parseVersion("1.2.3+1234"); assertThat(version.toString(), Matchers.equalTo("1.2.3+1234")); } @Test public void testSemanticVersionWithPreReleaseBuild() { SemanticVersion version = SemanticVersion.parseVersion("1.2.3-alpha+1234"); assertThat(version.toString(), Matchers.equalTo("1.2.3-alpha+1234")); } @Test public void testSemanticVersionWithPrefixPreReleaseBuild() { SemanticVersion version = SemanticVersion.parseVersion("v1.2.3-alpha+1234"); assertThat(version.toString(), Matchers.equalTo("v1.2.3-alpha+1234")); } @Test public void testCompareTo() { assertThat(SemanticVersion.parseVersion("v1.0.0").compareTo( SemanticVersion.parseVersion("v2.0.0")), Matchers.lessThan(0)); assertThat(SemanticVersion.parseVersion("v2.0.0").compareTo( SemanticVersion.parseVersion("v2.1.0")), Matchers.lessThan(0)); assertThat(SemanticVersion.parseVersion("v2.1.0").compareTo( SemanticVersion.parseVersion("v2.1.1")), Matchers.lessThan(0)); assertThat(SemanticVersion.parseVersion("v1.2.3").compareTo( SemanticVersion.parseVersion("v1.2.3")), Matchers.equalTo(0)); // Build metadata is ignored assertThat(SemanticVersion.parseVersion("v1.2.3-alpha+102030").compareTo( SemanticVersion.parseVersion("v1.2.3-alpha+405060")), Matchers.equalTo(0)); // 1.0.0-alpha < 1.0.0-alpha.1 < 1.0.0-alpha.beta < 1.0.0-beta < 1.0.0-beta.2 < 1.0.0-beta.11 < 1.0.0-rc.1 < 1.0.0 assertThat(SemanticVersion.parseVersion("1.0.0-alpha").compareTo( SemanticVersion.parseVersion("1.0.0-alpha.1")), Matchers.lessThan(0)); assertThat(SemanticVersion.parseVersion("1.0.0-alpha.1").compareTo( SemanticVersion.parseVersion("1.0.0-alpha.beta")), Matchers.lessThan(0)); assertThat(SemanticVersion.parseVersion("1.0.0-alpha.beta").compareTo( SemanticVersion.parseVersion("1.0.0-beta")), Matchers.lessThan(0)); assertThat(SemanticVersion.parseVersion("1.0.0-beta").compareTo( SemanticVersion.parseVersion("1.0.0-beta.2")), Matchers.lessThan(0)); assertThat(SemanticVersion.parseVersion("1.0.0-beta.2").compareTo( SemanticVersion.parseVersion("1.0.0-beta.11")), Matchers.lessThan(0)); assertThat(SemanticVersion.parseVersion("1.0.0-beta.11").compareTo( SemanticVersion.parseVersion("1.0.0-rc.1")), Matchers.lessThan(0)); assertThat(SemanticVersion.parseVersion("1.0.0-rc.1").compareTo( SemanticVersion.parseVersion("1.0.0")), Matchers.lessThan(0)); // Reversed direction assertThat(SemanticVersion.parseVersion("1.0.0-alpha.1").compareTo( SemanticVersion.parseVersion("1.0.0-alpha")), Matchers.greaterThan(0)); assertThat(SemanticVersion.parseVersion("1.0.0-beta").compareTo( SemanticVersion.parseVersion("1.0.0-alpha.alpha.1")), Matchers.greaterThan(0)); assertThat(SemanticVersion.parseVersion("1.0.0-beta").compareTo( SemanticVersion.parseVersion("1.0.0-alpha.beta")), Matchers.greaterThan(0)); assertThat(SemanticVersion.parseVersion("1.0.0-beta.2").compareTo( SemanticVersion.parseVersion("1.0.0-beta")), Matchers.greaterThan(0)); assertThat(SemanticVersion.parseVersion("1.0.0-beta.11").compareTo( SemanticVersion.parseVersion("1.0.0-beta.2")), Matchers.greaterThan(0)); assertThat(SemanticVersion.parseVersion("1.0.0-rc.1").compareTo( SemanticVersion.parseVersion("1.0.0-beta.11")), Matchers.greaterThan(0)); assertThat(SemanticVersion.parseVersion("1.0.0").compareTo( SemanticVersion.parseVersion("1.0.0-rc.1")), Matchers.greaterThan(0)); } @Test public void testCompareToWithGoPseudoVersions() { assertThat(SemanticVersion.parseVersion("v1.2.3-20200518203908-8018eb2c26ba").compareTo( SemanticVersion.parseVersion("v1.2.3-20191204190536-9bdfabe68543")), Matchers.greaterThan(0)); } }
8,934
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/test/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/test/java/software/amazon/smithy/go/codegen/EnumShapeGeneratorTest.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen; import java.util.logging.Logger; import org.junit.jupiter.api.Test; import software.amazon.smithy.build.MockManifest; import software.amazon.smithy.build.PluginContext; import software.amazon.smithy.go.codegen.GoCodegenPlugin; import software.amazon.smithy.model.Model; import static org.hamcrest.Matchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static software.amazon.smithy.go.codegen.TestUtils.buildMockPluginContext; import static software.amazon.smithy.go.codegen.TestUtils.loadSmithyModelFromResource; import static software.amazon.smithy.go.codegen.TestUtils.loadExpectedFileStringFromResource; public class EnumShapeGeneratorTest { private static final Logger LOGGER = Logger.getLogger(EnumShapeGeneratorTest.class.getName()); @Test public void testEnumShapeTest() { // Arrange Model model = loadSmithyModelFromResource("enum-shape-test"); MockManifest manifest = new MockManifest(); PluginContext context = buildMockPluginContext(model, manifest, "smithy.example#Example"); // Act (new GoCodegenPlugin()).execute(context); // Assert String actualSuitEnumShapeCode = manifest.getFileString("types/enums.go").get(); String expectedSuitEnumShapeCode = loadExpectedFileStringFromResource("enum-shape-test", "types/enums.go"); assertThat("enum shape actual generated code is equal to the expected generated code", actualSuitEnumShapeCode, is(expectedSuitEnumShapeCode)); } }
8,935
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/test/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/test/java/software/amazon/smithy/go/codegen/DocumentationConverterTest.java
package software.amazon.smithy.go.codegen; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; public class DocumentationConverterTest { private static final int DEFAULT_DOC_WRAP_LENGTH = 80; @ParameterizedTest @MethodSource("cases") void convertsDocs(String given, String expected) { assertThat(DocumentationConverter.convert(given, DEFAULT_DOC_WRAP_LENGTH), equalTo(expected)); } private static Stream<Arguments> cases() { return Stream.of( Arguments.of( "Testing 1 2 3", "Testing 1 2 3" ), Arguments.of( "<a href=\"https://example.com\">a link</a>", "a link (https://example.com)" ), Arguments.of( "<a href=\" https://example.com\">a link</a>", "a link (https://example.com)" ), Arguments.of( "<a>empty link</a>", "empty link" ), Arguments.of( "<ul><li>Testing 1 2 3</li> <li>FooBar</li></ul>", " - Testing 1 2 3\n - FooBar" ), Arguments.of( "<ul> <li>Testing 1 2 3</li> <li>FooBar</li> </ul>", " - Testing 1 2 3\n - FooBar" ), Arguments.of( " <ul> <li>Testing 1 2 3</li> <li>FooBar</li> </ul>", " - Testing 1 2 3\n - FooBar" ), Arguments.of( "<ul> <li> <p>Testing 1 2 3</p> </li><li> <p>FooBar</p></li></ul>", " - Testing 1 2 3\n - FooBar" ), Arguments.of( "<ul> <li><code>Testing</code>: 1 2 3</li> <li>FooBar</li> </ul>", " - Testing : 1 2 3\n - FooBar" ), Arguments.of( "<ul> <li><p><code>FOO</code> Bar</p></li><li><p><code>Xyz</code> ABC</p></li></ul>", " - FOO Bar\n - Xyz ABC" ), Arguments.of( "<ul><li> foo</li><li>\tbar</li><li>\nbaz</li></ul>", " - foo\n - bar\n - baz" ), Arguments.of( "<p><code>Testing</code>: 1 2 3</p>", "Testing : 1 2 3" ), Arguments.of( "<pre><code>Testing</code></pre>", " Testing" ), Arguments.of( "<p>Testing 1 2 3</p>", "Testing 1 2 3" ), Arguments.of( "<span data-target-type=\"operation\" data-service=\"secretsmanager\" " + "data-target=\"CreateSecret\">CreateSecret</span> <span data-target-type=" + "\"structure\" data-service=\"secretsmanager\" data-target=\"SecretListEntry\">" + "SecretListEntry</span> <span data-target-type=\"structure\" data-service=" + "\"secretsmanager\" data-target=\"CreateSecret$SecretName\">SecretName</span> " + "<span data-target-type=\"structure\" data-service=\"secretsmanager\" " + "data-target=\"SecretListEntry$KmsKeyId\">KmsKeyId</span>", "CreateSecret SecretListEntry SecretName KmsKeyId" ), Arguments.of( "<p> Deletes the replication configuration from the bucket. For information about replication" + " configuration, see " + "<a href=\" https://docs.aws.amazon.com/AmazonS3/latest/dev/crr.html\">" + "Cross-Region Replication (CRR)</a> in the <i>Amazon S3 Developer Guide</i>. </p>", "Deletes the replication configuration from the bucket. For information about\n" + "replication configuration, see Cross-Region Replication (CRR) (https://docs.aws.amazon.com/AmazonS3/latest/dev/crr.html)\n" + "in the Amazon S3 Developer Guide." ), Arguments.of( "* foo\n* bar", " - foo\n - bar" ), Arguments.of( "[a link](https://example.com)", "a link (https://example.com)" ), Arguments.of("", ""), Arguments.of("<!-- foo bar -->", ""), Arguments.of("# Foo\nbar", "Foo\nbar"), Arguments.of("<h1>Foo</h1>bar", "Foo\nbar"), Arguments.of("## Foo\nbar", "Foo\nbar"), Arguments.of("<h2>Foo</h2>bar", "Foo\nbar"), Arguments.of("### Foo\nbar", "Foo\nbar"), Arguments.of("<h3>Foo</h3>bar", "Foo\nbar"), Arguments.of("#### Foo\nbar", "Foo\nbar"), Arguments.of("<h4>Foo</h4>bar", "Foo\nbar"), Arguments.of("##### Foo\nbar", "Foo\nbar"), Arguments.of("<h5>Foo</h5>bar", "Foo\nbar"), Arguments.of("###### Foo\nbar", "Foo\nbar"), Arguments.of("<h6>Foo</h6>bar", "Foo\nbar"), Arguments.of("Inline `code`", "Inline code"), Arguments.of("```\ncode block\n ```", " code block"), Arguments.of("```java\ncode block\n ```", " code block"), Arguments.of("foo<br/>bar", "foo\n\nbar"), Arguments.of(" <p>foo</p>", "foo") ); } }
8,936
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/SmithyGoDependency.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen; /** * A class of constants for dependencies used by this package. */ public final class SmithyGoDependency { // The version in the stdlib dependencies should reflect the minimum Go version. // The values aren't currently used, but they could potentially used to dynamically // set the minimum go version. public static final GoDependency BIG = stdlib("math/big"); public static final GoDependency TIME = stdlib("time"); public static final GoDependency FMT = stdlib("fmt"); public static final GoDependency CONTEXT = stdlib("context"); public static final GoDependency STRCONV = stdlib("strconv"); public static final GoDependency BASE64 = stdlib("encoding/base64"); public static final GoDependency NET = stdlib("net"); public static final GoDependency NET_URL = stdlib("net/url"); public static final GoDependency NET_HTTP = stdlib("net/http"); public static final GoDependency NET_HTTP_TEST = stdlib("net/http/httptest"); public static final GoDependency BYTES = stdlib("bytes"); public static final GoDependency STRINGS = stdlib("strings"); public static final GoDependency JSON = stdlib("encoding/json"); public static final GoDependency IO = stdlib("io"); public static final GoDependency IOUTIL = stdlib("io/ioutil"); public static final GoDependency CRYPTORAND = stdlib("crypto/rand", "cryptorand"); public static final GoDependency TESTING = stdlib("testing"); public static final GoDependency ERRORS = stdlib("errors"); public static final GoDependency XML = stdlib("encoding/xml"); public static final GoDependency SYNC = stdlib("sync"); public static final GoDependency PATH = stdlib("path"); public static final GoDependency LOG = stdlib("log"); public static final GoDependency OS = stdlib("os"); public static final GoDependency PATH_FILEPATH = stdlib("path/filepath"); public static final GoDependency REFLECT = stdlib("reflect"); public static final GoDependency SMITHY = smithy(null, "smithy"); public static final GoDependency SMITHY_TRANSPORT = smithy("transport", "smithytransport"); public static final GoDependency SMITHY_HTTP_TRANSPORT = smithy("transport/http", "smithyhttp"); public static final GoDependency SMITHY_MIDDLEWARE = smithy("middleware"); public static final GoDependency SMITHY_PRIVATE_PROTOCOL = smithy("private/protocol", "smithyprivateprotocol"); public static final GoDependency SMITHY_TIME = smithy("time", "smithytime"); public static final GoDependency SMITHY_HTTP_BINDING = smithy("encoding/httpbinding"); public static final GoDependency SMITHY_JSON = smithy("encoding/json", "smithyjson"); public static final GoDependency SMITHY_XML = smithy("encoding/xml", "smithyxml"); public static final GoDependency SMITHY_IO = smithy("io", "smithyio"); public static final GoDependency SMITHY_LOGGING = smithy("logging"); public static final GoDependency SMITHY_PTR = smithy("ptr"); public static final GoDependency SMITHY_RAND = smithy("rand", "smithyrand"); public static final GoDependency SMITHY_TESTING = smithy("testing", "smithytesting"); public static final GoDependency SMITHY_WAITERS = smithy("waiter", "smithywaiter"); public static final GoDependency SMITHY_DOCUMENT = smithy("document", "smithydocument"); public static final GoDependency SMITHY_DOCUMENT_JSON = smithy("document/json", "smithydocumentjson"); public static final GoDependency SMITHY_SYNC = smithy("sync", "smithysync"); public static final GoDependency SMITHY_AUTH_BEARER = smithy("auth/bearer"); public static final GoDependency SMITHY_ENDPOINTS = smithy("endpoints", "smithyendpoints"); public static final GoDependency SMITHY_ENDPOINT_RULESFN = smithy("endpoints/private/rulesfn"); public static final GoDependency GO_CMP = goCmp("cmp"); public static final GoDependency GO_CMP_OPTIONS = goCmp("cmp/cmpopts"); public static final GoDependency GO_JMESPATH = goJmespath(null); public static final GoDependency MATH = stdlib("math"); private static final String SMITHY_SOURCE_PATH = "github.com/aws/smithy-go"; private static final String GO_CMP_SOURCE_PATH = "github.com/google/go-cmp"; private static final String GO_JMESPATH_SOURCE_PATH = "github.com/jmespath/go-jmespath"; private SmithyGoDependency() { } /** * Get a {@link GoDependency} representing the standard library package import path. * * @param importPath standard library import path * @return the {@link GoDependency} for the package import path */ public static GoDependency stdlib(String importPath) { return GoDependency.standardLibraryDependency(importPath, Versions.GO_STDLIB); } /** * Get a {@link GoDependency} representing the standard library package import path with the given alias. * * @param importPath standard library package import path * @param alias the package alias * @return the {@link GoDependency} for the package import path */ public static GoDependency stdlib(String importPath, String alias) { return GoDependency.standardLibraryDependency(importPath, Versions.GO_STDLIB, alias); } private static GoDependency smithy(String relativePath) { return smithy(relativePath, null); } private static GoDependency smithy(String relativePath, String alias) { return relativePackage(SMITHY_SOURCE_PATH, relativePath, Versions.SMITHY_GO, alias); } private static GoDependency goCmp(String relativePath) { return relativePackage(GO_CMP_SOURCE_PATH, relativePath, Versions.GO_CMP, null); } private static GoDependency goJmespath(String relativePath) { return relativePackage(GO_JMESPATH_SOURCE_PATH, relativePath, Versions.GO_JMESPATH, null); } private static GoDependency relativePackage( String moduleImportPath, String relativePath, String version, String alias ) { String importPath = moduleImportPath; if (relativePath != null) { importPath = importPath + "/" + relativePath; } return GoDependency.moduleDependency(moduleImportPath, importPath, version, alias); } private static final class Versions { private static final String GO_STDLIB = "1.15"; private static final String GO_CMP = "v0.5.4"; private static final String SMITHY_GO = "v1.4.0"; private static final String GO_JMESPATH = "v0.4.0"; } }
8,937
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/GoDelegator.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen; import java.util.function.Consumer; import software.amazon.smithy.build.FileManifest; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.codegen.core.SymbolProvider; import software.amazon.smithy.codegen.core.SymbolReference; import software.amazon.smithy.model.shapes.Shape; /** * Manages writers for Go files.Based off of GoWriterDelegator adding support * for getting shape specific GoWriters. */ public final class GoDelegator extends GoWriterDelegator { private final SymbolProvider symbolProvider; GoDelegator(FileManifest fileManifest, SymbolProvider symbolProvider) { super(fileManifest); this.symbolProvider = symbolProvider; } /** * Gets a previously created writer or creates a new one if needed. * * @param shape Shape to create the writer for. * @param writerConsumer Consumer that accepts and works with the file. */ public void useShapeWriter(Shape shape, Consumer<GoWriter> writerConsumer) { Symbol symbol = symbolProvider.toSymbol(shape); useShapeWriter(symbol, writerConsumer); } /** * Gets a previously created writer or creates a new one for the a Go test file for the associated shape. * * @param shape Shape to create the writer for. * @param writerConsumer Consumer that accepts and works with the file. */ public void useShapeTestWriter(Shape shape, Consumer<GoWriter> writerConsumer) { Symbol symbol = symbolProvider.toSymbol(shape); String filename = symbol.getDefinitionFile(); StringBuilder b = new StringBuilder(filename); b.insert(filename.lastIndexOf(".go"), "_test"); filename = b.toString(); symbol = symbol.toBuilder() .definitionFile(filename) .build(); useShapeWriter(symbol, writerConsumer); } /** * Gets a previously created writer or creates a new one for the a Go public package test file for the associated * shape. * * @param shape Shape to create the writer for. * @param writerConsumer Consumer that accepts and works with the file. */ public void useShapeExportedTestWriter(Shape shape, Consumer<GoWriter> writerConsumer) { Symbol symbol = symbolProvider.toSymbol(shape); String filename = symbol.getDefinitionFile(); StringBuilder b = new StringBuilder(filename); b.insert(filename.lastIndexOf(".go"), "_exported_test"); filename = b.toString(); symbol = symbol.toBuilder() .definitionFile(filename) .namespace(symbol.getNamespace() + "_test", symbol.getNamespaceDelimiter()) .build(); useShapeWriter(symbol, writerConsumer); } /** * Gets a previously created writer or creates a new one if needed. * * @param symbol symbol to create the writer for. * @param writerConsumer Consumer that accepts and works with the file. */ private void useShapeWriter(Symbol symbol, Consumer<GoWriter> writerConsumer) { GoWriter writer = checkoutWriter(symbol.getDefinitionFile(), symbol.getNamespace()); // Add any needed DECLARE symbols. writer.addImportReferences(symbol, SymbolReference.ContextOption.DECLARE); symbol.getDependencies().forEach(writer::addDependency); writer.pushState(); writerConsumer.accept(writer); writer.popState(); } }
8,938
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/SymbolUtils.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.model.shapes.Shape; /** * Common symbol utility building functions. */ public final class SymbolUtils { public static final String POINTABLE = "pointable"; public static final String NAMESPACE_ALIAS = "namespaceAlias"; public static final String GO_UNIVERSE_TYPE = "universeType"; public static final String GO_SLICE = "goSlice"; public static final String GO_MAP = "goMap"; public static final String GO_ELEMENT_TYPE = "goElementType"; // Used when a given shape must be represented differently on input. public static final String INPUT_VARIANT = "inputVariant"; private SymbolUtils() { } /** * Create a value symbol builder. * * @param typeName the name of the type. * @return the symbol builder type. */ public static Symbol.Builder createValueSymbolBuilder(String typeName) { return Symbol.builder() .putProperty(POINTABLE, false) .name(typeName); } /** * Create a pointable symbol builder. * * @param typeName the name of the type. * @return the symbol builder. */ public static Symbol.Builder createPointableSymbolBuilder(String typeName) { return Symbol.builder() .putProperty(POINTABLE, true) .name(typeName); } /** * Create a value symbol builder. * * @param shape the shape that the type is for. * @param typeName the name of the type. * @return the symbol builder. */ public static Symbol.Builder createValueSymbolBuilder(Shape shape, String typeName) { return createValueSymbolBuilder(typeName).putProperty("shape", shape); } /** * Create a pointable symbol builder. * * @param shape the shape that the type is for. * @param typeName the name of the type. * @return the symbol builder. */ public static Symbol.Builder createPointableSymbolBuilder(Shape shape, String typeName) { return createPointableSymbolBuilder(typeName).putProperty("shape", shape); } /** * Create a pointable symbol builder. * * @param typeName the name of the type. * @param namespace the namespace of the type. * @return the symbol builder. */ public static Symbol.Builder createPointableSymbolBuilder(String typeName, String namespace) { return createPointableSymbolBuilder(typeName).namespace(namespace, "."); } /** * Create a value symbol builder. * * @param typeName the name of the type. * @param namespace the namespace of the type. * @return the symbol builder. */ public static Symbol.Builder createValueSymbolBuilder(String typeName, String namespace) { return createValueSymbolBuilder(typeName).namespace(namespace, "."); } /** * Create a pointable symbol builder. * * @param shape the shape that the type is for. * @param typeName the name of the type. * @param namespace the namespace of the type. * @return the symbol builder. */ public static Symbol.Builder createPointableSymbolBuilder(Shape shape, String typeName, String namespace) { return createPointableSymbolBuilder(shape, typeName).namespace(namespace, "."); } /** * Create a value symbol builder. * * @param shape the shape that the type is for. * @param typeName the name of the type. * @param namespace the namespace of the type. * @return the symbol builder. */ public static Symbol.Builder createValueSymbolBuilder(Shape shape, String typeName, String namespace) { return createValueSymbolBuilder(shape, typeName).namespace(namespace, "."); } /** * Create a pointable symbol builder. * * @param shape the shape that the type is for. * @param typeName the name of the type. * @param namespace the namespace of the type. * @return the symbol builder. */ public static Symbol.Builder createPointableSymbolBuilder(Shape shape, String typeName, GoDependency namespace) { return setImportedNamespace(createPointableSymbolBuilder(shape, typeName), namespace); } /** * Create a value symbol builder. * * @param shape the shape that the type is for. * @param typeName the name of the type. * @param namespace the namespace of the type. * @return the symbol builder. */ public static Symbol.Builder createValueSymbolBuilder(Shape shape, String typeName, GoDependency namespace) { return setImportedNamespace(createValueSymbolBuilder(shape, typeName), namespace); } /** * Create a pointable symbol builder. * * @param typeName the name of the type. * @param namespace the namespace of the type. * @return the symbol builder. */ public static Symbol.Builder createPointableSymbolBuilder(String typeName, GoDependency namespace) { return setImportedNamespace(createPointableSymbolBuilder(typeName), namespace); } /** * Create a value symbol builder. * * @param typeName the name of the type. * @param namespace the namespace of the type. * @return the symbol builder. */ public static Symbol.Builder createValueSymbolBuilder(String typeName, GoDependency namespace) { return setImportedNamespace(createValueSymbolBuilder(typeName), namespace); } private static Symbol.Builder setImportedNamespace(Symbol.Builder builder, GoDependency dependency) { return builder.namespace(dependency.getImportPath(), ".") .addDependency(dependency) .putProperty(NAMESPACE_ALIAS, dependency.getAlias()); } /** * Go declares several built-in language types in what is known as the Universe block. This function determines * whether the provided symbol represents a Go universe type. * * @param symbol the symbol to check * @return whether the symbol type is in the Go universe block * @see <a href="https://golang.org/ref/spec#Predeclared_identifiers">The Go Programming Language Specification</a> */ public static boolean isUniverseType(Symbol symbol) { return symbol.getProperty(SymbolUtils.GO_UNIVERSE_TYPE, Boolean.class) .orElse(false); } public static Symbol.Builder getPackageSymbol( String importPath, String symbolName, String namespaceAlias, boolean pointable ) { Symbol.Builder builder; if (pointable) { builder = SymbolUtils.createPointableSymbolBuilder(symbolName); } else { builder = SymbolUtils.createValueSymbolBuilder(symbolName); } // TODO this doesn't seem right return builder.namespace(importPath, "/").putProperty(SymbolUtils.NAMESPACE_ALIAS, namespaceAlias); } }
8,939
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/GoModuleInfo.java
/* * Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.function.Predicate; import java.util.stream.Collectors; import software.amazon.smithy.codegen.core.SymbolDependency; import software.amazon.smithy.utils.BuilderRef; import software.amazon.smithy.utils.SmithyBuilder; public final class GoModuleInfo { public static final String DEFAULT_GO_DIRECTIVE = "1.15"; private List<SymbolDependency> dependencies; private List<SymbolDependency> stdLibDependencies; private List<SymbolDependency> nonStdLibDependencies; private String goDirective; private Map<String, String> minimumNonStdLibDependencies; private GoModuleInfo(Builder builder) { goDirective = SmithyBuilder.requiredState("goDirective", builder.goDirective); dependencies = builder.dependencies.copy(); // Intermediate dependency information stdLibDependencies = gatherStdLibDependencies(); nonStdLibDependencies = gatherNonStdLibDependencies(); // Module information used by ManifestWriter and GoModGenerator goDirective = calculateMinimumGoDirective(); minimumNonStdLibDependencies = gatherMinimumNonStdDependencies(); } public String getGoDirective() { return goDirective; } public Map<String, String> getMinimumNonStdLibDependencies() { return minimumNonStdLibDependencies; } private String calculateMinimumGoDirective() { String minimumGoDirective = goDirective; if (minimumGoDirective.compareTo(DEFAULT_GO_DIRECTIVE) < 0) { throw new IllegalArgumentException( "`goDirective` must be greater than or equal to the default go directive (" + DEFAULT_GO_DIRECTIVE + "): " + minimumGoDirective); } for (SymbolDependency dependency : stdLibDependencies) { var otherVersion = dependency.getVersion(); if (minimumGoDirective.compareTo(otherVersion) < 0) { minimumGoDirective = otherVersion; } } return minimumGoDirective; } private List<SymbolDependency> gatherStdLibDependencies() { return filterDependencies(dependency -> dependency.getDependencyType().equals(GoDependency.Type.STANDARD_LIBRARY.toString())); } private List<SymbolDependency> gatherNonStdLibDependencies() { return filterDependencies(dependency -> !dependency.getDependencyType().equals(GoDependency.Type.STANDARD_LIBRARY.toString())); } private List<SymbolDependency> filterDependencies( Predicate<SymbolDependency> predicate ) { List<SymbolDependency> filteredDependencies = new ArrayList<>(); for (SymbolDependency dependency : dependencies) { if (predicate.test(dependency)) { filteredDependencies.add(dependency); } } return filteredDependencies; } private Map<String, String> gatherMinimumNonStdDependencies() { return SymbolDependency.gatherDependencies(nonStdLibDependencies.stream(), GoDependency::mergeByMinimumVersionSelection).entrySet().stream().flatMap( entry -> entry.getValue().entrySet().stream()).collect( Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().getVersion(), (a, b) -> b, TreeMap::new)); } public static class Builder implements SmithyBuilder<GoModuleInfo> { private String goDirective = DEFAULT_GO_DIRECTIVE; private final BuilderRef<List<SymbolDependency>> dependencies = BuilderRef.forList(); public Builder goDirective(String goDirective) { this.goDirective = goDirective; return this; } public Builder dependencies(List<SymbolDependency> dependencies) { this.dependencies.clear(); this.dependencies.get().addAll(dependencies); return this; } @Override public GoModuleInfo build() { return new GoModuleInfo(this); } } }
8,940
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/ShapeValueGenerator.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * * */ package software.amazon.smithy.go.codegen; import java.math.BigInteger; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.logging.Logger; import software.amazon.smithy.codegen.core.CodegenException; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.codegen.core.SymbolProvider; import software.amazon.smithy.go.codegen.knowledge.GoPointableIndex; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.node.ArrayNode; import software.amazon.smithy.model.node.BooleanNode; import software.amazon.smithy.model.node.Node; import software.amazon.smithy.model.node.NodeVisitor; import software.amazon.smithy.model.node.NullNode; import software.amazon.smithy.model.node.NumberNode; import software.amazon.smithy.model.node.ObjectNode; import software.amazon.smithy.model.node.StringNode; import software.amazon.smithy.model.shapes.MapShape; import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeType; import software.amazon.smithy.model.shapes.SimpleShape; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.shapes.UnionShape; import software.amazon.smithy.model.traits.EnumTrait; import software.amazon.smithy.model.traits.HttpPrefixHeadersTrait; import software.amazon.smithy.model.traits.StreamingTrait; import software.amazon.smithy.model.traits.Trait; import software.amazon.smithy.utils.ListUtils; import software.amazon.smithy.utils.OptionalUtils; import software.amazon.smithy.utils.SmithyBuilder; /** * Generates a shape type declaration based on the parameters provided. */ public final class ShapeValueGenerator { private static final Logger LOGGER = Logger.getLogger(ShapeValueGenerator.class.getName()); private final GoSettings settings; private final Model model; private final SymbolProvider symbolProvider; private final GoPointableIndex pointableIndex; private final Config config; /** * Initializes a shape value generator. * * @param settings the Smithy Go settings. * @param model the Smithy model references. * @param symbolProvider the symbol provider. */ public ShapeValueGenerator(GoSettings settings, Model model, SymbolProvider symbolProvider) { this(settings, model, symbolProvider, Config.builder().build()); } /** * Initializes a shape value generator. * * @param settings the Smithy Go settings. * @param model the Smithy model references. * @param symbolProvider the symbol provider. * @param config the shape value generator config. */ public ShapeValueGenerator(GoSettings settings, Model model, SymbolProvider symbolProvider, Config config) { this.settings = settings; this.model = model; this.symbolProvider = symbolProvider; this.pointableIndex = GoPointableIndex.of(model); this.config = config; } /** * Writes generation of a shape value type declaration for the given the parameters. * * @param writer writer to write generated code with. * @param shape the shape that will be declared. * @param params parameters to fill the generated shape declaration. */ public void writePointableStructureShapeValueInline(GoWriter writer, StructureShape shape, Node params) { if (params.isNullNode()) { writer.writeInline("nil"); } // Input/output struct top level shapes are special since they are the only shape that can be used directly, // not within the context of a member shape reference. Symbol symbol = symbolProvider.toSymbol(shape); writer.write("&$T{", symbol); params.accept(new ShapeValueNodeVisitor(writer, this, shape, ListUtils.copyOf(shape.getAllTraits().values()), config)); writer.writeInline("}"); } /** * Writes generation of a member shape value type declaration for the given the parameters. * * @param writer writer to write generated code with. * @param member the shape that will be declared. * @param params parameters to fill the generated shape declaration. */ protected void writeMemberValueInline(GoWriter writer, MemberShape member, Node params) { Shape targetShape = model.expectShape(member.getTarget()); // Null params need to be represented as zero values for member, if (params.isNullNode()) { if (pointableIndex.isNillable(member)) { writer.writeInline("nil"); } else if (targetShape.getType() == ShapeType.STRING && targetShape.hasTrait(EnumTrait.class)) { Symbol enumSymbol = symbolProvider.toSymbol(targetShape); writer.writeInline("$T($S)", enumSymbol, ""); } else { Symbol shapeSymbol = symbolProvider.toSymbol(member); writer.writeInline("func() (v $P) { return v }()", shapeSymbol); } return; } switch (targetShape.getType()) { case STRUCTURE: structDeclShapeValue(writer, member, params); break; case SET: case LIST: listDeclShapeValue(writer, member, params); break; case MAP: mapDeclShapeValue(writer, member, params); break; case UNION: unionDeclShapeValue(writer, member, params.expectObjectNode()); break; case DOCUMENT: documentDeclShapeValue(writer, member, params); break; default: writeScalarPointerInline(writer, member, params); } } private void documentDeclShapeValue(GoWriter writer, MemberShape member, Node params) { Symbol newMarshaler = ProtocolDocumentGenerator.Utilities.getDocumentSymbolBuilder(settings, ProtocolDocumentGenerator.NEW_LAZY_DOCUMENT).build(); writer.writeInline("$T(", newMarshaler); params.accept(new DocumentValueNodeVisitor(writer)); writer.writeInline(")"); } /** * Writes the declaration for a Go structure. Delegates to the runner for member fields within the structure. * * @param writer writer to write generated code with. * @param member the structure shape * @param params parameters to fill the generated shape declaration. */ protected void structDeclShapeValue(GoWriter writer, MemberShape member, Node params) { Symbol symbol = symbolProvider.toSymbol(member); String addr = CodegenUtils.asAddressIfAddressable(model, pointableIndex, member, ""); writer.write("$L$T{", addr, symbol); params.accept(new ShapeValueNodeVisitor(writer, this, model.expectShape(member.getTarget()), ListUtils.copyOf(member.getAllTraits().values()), config)); writer.writeInline("}"); } /** * Writes the declaration for a Go union. * * @param writer writer to write generated code with. * @param member the union shape. * @param params the params. */ protected void unionDeclShapeValue(GoWriter writer, MemberShape member, ObjectNode params) { UnionShape targetShape = (UnionShape) model.expectShape(member.getTarget()); for (Map.Entry<StringNode, Node> entry : params.getMembers().entrySet()) { targetShape.getMember(entry.getKey().toString()).ifPresent((unionMember) -> { Shape unionTarget = model.expectShape(unionMember.getTarget()); // Need to manually create a symbol builder for a union member struct type because the "member" // of a union will return the inner value type not the member not the member type it self. Symbol memberSymbol = SymbolUtils.createPointableSymbolBuilder( symbolProvider.toMemberName(unionMember), symbolProvider.toSymbol(targetShape).getNamespace() ).build(); // Union member types are always pointers writer.writeInline("&$T{Value: ", memberSymbol); if (unionTarget instanceof SimpleShape) { writeScalarValueInline(writer, unionMember, entry.getValue()); } else { writeMemberValueInline(writer, unionMember, entry.getValue()); } writer.writeInline("}"); }); return; } } /** * Writes the declaration for a Go slice. Delegates to the runner for fields within the slice. * * @param writer writer to write generated code with. * @param member the collection shape * @param params parameters to fill the generated shape declaration. */ protected void listDeclShapeValue(GoWriter writer, MemberShape member, Node params) { writer.write("$P{", symbolProvider.toSymbol(member)); params.accept(new ShapeValueNodeVisitor(writer, this, model.expectShape(member.getTarget()), ListUtils.copyOf(member.getAllTraits().values()), config)); writer.writeInline("}"); } /** * Writes the declaration for a Go map. Delegates to the runner for key/value fields within the map. * * @param writer writer to write generated code with. * @param member the map shape. * @param params parameters to fill the generated shape declaration. */ protected void mapDeclShapeValue(GoWriter writer, MemberShape member, Node params) { writer.write("$P{", symbolProvider.toSymbol(member)); params.accept(new ShapeValueNodeVisitor(writer, this, model.expectShape(member.getTarget()), ListUtils.copyOf(member.getAllTraits().values()), config)); writer.writeInline("}"); } private void writeScalarWrapper( GoWriter writer, MemberShape member, Node params, String funcName, TriConsumer<GoWriter, MemberShape, Node> inner ) { if (pointableIndex.isPointable(member)) { writer.addUseImports(SmithyGoDependency.SMITHY_PTR); writer.writeInline("ptr." + funcName + "("); inner.accept(writer, member, params); writer.writeInline(")"); } else { inner.accept(writer, member, params); } } /** * Writes scalar values with pointer value wrapping as needed based on the shape type. * * @param writer writer to write generated code with. * @param member scalar shape. * @param params parameters to fill the generated shape declaration. */ protected void writeScalarPointerInline(GoWriter writer, MemberShape member, Node params) { Shape target = model.expectShape(member.getTarget()); String funcName = ""; switch (target.getType()) { case BOOLEAN: funcName = "Bool"; break; case STRING: funcName = "String"; break; case ENUM: funcName = target.getId().getName(); break; case TIMESTAMP: funcName = "Time"; break; case BYTE: funcName = "Int8"; break; case SHORT: funcName = "Int16"; break; case INTEGER: case INT_ENUM: funcName = "Int32"; break; case LONG: funcName = "Int64"; break; case FLOAT: funcName = "Float32"; break; case DOUBLE: funcName = "Float64"; break; case BLOB: break; case BIG_INTEGER: case BIG_DECIMAL: return; default: throw new CodegenException("unexpected shape type " + target.getType()); } writeScalarWrapper(writer, member, params, funcName, this::writeScalarValueInline); } protected void writeScalarValueInline(GoWriter writer, MemberShape member, Node params) { Shape target = model.expectShape(member.getTarget()); String closing = ""; switch (target.getType()) { case BLOB: // blob streams are io.Readers not byte slices. if (target.hasTrait(StreamingTrait.class)) { writer.addUseImports(SmithyGoDependency.SMITHY_IO); writer.addUseImports(SmithyGoDependency.BYTES); writer.writeInline("smithyio.ReadSeekNopCloser{ReadSeeker: bytes.NewReader([]byte("); closing = "))}"; } else { writer.writeInline("[]byte("); closing = ")"; } break; case STRING: // String streams are io.Readers not strings. if (target.hasTrait(StreamingTrait.class)) { writer.addUseImports(SmithyGoDependency.SMITHY_IO); writer.addUseImports(SmithyGoDependency.STRINGS); writer.writeInline("smithyio.ReadSeekNopCloser{ReadSeeker: strings.NewReader("); closing = ")}"; } else if (target.hasTrait(EnumTrait.class)) { // Enum are not pointers, but string alias values Symbol enumSymbol = symbolProvider.toSymbol(target); writer.writeInline("$T(", enumSymbol); closing = ")"; } break; case ENUM: // Enum are not pointers, but string alias values Symbol enumSymbol = symbolProvider.toSymbol(target); writer.writeInline("$T(", enumSymbol); closing = ")"; break; default: break; } params.accept(new ShapeValueNodeVisitor(writer, this, target, ListUtils.copyOf(member.getAllTraits().values()), config)); writer.writeInline(closing); } /** * Configuration that determines how shapes values are generated. */ public static final class Config { private final boolean normalizeHttpPrefixHeaderKeys; private Config(Builder builder) { normalizeHttpPrefixHeaderKeys = builder.normalizeHttpPrefixHeaderKeys; } public static Builder builder() { return new Builder(); } /** * Returns whether maps with the httpPrefixHeader trait should have their keys normalized. * * @return whether to normalize http prefix header keys */ public boolean isNormalizeHttpPrefixHeaderKeys() { return normalizeHttpPrefixHeaderKeys; } public static final class Builder implements SmithyBuilder<Config> { private boolean normalizeHttpPrefixHeaderKeys; public Builder normalizeHttpPrefixHeaderKeys(boolean normalizeHttpPrefixHeaderKeys) { this.normalizeHttpPrefixHeaderKeys = normalizeHttpPrefixHeaderKeys; return this; } @Override public Config build() { return new Config(this); } } } private static final class DocumentValueNodeVisitor implements NodeVisitor<Void> { private final GoWriter writer; private DocumentValueNodeVisitor(GoWriter writer) { this.writer = writer; } @Override public Void arrayNode(ArrayNode node) { writer.writeInline("[]interface{}{\n"); for (Node element : node.getElements()) { element.accept(this); writer.writeInline(",\n"); } writer.writeInline("}"); return null; } @Override public Void booleanNode(BooleanNode node) { if (node.getValue()) { writer.writeInline("true"); } else { writer.writeInline("false"); } return null; } @Override public Void nullNode(NullNode node) { writer.writeInline("nil"); return null; } @Override public Void numberNode(NumberNode node) { if (node.isNaturalNumber()) { Number value = node.getValue(); if (value instanceof BigInteger) { writer.addUseImports(SmithyGoDependency.BIG); writer.writeInline("func () *big.Int {\n" + "\ti, ok := (&big.Int{}).SetString($S, 10)\n" + "\tif !ok { panic(\"failed to parse string to integer: \" + $S) }\n" + "\treturn i\n" + "}()", value, value); } else { writer.writeInline("$L", node.getValue()); } } else { Number value = node.getValue(); if (value instanceof Float) { writer.writeInline("float32($L)", value.floatValue(), value); } else if (value instanceof Double) { writer.writeInline("float64($L)", value.doubleValue(), value); } else { writer.addUseImports(SmithyGoDependency.BIG); writer.writeInline("func () *big.Float {\n" + "\tf, ok := (&big.Float{}).SetString($S)\n" + "\tif !ok { panic(\"failed to parse string to float: \" + $S) }\n" + "\treturn f\n" + "}()", value, value); } } return null; } @Override public Void objectNode(ObjectNode node) { writer.writeInline("map[string]interface{}{\n"); node.getMembers().forEach((key, value) -> { writer.writeInline("$S: ", key.getValue()); value.accept(this); writer.writeInline(",\n"); }); writer.writeInline("}"); return null; } @Override public Void stringNode(StringNode node) { writer.writeInline("$S", node.getValue()); return null; } } /** * NodeVisitor to walk shape value declarations with node values. */ private final class ShapeValueNodeVisitor implements NodeVisitor<Void> { private final GoWriter writer; private final ShapeValueGenerator valueGen; private final Shape currentShape; private final List<Trait> traits; private final Config config; /** * Initializes shape value visitor. * * @param writer writer to write generated code with. * @param valueGen shape value generator. * @param shape the shape that visiting is relative to. */ private ShapeValueNodeVisitor(GoWriter writer, ShapeValueGenerator valueGen, Shape shape) { this(writer, valueGen, shape, ListUtils.of()); } /** * Initializes shape value visitor. * * @param writer writer to write generated code with. * @param valueGen shape value generator. * @param shape the shape that visiting is relative to. * @param traits the traits applied to the target shape by a MemberShape. */ private ShapeValueNodeVisitor(GoWriter writer, ShapeValueGenerator valueGen, Shape shape, List<Trait> traits) { this(writer, valueGen, shape, traits, Config.builder().build()); } /** * Initializes shape value visitor. * * @param writer writer to write generated code with. * @param valueGen shape value generator. * @param shape the shape that visiting is relative to. * @param traits the traits applied to the target shape by a MemberShape. * @param config the shape value generator config. */ private ShapeValueNodeVisitor( GoWriter writer, ShapeValueGenerator valueGen, Shape shape, List<Trait> traits, Config config ) { this.writer = writer; this.valueGen = valueGen; this.currentShape = shape; this.traits = traits; this.config = config; } /** * When array nodes elements are encountered. * * @param node the node * @return always null */ @Override public Void arrayNode(ArrayNode node) { MemberShape memberShape = CodegenUtils.expectCollectionShape(this.currentShape).getMember(); node.getElements().forEach(element -> { valueGen.writeMemberValueInline(writer, memberShape, element); writer.write(","); }); return null; } /** * When an object node elements are encountered. * * @param node the node * @return always null */ @Override public Void objectNode(ObjectNode node) { node.getMembers().forEach((keyNode, valueNode) -> { MemberShape member; switch (currentShape.getType()) { case STRUCTURE: if (currentShape.asStructureShape().get().getMember(keyNode.getValue()).isPresent()) { member = currentShape.asStructureShape().get().getMember(keyNode.getValue()).get(); } else { throw new CodegenException( "unknown member " + currentShape.getId() + "." + keyNode.getValue()); } String memberName = symbolProvider.toMemberName(member); writer.write("$L: ", memberName); valueGen.writeMemberValueInline(writer, member, valueNode); writer.write(","); break; case MAP: MapShape mapShape = this.currentShape.asMapShape().get(); String keyValue = keyNode.getValue(); if (config.isNormalizeHttpPrefixHeaderKeys()) { keyValue = OptionalUtils.or(getTrait(HttpPrefixHeadersTrait.class), () -> mapShape.getTrait(HttpPrefixHeadersTrait.class)) .map(httpPrefixHeadersTrait -> keyNode.getValue().toLowerCase()) .orElse(keyValue); } writer.write("$S: ", keyValue); valueGen.writeMemberValueInline(writer, mapShape.getValue(), valueNode); writer.write(","); break; default: throw new CodegenException("unexpected shape type " + currentShape.getType()); } }); return null; } /** * When boolean nodes are encountered. * * @param node the node * @return always null */ @Override public Void booleanNode(BooleanNode node) { if (!currentShape.getType().equals(ShapeType.BOOLEAN)) { throw new CodegenException("unexpected shape type " + currentShape + " for boolean value"); } writer.writeInline("$L", node.getValue() ? "true" : "false"); return null; } /** * When null nodes are encountered. * * @param node the node * @return always null */ @Override public Void nullNode(NullNode node) { throw new CodegenException("unexpected null node walked, should not be encountered in walker"); } /** * When number nodes are encountered. * * @param node the node * @return always null */ @Override public Void numberNode(NumberNode node) { switch (currentShape.getType()) { case TIMESTAMP: writer.addUseImports(SmithyGoDependency.SMITHY_TIME); writer.writeInline("smithytime.ParseEpochSeconds($L)", node.getValue()); break; case BYTE: case SHORT: case INTEGER: case INT_ENUM: case LONG: case FLOAT: case DOUBLE: writer.writeInline("$L", node.getValue()); break; case BIG_INTEGER: writeInlineBigIntegerInit(writer, node.getValue()); break; case BIG_DECIMAL: writeInlineBigDecimalInit(writer, node.getValue()); break; default: throw new CodegenException("unexpected shape type " + currentShape + " for string value"); } return null; } /** * When string nodes are encountered. * * @param node the node * @return always null */ @Override public Void stringNode(StringNode node) { switch (currentShape.getType()) { case BLOB: case STRING: writer.writeInline("$S", node.getValue()); break; case ENUM: writer.writeInline("$S", node.getValue()); break; case BIG_INTEGER: writeInlineBigIntegerInit(writer, node.getValue()); break; case BIG_DECIMAL: writeInlineBigDecimalInit(writer, node.getValue()); break; case DOUBLE: writeInlineNonNumericFloat(writer, node.getValue()); break; case FLOAT: writer.writeInline("float32("); writeInlineNonNumericFloat(writer, node.getValue()); writer.writeInline(")"); break; default: throw new CodegenException("unexpected shape type " + currentShape.getType()); } return null; } private void writeInlineBigDecimalInit(GoWriter writer, Object value) { writer.addUseImports(SmithyGoDependency.BIG); writer.writeInline("func() *big.Float {\n" + " i, ok := big.ParseFloat($S, 10, 200, big.ToNearestAway)\n" + " if !ok { panic(\"invalid generated param value, \" + $S) }\n" + " return i" + "}()", value, value); } private void writeInlineBigIntegerInit(GoWriter writer, Object value) { writer.addUseImports(SmithyGoDependency.BIG); writer.writeInline("func() *big.Int {\n" + " i, ok := new(big.Int).SetString($S, 10)\n" + " if !ok { panic(\"invalid generated param value, \" + $S) }\n" + " return i" + "}()", value, value); } private void writeInlineNonNumericFloat(GoWriter writer, String value) { writer.addUseImports(SmithyGoDependency.stdlib("math")); switch (value) { case "NaN": writer.writeInline("math.NaN()"); break; case "Infinity": writer.writeInline("math.Inf(1)"); break; case "-Infinity": writer.writeInline("math.Inf(-1)"); break; default: throw new CodegenException(String.format( "Unexpected string value for `%s`: \"%s\"", currentShape.getId(), value)); } } private <T extends Trait> Optional<T> getTrait(Class<T> traitClass) { for (Trait trait : traits) { if (traitClass.isInstance(trait)) { return Optional.of((T) trait); } } return Optional.empty(); } } }
8,941
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/EnumGenerator.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen; import java.util.LinkedHashSet; import java.util.Locale; import java.util.Set; import java.util.logging.Logger; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.codegen.core.SymbolProvider; import software.amazon.smithy.model.shapes.StringShape; import software.amazon.smithy.model.traits.EnumDefinition; import software.amazon.smithy.model.traits.EnumTrait; import software.amazon.smithy.utils.StringUtils; /** * Renders enums and their constants. */ final class EnumGenerator implements Runnable { private static final Logger LOGGER = Logger.getLogger(EnumGenerator.class.getName()); private final SymbolProvider symbolProvider; private final GoWriter writer; private final StringShape shape; EnumGenerator(SymbolProvider symbolProvider, GoWriter writer, StringShape shape) { this.symbolProvider = symbolProvider; this.writer = writer; this.shape = shape; } @Override public void run() { Symbol symbol = symbolProvider.toSymbol(shape); EnumTrait enumTrait = shape.expectTrait(EnumTrait.class); writer.write("type $L string", symbol.getName()).write(""); // Don't generate constants if there are no explicitly modeled names. We only need to // look at one, since Smithy validates that if one has a name then they must all have // a name. if (enumTrait.getValues().get(0).getName().isPresent()) { writer.writeDocs(String.format("Enum values for %s", symbol.getName())); Set<String> constants = new LinkedHashSet<>(); writer.openBlock("const (", ")", () -> { for (EnumDefinition definition : enumTrait.getValues()) { StringBuilder labelBuilder = new StringBuilder(symbol.getName()); String name = definition.getName().get(); for (String part : name.split("(?U)[\\W_]")) { if (part.matches(".*[a-z].*") && part.matches(".*[A-Z].*")) { // Mixed case names should not be changed other than first letter capitalized. labelBuilder.append(StringUtils.capitalize(part)); } else { // For all non-mixed case parts title case first letter, followed by all other lower cased. labelBuilder.append(StringUtils.capitalize(part.toLowerCase(Locale.US))); } } String label = labelBuilder.toString(); // If camel-casing would cause a conflict, don't camel-case this enum value. if (constants.contains(label)) { LOGGER.warning(String.format( "Multiple enums resolved to the same name, `%s`, using unaltered value for: %s", label, name)); label = name; } constants.add(label); definition.getDocumentation().ifPresent(writer::writeDocs); writer.write("$L $L = $S", label, symbol.getName(), definition.getValue()); } }).write(""); } writer.writeDocs(String.format("Values returns all known values for %s. Note that this can be expanded in the " + "future, and so it is only as up to date as the client.%n%nThe ordering of this slice is not " + "guaranteed to be stable across updates.", symbol.getName())); writer.openBlock("func ($L) Values() []$L {", "}", symbol.getName(), symbol.getName(), () -> { writer.openBlock("return []$L{", "}", symbol.getName(), () -> { for (EnumDefinition definition : enumTrait.getValues()) { writer.write("$S,", definition.getValue()); } }); }); } }
8,942
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/GoSettings.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen; import java.util.Arrays; import java.util.Objects; import java.util.Optional; import java.util.Set; import software.amazon.smithy.codegen.core.CodegenException; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.knowledge.ServiceIndex; import software.amazon.smithy.model.node.ObjectNode; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.ShapeId; /** * Settings used by {@link GoCodegenPlugin}. */ public final class GoSettings { private static final String SERVICE = "service"; private static final String MODULE_NAME = "module"; private static final String MODULE_DESCRIPTION = "moduleDescription"; private static final String MODULE_VERSION = "moduleVersion"; private static final String GENERATE_GO_MOD = "generateGoMod"; private static final String GO_DIRECTIVE = "goDirective"; private ShapeId service; private String moduleName; private String moduleDescription = ""; private String moduleVersion; private Boolean generateGoMod = false; private String goDirective = GoModuleInfo.DEFAULT_GO_DIRECTIVE; private ShapeId protocol; /** * Create a settings object from a configuration object node. * * @param config Config object to load. * @return Returns the extracted settings. */ public static GoSettings from(ObjectNode config) { GoSettings settings = new GoSettings(); config.warnIfAdditionalProperties( Arrays.asList(SERVICE, MODULE_NAME, MODULE_DESCRIPTION, MODULE_VERSION, GENERATE_GO_MOD, GO_DIRECTIVE)); settings.setService(config.expectStringMember(SERVICE).expectShapeId()); settings.setModuleName(config.expectStringMember(MODULE_NAME).getValue()); settings.setModuleDescription(config.getStringMemberOrDefault( MODULE_DESCRIPTION, settings.getModuleName() + " client")); settings.setModuleVersion(config.getStringMemberOrDefault(MODULE_VERSION, null)); settings.setGenerateGoMod(config.getBooleanMemberOrDefault(GENERATE_GO_MOD, false)); settings.setGoDirective(config.getStringMemberOrDefault(GO_DIRECTIVE, GoModuleInfo.DEFAULT_GO_DIRECTIVE)); return settings; } /** * Gets the id of the service that is being generated. * * @return Returns the service id. * @throws NullPointerException if the service has not been set. */ public ShapeId getService() { return Objects.requireNonNull(service, SERVICE + " not set"); } /** * Gets the corresponding {@link ServiceShape} from a model. * * @param model Model to search for the service shape by ID. * @return Returns the found {@code Service}. * @throws NullPointerException if the service has not been set. * @throws CodegenException if the service is invalid or not found. */ public ServiceShape getService(Model model) { return model .getShape(getService()) .orElseThrow(() -> new CodegenException("Service shape not found: " + getService())) .asServiceShape() .orElseThrow(() -> new CodegenException("Shape is not a Service: " + getService())); } /** * Sets the service to generate. * * @param service The service to generate. */ public void setService(ShapeId service) { this.service = Objects.requireNonNull(service); } /** * Gets the required module name for the module that will be generated. * * @return Returns the module name. * @throws NullPointerException if the module name has not been set. */ public String getModuleName() { return Objects.requireNonNull(moduleName, MODULE_NAME + " not set"); } /** * Sets the name of the module to generate. * * @param moduleName The name of the module to generate. */ public void setModuleName(String moduleName) { this.moduleName = Objects.requireNonNull(moduleName); } /** * Gets the optional module description for the module that will be generated. * * @return Returns the module description. */ public String getModuleDescription() { return moduleDescription; } /** * Sets the description of the module to generate. * * @param moduleDescription The description of the module to generate. */ public void setModuleDescription(String moduleDescription) { this.moduleDescription = Objects.requireNonNull(moduleDescription); } /** * Gets the optional module version for the module that will be generated. * * @return Returns the module version. */ public Optional<String> getModuleVersion() { return Optional.ofNullable(moduleVersion); } /** * Sets the version of the module to generate. * * @param moduleVersion The version of the module to generate. */ public void setModuleVersion(String moduleVersion) { if (moduleVersion != null) { this.moduleVersion = moduleVersion; } } /** * Gets the flag for generating go.mod file. * * @return Returns if go.mod will be generated (true) or not (false) */ public Boolean getGenerateGoMod() { return generateGoMod; } /** * Sets the flag for generating go.mod file. * * @param generateGoMod If go.mod will be generated (true) or not (false) */ public void setGenerateGoMod(Boolean generateGoMod) { this.generateGoMod = Objects.requireNonNull(generateGoMod); } /** * Gets the optional Go directive for the module that will be generated. * * @return Returns the Go directive. */ public String getGoDirective() { return goDirective; } /** * Sets the Go directive of the module to generate. * * @param goDirective The Go directive of the module to generate. */ public void setGoDirective(String goDirective) { this.goDirective = Objects.requireNonNull(goDirective); } /** * Gets the configured protocol to generate. * * @return Returns the configured protocol. */ public ShapeId getProtocol() { return protocol; } /** * Resolves the highest priority protocol from a service shape that is * supported by the generator. * * @param serviceIndex Service index containing the support * @param service Service to get the protocols from if "protocols" is not set. * @param supportedProtocolTraits The set of protocol traits supported by the generator. * @return Returns the resolved protocol name. * @throws UnresolvableProtocolException if no protocol could be resolved. */ public ShapeId resolveServiceProtocol( ServiceIndex serviceIndex, ServiceShape service, Set<ShapeId> supportedProtocolTraits) { if (protocol != null) { return protocol; } Set<ShapeId> resolvedProtocols = serviceIndex.getProtocols(service).keySet(); return resolvedProtocols.stream() .filter(supportedProtocolTraits::contains) .findFirst() .orElseThrow(() -> new UnresolvableProtocolException(String.format( "The %s service supports the following unsupported protocols %s. The following protocol " + "generators were found on the class path: %s", service.getId(), resolvedProtocols, supportedProtocolTraits))); } /** * Sets the protocol to generate. * * @param protocol Protocols to generate. */ public void setProtocol(ShapeId protocol) { this.protocol = Objects.requireNonNull(protocol); } }
8,943
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/DocumentationConverter.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen; import java.util.Set; import org.commonmark.node.BlockQuote; import org.commonmark.node.FencedCodeBlock; import org.commonmark.node.Heading; import org.commonmark.node.HtmlBlock; import org.commonmark.node.ListBlock; import org.commonmark.node.ThematicBreak; import org.commonmark.parser.Parser; import org.commonmark.renderer.html.HtmlRenderer; import org.jsoup.Jsoup; import org.jsoup.nodes.Node; import org.jsoup.nodes.TextNode; import org.jsoup.safety.Safelist; import org.jsoup.select.NodeTraversor; import org.jsoup.select.NodeVisitor; import software.amazon.smithy.utils.CodeWriter; import software.amazon.smithy.utils.SetUtils; import software.amazon.smithy.utils.StringUtils; /** * Converts commonmark-formatted documentation into godoc format. */ public final class DocumentationConverter { // godoc only supports text blocks, root-level non-inline code blocks, headers, and links. // This allowlist strips out anything we can't reasonably convert, vastly simplifying the // node tree we end up having to crawl through. private static final Safelist GODOC_ALLOWLIST = new Safelist() .addTags("code", "pre", "ul", "ol", "li", "a", "br", "h1", "h2", "h3", "h4", "h5", "h6") .addAttributes("a", "href") .addProtocols("a", "href", "http", "https", "mailto"); // Construct a markdown parser that specifically ignores parsing indented code blocks. This // is because HTML blocks can have really wonky formatting that can be mis-attributed to an // indented code blocks. We may need to add a configuration option to re-enable this. private static final Parser MARKDOWN_PARSER = Parser.builder() .enabledBlockTypes(SetUtils.of( Heading.class, HtmlBlock.class, ThematicBreak.class, FencedCodeBlock.class, BlockQuote.class, ListBlock.class)) .build(); private DocumentationConverter() {} /** * Converts a commonmark formatted string into a godoc formatted string. * * @param docs commonmark formatted documentation * @return godoc formatted documentation */ public static String convert(String docs, int docWrapLength) { // Smithy's documentation format is commonmark, which can inline html. So here we convert // to html so we have a single known format to work with. String htmlDocs = HtmlRenderer.builder().escapeHtml(false).build().render(MARKDOWN_PARSER.parse(docs)); // Strip out tags and attributes we can't reasonably convert to godoc. htmlDocs = Jsoup.clean(htmlDocs, GODOC_ALLOWLIST); // Now we parse the html and visit the resultant nodes to render the godoc. FormattingVisitor formatter = new FormattingVisitor(docWrapLength); Node body = Jsoup.parse(htmlDocs).body(); NodeTraversor.traverse(formatter, body); return formatter.toString(); } private static class FormattingVisitor implements NodeVisitor { private static final Set<String> TEXT_BLOCK_NODES = SetUtils.of( "br", "p", "h1", "h2", "h3", "h4", "h5", "h6", "note" ); private static final Set<String> LIST_BLOCK_NODES = SetUtils.of("ul", "ol"); private static final Set<String> CODE_BLOCK_NODES = SetUtils.of("pre", "code"); private final CodeWriter writer; private boolean needsListPrefix = false; private boolean shouldStripPrefixWhitespace = false; private int docWrapLength; private int listDepth; // the last line string written, used to calculate the remaining spaces to reach docWrapLength // and determine if a split char is needed between it and next string private String lastLineString; FormattingVisitor(int docWrapLength) { writer = new CodeWriter(); writer.trimTrailingSpaces(false); writer.trimBlankLines(); writer.insertTrailingNewline(false); this.docWrapLength = docWrapLength; this.lastLineString = ""; } @Override public void head(Node node, int depth) { String name = node.nodeName(); if (isTopLevelCodeBlock(node, depth)) { writer.indent(); } if (node instanceof TextNode) { writeText((TextNode) node); } else if (TEXT_BLOCK_NODES.contains(name) || isTopLevelCodeBlock(node, depth)) { writeNewline(); writeIndent(); } else if (LIST_BLOCK_NODES.contains(name)) { listDepth++; } else if (name.equals("li")) { // We don't actually write out the list prefix here in case the list element // starts with one or more text blocks. By deferring writing those out until // the first bit of actual text, we can ensure that no intermediary newlines // are kept. It also has the added benefit of eliminating empty list elements. needsListPrefix = true; } } private void writeText(TextNode node) { if (node.isBlank()) { return; } // Docs can have valid $ characters that shouldn't run through formatters. String text = node.text().replace("$", "$$"); if (shouldStripPrefixWhitespace) { shouldStripPrefixWhitespace = false; text = StringUtils.stripStart(text, " \t"); } if (listDepth > 0) { text = StringUtils.stripStart(text, " \t"); if (needsListPrefix) { needsListPrefix = false; text = " - " + text; writeNewline(); } writeWrappedText(text, "\n "); } else { writeWrappedText(text, "\n"); } } private void writeWrappedText(String text, String newLineIndent) { // check the last line's remaining space to see if test should be // split to 2 parts to write to current and next line // note that wrapped text will not contain desired indent at the beginning, // so indent will be added to the wrapped text when it is written to a new line // right boundary index of text to be written to the same line exceeding // neither docWrapLength nor text length int trailingLineCutoff = Math.min(Math.max(docWrapLength - lastLineString.length(), 0), text.length()); // the index of last space on the left of boundary if exist int lastSpace = text.substring(0, trailingLineCutoff).lastIndexOf(" "); // if current line is large enough to put the text, just append complete text to current line // otherwise, cut out next line string starting from lastSpace index String appendString = trailingLineCutoff < text.length() ? text.substring(0, lastSpace + 1) : text; String nextLineString = trailingLineCutoff < text.length() ? text.substring(lastSpace + 1) : ""; if (!appendString.isEmpty()) { ensureSplit(" ", appendString); writeInline(appendString); } if (!nextLineString.isEmpty()) { nextLineString = StringUtils.stripStart(newLineIndent, "\n") + StringUtils.wrap(nextLineString, docWrapLength, newLineIndent, false); writeNewline(); writeInline(nextLineString); } } private void ensureSplit(String split, String text) { if (!text.startsWith(split) && !lastLineString.isEmpty() && !lastLineString.endsWith(split)) { writeInline(split); } } private void writeNewline() { // While jsoup will strip out redundant whitespace, it will still leave some. If we // start a new line then we want to make sure we don't keep any prefixing whitespace. // need to refresh last line string shouldStripPrefixWhitespace = true; writer.write(""); lastLineString = ""; } private void writeInline(String contents, String... args) { // write text at the current line, update last line string String formatText = writer.format(contents, args); writer.writeInlineWithNoFormatting(formatText); formatText = lastLineString + formatText; lastLineString = formatText.substring(formatText.lastIndexOf("\n") + 1); } void writeIndent() { writer.setNewline("").write("").setNewline("\n"); } private boolean isTopLevelCodeBlock(Node node, int depth) { // The node must be a code block node if (!CODE_BLOCK_NODES.contains(node.nodeName())) { return false; } // It must either have no siblings or its siblings must be separate blocks. if (!allSiblingsAreBlocks(node)) { return false; } // Depth 0 will always be a "body" element, so depth 1 means it's top level. if (depth == 1) { return true; } // If its depth is 2, it could still be effectively top level if its parent is a p // node whose siblings are all blocks. Node parent = node.parent(); return depth == 2 && parent.nodeName().equals("p") && allSiblingsAreBlocks(parent); } /** * Determines whether a given node's siblings are all text blocks, code blocks, or lists. * * <p>Siblings that are blank text nodes are skipped. * * @param node The node whose siblings should be checked. * @return true if the node's siblings are blocks, otherwise false. */ private boolean allSiblingsAreBlocks(Node node) { // Find the nearest sibling to the left which is not a blank text node. Node previous = node.previousSibling(); while (true) { if (previous instanceof TextNode) { if (((TextNode) previous).isBlank()) { previous = previous.previousSibling(); continue; } } break; } // Find the nearest sibling to the right which is not a blank text node. Node next = node.nextSibling(); while (true) { if (next instanceof TextNode) { if (((TextNode) next).isBlank()) { next = next.nextSibling(); continue; } } break; } return (previous == null || isBlockNode(previous)) && (next == null || isBlockNode(next)); } private boolean isBlockNode(Node node) { String name = node.nodeName(); return TEXT_BLOCK_NODES.contains(name) || LIST_BLOCK_NODES.contains(name) || CODE_BLOCK_NODES.contains(name); } @Override public void tail(Node node, int depth) { String name = node.nodeName(); if (isTopLevelCodeBlock(node, depth)) { writer.dedent(); } if (TEXT_BLOCK_NODES.contains(name) || isTopLevelCodeBlock(node, depth)) { writeNewline(); } else if (LIST_BLOCK_NODES.contains(name)) { listDepth--; if (listDepth == 0) { writeNewline(); } } else if (name.equals("a")) { String url = node.absUrl("href"); if (!url.isEmpty()) { // godoc can't render links with text bodies, so we simply append the link. // Full links do get rendered. writeInline(" ($L)", url); } } else if (name.equals("li")) { // Clear out the expectation of a list element if the element's body is empty. needsListPrefix = false; } } @Override public String toString() { String result = writer.toString(); if (StringUtils.isBlank(result)) { return ""; } // Strip trailing whitespace from every line. We can't use the codewriter for this due to // not knowing when a line will end, as we typically build them up over many elements. String[] lines = result.split("\n", -1); for (int i = 0; i < lines.length; i++) { lines[i] = StringUtils.stripEnd(lines[i], " \t"); } result = String.join("\n", lines); // Strip out leading and trailing newlines. return StringUtils.strip(result, "\n"); } } }
8,944
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/MiddlewareIdentifier.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen; import java.util.Objects; import java.util.Optional; import software.amazon.smithy.codegen.core.CodegenException; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.utils.SmithyBuilder; /** * A String or Go Symbol of type string used for middleware to identify themselves by. */ public final class MiddlewareIdentifier { private final String string; private final Symbol symbol; private MiddlewareIdentifier(Builder builder) { if ((Objects.isNull(builder.string) && Objects.isNull(builder.symbol))) { throw new IllegalStateException("string or symbol must be provided"); } if ((!Objects.isNull(builder.string) && !Objects.isNull(builder.symbol))) { throw new IllegalStateException("either string or symbol must be provided, not both"); } string = builder.string; symbol = builder.symbol; } public Optional<String> getString() { return Optional.ofNullable(string); } public Optional<Symbol> getSymbol() { return Optional.ofNullable(symbol); } public void writeInline(GoWriter writer) { if (getSymbol().isPresent()) { writer.writeInline("$T", getSymbol().get()); } else if (getString().isPresent()) { writer.writeInline("$S", getString().get()); } else { throw new CodegenException("unsupported identifier state"); } } public static MiddlewareIdentifier symbol(Symbol symbol) { return builder().symbol(symbol).build(); } public static MiddlewareIdentifier string(String string) { return builder().name(string).build(); } @Override public String toString() { if (symbol != null) { return symbol.toString(); } else if (string != null) { return string; } else { throw new CodegenException("unexpected identifier state"); } } public static Builder builder() { return new Builder(); } @Override public int hashCode() { return Objects.hash(string, symbol); } @Override public boolean equals(Object o) { if (this == o) { return true; } else if (!(o instanceof MiddlewareIdentifier)) { return false; } MiddlewareIdentifier identifier = (MiddlewareIdentifier) o; return Objects.equals(string, identifier.string) && ((symbol == identifier.symbol) || (symbol != null && identifier.symbol != null && symbol.getNamespace().equals(identifier.symbol.getNamespace()) && symbol.getName().equals(identifier.symbol.getName()))); } /** * A builder for {@link MiddlewareIdentifier}. */ public static class Builder implements SmithyBuilder<MiddlewareIdentifier> { private String string; private Symbol symbol; public Builder name(String name) { this.string = name; return this; } public Builder symbol(Symbol symbol) { this.symbol = symbol; return this; } @Override public MiddlewareIdentifier build() { return new MiddlewareIdentifier(this); } } }
8,945
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/AddOperationShapes.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen; import java.util.TreeSet; import java.util.logging.Logger; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.knowledge.TopDownIndex; import software.amazon.smithy.model.shapes.AbstractShapeBuilder; import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; import software.amazon.smithy.model.shapes.StructureShape; /** * Ensures that each operation has a unique input and output shape. */ public final class AddOperationShapes { private static final Logger LOGGER = Logger.getLogger(AddOperationShapes.class.getName()); private AddOperationShapes() { } /** * Processes the given model and returns a new model ensuring service operation has an unique input and output * synthesized shape. * * @param model the model * @param serviceShapeId the service shape * @return a model with unique operation input and output shapes */ public static Model execute(Model model, ShapeId serviceShapeId) { TopDownIndex topDownIndex = model.getKnowledge(TopDownIndex.class); ServiceShape service = model.expectShape(serviceShapeId, ServiceShape.class); TreeSet<OperationShape> operations = new TreeSet<>(topDownIndex.getContainedOperations( model.expectShape(serviceShapeId))); Model.Builder modelBuilder = model.toBuilder(); for (OperationShape operation : operations) { ShapeId operationId = operation.getId(); LOGGER.info(() -> "building unique input/output shapes for " + operationId); StructureShape newInputShape = operation.getInput() .map(shapeId -> cloneOperationShape( service, operationId, (StructureShape) model.expectShape(shapeId), "Input")) .orElseGet(() -> emptyOperationStructure(service, operationId, "Input")); StructureShape newOutputShape = operation.getOutput() .map(shapeId -> cloneOperationShape( service, operationId, (StructureShape) model.expectShape(shapeId), "Output")) .orElseGet(() -> emptyOperationStructure(service, operationId, "Output")); // Add new input/output to model modelBuilder.addShape(newInputShape); modelBuilder.addShape(newOutputShape); // Update operation model with the input/output shape ids modelBuilder.addShape(operation.toBuilder() .input(newInputShape.toShapeId()) .output(newOutputShape.toShapeId()) .build()); } return modelBuilder.build(); } private static StructureShape emptyOperationStructure(ServiceShape service, ShapeId opShapeId, String suffix) { return StructureShape.builder() .id(ShapeId.fromParts(CodegenUtils.getSyntheticTypeNamespace(), opShapeId.getName(service) + suffix)) .addTrait(Synthetic.builder().build()) .build(); } private static StructureShape cloneOperationShape( ServiceShape service, ShapeId operationShapeId, StructureShape structureShape, String suffix ) { return (StructureShape) cloneShape(structureShape, operationShapeId.getName(service) + suffix); } private static Shape cloneShape(Shape shape, String cloneShapeName) { ShapeId cloneShapeId = ShapeId.fromParts(CodegenUtils.getSyntheticTypeNamespace(), cloneShapeName); AbstractShapeBuilder builder = Shape.shapeToBuilder(shape) .id(cloneShapeId) .addTrait(Synthetic.builder() .archetype(shape.getId()) .build()); shape.members().forEach(memberShape -> { builder.addMember(memberShape.toBuilder() .id(cloneShapeId.withMember(memberShape.getMemberName())) .build()); }); return (Shape) builder.build(); } }
8,946
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/GoUniverseTypes.java
/* * Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen; import software.amazon.smithy.codegen.core.Symbol; /** * Collection of Symbol constants for golang universe types. * See <a href="https://go.dev/ref/spec#Predeclared_identifiers">predeclared identifiers</a>. */ public final class GoUniverseTypes { public static Symbol tAny = universe("any"); public static Symbol tBool = universe("bool"); public static Symbol tByte = universe("byte"); public static Symbol tComparable = universe("comparable"); public static Symbol tComplex64 = universe("complex64"); public static Symbol tComplex128 = universe("complex128"); public static Symbol tError = universe("error"); public static Symbol tFloat32 = universe("float32"); public static Symbol tFloat64 = universe("float64"); public static Symbol tInt = universe("int"); public static Symbol tInt8 = universe("int8"); public static Symbol tInt16 = universe("int16"); public static Symbol tInt32 = universe("int32"); public static Symbol tInt64 = universe("int64"); public static Symbol tRune = universe("rune"); public static Symbol tString = universe("string"); public static Symbol tUint = universe("uint"); public static Symbol tUint8 = universe("uint8"); public static Symbol tUint16 = universe("uint16"); public static Symbol tUint32 = universe("uint32"); public static Symbol tUint64 = universe("uint64"); public static Symbol tUintptr = universe("uintptr"); private GoUniverseTypes() {} private static Symbol universe(String name) { return SymbolUtils.createValueSymbolBuilder(name).putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true).build(); } }
8,947
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/ImportDeclarations.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen; import java.util.Map; import java.util.TreeMap; import software.amazon.smithy.codegen.core.CodegenException; import software.amazon.smithy.utils.StringUtils; /** * Container and formatter for go imports. */ final class ImportDeclarations { private final Map<String, String> imports = new TreeMap<>(); ImportDeclarations addImport(String importPath, String alias) { String importAlias = CodegenUtils.getDefaultPackageImportName(importPath); if (!StringUtils.isBlank(alias)) { if (alias.equals(".")) { // Global imports are generally a bad practice. throw new CodegenException("Globally importing packages is forbidden: " + importPath); } importAlias = alias; } // Ensure that multiple packages cannot be imported with the same name. if (imports.containsKey(importAlias) && !imports.get(importAlias).equals(importPath)) { throw new CodegenException("Import name collision: " + importAlias + ". Previous: " + imports.get(importAlias) + "New: " + importPath); } imports.putIfAbsent(importAlias, importPath); return this; } ImportDeclarations addImports(ImportDeclarations other) { other.imports.forEach((importAlias, importPath) -> { addImport(importPath, importAlias); }); return this; } @Override public String toString() { if (imports.isEmpty()) { return ""; } StringBuilder builder = new StringBuilder("import (\n"); for (Map.Entry<String, String> entry : imports.entrySet()) { builder.append('\t'); builder.append(createImportStatement(entry)); builder.append('\n'); } builder.append(")\n\n"); return builder.toString(); } private String createImportStatement(Map.Entry<String, String> entry) { String formattedPackageName = "\"" + entry.getValue() + "\""; return CodegenUtils.getDefaultPackageImportName(entry.getValue()).equals(entry.getKey()) ? formattedPackageName : entry.getKey() + " " + formattedPackageName; } }
8,948
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/GoValueAccessUtils.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * * */ package software.amazon.smithy.go.codegen; import java.util.function.Consumer; import software.amazon.smithy.codegen.core.SymbolProvider; import software.amazon.smithy.go.codegen.knowledge.GoPointableIndex; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.CollectionShape; import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeType; import software.amazon.smithy.model.traits.EnumTrait; /** * Utilities for generating accessor checks around other generated blocks. */ public final class GoValueAccessUtils { private GoValueAccessUtils() { } /** * Writes non-zero conditional checks around a lambda specific to the member shape type. * <p> * Note: Collections and map member values by default will not have individual checks on member values. To check * not empty strings set the ignoreEmptyString to false. * * @param model smithy model * @param writer go writer * @param member API shape member to determine wrapping check with * @param operand string of text with access to value * @param ignoreEmptyString if empty strings also checked * @param ignoreUnboxedTypes if unboxed member types should be ignored * @param lambda lambda to run */ public static void writeIfNonZeroValue( Model model, GoWriter writer, MemberShape member, String operand, boolean ignoreEmptyString, boolean ignoreUnboxedTypes, Runnable lambda ) { Shape targetShape = model.expectShape(member.getTarget()); Shape container = model.expectShape(member.getContainer()); // default to empty block for variable scoping with not value check. String check = "{"; if (GoPointableIndex.of(model).isNillable(member)) { if (!ignoreEmptyString && targetShape.getType() == ShapeType.STRING) { check = String.format("if %s != nil && len(*%s) > 0 {", operand, operand); } else { check = String.format("if %s != nil {", operand); } } else if (container instanceof CollectionShape || container.getType() == ShapeType.MAP) { if (!ignoreEmptyString && targetShape.getType() == ShapeType.STRING) { check = String.format("if len(%s) > 0 {", operand); } else if (!ignoreEmptyString && targetShape.getType() == ShapeType.ENUM) { check = String.format("if len(%s) > 0 {", operand); } } else if (targetShape.hasTrait(EnumTrait.class)) { check = String.format("if len(%s) > 0 {", operand); } else if (!ignoreUnboxedTypes && targetShape.getType() == ShapeType.BOOLEAN) { check = String.format("if %s {", operand); } else if (!ignoreUnboxedTypes && CodegenUtils.isNumber(targetShape)) { check = String.format("if %s != 0 {", operand); } else if (!ignoreEmptyString && targetShape.getType() == ShapeType.STRING) { check = String.format("if len(%s) > 0 {", operand); } writer.openBlock(check, "}", lambda); } /** * Writes non-zero conditional checks around a lambda specific to the member shape type. * <p> * Ignores empty strings of string pointers, and nested within list and maps. * * @param model smithy model * @param writer go writer * @param member API shape member to determine wrapping check with * @param operand string of text with access to value * @param lambda lambda to run */ public static void writeIfNonZeroValue( Model model, GoWriter writer, MemberShape member, String operand, Runnable lambda ) { writeIfNonZeroValue(model, writer, member, operand, true, false, lambda); } /** * Writes non-zero conditional check around a lambda specific to a member of a container. * <p> * Ignores empty strings of string pointers, and members nested within list and maps. * * @param model smithy model * @param symbolProvider symbol provider * @param writer go writer * @param member API shape member to determine wrapping check with * @param container operand of source member is a part of. * @param lambda lambda to run */ public static void writeIfNonZeroValueMember( Model model, SymbolProvider symbolProvider, GoWriter writer, MemberShape member, String container, Consumer<String> lambda ) { writeIfNonZeroValueMember(model, symbolProvider, writer, member, container, true, false, lambda); } /** * Writes non-zero conditional check around a lambda specific to a member of a container. * <p> * Note: Collections and map member values by default will not have individual checks on member values. To check * not empty strings set the ignoreEmptyString to false. * * @param model smithy model * @param symbolProvider symbol provider * @param writer go writer * @param member API shape member to determine wrapping check with * @param container operand of source member is a part of. * @param ignoreEmptyString if empty strings also checked * @param ignoreUnboxedTypes if unboxed member types should be ignored * @param lambda lambda to run */ public static void writeIfNonZeroValueMember( Model model, SymbolProvider symbolProvider, GoWriter writer, MemberShape member, String container, boolean ignoreEmptyString, boolean ignoreUnboxedTypes, Consumer<String> lambda ) { String memberName = symbolProvider.toMemberName(member); String operand = container + "." + memberName; writeIfNonZeroValue(model, writer, member, operand, ignoreEmptyString, ignoreUnboxedTypes, () -> { lambda.accept(operand); }); } /** * Writes zero conditional checks around a lambda specific to the member shape type. * <p> * Members with containers of Collection and map shapes, will ignore the lambda block * and not call it. Optionally will ignore empty strings based on the ignoreEmptyString flag. * <p> * Non-nillable shapes other than Enum, Boolean, and Number will ignore the lambda block. Optionally will ignore * empty strings based on the ignoreEmptyString flag. * <p> * Note: Collections and map member values by default will not have individual checks on member values. To check * for empty strings set the ignoreEmptyString to false. * * @param model smithy model * @param writer go writer * @param member API shape member to determine wrapping check with * @param operand string of text with access to value * @param ignoreEmptyString if empty strings also checked * @param ignoreUnboxedTypes if unboxed member types should be ignored * @param lambda lambda to run */ public static void writeIfZeroValue( Model model, GoWriter writer, MemberShape member, String operand, boolean ignoreEmptyString, boolean ignoreUnboxedTypes, Runnable lambda ) { Shape targetShape = model.expectShape(member.getTarget()); Shape container = model.expectShape(member.getContainer()); String check = "{"; if (GoPointableIndex.of(model).isNillable(member)) { if (!ignoreEmptyString && targetShape.getType() == ShapeType.STRING) { check = String.format("if %s == nil || len(*%s) == 0 {", operand, operand); } else { check = String.format("if %s == nil {", operand); } } else if (container instanceof CollectionShape || container.getType() == ShapeType.MAP) { // Always serialize values in map/list/sets, no additional check, which means that the // lambda will not be run, because there is no zero value to check against. if (!ignoreEmptyString && targetShape.getType() == ShapeType.STRING) { check = String.format("if len(%s) == 0 {", operand); } else { return; } } else if (targetShape.hasTrait(EnumTrait.class)) { check = String.format("if len(%s) == 0 {", operand); } else if (!ignoreUnboxedTypes && targetShape.getType() == ShapeType.BOOLEAN) { check = String.format("if !%s {", operand); } else if (!ignoreUnboxedTypes && CodegenUtils.isNumber(targetShape)) { check = String.format("if %s == 0 {", operand); } else if (!ignoreEmptyString && targetShape.getType() == ShapeType.STRING) { check = String.format("if len(%s) == 0 {", operand); } else { // default to empty block for variable scoping with not value check. return; } writer.openBlock(check, "}", lambda); } /** * Writes zero conditional checks around a lambda specific to the member shape type. * <p> * Ignores empty strings of string pointers, and members nested within list and maps. * * @param model smithy model * @param writer go writer * @param member API shape member to determine wrapping check with * @param operand string of text with access to value * @param lambda lambda to run */ public static void writeIfZeroValue( Model model, GoWriter writer, MemberShape member, String operand, Runnable lambda ) { writeIfZeroValue(model, writer, member, operand, true, false, lambda); } /** * Writes zero conditional check around a lambda specific to a member of a container. * <p> * Ignores empty strings of string pointers, and members nested within list and maps. * * @param model smithy model * @param symbolProvider symbol provider * @param writer go writer * @param member API shape member to determine wrapping check with * @param container operand of source member is a part of. * @param lambda lambda to run */ public static void writeIfZeroValueMember( Model model, SymbolProvider symbolProvider, GoWriter writer, MemberShape member, String container, Consumer<String> lambda ) { writeIfZeroValueMember(model, symbolProvider, writer, member, container, true, false, lambda); } /** * Writes zero conditional check around a lambda specific to a member of a container. * <p> * Ignores empty strings of string pointers, and members nested within list and maps. * * @param model smithy model * @param symbolProvider symbol provider * @param writer go writer * @param member API shape member to determine wrapping check with * @param container operand of source member is a part of. * @param ignoreEmptyString if empty strings also checked * @param ignoreUnboxedTypes if unboxed member types should be ignored * @param lambda lambda to run */ public static void writeIfZeroValueMember( Model model, SymbolProvider symbolProvider, GoWriter writer, MemberShape member, String container, boolean ignoreEmptyString, boolean ignoreUnboxedTypes, Consumer<String> lambda ) { String memberName = symbolProvider.toMemberName(member); String operand = container + "." + memberName; writeIfZeroValue(model, writer, member, operand, ignoreEmptyString, ignoreUnboxedTypes, () -> { lambda.accept(operand); }); } }
8,949
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/GoWriterDelegator.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Consumer; import software.amazon.smithy.build.FileManifest; import software.amazon.smithy.codegen.core.SymbolDependency; public class GoWriterDelegator { private final FileManifest fileManifest; private final Map<String, GoWriter> writers = new HashMap<>(); public GoWriterDelegator(FileManifest fileManifest) { this.fileManifest = fileManifest; } /** * Writes all pending writers to disk and then clears them out. */ public void flushWriters() { writers.forEach((filename, writer) -> fileManifest.writeFile(filename, writer.toString())); writers.clear(); } /** * Gets all the dependencies that have been registered in writers owned by the * delegator. * * @return Returns all the dependencies. */ public List<SymbolDependency> getDependencies() { List<SymbolDependency> resolved = new ArrayList<>(); writers.values().forEach(s -> resolved.addAll(s.getDependencies())); return resolved; } /** * Gets a previously created writer or creates a new one if needed * and adds a new line if the writer already exists. * * @param filename Name of the file to create. * @param namespace Namespace of the file's content. * @param writerConsumer Consumer that accepts and works with the file. */ public void useFileWriter(String filename, String namespace, Consumer<GoWriter> writerConsumer) { writerConsumer.accept(checkoutWriter(filename, namespace)); } GoWriter checkoutWriter(String filename, String namespace) { String formattedFilename = Paths.get(filename).normalize().toString(); boolean needsNewline = writers.containsKey(formattedFilename); GoWriter writer = writers.computeIfAbsent(formattedFilename, f -> new GoWriter(namespace)); if (needsNewline) { writer.write("\n"); } return writer; } }
8,950
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/IntEnumGenerator.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen; import java.util.LinkedHashSet; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.logging.Logger; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.codegen.core.SymbolProvider; import software.amazon.smithy.model.shapes.IntEnumShape; import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.traits.DocumentationTrait; import software.amazon.smithy.model.traits.EnumValueTrait; import software.amazon.smithy.utils.StringUtils; /** * Renders intEnums and their constants. */ final class IntEnumGenerator implements Runnable { private static final Logger LOGGER = Logger.getLogger(IntEnumGenerator.class.getName()); private final SymbolProvider symbolProvider; private final GoWriter writer; private final IntEnumShape shape; IntEnumGenerator(SymbolProvider symbolProvider, GoWriter writer, IntEnumShape shape) { this.symbolProvider = symbolProvider; this.writer = writer; this.shape = shape; } @Override public void run() { Symbol symbol = symbolProvider.toSymbol(shape); // TODO(smithy): Use type alias instead of type definition until refactoring // protocol generators is prioritized. writer.write("type $L = int32", symbol.getName()).write(""); writer.writeDocs(String.format("Enum values for %s", symbol.getName())); Set<String> constants = new LinkedHashSet<>(); writer.openBlock("const (", ")", () -> { for (Map.Entry<String, MemberShape> entry : shape.getAllMembers().entrySet()) { StringBuilder labelBuilder = new StringBuilder(symbol.getName()); String name = entry.getKey(); for (String part : name.split("(?U)[\\W_]")) { if (part.matches(".*[a-z].*") && part.matches(".*[A-Z].*")) { // Mixed case names should not be changed other than first letter capitalized. labelBuilder.append(StringUtils.capitalize(part)); } else { // For all non-mixed case parts title case first letter, followed by all other lower cased. labelBuilder.append(StringUtils.capitalize(part.toLowerCase(Locale.US))); } } String label = labelBuilder.toString(); // If camel-casing would cause a conflict, don't camel-case this enum value. if (constants.contains(label)) { LOGGER.warning(String.format( "Multiple enums resolved to the same name, `%s`, using unaltered value for: %s", label, name)); label = name; } constants.add(label); entry.getValue().getTrait(DocumentationTrait.class) .ifPresent(trait -> writer.writeDocs(trait.getValue())); writer.write("$L $L = $L", label, symbol.getName(), entry.getValue().expectTrait(EnumValueTrait.class).expectIntValue()); } }).write(""); // TODO(smithy): type aliases don't allow defining methods on base types (e.g. int32). // Uncomment generating the Value() method when the type alias is migrated to type definition. /* writer.writeDocs(String.format("Values returns all known values for %s. Note that this can be expanded in the " + "future, and so it is only as up to date as the client.%n%nThe ordering of this slice is not " + "guaranteed to be stable across updates.", symbol.getName())); writer.openBlock("func ($L) Values() []$L {", "}", symbol.getName(), symbol.getName(), () -> { writer.openBlock("return []$L{", "}", symbol.getName(), () -> { for (Map.Entry<String, Integer> entry : shape.getEnumValues().entrySet()) { writer.write("$L,", entry.getValue()); } }); }); */ } }
8,951
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/SymbolVisitor.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.logging.Logger; import software.amazon.smithy.codegen.core.CodegenException; import software.amazon.smithy.codegen.core.ReservedWordSymbolProvider; import software.amazon.smithy.codegen.core.ReservedWords; import software.amazon.smithy.codegen.core.ReservedWordsBuilder; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.codegen.core.SymbolProvider; import software.amazon.smithy.go.codegen.knowledge.GoPointableIndex; import software.amazon.smithy.go.codegen.trait.UnexportedMemberTrait; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.knowledge.NeighborProviderIndex; import software.amazon.smithy.model.neighbor.NeighborProvider; import software.amazon.smithy.model.neighbor.Relationship; import software.amazon.smithy.model.neighbor.RelationshipType; import software.amazon.smithy.model.shapes.BigDecimalShape; import software.amazon.smithy.model.shapes.BigIntegerShape; import software.amazon.smithy.model.shapes.BlobShape; import software.amazon.smithy.model.shapes.BooleanShape; import software.amazon.smithy.model.shapes.ByteShape; import software.amazon.smithy.model.shapes.CollectionShape; import software.amazon.smithy.model.shapes.DocumentShape; import software.amazon.smithy.model.shapes.DoubleShape; import software.amazon.smithy.model.shapes.FloatShape; import software.amazon.smithy.model.shapes.IntEnumShape; import software.amazon.smithy.model.shapes.IntegerShape; import software.amazon.smithy.model.shapes.ListShape; import software.amazon.smithy.model.shapes.LongShape; import software.amazon.smithy.model.shapes.MapShape; import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.ResourceShape; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.SetShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; import software.amazon.smithy.model.shapes.ShapeVisitor; import software.amazon.smithy.model.shapes.ShortShape; import software.amazon.smithy.model.shapes.StringShape; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.shapes.TimestampShape; import software.amazon.smithy.model.shapes.UnionShape; import software.amazon.smithy.model.traits.EnumTrait; import software.amazon.smithy.model.traits.ErrorTrait; import software.amazon.smithy.model.traits.StreamingTrait; import software.amazon.smithy.utils.StringUtils; /** * Responsible for type mapping and file/identifier formatting. * * <p>Reserved words for Go are automatically escaped so that they are * suffixed with "_". See "reserved-words.txt" for the list of words. */ final class SymbolVisitor implements SymbolProvider, ShapeVisitor<Symbol> { private static final Logger LOGGER = Logger.getLogger(SymbolVisitor.class.getName()); private final Model model; private final String rootModuleName; private final String typesPackageName; private final ReservedWordSymbolProvider.Escaper escaper; private final ReservedWordSymbolProvider.Escaper errorMemberEscaper; private final Map<ShapeId, ReservedWordSymbolProvider.Escaper> structureSpecificMemberEscapers = new HashMap<>(); private final GoPointableIndex pointableIndex; private final GoSettings settings; SymbolVisitor(Model model, GoSettings settings) { this.model = model; this.settings = settings; this.rootModuleName = settings.getModuleName(); this.typesPackageName = this.rootModuleName + "/types"; this.pointableIndex = GoPointableIndex.of(model); // Reserve the generated names for union members, including the unknown case. ReservedWordsBuilder reservedNames = new ReservedWordsBuilder() .put(UnionGenerator.UNKNOWN_MEMBER_NAME, escapeWithTrailingUnderscore(UnionGenerator.UNKNOWN_MEMBER_NAME)); reserveUnionMemberNames(model, reservedNames); ReservedWords reservedMembers = new ReservedWordsBuilder() // Since Go only exports names if the first character is upper case and all // the go reserved words are lower case, it's functionally impossible to conflict, // so we only need to protect against common names. As of now there's only one. .put("String", "String_") .put("GetStream", "GetStream_") .build(); model.shapes(StructureShape.class) .filter(this::supportsInheritance) .forEach(this::reserveInterfaceMemberAccessors); escaper = ReservedWordSymbolProvider.builder() .nameReservedWords(reservedNames.build()) .memberReservedWords(reservedMembers) // Only escape words when the symbol has a definition file to // prevent escaping intentional references to built-in types. .escapePredicate((shape, symbol) -> !StringUtils.isEmpty(symbol.getDefinitionFile())) .buildEscaper(); // Reserved words that only apply to error members. ReservedWords reservedErrorMembers = new ReservedWordsBuilder() .put("ErrorCode", "ErrorCode_") .put("ErrorMessage", "ErrorMessage_") .put("ErrorFault", "ErrorFault_") .put("Unwrap", "Unwrap_") .put("Error", "Error_") .put("ErrorCodeOverride", "ErrorCodeOverride_") .build(); errorMemberEscaper = ReservedWordSymbolProvider.builder() .memberReservedWords(ReservedWords.compose(reservedMembers, reservedErrorMembers)) .escapePredicate((shape, symbol) -> !StringUtils.isEmpty(symbol.getDefinitionFile())) .buildEscaper(); } /** * Reserves generated member names for unions. * * <p>These have the format {UnionName}Member{MemberName}. * * @param model The model whose unions should be reserved. * @param builder A reserved words builder to add on to. */ private void reserveUnionMemberNames(Model model, ReservedWordsBuilder builder) { model.shapes(UnionShape.class).forEach(union -> { for (MemberShape member : union.getAllMembers().values()) { String memberName = formatUnionMemberName(union, member); builder.put(memberName, escapeWithTrailingUnderscore(memberName)); } }); } private boolean supportsInheritance(Shape shape) { return shape.isStructureShape() && shape.hasTrait(ErrorTrait.class); } /** * Reserves Get* and Has* member names for the given structure for use as accessor methods. * * <p>These reservations will only apply to the given structure, not to other structures. * * @param shape The structure shape whose members should be reserved. */ private void reserveInterfaceMemberAccessors(StructureShape shape) { ReservedWordsBuilder builder = new ReservedWordsBuilder(); for (MemberShape member : shape.getAllMembers().values()) { String name = getDefaultMemberName(member); String getterName = "Get" + name; String haserName = "Has" + name; builder.put(getterName, escapeWithTrailingUnderscore(getterName)); builder.put(haserName, escapeWithTrailingUnderscore(haserName)); } ReservedWordSymbolProvider.Escaper structureSpecificMemberEscaper = ReservedWordSymbolProvider.builder() .memberReservedWords(builder.build()) .buildEscaper(); structureSpecificMemberEscapers.put(shape.getId(), structureSpecificMemberEscaper); } private String escapeWithTrailingUnderscore(String symbolName) { return symbolName + "_"; } @Override public Symbol toSymbol(Shape shape) { Symbol symbol = shape.accept(this); LOGGER.fine(() -> String.format("Creating symbol from %s: %s", shape, symbol)); return linkArchetypeShape(shape, escaper.escapeSymbol(shape, symbol)); } /** * Links the archetype shape id for the symbol. * * @param shape the model shape * @param symbol the symbol to set the archetype property on * @return the symbol with archetype set if shape is a synthetic clone otherwise the original symbol */ private Symbol linkArchetypeShape(Shape shape, Symbol symbol) { return shape.getTrait(Synthetic.class) .map(synthetic -> symbol.toBuilder() .putProperty("archetype", synthetic.getArchetype()) .build()) .orElse(symbol); } @Override public String toMemberName(MemberShape shape) { Shape container = model.expectShape(shape.getContainer()); if (container.isUnionShape()) { // Union member names are not escaped as they are used to build the escape set. return formatUnionMemberName(container.asUnionShape().get(), shape); } String memberName = getDefaultMemberName(shape); memberName = escaper.escapeMemberName(memberName); // Escape words reserved for the specific container. if (structureSpecificMemberEscapers.containsKey(shape.getContainer())) { memberName = structureSpecificMemberEscapers.get(shape.getContainer()).escapeMemberName(memberName); } // Escape words that are only reserved for error members. if (isErrorMember(shape)) { memberName = errorMemberEscaper.escapeMemberName(memberName); } return memberName; } private String formatUnionMemberName(UnionShape union, MemberShape member) { return String.format("%sMember%s", getDefaultShapeName(union), getDefaultMemberName(member)); } private String getDefaultShapeName(Shape shape) { ServiceShape serviceShape = model.expectShape(settings.getService(), ServiceShape.class); return StringUtils.capitalize(removeLeadingInvalidIdentCharacters(shape.getId().getName(serviceShape))); } private String getDefaultMemberName(MemberShape shape) { String memberName = StringUtils.capitalize(removeLeadingInvalidIdentCharacters(shape.getMemberName())); // change to lowercase first character if unexported structure member. if (model.expectShape(shape.getContainer()).isStructureShape() && shape.hasTrait(UnexportedMemberTrait.class)) { memberName = Character.toLowerCase(memberName.charAt(0)) + memberName.substring(1); } return memberName; } private String removeLeadingInvalidIdentCharacters(String value) { if (Character.isAlphabetic(value.charAt(0))) { return value; } int i; for (i = 0; i < value.length(); i++) { if (Character.isAlphabetic(value.charAt(i))) { break; } } String remaining = value.substring(i); if (remaining.length() == 0) { throw new CodegenException("tried to clean name " + value + ", but resulted in empty string"); } return remaining; } private boolean isErrorMember(MemberShape shape) { return model.getShape(shape.getContainer()) .map(container -> container.hasTrait(ErrorTrait.ID)) .orElse(false); } @Override public Symbol blobShape(BlobShape shape) { if (shape.hasTrait(StreamingTrait.ID)) { Symbol inputVariant = symbolBuilderFor(shape, "Reader", SmithyGoDependency.IO).build(); return symbolBuilderFor(shape, "ReadCloser", SmithyGoDependency.IO) .putProperty(SymbolUtils.INPUT_VARIANT, inputVariant) .build(); } return symbolBuilderFor(shape, "[]byte") .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) .build(); } @Override public Symbol booleanShape(BooleanShape shape) { return symbolBuilderFor(shape, "bool") .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) .build(); } @Override public Symbol listShape(ListShape shape) { return createCollectionSymbol(shape); } @Override public Symbol setShape(SetShape shape) { // Go doesn't have a set type. Rather than hack together a set using a map, // we instead just create a list and let the service be responsible for // asserting that there are no duplicates. return createCollectionSymbol(shape); } private Symbol createCollectionSymbol(CollectionShape shape) { Symbol reference = toSymbol(shape.getMember()); // Shape name will be unused for symbols that represent a slice, but in the event it does we set the collection // shape's name to make debugging simpler. return symbolBuilderFor(shape, getDefaultShapeName(shape)) .putProperty(SymbolUtils.GO_SLICE, true) .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, reference.getProperty(SymbolUtils.GO_UNIVERSE_TYPE, Boolean.class).orElse(false)) .putProperty(SymbolUtils.GO_ELEMENT_TYPE, reference) .build(); } @Override public Symbol mapShape(MapShape shape) { Symbol reference = toSymbol(shape.getValue()); // Shape name will be unused for symbols that represent a map, but in the event it does we set the map shape's // name to make debugging simpler. return symbolBuilderFor(shape, getDefaultShapeName(shape)) .putProperty(SymbolUtils.GO_MAP, true) .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, reference.getProperty(SymbolUtils.GO_UNIVERSE_TYPE, Boolean.class).orElse(false)) .putProperty(SymbolUtils.GO_ELEMENT_TYPE, reference) .build(); } private Symbol.Builder symbolBuilderFor(Shape shape, String typeName) { if (pointableIndex.isPointable(shape)) { return SymbolUtils.createPointableSymbolBuilder(shape, typeName); } return SymbolUtils.createValueSymbolBuilder(shape, typeName); } private Symbol.Builder symbolBuilderFor(Shape shape, String typeName, GoDependency namespace) { if (pointableIndex.isPointable(shape)) { return SymbolUtils.createPointableSymbolBuilder(shape, typeName, namespace); } return SymbolUtils.createValueSymbolBuilder(shape, typeName, namespace); } private Symbol.Builder symbolBuilderFor(Shape shape, String typeName, String namespace) { if (pointableIndex.isPointable(shape)) { return SymbolUtils.createPointableSymbolBuilder(shape, typeName, namespace); } return SymbolUtils.createValueSymbolBuilder(shape, typeName, namespace); } @Override public Symbol byteShape(ByteShape shape) { return symbolBuilderFor(shape, "int8") .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) .build(); } @Override public Symbol shortShape(ShortShape shape) { return symbolBuilderFor(shape, "int16") .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) .build(); } @Override public Symbol integerShape(IntegerShape shape) { return symbolBuilderFor(shape, "int32") .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) .build(); } @Override public Symbol longShape(LongShape shape) { return symbolBuilderFor(shape, "int64") .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) .build(); } @Override public Symbol floatShape(FloatShape shape) { return symbolBuilderFor(shape, "float32") .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) .build(); } @Override public Symbol doubleShape(DoubleShape shape) { return symbolBuilderFor(shape, "float64") .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) .build(); } @Override public Symbol bigIntegerShape(BigIntegerShape shape) { return createBigSymbol(shape, "Int"); } @Override public Symbol bigDecimalShape(BigDecimalShape shape) { return createBigSymbol(shape, "Float"); } private Symbol createBigSymbol(Shape shape, String symbolName) { return symbolBuilderFor(shape, symbolName, SmithyGoDependency.BIG) .build(); } @Override public Symbol documentShape(DocumentShape shape) { return ProtocolDocumentGenerator.Utilities.getDocumentSymbolBuilder(settings, ProtocolDocumentGenerator.DOCUMENT_INTERFACE_NAME) .build(); } @Override public Symbol operationShape(OperationShape shape) { String name = getDefaultShapeName(shape); return SymbolUtils.createPointableSymbolBuilder(shape, name, rootModuleName) .definitionFile(String.format("./api_op_%s.go", name)) .build(); } @Override public Symbol resourceShape(ResourceShape shape) { // TODO: implement resources return SymbolUtils.createPointableSymbolBuilder(shape, "nil").build(); } @Override public Symbol serviceShape(ServiceShape shape) { return symbolBuilderFor(shape, "Client", rootModuleName) .definitionFile("./api_client.go") .build(); } @Override public Symbol stringShape(StringShape shape) { if (shape.hasTrait(EnumTrait.class)) { String name = getDefaultShapeName(shape); return symbolBuilderFor(shape, name, typesPackageName) .definitionFile("./types/enums.go") .build(); } return symbolBuilderFor(shape, "string") .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true) .build(); } @Override public Symbol structureShape(StructureShape shape) { String name = getDefaultShapeName(shape); if (shape.getId().getNamespace().equals(CodegenUtils.getSyntheticTypeNamespace())) { Optional<String> boundOperationName = getNameOfBoundOperation(shape); if (boundOperationName.isPresent()) { return symbolBuilderFor(shape, name, rootModuleName) .definitionFile("./api_op_" + boundOperationName.get() + ".go") .build(); } } Symbol.Builder builder = symbolBuilderFor(shape, name, typesPackageName); if (shape.hasTrait(ErrorTrait.ID)) { builder.definitionFile("./types/errors.go"); } else { builder.definitionFile("./types/types.go"); } return builder.build(); } private Optional<String> getNameOfBoundOperation(StructureShape shape) { NeighborProvider provider = NeighborProviderIndex.of(model).getReverseProvider(); for (Relationship relationship : provider.getNeighbors(shape)) { RelationshipType relationshipType = relationship.getRelationshipType(); if (relationshipType == RelationshipType.INPUT || relationshipType == RelationshipType.OUTPUT) { return Optional.of(getDefaultShapeName(relationship.getNeighborShape().get())); } } return Optional.empty(); } @Override public Symbol unionShape(UnionShape shape) { String name = getDefaultShapeName(shape); return symbolBuilderFor(shape, name, typesPackageName) .definitionFile("./types/types.go") .build(); } @Override public Symbol memberShape(MemberShape member) { Shape targetShape = model.expectShape(member.getTarget()); return toSymbol(targetShape) .toBuilder() .putProperty(SymbolUtils.POINTABLE, pointableIndex.isPointable(member)) .build(); } @Override public Symbol timestampShape(TimestampShape shape) { return symbolBuilderFor(shape, "Time", SmithyGoDependency.TIME).build(); } @Override public Symbol intEnumShape(IntEnumShape shape) { String name = getDefaultShapeName(shape); return symbolBuilderFor(shape, name, typesPackageName) .definitionFile("./types/enums.go") .build(); } }
8,952
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/GoEventStreamIndex.java
/* * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.TreeSet; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.knowledge.EventStreamIndex; import software.amazon.smithy.model.knowledge.EventStreamInfo; import software.amazon.smithy.model.knowledge.KnowledgeIndex; import software.amazon.smithy.model.knowledge.TopDownIndex; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.ShapeId; import software.amazon.smithy.model.shapes.ToShapeId; /** * Provides a knowledge index about event streams and their corresponding usage in operations. */ public class GoEventStreamIndex implements KnowledgeIndex { final Map<ShapeId, Map<ShapeId, Set<EventStreamInfo>>> inputEventStreams = new HashMap<>(); final Map<ShapeId, Map<ShapeId, Set<EventStreamInfo>>> outputEventStreams = new HashMap<>(); public GoEventStreamIndex(Model model) { EventStreamIndex eventStreamIndex = EventStreamIndex.of(model); for (ServiceShape serviceShape : model.getServiceShapes()) { final Map<ShapeId, Set<EventStreamInfo>> serviceInputStreams = new HashMap<>(); final Map<ShapeId, Set<EventStreamInfo>> serviceOutputStreams = new HashMap<>(); TopDownIndex.of(model).getContainedOperations(serviceShape).forEach(operationShape -> { eventStreamIndex.getInputInfo(operationShape).ifPresent(eventStreamInfo -> { ShapeId eventStreamTargetId = eventStreamInfo.getEventStreamTarget().getId(); if (serviceInputStreams.containsKey(eventStreamTargetId)) { serviceInputStreams.get(eventStreamTargetId).add(eventStreamInfo); } else { TreeSet<EventStreamInfo> infos = new TreeSet<>( Comparator.comparing(EventStreamInfo::getOperation)); infos.add(eventStreamInfo); serviceInputStreams.put(eventStreamTargetId, infos); } }); eventStreamIndex.getOutputInfo(operationShape).ifPresent(eventStreamInfo -> { ShapeId eventStreamTargetId = eventStreamInfo.getEventStreamTarget().getId(); if (serviceOutputStreams.containsKey(eventStreamTargetId)) { serviceOutputStreams.get(eventStreamTargetId).add(eventStreamInfo); } else { TreeSet<EventStreamInfo> infos = new TreeSet<>( Comparator.comparing(EventStreamInfo::getOperation)); infos.add(eventStreamInfo); serviceOutputStreams.put(eventStreamTargetId, infos); } }); }); if (!serviceInputStreams.isEmpty()) { inputEventStreams.put(serviceShape.getId(), serviceInputStreams); } if (!serviceOutputStreams.isEmpty()) { outputEventStreams.put(serviceShape.getId(), serviceOutputStreams); } } } /** * Get the input event streams and their usages in operations for the provided service. * * @param service the service shape * @return the map of event stream unions to their corresponding event infos */ public Optional<Map<ShapeId, Set<EventStreamInfo>>> getInputEventStreams(ToShapeId service) { return Optional.ofNullable(inputEventStreams.get(service.toShapeId())); } /** * Get the output event streams and their usages in operations for the provided service. * * @param service the service shape * @return the map of event stream unions to their corresponding event infos */ public Optional<Map<ShapeId, Set<EventStreamInfo>>> getOutputEventStreams(ToShapeId service) { return Optional.ofNullable(outputEventStreams.get(service.toShapeId())); } /** * Returns a {@link GoEventStreamIndex} for the given model. * * @param model the model * @return the knowledge index */ public static GoEventStreamIndex of(Model model) { return model.getKnowledge(GoEventStreamIndex.class, GoEventStreamIndex::new); } }
8,953
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/ProtocolDocumentGenerator.java
/* * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen; import java.util.function.Consumer; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.go.codegen.integration.ProtocolGenerator; import software.amazon.smithy.go.codegen.integration.ProtocolGenerator.GenerationContext; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.selector.Selector; import software.amazon.smithy.model.shapes.ShapeId; import software.amazon.smithy.utils.IoUtils; /** * Generates the service's internal and external document Go packages. The document packages contain the service * specific document Interface definition, protocol specific document marshaler and unmarshaller implementations for * that interface, and constructors for creating service document types. */ public final class ProtocolDocumentGenerator { public static final String DOCUMENT_INTERFACE_NAME = "Interface"; public static final String NO_DOCUMENT_SERDE_TYPE_NAME = "noSmithyDocumentSerde"; public static final String NEW_LAZY_DOCUMENT = "NewLazyDocument"; public static final String INTERNAL_NEW_DOCUMENT_MARSHALER_FUNC = "NewDocumentMarshaler"; public static final String INTERNAL_NEW_DOCUMENT_UNMARSHALER_FUNC = "NewDocumentUnmarshaler"; public static final String INTERNAL_IS_DOCUMENT_INTERFACE = "IsInterface"; public static final String UNMARSHAL_SMITHY_DOCUMENT_METHOD = "UnmarshalSmithyDocument"; public static final String MARSHAL_SMITHY_DOCUMENT_METHOD = "MarshalSmithyDocument"; private static final String SERVICE_SMITHY_DOCUMENT_INTERFACE = "smithyDocument"; private static final String IS_SMITHY_DOCUMENT_METHOD = "isSmithyDocument"; private final GoSettings settings; private final GoDelegator delegator; private final Model model; private final boolean hasDocumentShapes; public ProtocolDocumentGenerator( GoSettings settings, Model model, GoDelegator delegator ) { this.settings = settings; this.model = model; this.delegator = delegator; ShapeId serviceId = settings.getService().toShapeId(); this.hasDocumentShapes = Selector.parse(String.format("[service = %s] ~> document", serviceId)) .matches(model).findAny() .isPresent(); } /** * Generates any required client types or functions to support protocol document types. */ public void generateDocumentSupport() { generateNoSerdeType(); generateInternalDocumentInterface(); generateDocumentPackage(); } /** * Generates the publicly accessible service document package. This package contains a type alias definition * for document interface, as well as a constructor function for creating a document marshaller. * <p> * This package is not generated if the service does not have any document shapes in the model. * * <pre>{@code * // <servicePath>/document * package document * * import ( * internaldocument "<servicePath>/internal/document" * ) * * type Interface = internaldocument.Interface * * func NewLazyDocument(v interface{}) Interface { * return internaldocument.NewDocumentMarshaler(v) * } * }</pre> */ private void generateDocumentPackage() { if (!this.hasDocumentShapes) { return; } writeDocumentPackage("doc.go", writer -> { String documentTemplate = IoUtils.readUtf8Resource(getClass(), "document_doc.go.template"); writer.writeRawPackageDocs(documentTemplate); }); writeDocumentPackage("document.go", writer -> { writer.writeDocs(String.format("%s defines a document which is a protocol-agnostic type which supports a " + "JSON-like data-model. You can use this type to send UTF-8 strings, arbitrary precision " + "numbers, booleans, nulls, a list of these values, and a map of UTF-8 strings to these " + "values.", DOCUMENT_INTERFACE_NAME)); writer.writeDocs(""); writer.writeDocs(String.format("You create a document type using the %s function and passing it the Go " + "type to marshal. When receiving a document in an API response, you use the " + "document's UnmarshalSmithyDocument function to decode the response to your desired Go " + "type. Unless documented specifically generated structure types in client packages or " + "client types packages are not supported at this time. Such types embed a " + "noSmithyDocumentSerde and will cause an error to be returned when attempting to send an " + "API request.", NEW_LAZY_DOCUMENT)); writer.writeDocs(""); writer.writeDocs("For more information see the accompanying package documentation and linked references."); writer.write("type $L = $T", DOCUMENT_INTERFACE_NAME, getInternalDocumentSymbol(DOCUMENT_INTERFACE_NAME)) .write(""); writer.writeDocs(String.format("You create document type using the %s function and passing it the Go " + "type to be marshaled and sent to the service. The document marshaler supports semantics similar " + "to the encoding/json Go standard library.", NEW_LAZY_DOCUMENT)); writer.writeDocs(""); writer.writeDocs("For more information see the accompanying package documentation and linked references."); writer.openBlock("func $L(v interface{}) $T {", "}", NEW_LAZY_DOCUMENT, getDocumentSymbol(DOCUMENT_INTERFACE_NAME), () -> { writer.write("return $T(v)", getInternalDocumentSymbol(INTERNAL_NEW_DOCUMENT_MARSHALER_FUNC)); }) .write(""); }); } /** * Generates an unexported type alias for the {@code github.com/aws/smithy-go/document#NoSerde} type in both the * service and types package. This allows for this type to be used as an embedded member in structures to * prevent usage of generated Smithy structure shapes as document types. Additionally, since the member is * unexported this prevents the need de-conflict naming collisions. * <p> * These type aliases are always generated regardless of whether there are document shapes present in the model * or not. * * <pre>{@code * package types * * type noSmithyDocumentSerde = smithydocument.NoSerde * * type ExampleStructureShape struct { * FieldOne *string * * noSmithyDocumentSerde * } * * }</pre> */ private void generateNoSerdeType() { Symbol noSerde = SymbolUtils.createValueSymbolBuilder("NoSerde", SmithyGoDependency.SMITHY_DOCUMENT).build(); delegator.useShapeWriter(settings.getService(model), writer -> { writer.write("type $L = $T", NO_DOCUMENT_SERDE_TYPE_NAME, noSerde); }); delegator.useFileWriter("./types/types.go", settings.getModuleName() + "/types", writer -> { writer.write("type $L = $T", NO_DOCUMENT_SERDE_TYPE_NAME, noSerde); }); } /** * Generates the document interface definition in the internal document package. * * <pre>{@code * import smithydocument "github.com/aws/smithy-go/document" * * type smithyDocument interface { * isSmithyDocument() * } * * type Interface interface { * smithydocument.Marshaler * smithydocument.Unmarshaler * smithyDocument * } * }</pre> */ private void generateInternalDocumentInterface() { if (!this.hasDocumentShapes) { return; } Symbol serviceSmithyDocumentInterface = getInternalDocumentSymbol(SERVICE_SMITHY_DOCUMENT_INTERFACE); Symbol internalDocumentInterface = getInternalDocumentSymbol(DOCUMENT_INTERFACE_NAME); Symbol smithyDocumentMarshaler = SymbolUtils.createValueSymbolBuilder("Marshaler", SmithyGoDependency.SMITHY_DOCUMENT).build(); Symbol smithyDocumentUnmarshaler = SymbolUtils.createValueSymbolBuilder("Unmarshaler", SmithyGoDependency.SMITHY_DOCUMENT).build(); writeInternalDocumentPackage("document.go", writer -> { writer.writeDocs(String.format("%s is an interface which is used to bind" + " a document type to its service client.", serviceSmithyDocumentInterface)); writer.openBlock("type $T interface {", "}", serviceSmithyDocumentInterface, () -> writer.write("$L()", IS_SMITHY_DOCUMENT_METHOD)) .write(""); writer.writeDocs(String.format("%s is a JSON-like data model type that is protocol agnostic and is used" + "to send open-content to a service.", internalDocumentInterface)); writer.openBlock("type $T interface {", "}", internalDocumentInterface, () -> { writer.write("$T", serviceSmithyDocumentInterface); writer.write("$T", smithyDocumentMarshaler); writer.write("$T", smithyDocumentUnmarshaler); }).write(""); }); writeInternalDocumentPackage("document_test.go", writer -> { writer.write("var _ $T = ($P)(nil)", serviceSmithyDocumentInterface, internalDocumentInterface); writer.write("var _ $T = ($P)(nil)", smithyDocumentMarshaler, internalDocumentInterface); writer.write("var _ $T = ($P)(nil)", smithyDocumentUnmarshaler, internalDocumentInterface); writer.write(""); }); } /** * Generates the internal document Go package for the service client. Delegates the logic for document marshaling * and unmarshalling types to the provided protocol generator using the given context. * <p> * Generate a document marshaler type for marshaling documents to the service's protocol document format. * * <pre>{@code * type documentMarshaler struct { * value interface{} * } * * func NewDocumentMarshaler(v interface{}) Interface { * // default or protocol implementation * } * * func (m *documentMarshaler) UnmarshalSmithyDocument(v interface{}) error { * // implemented by protocol generator * } * * func (m *documentUnmarshaler) MarshalSmithyDocument() ([]byte, error) { * // implemented by protocol generator * } * }</pre> * <p> * Generate a document marshaler type for unmarshalling documents from the service's protocol response to a Go * type. * * <pre>{@code * type documentUnmarshaler struct { * value interface{} * } * func NewDocumentUnmarshaler(v interface{}) Interface { * // default or protocol implementation * } * * func (m *documentUnmarshaler) UnmarshalSmithyDocument(v interface{}) error { * // implemented by protocol generator * } * * func (m *documentUnmarshaler) MarshalSmithyDocument() ([]byte, error) { * // implemented by protocol generator * } * }</pre> * <p> * Generate {@code IsInterface} function which is used to assert whether a given document type * is a valid service protocol document type implementation. * * <pre>{@code * func IsInterface(v Interface) bool { * // implementation * } * }</pre> * * @param protocolGenerator the protocol generator. * @param context the protocol generator context. */ public void generateInternalDocumentTypes(ProtocolGenerator protocolGenerator, GenerationContext context) { if (!this.hasDocumentShapes) { return; } writeInternalDocumentPackage("document.go", writer -> { Symbol marshalerSymbol = getInternalDocumentSymbol("documentMarshaler", true); Symbol unmarshalerSymbol = getInternalDocumentSymbol("documentUnmarshaler", true); Symbol isDocumentInterface = getInternalDocumentSymbol(INTERNAL_IS_DOCUMENT_INTERFACE); writeInternalDocumentImplementation( writer, marshalerSymbol, () -> { protocolGenerator.generateProtocolDocumentMarshalerUnmarshalDocument(context.toBuilder() .writer(writer) .build()); }, () -> { protocolGenerator.generateProtocolDocumentMarshalerMarshalDocument(context.toBuilder() .writer(writer) .build()); }); writeInternalDocumentImplementation(writer, unmarshalerSymbol, () -> { protocolGenerator.generateProtocolDocumentUnmarshalerUnmarshalDocument(context.toBuilder() .writer(writer) .build()); }, () -> { protocolGenerator.generateProtocolDocumentUnmarshalerMarshalDocument(context.toBuilder() .writer(writer) .build()); }); Symbol documentInterfaceSymbol = getInternalDocumentSymbol(DOCUMENT_INTERFACE_NAME); writer.writeDocs(String.format("%s creates a new document marshaler for the given input type", INTERNAL_NEW_DOCUMENT_MARSHALER_FUNC)); writer.openBlock("func $L(v interface{}) $T {", "}", INTERNAL_NEW_DOCUMENT_MARSHALER_FUNC, documentInterfaceSymbol, () -> { protocolGenerator.generateNewDocumentMarshaler(context.toBuilder() .writer(writer) .build(), marshalerSymbol); }).write(""); writer.writeDocs(String.format("%s creates a new document unmarshaler for the given service response", INTERNAL_NEW_DOCUMENT_UNMARSHALER_FUNC)); writer.openBlock("func $L(v interface{}) $T {", "}", INTERNAL_NEW_DOCUMENT_UNMARSHALER_FUNC, documentInterfaceSymbol, () -> { protocolGenerator.generateNewDocumentUnmarshaler(context.toBuilder() .writer(writer) .build(), unmarshalerSymbol); }).write(""); writer.writeDocs(String.format("%s returns whether the given Interface implementation is" + " a valid client implementation", isDocumentInterface)); writer.openBlock("func $T(v Interface) (ok bool) {", "}", isDocumentInterface, () -> { writer.openBlock("defer func() {", "}()", () -> { writer.openBlock("if err := recover(); err != nil {", "}", () -> writer.write("ok = false")); }); writer.write("v.$L()", IS_SMITHY_DOCUMENT_METHOD); writer.write("return true"); }).write(""); }); } private void writeInternalDocumentImplementation( GoWriter writer, Symbol typeSymbol, Runnable unmarshalMethodDefinition, Runnable marshalMethodDefinition ) { writer.openBlock("type $T struct {", "}", typeSymbol, () -> { writer.write("value interface{}"); }); writer.write(""); writer.openBlock("func (m $P) $L(v interface{}) error {", "}", typeSymbol, UNMARSHAL_SMITHY_DOCUMENT_METHOD, unmarshalMethodDefinition); writer.write(""); writer.openBlock("func (m $P) $L() ([]byte, error) {", "}", typeSymbol, MARSHAL_SMITHY_DOCUMENT_METHOD, marshalMethodDefinition); writer.write(""); writer.write("func (m $P) $L() {}", typeSymbol, IS_SMITHY_DOCUMENT_METHOD); writer.write(""); writer.write("var _ $T = ($P)(nil)", getInternalDocumentSymbol(DOCUMENT_INTERFACE_NAME, true), typeSymbol); writer.write(""); } private void writeDocumentPackage(String fileName, Consumer<GoWriter> writerConsumer) { delegator.useFileWriter(getDocumentFilePath(fileName), getDocumentPackage(), writerConsumer); } private void writeInternalDocumentPackage(String fileName, Consumer<GoWriter> writerConsumer) { delegator.useFileWriter(getInternalDocumentFilePath(fileName), getInternalDocumentPackage(), writerConsumer); } private String getInternalDocumentPackage() { return Utilities.getInternalDocumentPackage(settings); } private String getDocumentPackage() { return Utilities.getDocumentPackage(settings); } private String getInternalDocumentFilePath(String fileName) { return "./internal/document/" + fileName; } private String getDocumentFilePath(String fileName) { return "./document/" + fileName; } private Symbol getDocumentSymbol(String typeName) { return getDocumentSymbol(typeName, false); } private Symbol getDocumentSymbol(String typeName, boolean pointable) { return Utilities.getDocumentSymbolBuilder(settings, typeName, pointable).build(); } private Symbol getInternalDocumentSymbol(String typeName) { return getInternalDocumentSymbol(typeName, false); } private Symbol getInternalDocumentSymbol(String typeName, boolean pointable) { return Utilities.getInternalDocumentSymbolBuilder(settings, typeName, pointable).build(); } /** * Collection of helper utility functions for creating references to the service client's internal * and external document package types. */ public static final class Utilities { /** * Create a non-pointable {@link Symbol.Builder} for typeName in the service's document package. * * @param settings the Smithy Go settings. * @param typeName the name of the Go type. * @return the symbol builder. */ public static Symbol.Builder getDocumentSymbolBuilder(GoSettings settings, String typeName) { return getDocumentSymbolBuilder(settings, typeName, false); } /** * Create {@link Symbol.Builder} for typeName in the service's document package. * * @param settings the Smithy Go settings. * @param typeName the name of the Go type. * @param pointable whether typeName is pointable. * @return the symbol builder. */ public static Symbol.Builder getDocumentSymbolBuilder( GoSettings settings, String typeName, boolean pointable ) { return pointable ? SymbolUtils.createPointableSymbolBuilder(typeName, getDocumentPackage(settings)) : SymbolUtils.createValueSymbolBuilder(typeName, getDocumentPackage(settings)); } /** * Create a non-pointable {@link Symbol.Builder} for typeName in the service's internal document package. * * @param settings the Smithy Go settings. * @param typeName the name of the Go type. * @return the symbol builder. */ public static Symbol.Builder getInternalDocumentSymbolBuilder(GoSettings settings, String typeName) { return getInternalDocumentSymbolBuilder(settings, typeName, false); } /** * Create {@link Symbol.Builder} for typeName in the service's internal document package. * * @param settings the Smithy Go settings. * @param typeName the name of the Go type. * @param pointable whether typeName is pointable. * @return the symbol builder. */ public static Symbol.Builder getInternalDocumentSymbolBuilder( GoSettings settings, String typeName, boolean pointable ) { Symbol.Builder builder = pointable ? SymbolUtils.createPointableSymbolBuilder(typeName, getInternalDocumentPackage(settings)) : SymbolUtils.createValueSymbolBuilder(typeName, getInternalDocumentPackage(settings)); builder.putProperty(SymbolUtils.NAMESPACE_ALIAS, "internaldocument"); return builder; } private static String getInternalDocumentPackage(GoSettings settings) { return settings.getModuleName() + "/internal/document"; } private static String getDocumentPackage(GoSettings settings) { return settings.getModuleName() + "/document"; } } }
8,954
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/CodegenVisitor.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.ServiceLoader; import java.util.Set; import java.util.TreeSet; import java.util.logging.Logger; import java.util.stream.Collectors; import software.amazon.smithy.build.FileManifest; import software.amazon.smithy.build.PluginContext; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.codegen.core.SymbolDependency; import software.amazon.smithy.codegen.core.SymbolProvider; import software.amazon.smithy.go.codegen.integration.GoIntegration; import software.amazon.smithy.go.codegen.integration.ProtocolGenerator; import software.amazon.smithy.go.codegen.integration.RuntimeClientPlugin; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.knowledge.ServiceIndex; import software.amazon.smithy.model.knowledge.TopDownIndex; import software.amazon.smithy.model.neighbor.Walker; import software.amazon.smithy.model.shapes.IntEnumShape; import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; import software.amazon.smithy.model.shapes.ShapeVisitor; import software.amazon.smithy.model.shapes.StringShape; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.shapes.UnionShape; import software.amazon.smithy.model.traits.EnumTrait; import software.amazon.smithy.model.transform.ModelTransformer; import software.amazon.smithy.utils.OptionalUtils; /** * Orchestrates Go client generation. */ final class CodegenVisitor extends ShapeVisitor.Default<Void> { private static final Logger LOGGER = Logger.getLogger(CodegenVisitor.class.getName()); private final GoSettings settings; private final Model model; private final Model modelWithoutTraitShapes; private final ServiceShape service; private final FileManifest fileManifest; private final SymbolProvider symbolProvider; private final GoDelegator writers; private final List<GoIntegration> integrations = new ArrayList<>(); private final ProtocolGenerator protocolGenerator; private final ApplicationProtocol applicationProtocol; private final List<RuntimeClientPlugin> runtimePlugins = new ArrayList<>(); private final ProtocolDocumentGenerator protocolDocumentGenerator; private final EventStreamGenerator eventStreamGenerator; CodegenVisitor(PluginContext context) { // Load all integrations. ClassLoader loader = context.getPluginClassLoader().orElse(getClass().getClassLoader()); LOGGER.info("Attempting to discover GoIntegration from the classpath..."); ServiceLoader.load(GoIntegration.class, loader) .forEach(integration -> { LOGGER.info(() -> "Adding GoIntegration: " + integration.getClass().getName()); integrations.add(integration); }); integrations.sort(Comparator.comparingInt(GoIntegration::getOrder)); settings = GoSettings.from(context.getSettings()); fileManifest = context.getFileManifest(); Model resolvedModel = context.getModel(); var modelTransformer = ModelTransformer.create(); /* * smithy 1.23.0 added support for mixins. This transform flattens and applies * the mixins * and remove them from the model */ resolvedModel = modelTransformer.flattenAndRemoveMixins(resolvedModel); // Add unique operation input/output shapes resolvedModel = AddOperationShapes.execute(resolvedModel, settings.getService()); /* * smithy 1.12.0 added support for binding common errors to the service shape * this transform copies these common errors to the operations */ resolvedModel = modelTransformer.copyServiceErrorsToOperations(resolvedModel, settings.getService(resolvedModel)); LOGGER.info(() -> "Preprocessing smithy model"); for (GoIntegration goIntegration : integrations) { resolvedModel = goIntegration.preprocessModel(resolvedModel, settings); } model = resolvedModel; // process final model integrations.forEach(integration -> { integration.processFinalizedModel(settings, model); }); // fetch runtime plugins integrations.forEach(integration -> { integration.getClientPlugins().forEach(runtimePlugin -> { LOGGER.info(() -> "Adding Go runtime plugin: " + runtimePlugin); runtimePlugins.add(runtimePlugin); }); }); modelWithoutTraitShapes = modelTransformer.getModelWithoutTraitShapes(model); service = settings.getService(model); LOGGER.info(() -> "Generating Go client for service " + service.getId()); SymbolProvider resolvedProvider = GoCodegenPlugin.createSymbolProvider(model, settings); for (GoIntegration integration : integrations) { resolvedProvider = integration.decorateSymbolProvider(settings, model, resolvedProvider); } symbolProvider = resolvedProvider; protocolGenerator = resolveProtocolGenerator(integrations, model, service, settings); applicationProtocol = protocolGenerator == null ? ApplicationProtocol.createDefaultHttpApplicationProtocol() : protocolGenerator.getApplicationProtocol(); writers = new GoDelegator(fileManifest, symbolProvider); protocolDocumentGenerator = new ProtocolDocumentGenerator(settings, model, writers); this.eventStreamGenerator = new EventStreamGenerator(settings, model, writers, symbolProvider, service); } private static ProtocolGenerator resolveProtocolGenerator( Collection<GoIntegration> integrations, Model model, ServiceShape service, GoSettings settings) { // Collect all the supported protocol generators. Map<ShapeId, ProtocolGenerator> generators = new HashMap<>(); for (GoIntegration integration : integrations) { for (ProtocolGenerator generator : integration.getProtocolGenerators()) { generators.put(generator.getProtocol(), generator); } } ServiceIndex serviceIndex = ServiceIndex.of(model); ShapeId protocolTrait; try { protocolTrait = settings.resolveServiceProtocol(serviceIndex, service, generators.keySet()); settings.setProtocol(protocolTrait); } catch (UnresolvableProtocolException e) { LOGGER.warning("Unable to find a protocol generator for " + service.getId() + ": " + e.getMessage()); protocolTrait = null; } return protocolTrait != null ? generators.get(protocolTrait) : null; } void execute() { // Generate models that are connected to the service being generated. LOGGER.fine("Walking shapes from " + service.getId() + " to find shapes to generate"); Set<Shape> serviceShapes = new TreeSet<>(new Walker(modelWithoutTraitShapes).walkShapes(service)); for (Shape shape : serviceShapes) { shape.accept(this); } // Generate any required types and functions need to support protocol documents. protocolDocumentGenerator.generateDocumentSupport(); // Generate a struct to handle unknown tags in unions List<UnionShape> unions = serviceShapes.stream() .map(Shape::asUnionShape) .flatMap(OptionalUtils::stream) .collect(Collectors.toList()); if (!unions.isEmpty()) { writers.useShapeWriter(unions.get(0), writer -> { UnionGenerator.generateUnknownUnion(writer, unions, symbolProvider); }); } for (GoIntegration integration : integrations) { integration.writeAdditionalFiles(settings, model, symbolProvider, writers::useFileWriter); integration.writeAdditionalFiles(settings, model, symbolProvider, writers); } eventStreamGenerator.generateEventStreamInterfaces(); TopDownIndex.of(model).getContainedOperations(service) .forEach(eventStreamGenerator::generateOperationEventStreamStructure); if (protocolGenerator != null) { LOGGER.info("Generating serde for protocol " + protocolGenerator.getProtocol() + " on " + service.getId()); ProtocolGenerator.GenerationContext.Builder contextBuilder = ProtocolGenerator.GenerationContext.builder() .protocolName(protocolGenerator.getProtocolName()) .integrations(integrations) .model(model) .service(service) .settings(settings) .symbolProvider(symbolProvider) .delegator(writers); LOGGER.info("Generating serde for protocol " + protocolGenerator.getProtocol() + " on " + service.getId()); writers.useFileWriter("serializers.go", settings.getModuleName(), writer -> { ProtocolGenerator.GenerationContext context = contextBuilder.writer(writer).build(); protocolGenerator.generateRequestSerializers(context); protocolGenerator.generateSharedSerializerComponents(context); }); writers.useFileWriter("deserializers.go", settings.getModuleName(), writer -> { ProtocolGenerator.GenerationContext context = contextBuilder.writer(writer).build(); protocolGenerator.generateResponseDeserializers(context); protocolGenerator.generateSharedDeserializerComponents(context); }); if (eventStreamGenerator.hasEventStreamOperations()) { eventStreamGenerator.writeEventStreamImplementation(writer -> { ProtocolGenerator.GenerationContext context = contextBuilder.writer(writer).build(); protocolGenerator.generateEventStreamComponents(context); }); } writers.useFileWriter("endpoints.go", settings.getModuleName(), writer -> { ProtocolGenerator.GenerationContext context = contextBuilder.writer(writer).build(); protocolGenerator.generateEndpointResolution(context); }); writers.useFileWriter("endpoints_test.go", settings.getModuleName(), writer -> { ProtocolGenerator.GenerationContext context = contextBuilder.writer(writer).build(); protocolGenerator.generateEndpointResolutionTests(context); }); LOGGER.info("Generating protocol " + protocolGenerator.getProtocol() + " unit tests for " + service.getId()); writers.useFileWriter("protocol_test.go", settings.getModuleName(), writer -> { protocolGenerator.generateProtocolTests(contextBuilder.writer(writer).build()); }); protocolDocumentGenerator.generateInternalDocumentTypes(protocolGenerator, contextBuilder.build()); } LOGGER.fine("Flushing go writers"); List<SymbolDependency> dependencies = writers.getDependencies(); writers.flushWriters(); GoModuleInfo goModuleInfo = new GoModuleInfo.Builder() .goDirective(settings.getGoDirective()) .dependencies(dependencies) .build(); GoModGenerator.writeGoMod(settings, fileManifest, goModuleInfo); LOGGER.fine("Generating build manifest file"); ManifestWriter.writeManifest(settings, model, fileManifest, goModuleInfo); } @Override protected Void getDefault(Shape shape) { return null; } @Override public Void structureShape(StructureShape shape) { if (shape.getId().getNamespace().equals(CodegenUtils.getSyntheticTypeNamespace())) { return null; } Symbol symbol = symbolProvider.toSymbol(shape); writers.useShapeWriter(shape, writer -> new StructureGenerator( model, symbolProvider, writer, service, shape, symbol, protocolGenerator).run()); return null; } @Override public Void stringShape(StringShape shape) { if (shape.hasTrait(EnumTrait.class)) { writers.useShapeWriter(shape, writer -> new EnumGenerator(symbolProvider, writer, shape).run()); } return null; } @Override public Void unionShape(UnionShape shape) { UnionGenerator generator = new UnionGenerator(model, symbolProvider, shape); writers.useShapeWriter(shape, generator::generateUnion); writers.useShapeExportedTestWriter(shape, generator::generateUnionExamples); return null; } @Override public Void serviceShape(ServiceShape shape) { if (!Objects.equals(service, shape)) { LOGGER.fine(() -> "Skipping `" + shape.getId() + "` because it is not `" + service.getId() + "`"); return null; } // Write API client's package doc for the service. writers.useFileWriter("doc.go", settings.getModuleName(), (writer) -> { writer.writePackageDocs(String.format( "Package %s provides the API client, operations, and parameter types for %s.", CodegenUtils.getDefaultPackageImportName(settings.getModuleName()), CodegenUtils.getServiceTitle(shape, "the API"))); writer.writePackageDocs(""); writer.writePackageShapeDocs(shape); }); // Write API client type and utilities. writers.useShapeWriter(shape, serviceWriter -> { new ServiceGenerator(settings, model, symbolProvider, serviceWriter, shape, integrations, runtimePlugins, applicationProtocol).run(); // Generate each operation for the service. We do this here instead of via the // operation visitor method to // limit it to the operations bound to the service. TopDownIndex topDownIndex = model.getKnowledge(TopDownIndex.class); Set<OperationShape> containedOperations = new TreeSet<>(topDownIndex.getContainedOperations(service)); for (OperationShape operation : containedOperations) { Symbol operationSymbol = symbolProvider.toSymbol(operation); writers.useShapeWriter( operation, operationWriter -> new OperationGenerator(settings, model, symbolProvider, operationWriter, service, operation, operationSymbol, applicationProtocol, protocolGenerator, runtimePlugins).run()); } }); return null; } @Override public Void intEnumShape(IntEnumShape shape) { writers.useShapeWriter(shape, writer -> new IntEnumGenerator(symbolProvider, writer, shape).run()); return null; } }
8,955
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/ManifestWriter.java
/* * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; import java.util.stream.Collectors; import software.amazon.smithy.build.FileManifest; import software.amazon.smithy.codegen.core.CodegenException; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.node.ArrayNode; import software.amazon.smithy.model.node.BooleanNode; import software.amazon.smithy.model.node.Node; import software.amazon.smithy.model.node.ObjectNode; import software.amazon.smithy.model.node.StringNode; import software.amazon.smithy.model.traits.UnstableTrait; import software.amazon.smithy.utils.SmithyBuilder; /** * Generates a manifest description of the generated code, minimum go version, * and minimum dependencies required. */ public final class ManifestWriter { private static final Logger LOGGER = Logger.getLogger(ManifestWriter.class.getName()); private static final String GENERATED_JSON = "generated.json"; private final String moduleName; private final FileManifest fileManifest; private final GoModuleInfo goModuleInfo; private final boolean isUnstable; private ManifestWriter(Builder builder) { moduleName = SmithyBuilder.requiredState("moduleName", builder.moduleName); fileManifest = SmithyBuilder.requiredState("fileManifest", builder.fileManifest); goModuleInfo = SmithyBuilder.requiredState("goModuleInfo", builder.goModuleInfo); isUnstable = builder.isUnstable; } /** * Write the manifest description of the Smithy model based generated source code. * * @param settings the go settings * @param model the smithy model * @param fileManifest the file manifest * @param goModuleInfo the go module info */ public static void writeManifest( GoSettings settings, Model model, FileManifest fileManifest, GoModuleInfo goModuleInfo ) { builder() .moduleName(settings.getModuleName()) .fileManifest(fileManifest) .goModuleInfo(goModuleInfo) .isUnstable(settings.getService(model).getTrait(UnstableTrait.class).isPresent()) .build() .writeManifest(); } /** * Write the manifest description of the generated code. */ public void writeManifest() { Path manifestFile = fileManifest.getBaseDir().resolve(GENERATED_JSON); if (Files.exists(manifestFile)) { try { Files.delete(manifestFile); } catch (IOException e) { throw new CodegenException("Failed to delete existing " + GENERATED_JSON + " file", e); } } fileManifest.addFile(manifestFile); LOGGER.fine("Creating manifest at path " + manifestFile.toString()); Node generatedJson = buildManifestFile(); fileManifest.writeFile(manifestFile.toString(), Node.prettyPrintJson(generatedJson) + "\n"); } private Node buildManifestFile() { Map<StringNode, Node> dependencyNodes = gatherDependencyNodes(goModuleInfo.getMinimumNonStdLibDependencies()); Collection<String> generatedFiles = gatherGeneratedFiles(fileManifest); return ObjectNode.objectNode(Map.of( StringNode.from("module"), StringNode.from(moduleName), StringNode.from("go"), StringNode.from(goModuleInfo.getGoDirective()), StringNode.from("dependencies"), ObjectNode.objectNode(dependencyNodes), StringNode.from("files"), ArrayNode.fromStrings(generatedFiles), StringNode.from("unstable"), BooleanNode.from(isUnstable) )).withDeepSortedKeys(); } private Map<StringNode, Node> gatherDependencyNodes(Map<String, String> dependencies) { Map<StringNode, Node> dependencyNodes = new HashMap<>(); for (Map.Entry<String, String> entry : dependencies.entrySet()) { dependencyNodes.put(StringNode.from(entry.getKey()), StringNode.from(entry.getValue())); } return dependencyNodes; } private static Collection<String> gatherGeneratedFiles(FileManifest fileManifest) { Collection<String> generatedFiles = new ArrayList<>(); Path baseDir = fileManifest.getBaseDir(); for (Path filePath : fileManifest.getFiles()) { generatedFiles.add(baseDir.relativize(filePath).toString()); } generatedFiles = generatedFiles.stream().sorted().collect(Collectors.toList()); return generatedFiles; } public static Builder builder() { return new Builder(); } public static class Builder implements SmithyBuilder<ManifestWriter> { private String moduleName; private FileManifest fileManifest; private GoModuleInfo goModuleInfo; private boolean isUnstable; public Builder moduleName(String moduleName) { this.moduleName = moduleName; return this; } public Builder fileManifest(FileManifest fileManifest) { this.fileManifest = fileManifest; return this; } public Builder goModuleInfo(GoModuleInfo goModuleInfo) { this.goModuleInfo = goModuleInfo; return this; } public Builder isUnstable(boolean isUnstable) { this.isUnstable = isUnstable; return this; } @Override public ManifestWriter build() { return new ManifestWriter(this); } } }
8,956
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/UnionGenerator.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.TreeSet; import java.util.stream.Collectors; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.codegen.core.SymbolProvider; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.SimpleShape; import software.amazon.smithy.model.shapes.UnionShape; import software.amazon.smithy.model.traits.ErrorTrait; import software.amazon.smithy.model.traits.StreamingTrait; /** * Renders unions and type aliases for all their members. */ public class UnionGenerator { public static final String UNKNOWN_MEMBER_NAME = "UnknownUnionMember"; private final Model model; private final SymbolProvider symbolProvider; private final UnionShape shape; private final boolean isEventStream; UnionGenerator(Model model, SymbolProvider symbolProvider, UnionShape shape) { this.model = model; this.symbolProvider = symbolProvider; this.shape = shape; this.isEventStream = StreamingTrait.isEventStream(shape); } /** * Generates the Go type definitions for the UnionShape. * * @param writer the writer */ public void generateUnion(GoWriter writer) { Symbol symbol = symbolProvider.toSymbol(shape); Collection<MemberShape> memberShapes = shape.getAllMembers().values() .stream() .filter(memberShape -> !isEventStreamErrorMember(memberShape)) .collect(Collectors.toCollection(TreeSet::new)); // Creates the parent interface for the union, which only defines a // non-exported method whose purpose is only to enable satisfying the // interface. if (writer.writeShapeDocs(shape)) { writer.writeDocs(""); } writer.writeDocs("The following types satisfy this interface:"); memberShapes.stream().map(symbolProvider::toMemberName).forEach(name -> { writer.write("// " + name); }); writer.openBlock("type $L interface {", "}", symbol.getName(), () -> { writer.write("is$L()", symbol.getName()); }).write(""); // Create structs for each member that satisfy the interface. for (MemberShape member : memberShapes) { Symbol memberSymbol = symbolProvider.toSymbol(member); String exportedMemberName = symbolProvider.toMemberName(member); Shape target = model.expectShape(member.getTarget()); // Create the member's concrete type writer.writeMemberDocs(model, member); writer.openBlock("type $L struct {", "}", exportedMemberName, () -> { // Union members can't have null values, so for simple shapes we don't // use pointers. We have to use pointers for complex shapes since, // for example, we could still have a map that's empty or which has // null values. if (target instanceof SimpleShape) { writer.write("Value $T", memberSymbol); } else { writer.write("Value $P", memberSymbol); } writer.write(""); writer.write("$L", ProtocolDocumentGenerator.NO_DOCUMENT_SERDE_TYPE_NAME); }); writer.write("func (*$L) is$L() {}", exportedMemberName, symbol.getName()); } } private boolean isEventStreamErrorMember(MemberShape memberShape) { return isEventStream && memberShape.getMemberTrait(model, ErrorTrait.class).isPresent(); } /** * Generates union usage examples for documentation. * * @param writer the writer */ public void generateUnionExamples(GoWriter writer) { Symbol symbol = symbolProvider.toSymbol(shape); Set<MemberShape> members = shape.getAllMembers().values().stream() .filter(memberShape -> !isEventStreamErrorMember(memberShape)) .collect(Collectors.toCollection(TreeSet::new)); Set<Symbol> referenced = new HashSet<>(); writer.openBlock("func Example$L_outputUsage() {", "}", symbol.getName(), () -> { writer.write("var union $P", symbol); writer.writeDocs("type switches can be used to check the union value"); writer.openBlock("switch v := union.(type) {", "}", () -> { for (MemberShape member : members) { Symbol targetSymbol = symbolProvider.toSymbol(model.expectShape(member.getTarget())); referenced.add(targetSymbol); Symbol memberSymbol = SymbolUtils.createValueSymbolBuilder(symbolProvider.toMemberName(member), symbol.getNamespace()).build(); writer.openBlock("case *$T:", "", memberSymbol, () -> { writer.write("_ = v.Value // Value is $T", targetSymbol); }); } writer.addUseImports(SmithyGoDependency.FMT); Symbol unknownUnionMember = SymbolUtils.createPointableSymbolBuilder("UnknownUnionMember", symbol.getNamespace()).build(); writer.openBlock("case $P:", "", unknownUnionMember, () -> { writer.write("fmt.Println(\"unknown tag:\", v.Tag)"); }); writer.openBlock("default:", "", () -> { writer.write("fmt.Println(\"union is nil or unknown type\")"); }); }); }).write(""); referenced.forEach(s -> { writer.write("var _ $P", s); }); } /** * Generates a struct for unknown union values that applies to every union in the given set. * * @param writer The writer to write the union to. * @param unions A set of unions whose interfaces the union should apply to. * @param symbolProvider A symbol provider used to get the symbols for the unions. */ public static void generateUnknownUnion( GoWriter writer, Collection<UnionShape> unions, SymbolProvider symbolProvider ) { // Creates a fallback type for use when an unknown member is found. This // could be the result of an outdated client, for example. writer.writeDocs(UNKNOWN_MEMBER_NAME + " is returned when a union member is returned over the wire, but has an unknown tag."); writer.openBlock("type $L struct {", "}", UNKNOWN_MEMBER_NAME, () -> { // The tag (member) name received over the wire. writer.write("Tag string"); // The value received. writer.write("Value []byte"); writer.write(""); writer.write("$L", ProtocolDocumentGenerator.NO_DOCUMENT_SERDE_TYPE_NAME); }); for (UnionShape union : unions) { writer.write("func (*$L) is$L() {}", UNKNOWN_MEMBER_NAME, symbolProvider.toSymbol(union).getName()); } } }
8,957
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/UnresolvableProtocolException.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen; import software.amazon.smithy.codegen.core.CodegenException; public class UnresolvableProtocolException extends CodegenException { public UnresolvableProtocolException(String message) { super(message); } }
8,958
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/SemanticVersion.java
/* * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen; import java.util.Comparator; import java.util.Objects; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import software.amazon.smithy.utils.SmithyBuilder; /** * A semantic version parser that allows for prefixes to be compatible with Go version tags. */ public final class SemanticVersion { // Regular Expression from https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string private static final Pattern SEMVER_PATTERN = Pattern.compile("^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)" + "(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?" + "(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$"); private final String prefix; private final int major; private final int minor; private final int patch; private final String preRelease; private final String build; private SemanticVersion(Builder builder) { prefix = builder.prefix; major = builder.major; minor = builder.minor; patch = builder.patch; preRelease = builder.preRelease; build = builder.build; } /** * The semantic version prefix present before the major version. * * @return the optional prefix */ public Optional<String> getPrefix() { return Optional.ofNullable(prefix); } /** * The major version number. * * @return the major version */ public int getMajor() { return major; } /** * The minor version number. * * @return the minor version */ public int getMinor() { return minor; } /** * The patch version number. * * @return the patch version */ public int getPatch() { return patch; } public Optional<String> getPreRelease() { return Optional.ofNullable(preRelease); } public Optional<String> getBuild() { return Optional.ofNullable(build); } @Override public String toString() { StringBuilder builder = new StringBuilder(); if (getPrefix().isPresent()) { builder.append(getPrefix().get()); } builder.append(getMajor()); builder.append('.'); builder.append(getMinor()); builder.append('.'); builder.append(getPatch()); if (getPreRelease().isPresent()) { builder.append('-'); builder.append(getPreRelease().get()); } if (getBuild().isPresent()) { builder.append('+'); builder.append(getBuild().get()); } return builder.toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SemanticVersion that = (SemanticVersion) o; return getMajor() == that.getMajor() && getMinor() == that.getMinor() && getPatch() == that.getPatch() && getPrefix().equals(that.getPrefix()) && getPreRelease().equals(that.getPreRelease()) && getBuild().equals(that.getBuild()); } @Override public int hashCode() { return Objects.hash(getPrefix(), getMajor(), getMinor(), getPatch(), getPreRelease(), getBuild()); } /** * Parse a semantic version string into a {@link SemanticVersion}. * * @param version the semantic version string * @return the SemanticVersion representing the parsed value */ public static SemanticVersion parseVersion(String version) { char[] parseArr = version.toCharArray(); StringBuilder prefixBuilder = new StringBuilder(); int position = 0; while (position < parseArr.length && !Character.isDigit(parseArr[position])) { prefixBuilder.append(parseArr[position]); position++; } String prefix = null; if (prefixBuilder.length() > 0) { prefix = prefixBuilder.toString(); } Matcher matcher = SEMVER_PATTERN.matcher(version.substring(position)); if (!matcher.matches()) { throw newInvalidSemanticVersion(version); } return builder() .prefix(prefix) .major(Integer.parseInt(matcher.group(1))) .minor(Integer.parseInt(matcher.group(2))) .patch(Integer.parseInt(matcher.group(3))) .preRelease(matcher.group(4)) .build(matcher.group(5)) .build(); } private static IllegalArgumentException newInvalidSemanticVersion(String version) { return new IllegalArgumentException("Invalid semantic version string: " + version); } /** * Get a {@link SemanticVersion} builder. * * @return the builder */ public static Builder builder() { return new Builder(); } /** * Return a builder for this {@link SemanticVersion}. * * @return the builder */ public Builder toBuilder() { return builder() .prefix(this.prefix) .major(this.major) .minor(this.minor) .patch(this.patch) .preRelease(this.preRelease) .build(this.build); } /** * Compare two {@link SemanticVersion}, ignoring prefix strings. To validate that prefix strings match * see the overloaded function signature. * * @param o the {@link SemanticVersion} to be compared. * @return the value {@code 0} if this {@code SemanticVersion} is * equal to the argument {@code SemanticVersion}; a value less than * {@code 0} if this {@code SemanticVersion} is less * than the argument {@code SemanticVersion}; and a value greater * than {@code 0} if this {@code SemanticVersion} is * greater than the argument {@code SemanticVersion}. */ public int compareTo(SemanticVersion o) { return compareTo(o, (o1, o2) -> 0); } /** * Compare two {@link SemanticVersion}, using the prefixComparator for comparing the prefix strings. * * @param o the {@link SemanticVersion} to be compared. * @param prefixComparator the comparator for comparing prefixes * @return the value {@code 0} if this {@code SemanticVersion} is * equal to the argument {@code SemanticVersion}; a value less than * {@code 0} if this {@code SemanticVersion} is less * than the argument {@code SemanticVersion}; and a value greater * than {@code 0} if this {@code SemanticVersion} is * greater than the argument {@code SemanticVersion}. */ public int compareTo( SemanticVersion o, Comparator<Optional<String>> prefixComparator ) { int cmp = prefixComparator.compare(getPrefix(), o.getPrefix()); if (cmp != 0) { return cmp; } cmp = Integer.compare(getMajor(), o.getMajor()); if (cmp != 0) { return cmp; } cmp = Integer.compare(getMinor(), o.getMinor()); if (cmp != 0) { return cmp; } cmp = Integer.compare(getPatch(), o.getPatch()); if (cmp != 0) { return cmp; } if (!getPreRelease().isPresent() && !o.getPreRelease().isPresent()) { return 0; } if (!getPreRelease().isPresent()) { return 1; } if (!o.getPreRelease().isPresent()) { return -1; } return comparePreRelease(getPreRelease().get(), o.getPreRelease().get()); } private static int comparePreRelease(String x, String y) { String[] xIdentifiers = x.split("\\."); String[] yIdentifiers = y.split("\\."); int cmp = 0; int xPos = 0; int yPos = 0; while (xPos < xIdentifiers.length && yPos < yIdentifiers.length && cmp == 0) { Optional<Integer> xInt = parsePositiveInteger(xIdentifiers[xPos]); Optional<Integer> yInt = parsePositiveInteger(yIdentifiers[yPos]); if (xInt.isPresent() && yInt.isPresent()) { cmp = Integer.compare(xInt.get(), yInt.get()); continue; } if (xInt.isPresent()) { cmp = -1; continue; } if (yInt.isPresent()) { cmp = 1; continue; } cmp = xIdentifiers[xPos].compareTo(yIdentifiers[yPos]); xPos++; yPos++; } if (cmp != 0) { return cmp; } int xRemaining = xIdentifiers.length - 1 - xPos; int yRemaining = yIdentifiers.length - 1 - yPos; if (xRemaining == yRemaining) { return 0; } return (xRemaining < yRemaining) ? -1 : 1; } private static Optional<Integer> parsePositiveInteger(String value) { try { int i = Integer.parseInt(value); if (i < 0) { return Optional.empty(); } return Optional.of(i); } catch (NumberFormatException e) { return Optional.empty(); } } /** * Builder for {@link SemanticVersion}. */ public static final class Builder implements SmithyBuilder<SemanticVersion> { private String prefix; private int major; private int minor; private int patch; private String preRelease; private String build; private Builder() { } public Builder prefix(String prefix) { this.prefix = prefix; return this; } public Builder major(int major) { this.major = major; return this; } public Builder minor(int minor) { this.minor = minor; return this; } public Builder patch(int patch) { this.patch = patch; return this; } public Builder preRelease(String preRelease) { this.preRelease = preRelease; return this; } public Builder build(String build) { this.build = build; return this; } @Override public SemanticVersion build() { return new SemanticVersion(this); } } }
8,959
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/StructureGenerator.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen; import java.util.Map; import java.util.Set; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.codegen.core.SymbolProvider; import software.amazon.smithy.go.codegen.integration.ProtocolGenerator; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.traits.ErrorTrait; import software.amazon.smithy.model.traits.StreamingTrait; import software.amazon.smithy.utils.MapUtils; import software.amazon.smithy.utils.SetUtils; /** * Renders structures. */ final class StructureGenerator implements Runnable { private static final Map<String, String> STANDARD_ERROR_MEMBERS = MapUtils.of( "ErrorCode", "string", "ErrorMessage", "string", "ErrorFault", "string" ); private static final Set<String> ERROR_MEMBER_NAMES = SetUtils.of("ErrorMessage", "Message", "ErrorCodeOverride"); private final Model model; private final SymbolProvider symbolProvider; private final GoWriter writer; private final StructureShape shape; private final Symbol symbol; private final ServiceShape service; private final ProtocolGenerator protocolGenerator; StructureGenerator( Model model, SymbolProvider symbolProvider, GoWriter writer, ServiceShape service, StructureShape shape, Symbol symbol, ProtocolGenerator protocolGenerator ) { this.model = model; this.symbolProvider = symbolProvider; this.writer = writer; this.service = service; this.shape = shape; this.symbol = symbol; this.protocolGenerator = protocolGenerator; } @Override public void run() { if (!shape.hasTrait(ErrorTrait.class)) { renderStructure(() -> { }); } else { renderErrorStructure(); } } /** * Renders a non-error structure. * * @param runnable A runnable that runs before the structure definition is closed. This can be used to write * additional members. */ public void renderStructure(Runnable runnable) { renderStructure(runnable, false); } /** * Renders a non-error structure. * * @param runnable A runnable that runs before the structure definition is closed. This can be used to write * additional members. * @param isInputStructure A boolean indicating if input variants for member symbols should be used. */ public void renderStructure(Runnable runnable, boolean isInputStructure) { writer.writeShapeDocs(shape); writer.openBlock("type $L struct {", symbol.getName()); CodegenUtils.SortedMembers sortedMembers = new CodegenUtils.SortedMembers(symbolProvider); shape.getAllMembers().values().stream() .filter(memberShape -> !StreamingTrait.isEventStream(model, memberShape)) .sorted(sortedMembers) .forEach((member) -> { writer.write(""); String memberName = symbolProvider.toMemberName(member); writer.writeMemberDocs(model, member); Symbol memberSymbol = symbolProvider.toSymbol(member); if (isInputStructure) { memberSymbol = memberSymbol.getProperty(SymbolUtils.INPUT_VARIANT, Symbol.class) .orElse(memberSymbol); } writer.write("$L $P", memberName, memberSymbol); }); runnable.run(); // At this moment there is no support for the concept of modeled document structure types. // We embed the NoSerde type to prevent usage of the generated structure shapes from being used // as document types themselves, or part of broader document-type structures. This avoids making backwards // incompatible changes if the document type representation changes if it is later annotated as a modeled // document type. This restriction may be relaxed later by removing this constraint. writer.write(""); writer.write("$L", ProtocolDocumentGenerator.NO_DOCUMENT_SERDE_TYPE_NAME); writer.closeBlock("}").write(""); } /** * Renders an error structure and supporting methods. */ private void renderErrorStructure() { Symbol structureSymbol = symbolProvider.toSymbol(shape); writer.addUseImports(SmithyGoDependency.SMITHY); writer.addUseImports(SmithyGoDependency.FMT); ErrorTrait errorTrait = shape.expectTrait(ErrorTrait.class); // Write out a struct to hold the error data. writer.writeShapeDocs(shape); writer.openBlock("type $L struct {", "}", structureSymbol.getName(), () -> { // The message is the only part of the standard APIError interface that isn't known ahead of time. // Message is a pointer mostly for the sake of consistency. writer.write("Message *string").write(""); writer.write("ErrorCodeOverride *string").write(""); for (MemberShape member : shape.getAllMembers().values()) { String memberName = symbolProvider.toMemberName(member); // error messages are represented under Message for consistency if (!ERROR_MEMBER_NAMES.contains(memberName)) { writer.write("$L $P", memberName, symbolProvider.toSymbol(member)); } } writer.write(""); writer.write("$L", ProtocolDocumentGenerator.NO_DOCUMENT_SERDE_TYPE_NAME); }).write(""); // write the Error method to satisfy the standard error interface writer.openBlock("func (e *$L) Error() string {", "}", structureSymbol.getName(), () -> { writer.write("return fmt.Sprintf(\"%s: %s\", e.ErrorCode(), e.ErrorMessage())"); }); // Write out methods to satisfy the APIError interface. All but the message are known ahead of time, // and for those we just encode the information in the method itself. writer.openBlock("func (e *$L) ErrorMessage() string {", "}", structureSymbol.getName(), () -> { writer.openBlock("if e.Message == nil {", "}", () -> { writer.write("return \"\""); }); writer.write("return *e.Message"); }); String errorCode = protocolGenerator == null ? shape.getId().getName(service) : protocolGenerator.getErrorCode(service, shape); writer.openBlock("func (e *$L) ErrorCode() string {", "}", structureSymbol.getName(), () -> { writer.openBlock("if e == nil || e.ErrorCodeOverride == nil {", "}", () -> { writer.write("return $S", errorCode); }); writer.write("return *e.ErrorCodeOverride"); }); String fault = "smithy.FaultUnknown"; if (errorTrait.isClientError()) { fault = "smithy.FaultClient"; } else if (errorTrait.isServerError()) { fault = "smithy.FaultServer"; } writer.write("func (e *$L) ErrorFault() smithy.ErrorFault { return $L }", structureSymbol.getName(), fault); } }
8,960
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/EventStreamGenerator.java
/* * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen; import java.util.Set; import java.util.TreeSet; import java.util.function.Consumer; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.codegen.core.SymbolProvider; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.knowledge.EventStreamIndex; import software.amazon.smithy.model.knowledge.TopDownIndex; import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; import software.amazon.smithy.model.shapes.ToShapeId; import software.amazon.smithy.utils.StringUtils; public final class EventStreamGenerator { private static final String EVENT_STREAM_FILE = "eventstream.go"; private final GoSettings settings; private final Model model; private final GoDelegator writers; private final ServiceShape serviceShape; private final EventStreamIndex streamIndex; private final SymbolProvider symbolProvider; public EventStreamGenerator( GoSettings settings, Model model, GoDelegator writers, SymbolProvider symbolProvider, ServiceShape serviceShape ) { this.settings = settings; this.model = model; this.writers = writers; this.symbolProvider = symbolProvider; this.serviceShape = serviceShape; this.streamIndex = EventStreamIndex.of(this.model); } public void generateEventStreamInterfaces() { if (!hasEventStreamOperations()) { return; } final Set<ShapeId> inputEvents = new TreeSet<>(); final Set<ShapeId> outputEvents = new TreeSet<>(); TopDownIndex.of(model).getContainedOperations(serviceShape).forEach(operationShape -> { streamIndex.getInputInfo(operationShape).ifPresent(eventStreamInfo -> inputEvents.add(eventStreamInfo.getEventStreamMember().getTarget())); streamIndex.getOutputInfo(operationShape).ifPresent(eventStreamInfo -> outputEvents.add(eventStreamInfo.getEventStreamMember().getTarget())); }); Symbol context = SymbolUtils.createValueSymbolBuilder("Context", SmithyGoDependency.CONTEXT).build(); writers.useFileWriter(EVENT_STREAM_FILE, settings.getModuleName(), writer -> { inputEvents.forEach(shapeId -> { Shape shape = model.expectShape(shapeId); String writerInterfaceName = getEventStreamWriterInterfaceName(serviceShape, shape); writer.writeDocs(String.format("%s provides the interface for writing events to a stream.", writerInterfaceName)) .writeDocs("") .writeDocs("The writer's Close method must allow multiple concurrent calls."); writer.openBlock("type $L interface {", "}", writerInterfaceName, () -> { writer.write("Send($T, $T) error", context, symbolProvider.toSymbol(shape)); writer.write("Close() error"); writer.write("Err() error"); }); }); outputEvents.forEach(shapeId -> { Shape shape = model.expectShape(shapeId); String readerInterfaceName = getEventStreamReaderInterfaceName(serviceShape, shape); writer.writeDocs(String.format("%s provides the interface for reading events from a stream.", readerInterfaceName)) .writeDocs("") .writeDocs("The writer's Close method must allow multiple concurrent calls."); writer.openBlock("type $L interface {", "}", readerInterfaceName, () -> { writer.write("Events() <-chan $T", symbolProvider.toSymbol(shape)); writer.write("Close() error"); writer.write("Err() error"); }); }); }); } public boolean hasEventStreamOperations() { return hasEventStreamOperations(model, serviceShape, streamIndex); } public static boolean hasEventStreamOperations(Model model, ServiceShape serviceShape) { EventStreamIndex index = EventStreamIndex.of(model); return hasEventStreamOperations(model, serviceShape, index); } private static boolean hasEventStreamOperations(Model model, ServiceShape serviceShape, EventStreamIndex index) { return TopDownIndex.of(model).getContainedOperations(serviceShape).stream() .anyMatch(operationShape -> hasEventStream(model, operationShape, index)); } public void writeEventStreamImplementation(Consumer<GoWriter> goWriterConsumer) { writers.useFileWriter(EVENT_STREAM_FILE, settings.getModuleName(), goWriterConsumer); } public boolean hasEventStream(OperationShape operationShape) { EventStreamIndex index = EventStreamIndex.of(model); return hasEventStreamOperations(model, serviceShape, index); } public static boolean hasEventStream(Model model, OperationShape operationShape) { EventStreamIndex index = EventStreamIndex.of(model); return hasEventStream(model, operationShape, index); } private static boolean hasEventStream(Model model, OperationShape operationShape, EventStreamIndex index) { return index.getInputInfo(operationShape).isPresent() || index.getOutputInfo(operationShape).isPresent(); } public void generateOperationEventStreamStructure(OperationShape operationShape) { if (!hasEventStream(model, operationShape)) { return; } writers.useShapeWriter(operationShape, writer -> generateOperationEventStreamStructure(writer, operationShape)); } private void generateOperationEventStreamStructure(GoWriter writer, OperationShape operationShape) { var opEventStreamStructure = getEventStreamOperationStructureSymbol(serviceShape, operationShape); var constructor = getEventStreamOperationStructureConstructor(serviceShape, operationShape); var inputInfo = streamIndex.getInputInfo(operationShape); var outputInfo = streamIndex.getOutputInfo(operationShape); writer.write(""" // $T provides the event stream handling for the $L operation. // // For testing and mocking the event stream this type should be initialized via // the $T constructor function. Using the functional options // to pass in nested mock behavior.""", opEventStreamStructure, operationShape.getId().getName(), constructor ); writer.openBlock("type $T struct {", "}", opEventStreamStructure, () -> { inputInfo.ifPresent(eventStreamInfo -> { var eventStreamTarget = eventStreamInfo.getEventStreamTarget(); var writerInterfaceName = getEventStreamWriterInterfaceName(serviceShape, eventStreamTarget); writer.writeDocs(String.format(""" %s is the EventStream writer for the %s events. This value is automatically set by the SDK when the API call is made Use this member when unit testing your code with the SDK to mock out the EventStream Writer.""", writerInterfaceName, eventStreamTarget.getId().getName(serviceShape))) .writeDocs("") .writeDocs("Must not be nil.") .write("Writer $L", writerInterfaceName).write(""); }); outputInfo.ifPresent(eventStreamInfo -> { var eventStreamTarget = eventStreamInfo.getEventStreamTarget(); var readerInterfaceName = getEventStreamReaderInterfaceName(serviceShape, eventStreamTarget); writer.writeDocs(String.format(""" %s is the EventStream reader for the %s events. This value is automatically set by the SDK when the API call is made Use this member when unit testing your code with the SDK to mock out the EventStream Reader.""", readerInterfaceName, eventStreamTarget.getId().getName(serviceShape))) .writeDocs("") .writeDocs("Must not be nil.") .write("Reader $L", readerInterfaceName).write(""); }); writer.write("done chan struct{}") .write("closeOnce $T", SymbolUtils.createValueSymbolBuilder("Once", SmithyGoDependency.SYNC) .build()) .write("err $P", SymbolUtils.createPointableSymbolBuilder("OnceErr", SmithyGoDependency.SMITHY_SYNC).build()); }).write(""); writer.write(""" // $T initializes an $T. // This function should only be used for testing and mocking the $T // stream within your application.""", constructor, opEventStreamStructure, opEventStreamStructure); if (inputInfo.isPresent()) { writer.writeDocs(""); writer.writeDocs("The Writer member must be set before writing events to the stream."); } if (outputInfo.isPresent()) { writer.writeDocs(""); writer.writeDocs("The Reader member must be set before reading events from the stream."); } writer.openBlock("func $T(optFns ...func($P)) $P {", "}", constructor, opEventStreamStructure, opEventStreamStructure, () -> writer .openBlock("es := &$L{", "}", opEventStreamStructure, () -> writer .write("done: make(chan struct{}),") .write("err: $T(),", SymbolUtils.createValueSymbolBuilder("NewOnceErr", SmithyGoDependency.SMITHY_SYNC).build())) .openBlock("for _, fn := range optFns {", "}", () -> writer .write("fn(es)")) .write("return es")).write(""); if (inputInfo.isPresent()) { writer.write(""" // Send writes the event to the stream blocking until the event is written. // Returns an error if the event was not written. func (es $P) Send(ctx $P, event $P) error { return es.Writer.Send(ctx, event) } """, opEventStreamStructure, SymbolUtils.createValueSymbolBuilder("Context", SmithyGoDependency.CONTEXT).build(), symbolProvider.toSymbol(inputInfo.get().getEventStreamTarget())); } if (outputInfo.isPresent()) { writer.write(""" // Events returns a channel to read events from. func (es $P) Events() <-chan $P { return es.Reader.Events() } """, opEventStreamStructure, symbolProvider.toSymbol(outputInfo.get().getEventStreamTarget())); } writer.write(""" // Close closes the stream. This will also cause the stream to be closed. // Close must be called when done using the stream API. Not calling Close // may result in resource leaks. // // Will close the underlying EventStream writer and reader, and no more events can be // sent or received. func (es $P) Close() error { es.closeOnce.Do(es.safeClose) return es.Err() } """, opEventStreamStructure); writer.openBlock("func (es $P) safeClose() {", "}", opEventStreamStructure, () -> { writer.write(""" close(es.done) """); if (inputInfo.isPresent()) { var newTicker = SymbolUtils.createValueSymbolBuilder("NewTicker", SmithyGoDependency.TIME).build(); var second = SymbolUtils.createValueSymbolBuilder("Second", SmithyGoDependency.TIME).build(); writer.write(""" t := $T($T) defer t.Stop() writeCloseDone := make(chan error) go func() { if err := es.Writer.Close(); err != nil { es.err.SetError(err) } close(writeCloseDone) }() select { case <-t.C: case <-writeCloseDone: } """, newTicker, second); } if (outputInfo.isPresent()) { writer.write("es.Reader.Close()"); } }).write(""); writer.writeDocs(""" Err returns any error that occurred while reading or writing EventStream Events from the service API's response. Returns nil if there were no errors."""); writer.openBlock("func (es $P) Err() error {", "}", opEventStreamStructure, () -> { writer.write(""" if err := es.err.Err(); err != nil { return err } """); if (inputInfo.isPresent()) { writer.write(""" if err := es.Writer.Err(); err != nil { return err } """); } if (outputInfo.isPresent()) { writer.write(""" if err := es.Reader.Err(); err != nil { return err } """); } writer.write("return nil"); }).write(""); writer.openBlock("func (es $P) waitStreamClose() {", "}", opEventStreamStructure, () -> { writer.write(""" type errorSet interface { ErrorSet() <-chan struct{} } """); if (inputInfo.isPresent()) { writer.write(""" var inputErrCh <-chan struct{} if v, ok := es.Writer.(errorSet); ok { inputErrCh = v.ErrorSet() } """); } if (outputInfo.isPresent()) { writer.write(""" var outputErrCh <-chan struct{} if v, ok := es.Reader.(errorSet); ok { outputErrCh = v.ErrorSet() } var outputClosedCh <-chan struct{} if v, ok := es.Reader.(interface{ Closed() <-chan struct{} }); ok { outputClosedCh = v.Closed() } """); } writer.openBlock("select {", "}", () -> { writer.write("case <-es.done:"); if (inputInfo.isPresent()) { writer.write(""" case <-inputErrCh: es.err.SetError(es.Writer.Err()) es.Close() """); } if (outputInfo.isPresent()) { writer.write(""" case <-outputErrCh: es.err.SetError(es.Reader.Err()) es.Close() case <-outputClosedCh: if err := es.Reader.Err(); err != nil { es.err.SetError(es.Reader.Err()) } es.Close() """); } }); }).write(""); } public static Symbol getEventStreamOperationStructureConstructor( ServiceShape serviceShape, OperationShape operationShape ) { var symbol = getEventStreamOperationStructureSymbol(serviceShape, operationShape); return SymbolUtils.createValueSymbolBuilder("New" + symbol.getName()).build(); } public static Symbol getEventStreamOperationStructureSymbol( ServiceShape serviceShape, OperationShape operationShape ) { String name = StringUtils.capitalize(operationShape.getId().getName(serviceShape)); return SymbolUtils.createPointableSymbolBuilder(name + "EventStream") .build(); } public static String getEventStreamWriterInterfaceName(ServiceShape serviceShape, ToShapeId shape) { String name = StringUtils.capitalize(shape.toShapeId().getName(serviceShape)); return name + "Writer"; } public static String getEventStreamReaderInterfaceName(ServiceShape serviceShape, ToShapeId shape) { String name = StringUtils.capitalize(shape.toShapeId().getName(serviceShape)); return name + "Reader"; } }
8,961
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/GoStackStepMiddlewareGenerator.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen; import java.util.function.BiConsumer; import software.amazon.smithy.codegen.core.Symbol; /** * Helper for generating stack step middleware. */ public final class GoStackStepMiddlewareGenerator { private static final Symbol CONTEXT_TYPE = SymbolUtils.createValueSymbolBuilder( "Context", SmithyGoDependency.CONTEXT).build(); private static final Symbol METADATA_TYPE = SymbolUtils.createValueSymbolBuilder( "Metadata", SmithyGoDependency.SMITHY_MIDDLEWARE).build(); private final Symbol middlewareSymbol; private final MiddlewareIdentifier middlewareId; private final String handleMethodName; private final Symbol inputType; private final Symbol outputType; private final Symbol handlerType; /** * Creates a new middleware generator with the given builder definition. * * @param builder the builder to create the generator with. */ public GoStackStepMiddlewareGenerator(Builder builder) { this.middlewareSymbol = SymbolUtils.createPointableSymbolBuilder(builder.name).build(); this.middlewareId = builder.id; this.handleMethodName = builder.handleMethodName; this.inputType = builder.inputType; this.outputType = builder.outputType; this.handlerType = builder.handlerType; } /** * Create a new InitializeStep middleware generator with the provided type name. * * @param name is the type name to identify the middleware. * @param id the unique ID for the middleware. * @return the middleware generator. */ public static GoStackStepMiddlewareGenerator createInitializeStepMiddleware(String name, MiddlewareIdentifier id) { return createMiddleware(name, id, "HandleInitialize", SymbolUtils.createValueSymbolBuilder("InitializeInput", SmithyGoDependency.SMITHY_MIDDLEWARE).build(), SymbolUtils.createValueSymbolBuilder("InitializeOutput", SmithyGoDependency.SMITHY_MIDDLEWARE).build(), SymbolUtils.createValueSymbolBuilder("InitializeHandler", SmithyGoDependency.SMITHY_MIDDLEWARE) .build()); } /** * Create a new BuildStep middleware generator with the provided type name. * * @param name is the type name to identify the middleware. * @param id the unique ID for the middleware. * @return the middleware generator. */ public static GoStackStepMiddlewareGenerator createBuildStepMiddleware(String name, MiddlewareIdentifier id) { return createMiddleware(name, id, "HandleBuild", SymbolUtils.createValueSymbolBuilder("BuildInput", SmithyGoDependency.SMITHY_MIDDLEWARE).build(), SymbolUtils.createValueSymbolBuilder("BuildOutput", SmithyGoDependency.SMITHY_MIDDLEWARE).build(), SymbolUtils.createValueSymbolBuilder("BuildHandler", SmithyGoDependency.SMITHY_MIDDLEWARE).build()); } /** * Create a new SerializeStep middleware generator with the provided type name. * * @param name is the type name to identify the middleware. * @param id the unique ID for the middleware. * @return the middleware generator. */ public static GoStackStepMiddlewareGenerator createSerializeStepMiddleware(String name, MiddlewareIdentifier id) { return createMiddleware(name, id, "HandleSerialize", SymbolUtils.createValueSymbolBuilder("SerializeInput", SmithyGoDependency.SMITHY_MIDDLEWARE).build(), SymbolUtils.createValueSymbolBuilder("SerializeOutput", SmithyGoDependency.SMITHY_MIDDLEWARE).build(), SymbolUtils.createValueSymbolBuilder("SerializeHandler", SmithyGoDependency.SMITHY_MIDDLEWARE).build()); } /** * Create a new DeserializeStep middleware generator with the provided type name. * * @param name is the type name to identify the middleware. * @param id the unique ID for the middleware. * @return the middleware generator. */ public static GoStackStepMiddlewareGenerator createDeserializeStepMiddleware(String name, MiddlewareIdentifier id) { return createMiddleware(name, id, "HandleDeserialize", SymbolUtils.createValueSymbolBuilder("DeserializeInput", SmithyGoDependency.SMITHY_MIDDLEWARE).build(), SymbolUtils.createValueSymbolBuilder("DeserializeOutput", SmithyGoDependency.SMITHY_MIDDLEWARE).build(), SymbolUtils.createValueSymbolBuilder("DeserializeHandler", SmithyGoDependency.SMITHY_MIDDLEWARE) .build()); } /** * Generates a new step middleware generator. * * @param name the name of the middleware type. * @param id the unique ID for the middleware. * @param handlerMethodName method name to be implemented. * @param inputType the middleware input type. * @param outputType the middleware output type. * @param handlerType the next handler type. * @return the middleware generator. */ public static GoStackStepMiddlewareGenerator createMiddleware( String name, MiddlewareIdentifier id, String handlerMethodName, Symbol inputType, Symbol outputType, Symbol handlerType ) { return builder() .name(name) .id(id) .handleMethodName(handlerMethodName) .inputType(inputType) .outputType(outputType) .handlerType(handlerType) .build(); } /** * Writes the middleware definition to the provided writer. * See the writeMiddleware overloaded function signature for a more complete definition. * * @param writer the writer to which the middleware definition will be written to. * @param handlerBodyConsumer is a consumer that will be call in the context of populating the handler definition. */ public void writeMiddleware( GoWriter writer, BiConsumer<GoStackStepMiddlewareGenerator, GoWriter> handlerBodyConsumer ) { writeMiddleware(writer, handlerBodyConsumer, (m, w) -> { }); } /** * Writes the middleware definition to the provided writer. * <p> * The following Go variables will be in scope of the handler body: * ctx - the Go standard library context.Context type. * in - the input for the given middleware type. * next - the next handler to be called. * out - the output for the given middleware type. * metadata - the smithy middleware.Metadata type. * err - the error interface type. * * @param writer the writer to which the middleware definition will be written to. * @param handlerBodyConsumer is a consumer that will be called in the context of populating the handler definition. * @param fieldConsumer is a consumer that will be called in the context of populating the struct members. */ public void writeMiddleware( GoWriter writer, BiConsumer<GoStackStepMiddlewareGenerator, GoWriter> handlerBodyConsumer, BiConsumer<GoStackStepMiddlewareGenerator, GoWriter> fieldConsumer ) { writer.addUseImports(CONTEXT_TYPE); writer.addUseImports(METADATA_TYPE); writer.addUseImports(inputType); writer.addUseImports(outputType); writer.addUseImports(handlerType); // generate the structure type definition for the middleware writer.openBlock("type $L struct {", "}", middlewareSymbol, () -> { fieldConsumer.accept(this, writer); }); writer.write(""); // each middleware step has to implement the ID function and return a unique string to identify itself with // here we return the name of the type writer.openBlock("func ($P) ID() string {", "}", middlewareSymbol, () -> { writer.writeInline("return "); middlewareId.writeInline(writer); writer.write(""); }); writer.write(""); // each middleware must implement their given handlerMethodName in order to satisfy the interface for // their respective step. writer.openBlock("func (m $P) $L(ctx $T, in $T, next $T) (\n" + "\tout $T, metadata $T, err error,\n" + ") {", "}", new Object[]{ middlewareSymbol, handleMethodName, CONTEXT_TYPE, inputType, handlerType, outputType, METADATA_TYPE, }, () -> { handlerBodyConsumer.accept(this, writer); }); } /** * Returns a new middleware generator builder. * * @return the middleware generator builder. */ public static Builder builder() { return new Builder(); } /** * Get the handle method name. * * @return handler method name. */ public String getHandleMethodName() { return handleMethodName; } /** * Get the middleware type symbol. * * @return Symbol for the middleware type. */ public Symbol getMiddlewareSymbol() { return middlewareSymbol; } /** * Get the id of the middleware. * * @return id for the middleware. */ public MiddlewareIdentifier getMiddlewareId() { return middlewareId; } /** * Get the input type symbol reference. * * @return the input type symbol reference. */ public Symbol getInputType() { return inputType; } /** * Get the output type symbol reference. * * @return the output type symbol reference. */ public Symbol getOutputType() { return outputType; } /** * Get the handler type symbol reference. * * @return the handler type symbol reference. */ public Symbol getHandlerType() { return handlerType; } /** * Get the context type symbol. * * @return the context type symbol. */ public static Symbol getContextType() { return CONTEXT_TYPE; } /** * Get the middleware metadata type symbol. * * @return the middleware metadata type symbol. */ public static Symbol getMiddlewareMetadataType() { return METADATA_TYPE; } /** * Builds a {@link GoStackStepMiddlewareGenerator}. */ public static class Builder { private String name; private MiddlewareIdentifier id; private String handleMethodName; private Symbol inputType; private Symbol outputType; private Symbol handlerType; /** * Builds the middleware generator. * * @return the middleware generator. */ public GoStackStepMiddlewareGenerator build() { return new GoStackStepMiddlewareGenerator(this); } /** * Sets the handler method name. * * @param handleMethodName the middleware handler method name to implement. * @return the builder. */ public Builder handleMethodName(String handleMethodName) { this.handleMethodName = handleMethodName; return this; } /** * Set the name of the middleware type to be generated. * * @param name the name of the middleware type. * @return the builder. */ public Builder name(String name) { this.name = name; return this; } /** * Set the id for the middleware to be generated. * * @param id the middleware stack identifier. * @return the builder. */ public Builder id(MiddlewareIdentifier id) { this.id = id; return this; } /** * Set the input type symbol reference for the middleware. * * @param inputType the symbol reference to the input type. * @return the builder. */ public Builder inputType(Symbol inputType) { this.inputType = inputType; return this; } /** * Set the output type symbol reference for the middleware. * * @param outputType the symbol reference to the output type. * @return the builder. */ public Builder outputType(Symbol outputType) { this.outputType = outputType; return this; } /** * Set the handler type symbol reference for the middleware. * * @param handlerType the symbol reference to the handler type. * @return the builder. */ public Builder handlerType(Symbol handlerType) { this.handlerType = handlerType; return this; } } }
8,962
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/OperationGenerator.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.stream.Stream; import software.amazon.smithy.codegen.core.CodegenException; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.codegen.core.SymbolProvider; import software.amazon.smithy.go.codegen.integration.MiddlewareRegistrar; import software.amazon.smithy.go.codegen.integration.ProtocolGenerator; import software.amazon.smithy.go.codegen.integration.RuntimeClientPlugin; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.knowledge.OperationIndex; import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.traits.DeprecatedTrait; import software.amazon.smithy.model.traits.StreamingTrait; /** * Generates a client operation and associated custom shapes. */ public final class OperationGenerator implements Runnable { private final GoSettings settings; private final Model model; private final SymbolProvider symbolProvider; private final GoWriter writer; private final ServiceShape service; private final OperationShape operation; private final Symbol operationSymbol; private final ApplicationProtocol applicationProtocol; private final ProtocolGenerator protocolGenerator; private final List<RuntimeClientPlugin> runtimeClientPlugins; OperationGenerator( GoSettings settings, Model model, SymbolProvider symbolProvider, GoWriter writer, ServiceShape service, OperationShape operation, Symbol operationSymbol, ApplicationProtocol applicationProtocol, ProtocolGenerator protocolGenerator, List<RuntimeClientPlugin> runtimeClientPlugins ) { this.settings = settings; this.model = model; this.symbolProvider = symbolProvider; this.writer = writer; this.service = service; this.operation = operation; this.operationSymbol = operationSymbol; this.applicationProtocol = applicationProtocol; this.protocolGenerator = protocolGenerator; this.runtimeClientPlugins = runtimeClientPlugins; } @Override public void run() { OperationIndex operationIndex = OperationIndex.of(model); Symbol serviceSymbol = symbolProvider.toSymbol(service); if (!operationIndex.getInput(operation).isPresent()) { // Theoretically this shouldn't ever get hit since we automatically insert synthetic inputs / outputs. throw new CodegenException( "Operations are required to have input shapes in order to allow for future evolution."); } StructureShape inputShape = operationIndex.getInput(operation).get(); Symbol inputSymbol = symbolProvider.toSymbol(inputShape); if (!operationIndex.getOutput(operation).isPresent()) { throw new CodegenException( "Operations are required to have output shapes in order to allow for future evolution."); } StructureShape outputShape = operationIndex.getOutput(operation).get(); Symbol outputSymbol = symbolProvider.toSymbol(outputShape); // Generate operation method final boolean hasDocs = writer.writeShapeDocs(operation); operation.getTrait(DeprecatedTrait.class) .ifPresent(trait -> { if (hasDocs) { writer.writeDocs(""); } final String defaultMessage = "This operation has been deprecated."; writer.writeDocs("Deprecated: " + trait.getMessage().map(s -> { if (s.length() == 0) { return defaultMessage; } return s; }).orElse(defaultMessage)); }); Symbol contextSymbol = SymbolUtils.createValueSymbolBuilder("Context", SmithyGoDependency.CONTEXT).build(); writer.openBlock("func (c $P) $T(ctx $T, params $P, optFns ...func(*Options)) ($P, error) {", "}", serviceSymbol, operationSymbol, contextSymbol, inputSymbol, outputSymbol, () -> { writer.write("if params == nil { params = &$T{} }", inputSymbol); writer.write(""); writer.write("result, metadata, err := c.invokeOperation(ctx, $S, params, optFns, c.$L)", operationSymbol.getName(), getAddOperationMiddlewareFuncName(operationSymbol)); writer.write("if err != nil { return nil, err }"); writer.write(""); writer.write("out := result.($P)", outputSymbol); writer.write("out.ResultMetadata = metadata"); writer.write("return out, nil"); }).write(""); // Write out the input and output structures. These are written out here to prevent naming conflicts with other // shapes in the model. new StructureGenerator(model, symbolProvider, writer, service, inputShape, inputSymbol, protocolGenerator) .renderStructure(() -> { }, true); // The output structure gets a metadata member added. Symbol metadataSymbol = SymbolUtils.createValueSymbolBuilder("Metadata", SmithyGoDependency.SMITHY_MIDDLEWARE) .build(); boolean hasEventStream = Stream.concat(inputShape.members().stream(), outputShape.members().stream()) .anyMatch(memberShape -> StreamingTrait.isEventStream(model, memberShape)); new StructureGenerator(model, symbolProvider, writer, service, outputShape, outputSymbol, protocolGenerator) .renderStructure(() -> { if (outputShape.getMemberNames().size() != 0) { writer.write(""); } if (hasEventStream) { writer.write("eventStream $P", EventStreamGenerator.getEventStreamOperationStructureSymbol(service, operation)) .write(""); } writer.writeDocs("Metadata pertaining to the operation's result."); writer.write("ResultMetadata $T", metadataSymbol); }); if (hasEventStream) { writer.write(""" // GetStream returns the type to interact with the event stream. func (o $P) GetStream() $P { return o.eventStream } """, outputSymbol, EventStreamGenerator.getEventStreamOperationStructureSymbol( service, operation)); } // Generate operation protocol middleware helper function generateAddOperationMiddleware(); } /** * Adds middleware to the operation middleware stack. */ private void generateAddOperationMiddleware() { Symbol stackSymbol = SymbolUtils.createPointableSymbolBuilder("Stack", SmithyGoDependency.SMITHY_MIDDLEWARE) .build(); writer.openBlock("func (c *Client) $L(stack $P, options Options) (err error) {", "}", getAddOperationMiddlewareFuncName(operationSymbol), stackSymbol, () -> { generateOperationProtocolMiddlewareAdders(); // Populate middleware's from runtime client plugins runtimeClientPlugins.forEach(runtimeClientPlugin -> { if (!runtimeClientPlugin.matchesService(model, service) && !runtimeClientPlugin.matchesOperation(model, service, operation)) { return; } if (!runtimeClientPlugin.registerMiddleware().isPresent()) { return; } MiddlewareRegistrar middlewareRegistrar = runtimeClientPlugin.registerMiddleware().get(); Collection<Symbol> functionArguments = middlewareRegistrar.getFunctionArguments(); // TODO these functions do not all return err like they should. This should be fixed. // TODO Must be fixed for all public functions. if (middlewareRegistrar.getInlineRegisterMiddlewareStatement() != null) { String registerStatement = String.format("if err = stack.%s", middlewareRegistrar.getInlineRegisterMiddlewareStatement()); writer.writeInline(registerStatement); writer.writeInline("$T(", middlewareRegistrar.getResolvedFunction()); if (functionArguments != null) { List<Symbol> args = new ArrayList<>(functionArguments); for (Symbol arg : args) { writer.writeInline("$P, ", arg); } } writer.writeInline(")"); writer.write(", $T); err != nil {\nreturn err\n}", middlewareRegistrar.getInlineRegisterMiddlewarePosition()); } else { writer.writeInline("if err = $T(stack", middlewareRegistrar.getResolvedFunction()); if (functionArguments != null) { List<Symbol> args = new ArrayList<>(functionArguments); for (Symbol arg : args) { writer.writeInline(", $P", arg); } } writer.write("); err != nil {\nreturn err\n}"); } }); writer.write("return nil"); }); } /** * Generate operation protocol middleware helper. */ private void generateOperationProtocolMiddlewareAdders() { if (protocolGenerator == null) { return; } writer.addUseImports(SmithyGoDependency.SMITHY_MIDDLEWARE); // Add request serializer middleware String serializerMiddlewareName = ProtocolGenerator.getSerializeMiddlewareName( operation.getId(), service, protocolGenerator.getProtocolName()); writer.write("err = stack.Serialize.Add(&$L{}, middleware.After)", serializerMiddlewareName); writer.write("if err != nil { return err }"); // Adds response deserializer middleware String deserializerMiddlewareName = ProtocolGenerator.getDeserializeMiddlewareName( operation.getId(), service, protocolGenerator.getProtocolName()); writer.write("err = stack.Deserialize.Add(&$L{}, middleware.After)", deserializerMiddlewareName); writer.write("if err != nil { return err }"); } /** * Returns the name of the operation's middleware mutator function, that adds all middleware for the operation to * the stack. * * @param operation symbol for operation * @return name of function */ public static String getAddOperationMiddlewareFuncName(Symbol operation) { return String.format("addOperation%sMiddlewares", operation.getName()); } }
8,963
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/CodegenUtils.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.nio.file.Path; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.function.Predicate; import java.util.logging.Logger; import software.amazon.smithy.codegen.core.CodegenException; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.codegen.core.SymbolProvider; import software.amazon.smithy.go.codegen.knowledge.GoPointableIndex; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.CollectionShape; import software.amazon.smithy.model.shapes.MapShape; import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeType; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.traits.RequiredTrait; import software.amazon.smithy.model.traits.TitleTrait; import software.amazon.smithy.utils.StringUtils; /** * Utility methods likely to be needed across packages. */ public final class CodegenUtils { private static final Logger LOGGER = Logger.getLogger(CodegenUtils.class.getName()); private static final String SYNTHETIC_NAMESPACE = "smithy.go.synthetic"; private CodegenUtils() { } /** * Executes a given shell command in a given directory. * * @param command The string command to execute, e.g. "go fmt". * @param directory The directory to run the command in. * @return Returns the console output of the command. */ public static String runCommand(String command, Path directory) { String[] finalizedCommand; if (System.getProperty("os.name").toLowerCase().startsWith("windows")) { finalizedCommand = new String[]{"cmd.exe", "/c", command}; } else { finalizedCommand = new String[]{"sh", "-c", command}; } ProcessBuilder processBuilder = new ProcessBuilder(finalizedCommand) .redirectErrorStream(true) .directory(directory.toFile()); try { Process process = processBuilder.start(); List<String> output = new ArrayList<>(); // Capture output for reporting. try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader( process.getInputStream(), Charset.defaultCharset()))) { String line; while ((line = bufferedReader.readLine()) != null) { LOGGER.finest(line); output.add(line); } } process.waitFor(); process.destroy(); String joinedOutput = String.join(System.lineSeparator(), output); if (process.exitValue() != 0) { throw new CodegenException(String.format( "Command `%s` failed with output:%n%n%s", command, joinedOutput)); } return joinedOutput; } catch (InterruptedException | IOException e) { throw new CodegenException(e); } } /** * Gets the name under which the given package will be exported by default. * * @param packageName The full package name of the exported package. * @return The name a the package will be imported under by default. */ public static String getDefaultPackageImportName(String packageName) { if (StringUtils.isBlank(packageName) || !packageName.contains("/")) { return packageName; } return packageName.substring(packageName.lastIndexOf('/') + 1); } /** * Gets the alias to use when referencing the given symbol outside of its namespace. * * <p>The default value is the last path component of the symbol's namespace. * * @param symbol The symbol whose whose namespace alias should be retrieved. * @return The alias of the symbol's namespace. */ public static String getSymbolNamespaceAlias(Symbol symbol) { return symbol.getProperty(SymbolUtils.NAMESPACE_ALIAS, String.class) .filter(StringUtils::isNotBlank) .orElse(CodegenUtils.getDefaultPackageImportName(symbol.getNamespace())); } /** * Detects if an annotated mediatype indicates JSON contents. * * @param mediaType The media type to inspect. * @return If the media type indicates JSON contents. */ public static boolean isJsonMediaType(String mediaType) { return mediaType.equals("application/json") || mediaType.endsWith("+json"); } /** * Get the namespace where synthetic types are generated at runtime. * * @return synthetic type namespace */ public static String getSyntheticTypeNamespace() { return CodegenUtils.SYNTHETIC_NAMESPACE; } /** * Get if the passed in shape is decorated as a synthetic clone, but there is no other shape the clone is * created from. * * @param shape the shape to check if its a stubbed synthetic clone without an archetype. * @return if the shape is synthetic clone, but not based on a specific shape. */ public static boolean isStubSynthetic(Shape shape) { Optional<Synthetic> optional = shape.getTrait(Synthetic.class); if (!optional.isPresent()) { return false; } Synthetic synth = optional.get(); return !synth.getArchetype().isPresent(); } /** * Returns the operand decorated with an &amp; if the address of the shape type can be taken. * * @param model API model reference * @param pointableIndex pointable index * @param shape shape to use * @param operand value to decorate * @return updated operand */ public static String asAddressIfAddressable( Model model, GoPointableIndex pointableIndex, Shape shape, String operand ) { boolean isStruct = shape.getType() == ShapeType.STRUCTURE; if (shape.isMemberShape()) { isStruct = model.expectShape(shape.asMemberShape().get().getTarget()).getType() == ShapeType.STRUCTURE; } boolean shouldAddress = pointableIndex.isPointable(shape) && isStruct; return shouldAddress ? "&" + operand : operand; } /** * Returns the operand decorated with an "*" if the shape is dereferencable. * * @param pointableIndex knowledge index for if shape is pointable. * @param shape The shape whose value needs to be read. * @param operand The value to be read from. * @return updated operand */ public static String getAsValueIfDereferencable( GoPointableIndex pointableIndex, Shape shape, String operand ) { if (!pointableIndex.isDereferencable(shape)) { return operand; } return '*' + operand; } /** * Returns the operand decorated as a pointer type, without creating double pointer. * * @param pointableIndex knowledge index for if shape is pointable. * @param shape The shape whose value of the type. * @param operand The value to read. * @return updated operand */ public static String getTypeAsTypePointer( GoPointableIndex pointableIndex, Shape shape, String operand ) { if (pointableIndex.isPointable(shape)) { return operand; } return '*' + operand; } /** * Get the pointer reference to operand , if symbol is pointable. * This method can be used by deserializers to get pointer to * operand. * * @param model model for api. * @param writer The writer dependencies will be added to, if needed. * @param pointableIndex knowledge index for if shape is pointable. * @param shape The shape whose value needs to be assigned. * @param operand The Operand is the value to be assigned to the symbol shape. * @return The Operand, along with pointer reference if applicable */ public static String getAsPointerIfPointable( Model model, GoWriter writer, GoPointableIndex pointableIndex, Shape shape, String operand ) { if (!pointableIndex.isPointable(shape)) { return operand; } if (shape.isMemberShape()) { shape = model.expectShape(shape.asMemberShape().get().getTarget()); } String prefix = ""; String suffix = ")"; switch (shape.getType()) { case STRING: prefix = "ptr.String("; break; case BOOLEAN: prefix = "ptr.Bool("; break; case BYTE: prefix = "ptr.Int8("; break; case SHORT: prefix = "ptr.Int16("; break; case INTEGER: prefix = "ptr.Int32("; break; case LONG: prefix = "ptr.Int64("; break; case FLOAT: prefix = "ptr.Float32("; break; case DOUBLE: prefix = "ptr.Float64("; break; case TIMESTAMP: prefix = "ptr.Time("; break; default: return '&' + operand; } writer.addUseImports(SmithyGoDependency.SMITHY_PTR); return prefix + operand + suffix; } /** * Returns the shape unpacked as a CollectionShape. Throws and exception if the passed in * shape is not a list or set. * * @param shape the list or set shape. * @return The unpacked CollectionShape. */ public static CollectionShape expectCollectionShape(Shape shape) { if (shape instanceof CollectionShape) { return (CollectionShape) (shape); } throw new CodegenException("expect shape " + shape.getId() + " to be Collection, was " + shape.getType()); } /** * Returns the shape unpacked as a MapShape. Throws and exception if the passed in * shape is not a map. * * @param shape the map shape. * @return The unpacked MapShape. */ public static MapShape expectMapShape(Shape shape) { if (shape instanceof MapShape) { return (MapShape) (shape); } throw new CodegenException("expect shape " + shape.getId() + " to be Map, was " + shape.getType()); } /** * Comparator to sort ShapeMember lists alphabetically, with required members first followed by optional members. */ public static final class SortedMembers implements Comparator<MemberShape> { private final SymbolProvider symbolProvider; /** * Initializes the SortedMembers. * * @param symbolProvider symbol provider used for codegen. */ public SortedMembers(SymbolProvider symbolProvider) { this.symbolProvider = symbolProvider; } @Override public int compare(MemberShape a, MemberShape b) { // first compare if the members are required or not, which ever member is required should win. If both // members are required or not required, continue on to alphabetic search. // If a is required but b isn't return -1 so a is sorted before b // If b is required but a isn't, return 1 so a is sorted after b // If both a and b are required or optional, use alphabetic sorting of a and b's member name. int requiredMember = 0; if (a.hasTrait(RequiredTrait.class)) { requiredMember -= 1; } if (b.hasTrait(RequiredTrait.class)) { requiredMember += 1; } if (requiredMember != 0) { return requiredMember; } return symbolProvider.toMemberName(a) .compareTo(symbolProvider.toMemberName(b)); } } /** * Attempts to find the first member by exact name in the containing structure. If the member is not found an * exception will be thrown. * * @param shape structure containing member * @param name member name * @return MemberShape if found */ public static MemberShape expectMember(StructureShape shape, String name) { return expectMember(shape, name::equals); } /** * Attempts to find the first member by name using a member name predicate in the containing structure. If the * member is not found an exception will be thrown. * * @param shape structure containing member * @param memberNamePredicate member name to search for * @return MemberShape if found */ public static MemberShape expectMember(StructureShape shape, Predicate<String> memberNamePredicate) { return shape.getAllMembers().values().stream() .filter((p) -> memberNamePredicate.test(p.getMemberName())) .findFirst() .orElseThrow(() -> new CodegenException("did not find member in structure shape, " + shape.getId())); } /** * Attempts to get the title of the API's service from the model. If unalbe to get the title the fallback value * will be returned instead. * * @param shape service shape * @param fallback string to return if service does not have a title * @return title of service */ public static String getServiceTitle(ServiceShape shape, String fallback) { return shape.getTrait(TitleTrait.class).map(TitleTrait::getValue).orElse(fallback); } /** * isNumber returns if the shape is a number shape. * * @param shape shape to check * @return true if is a number shape. */ public static boolean isNumber(Shape shape) { switch (shape.getType()) { case BYTE: case SHORT: case INTEGER: case INT_ENUM: case LONG: case FLOAT: case DOUBLE: return true; default: return false; } } }
8,964
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/ApplicationProtocol.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen; import java.util.Objects; import software.amazon.smithy.codegen.core.Symbol; /** * Represents the resolves {@link Symbol}s and references for an * application protocol (e.g., "http", "mqtt", etc). */ public final class ApplicationProtocol { private final String name; private final Symbol requestType; private final Symbol responseType; /** * Creates a resolved application protocol. * * @param name The protocol name (e.g., http, mqtt, etc). * @param requestType The type used to represent request messages for the protocol. * @param responseType The type used to represent response messages for the protocol. */ public ApplicationProtocol( String name, Symbol requestType, Symbol responseType ) { this.name = name; this.requestType = requestType; this.responseType = responseType; } /** * Creates a default HTTP application protocol. * * @return Returns the created application protocol. */ public static ApplicationProtocol createDefaultHttpApplicationProtocol() { return new ApplicationProtocol( "http", createHttpSymbol("Request"), createHttpSymbol("Response") ); } private static Symbol createHttpSymbol(String symbolName) { return SymbolUtils.createPointableSymbolBuilder(symbolName, SmithyGoDependency.SMITHY_HTTP_TRANSPORT) .build(); } /** * Gets the protocol name. * * <p>All HTTP protocols should start with "http". * All MQTT protocols should start with "mqtt". * * @return Returns the protocol name. */ public String getName() { return name; } /** * Checks if the protocol is an HTTP based protocol. * * @return Returns true if it is HTTP based. */ public boolean isHttpProtocol() { return getName().startsWith("http"); } /** * Gets the symbol used to refer to the request type for this protocol. * * @return Returns the protocol request type. */ public Symbol getRequestType() { return requestType; } /** * Gets the symbol used to refer to the response type for this protocol. * * @return Returns the protocol response type. */ public Symbol getResponseType() { return responseType; } @Override public boolean equals(Object o) { if (this == o) { return true; } else if (!(o instanceof ApplicationProtocol)) { return false; } ApplicationProtocol that = (ApplicationProtocol) o; return requestType.equals(that.requestType) && responseType.equals(that.responseType); } @Override public int hashCode() { return Objects.hash(requestType, responseType); } }
8,965
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/GoWriter.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.StringJoiner; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.logging.Logger; import java.util.regex.Pattern; import software.amazon.smithy.codegen.core.CodegenException; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.codegen.core.SymbolContainer; import software.amazon.smithy.codegen.core.SymbolDependency; import software.amazon.smithy.codegen.core.SymbolDependencyContainer; import software.amazon.smithy.codegen.core.SymbolReference; import software.amazon.smithy.go.codegen.knowledge.GoUsageIndex; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.loader.Prelude; import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.traits.DeprecatedTrait; import software.amazon.smithy.model.traits.DocumentationTrait; import software.amazon.smithy.model.traits.HttpPrefixHeadersTrait; import software.amazon.smithy.model.traits.MediaTypeTrait; import software.amazon.smithy.model.traits.RequiredTrait; import software.amazon.smithy.model.traits.StringTrait; import software.amazon.smithy.utils.AbstractCodeWriter; import software.amazon.smithy.utils.StringUtils; /** * Specialized code writer for managing Go dependencies. * * <p>Use the {@code $T} formatter to refer to {@link Symbol}s without using pointers. * * <p>Use the {@code $P} formatter to refer to {@link Symbol}s using pointers where appropriate. */ public final class GoWriter extends AbstractCodeWriter<GoWriter> { private static final Logger LOGGER = Logger.getLogger(GoWriter.class.getName()); private static final int DEFAULT_DOC_WRAP_LENGTH = 80; private static final Pattern ARGUMENT_NAME_PATTERN = Pattern.compile("\\$([a-z][a-zA-Z_0-9]+)(:\\w)?"); private final String fullPackageName; private final ImportDeclarations imports = new ImportDeclarations(); private final List<SymbolDependency> dependencies = new ArrayList<>(); private final boolean innerWriter; private int docWrapLength = DEFAULT_DOC_WRAP_LENGTH; private AbstractCodeWriter<GoWriter> packageDocs; /** * Initializes the GoWriter for the package and filename to be written to. * * @param fullPackageName package and filename to be written to. */ public GoWriter(String fullPackageName) { this.fullPackageName = fullPackageName; this.innerWriter = false; init(); } private GoWriter(String fullPackageName, boolean innerWriter) { this.fullPackageName = fullPackageName; this.innerWriter = innerWriter; init(); } private void init() { trimBlankLines(); trimTrailingSpaces(); setIndentText("\t"); putFormatter('T', new GoSymbolFormatter()); putFormatter('P', new PointableGoSymbolFormatter()); putFormatter('W', new GoWritableInjector()); if (!innerWriter) { packageDocs = new GoWriter(this.fullPackageName, true); } } // TODO figure out better way to annotate where the failure occurs, check templates and args // TODO to try to find programming bugs. /** * Joins multiple writables together within a single writable without newlines between writables in the list. * * @param writables list of writables to join * @param separator separator between writables * @return new writable */ public static Writable joinWritables(List<Writable> writables, String separator) { return (GoWriter w) -> { for (int i = 0; i < writables.size(); i++) { var writable = writables.get(i); var sep = separator; if (i == writables.size() - 1) { sep = ""; } w.writeInline("$W" + sep, writable); } }; } /** * Returns a Writable for the string and args to be composed inline to another writer's contents. * * @param contents string to write. * @param args Arguments to use when evaluating the contents string. * @return Writable to be evaluated. */ @SafeVarargs public static Writable goTemplate(String contents, Map<String, Object>... args) { validateTemplateArgsNotNull(args); return (GoWriter w) -> { w.writeGoTemplate(contents, args); }; } public static Writable goDocTemplate(String contents) { return goDocTemplate(contents, new HashMap<>()); } @SafeVarargs public static Writable goDocTemplate(String contents, Map<String, Object>... args) { validateTemplateArgsNotNull(args); return (GoWriter w) -> { w.writeGoDocTemplate(contents, args); }; } /** * Returns a Writable that can later be invoked to write the contents as template * as a code block instead of single content of text. * * @param beforeNewLine text before new line * @param afterNewLine text after new line * @param fn closure to write */ public static Writable goBlockTemplate( String beforeNewLine, String afterNewLine, Consumer<GoWriter> fn ) { return goBlockTemplate(beforeNewLine, afterNewLine, new Map[0], fn); } /** * Returns a Writable that can later be invoked to write the contents as template * as a code block instead of single content of text. * * @param beforeNewLine text before new line * @param afterNewLine text after new line * @param args1 template arguments * @param fn closure to write */ public static Writable goBlockTemplate( String beforeNewLine, String afterNewLine, Map<String, Object> args1, Consumer<GoWriter> fn ) { return goBlockTemplate(beforeNewLine, afterNewLine, new Map[]{args1}, fn); } /** * Returns a Writable that can later be invoked to write the contents as template * as a code block instead of single content of text. * * @param beforeNewLine text before new line * @param afterNewLine text after new line * @param args1 template arguments * @param args2 template arguments * @param fn closure to write */ public static Writable goBlockTemplate( String beforeNewLine, String afterNewLine, Map<String, Object> args1, Map<String, Object> args2, Consumer<GoWriter> fn ) { return goBlockTemplate(beforeNewLine, afterNewLine, new Map[]{args1, args2}, fn); } /** * Returns a Writable that can later be invoked to write the contents as template * as a code block instead of single content of text. * * @param beforeNewLine text before new line * @param afterNewLine text after new line * @param args1 template arguments * @param args2 template arguments * @param args3 template arguments * @param fn closure to write */ public static Writable goBlockTemplate( String beforeNewLine, String afterNewLine, Map<String, Object> args1, Map<String, Object> args2, Map<String, Object> args3, Consumer<GoWriter> fn ) { return goBlockTemplate(beforeNewLine, afterNewLine, new Map[]{args1, args2, args3}, fn); } /** * Returns a Writable that can later be invoked to write the contents as template * as a code block instead of single content of text. * * @param beforeNewLine text before new line * @param afterNewLine text after new line * @param args1 template arguments * @param args2 template arguments * @param args3 template arguments * @param args4 template arguments * @param fn closure to write */ public static Writable goBlockTemplate( String beforeNewLine, String afterNewLine, Map<String, Object> args1, Map<String, Object> args2, Map<String, Object> args3, Map<String, Object> args4, Consumer<GoWriter> fn ) { return goBlockTemplate(beforeNewLine, afterNewLine, new Map[]{args1, args2, args3, args4}, fn); } /** * Returns a Writable that can later be invoked to write the contents as template * as a code block instead of single content of text. * * @param beforeNewLine text before new line * @param afterNewLine text after new line * @param args1 template arguments * @param args2 template arguments * @param args3 template arguments * @param args4 template arguments * @param args5 template arguments * @param fn closure to write */ public static Writable goBlockTemplate( String beforeNewLine, String afterNewLine, Map<String, Object> args1, Map<String, Object> args2, Map<String, Object> args3, Map<String, Object> args4, Map<String, Object> args5, Consumer<GoWriter> fn ) { return goBlockTemplate(beforeNewLine, afterNewLine, new Map[]{args1, args2, args3, args4, args5}, fn); } /** * Returns a Writable that can later be invoked to write the contents as template * as a code block instead of single content of text. * * @param beforeNewLine text before new line * @param afterNewLine text after new line * @param args template arguments * @param fn closure to write */ public static Writable goBlockTemplate( String beforeNewLine, String afterNewLine, Map<String, Object>[] args, Consumer<GoWriter> fn ) { validateTemplateArgsNotNull(args); return (GoWriter w) -> { w.writeGoBlockTemplate(beforeNewLine, afterNewLine, args, fn); }; } /** * Returns a Writable that does nothing. * * @return Writable that does nothing */ public static Writable emptyGoTemplate() { return (GoWriter w) -> { }; } /** * Writes the contents and arguments as a template to the writer. * * @param contents string to write * @param args Arguments to use when evaluating the contents string. */ @SafeVarargs public final void writeGoTemplate(String contents, Map<String, Object>... args) { withTemplate(contents, args, (template) -> { try { write(contents); } catch (Exception e) { throw new CodegenException("Failed to render template\n" + contents + "\nReason: " + e.getMessage(), e); } }); } @SafeVarargs public final void writeGoDocTemplate(String contents, Map<String, Object>... args) { writeRenderedDocs(goTemplate(contents, args)); } /** * Writes the contents as template as a code block instead of single content fo text. * * @param beforeNewLine text before new line * @param afterNewLine text after new line * @param fn closure to write */ public void writeGoBlockTemplate( String beforeNewLine, String afterNewLine, Consumer<GoWriter> fn ) { writeGoBlockTemplate(beforeNewLine, afterNewLine, new Map[0], fn); } /** * Writes the contents as template as a code block instead of single content fo text. * * @param beforeNewLine text before new line * @param afterNewLine text after new line * @param arg1 first map argument * @param fn closure to write */ public void writeGoBlockTemplate( String beforeNewLine, String afterNewLine, Map<String, Object> arg1, Consumer<GoWriter> fn ) { writeGoBlockTemplate(beforeNewLine, afterNewLine, new Map[]{arg1}, fn); } /** * Writes the contents as template as a code block instead of single content fo text. * * @param beforeNewLine text before new line * @param afterNewLine text after new line * @param arg1 first map argument * @param arg2 second map argument * @param fn closure to write */ public void writeGoBlockTemplate( String beforeNewLine, String afterNewLine, Map<String, Object> arg1, Map<String, Object> arg2, Consumer<GoWriter> fn ) { writeGoBlockTemplate(beforeNewLine, afterNewLine, new Map[]{arg1, arg2}, fn); } /** * Writes the contents as template as a code block instead of single content fo text. * * @param beforeNewLine text before new line * @param afterNewLine text after new line * @param arg1 first map argument * @param arg2 second map argument * @param arg3 third map argument * @param fn closure to write */ public void writeGoBlockTemplate( String beforeNewLine, String afterNewLine, Map<String, Object> arg1, Map<String, Object> arg2, Map<String, Object> arg3, Consumer<GoWriter> fn ) { writeGoBlockTemplate(beforeNewLine, afterNewLine, new Map[]{arg1, arg2, arg3}, fn); } /** * Writes the contents as template as a code block instead of single content fo text. * * @param beforeNewLine text before new line * @param afterNewLine text after new line * @param arg1 first map argument * @param arg2 second map argument * @param arg3 third map argument * @param arg4 forth map argument * @param fn closure to write */ public void writeGoBlockTemplate( String beforeNewLine, String afterNewLine, Map<String, Object> arg1, Map<String, Object> arg2, Map<String, Object> arg3, Map<String, Object> arg4, Consumer<GoWriter> fn ) { writeGoBlockTemplate(beforeNewLine, afterNewLine, new Map[]{arg1, arg2, arg3, arg4}, fn); } /** * Writes the contents as template as a code block instead of single content fo text. * * @param beforeNewLine text before new line * @param afterNewLine text after new line * @param arg1 first map argument * @param arg2 second map argument * @param arg3 third map argument * @param arg4 forth map argument * @param arg5 forth map argument * @param fn closure to write */ public void writeGoBlockTemplate( String beforeNewLine, String afterNewLine, Map<String, Object> arg1, Map<String, Object> arg2, Map<String, Object> arg3, Map<String, Object> arg4, Map<String, Object> arg5, Consumer<GoWriter> fn ) { writeGoBlockTemplate(beforeNewLine, afterNewLine, new Map[]{arg1, arg2, arg3, arg4, arg5}, fn); } public void writeGoBlockTemplate( String beforeNewLine, String afterNewLine, Map<String, Object>[] args, Consumer<GoWriter> fn ) { withTemplate(beforeNewLine, args, (header) -> { conditionalBlock(header, afterNewLine, true, new Object[0], fn); }); } private void withTemplate( String template, Map<String, Object>[] argMaps, Consumer<String> fn ) { pushState(); for (var args : argMaps) { putContext(args); } validateContext(template); fn.accept(template); popState(); } private GoWriter conditionalBlock( String beforeNewLine, String afterNewLine, boolean conditional, Object[] args, Consumer<GoWriter> fn ) { if (conditional) { openBlock(beforeNewLine.trim(), args); } fn.accept(this); if (conditional) { closeBlock(afterNewLine.trim()); } return this; } private static void validateTemplateArgsNotNull(Map<String, Object>[] argMaps) { for (var args : argMaps) { args.forEach((k, v) -> { if (v == null) { throw new CodegenException("Template argument " + k + " cannot be null"); } }); } } private void validateContext(String template) { var matcher = ARGUMENT_NAME_PATTERN.matcher(template); while (matcher.find()) { var keyName = matcher.group(1); var value = getContext(keyName); if (value == null) { throw new CodegenException( "Go template expected " + keyName + " but was not present in context scope." + " Template: \n" + template); } } } /** * Sets the wrap length of doc strings written. * * @param wrapLength The wrap length of the doc string. * @return Returns the writer. */ public GoWriter setDocWrapLength(final int wrapLength) { this.docWrapLength = wrapLength; return this; } /** * Sets the wrap length of doc strings written to the default value for the Go writer. * * @return Returns the writer. */ public GoWriter setDocWrapLength() { this.docWrapLength = DEFAULT_DOC_WRAP_LENGTH; return this; } /** * Imports one or more symbols if necessary, using the name of the * symbol and only "USE" references. * * @param container Container of symbols to add. * @return Returns the writer. */ public GoWriter addUseImports(SymbolContainer container) { for (Symbol symbol : container.getSymbols()) { addImport(symbol, CodegenUtils.getSymbolNamespaceAlias(symbol), SymbolReference.ContextOption.USE); } return this; } /** * Imports a symbol reference if necessary, using the alias of the * reference and only associated "USE" references. * * @param symbolReference Symbol reference to import. * @return Returns the writer. */ public GoWriter addUseImports(SymbolReference symbolReference) { return addImport(symbolReference.getSymbol(), symbolReference.getAlias(), SymbolReference.ContextOption.USE); } /** * Adds and imports the given dependency. * * @param goDependency The GoDependency to import. * @return Returns the writer. */ public GoWriter addUseImports(GoDependency goDependency) { dependencies.addAll(goDependency.getDependencies()); return addImport(goDependency.getImportPath(), goDependency.getAlias()); } /** * Imports a symbol if necessary using a package alias and list of context options. * * @param symbol Symbol to optionally import. * @param packageAlias The alias to refer to the symbol's package by. * @param options The list of context options (e.g., is it a USE or DECLARE symbol). * @return Returns the writer. */ public GoWriter addImport(Symbol symbol, String packageAlias, SymbolReference.ContextOption... options) { LOGGER.finest(() -> { StringJoiner stackTrace = new StringJoiner("\n"); for (StackTraceElement element : Thread.currentThread().getStackTrace()) { stackTrace.add(element.toString()); } return String.format( "Adding Go import %s as `%s` (%s); Stack trace: %s", symbol.getNamespace(), packageAlias, Arrays.toString(options), stackTrace); }); // Always add dependencies. dependencies.addAll(symbol.getDependencies()); if (isExternalNamespace(symbol.getNamespace())) { addImport(symbol.getNamespace(), packageAlias); } // Just because the direct symbol wasn't imported doesn't mean that the // symbols it needs to be declared don't need to be imported. addImportReferences(symbol, options); return this; } private GoWriter addImports(GoWriter other) { this.imports.addImports(other.imports); return this; } private boolean isExternalNamespace(String namespace) { return !StringUtils.isBlank(namespace) && !namespace.equals(fullPackageName); } void addImportReferences(Symbol symbol, SymbolReference.ContextOption... options) { for (SymbolReference reference : symbol.getReferences()) { for (SymbolReference.ContextOption option : options) { if (reference.hasOption(option)) { addImport(reference.getSymbol(), reference.getAlias(), options); break; } } } } /** * Imports a package using an alias if necessary. * * @param packageName Package to import. * @param as Alias to refer to the package as. * @return Returns the writer. */ public GoWriter addImport(String packageName, String as) { imports.addImport(packageName, as); return this; } /** * Adds one or more dependencies to the generated code. * * <p>The dependencies of all writers created by the {@link GoDelegator} * are merged together to eventually generate a go.mod file. * * @param dependencies Go dependency to add. * @return Returns the writer. */ public GoWriter addDependency(SymbolDependencyContainer dependencies) { this.dependencies.addAll(dependencies.getDependencies()); return this; } private GoWriter addDependencies(GoWriter other) { this.dependencies.addAll(other.getDependencies()); return this; } Collection<SymbolDependency> getDependencies() { return dependencies; } /** * Writes documentation comments. * * @param runnable Runnable that handles actually writing docs with the writer. * @return Returns the writer. */ private void writeDocs(AbstractCodeWriter<GoWriter> writer, Runnable runnable) { writer.pushState("docs"); writer.setNewlinePrefix("// "); runnable.run(); writer.setNewlinePrefix(""); writer.popState(); } private void writeDocs(AbstractCodeWriter<GoWriter> writer, int docWrapLength, String docs) { String convertedDoc = DocumentationConverter.convert(docs, docWrapLength); writeDocs(writer, () -> writer.write(convertedDoc.replace("$", "$$"))); } /** * Writes documentation comments from a string. * * <p>This function escapes "$" characters so formatters are not run. * * @param docs Documentation to write. * @return Returns the writer. */ public GoWriter writeDocs(String docs) { writeDocs(this, docWrapLength, docs); return this; } /** * Writes documentation from an arbitrary Writable. * * @param writable Contents to be written. * @return Returns the writer. */ public GoWriter writeRenderedDocs(Writable writable) { writeRenderedDocs(this, docWrapLength, writable); return this; } private void writeRenderedDocs(AbstractCodeWriter<GoWriter> writer, int docWrapLength, Writable writable) { var innerWriter = new GoWriter(fullPackageName, true); writable.accept(innerWriter); var wrappedDocs = StringUtils.wrap(innerWriter.toString().trim(), docWrapLength); writeDocs(writer, () -> writer.write(wrappedDocs.replace("$", "$$"))); } /** * Writes the doc to the Go package docs that are written prior to the go package statement. * * @param docs documentation to write to package doc. * @return writer */ public GoWriter writePackageDocs(String docs) { writeDocs(packageDocs, docWrapLength, docs); return this; } /** * Writes the doc to the Go package docs that are written prior to the go package statement. This does not perform * line wrapping and the provided formatting must be valid Go doc. * * @param docs documentation to write to package doc. * @return writer */ public GoWriter writeRawPackageDocs(String docs) { writeDocs(packageDocs, () -> { packageDocs.write(docs); }); return this; } /** * Writes shape documentation comments if docs are present. * * @param shape Shape to write the documentation of. * @return Returns true if docs were written. */ boolean writeShapeDocs(Shape shape) { return shape.getTrait(DocumentationTrait.class) .map(DocumentationTrait::getValue) .map(docs -> { writeDocs(docs); return true; }).orElse(false); } /** * Writes shape documentation comments to the writer's package doc if docs are present. * * @param shape Shape to write the documentation of. * @return Returns true if docs were written. */ boolean writePackageShapeDocs(Shape shape) { return shape.getTrait(DocumentationTrait.class) .map(DocumentationTrait::getValue) .map(docs -> { writePackageDocs(docs); return true; }).orElse(false); } /** * Writes member shape documentation comments if docs are present. * * @param model Model used to dereference targets. * @param member Shape to write the documentation of. * @return Returns true if docs were written. */ boolean writeMemberDocs(Model model, MemberShape member) { boolean hasDocs; hasDocs = member.getMemberTrait(model, DocumentationTrait.class) .map(DocumentationTrait::getValue) .map(docs -> { writeDocs(docs); return true; }).orElse(false); Optional<String> stringOptional = member.getMemberTrait(model, MediaTypeTrait.class) .map(StringTrait::getValue); if (stringOptional.isPresent()) { if (hasDocs) { writeDocs(""); } writeDocs("This value conforms to the media type: " + stringOptional.get()); hasDocs = true; } GoUsageIndex usageIndex = GoUsageIndex.of(model); if (usageIndex.isUsedForOutput(member)) { if (member.getMemberTrait(model, HttpPrefixHeadersTrait.class).isPresent()) { if (hasDocs) { writeDocs(""); } writeDocs("Map keys will be normalized to lower-case."); hasDocs = true; } } if (member.getMemberTrait(model, RequiredTrait.class).isPresent()) { if (hasDocs) { writeDocs(""); } writeDocs("This member is required."); hasDocs = true; } Optional<DeprecatedTrait> deprecatedTrait = member.getMemberTrait(model, DeprecatedTrait.class); if (member.getTrait(DeprecatedTrait.class).isPresent() || isTargetDeprecated(model, member)) { if (hasDocs) { writeDocs(""); } final String defaultMessage = "This member has been deprecated."; String message = defaultMessage; if (deprecatedTrait.isPresent()) { message = deprecatedTrait.get().getMessage().map(s -> { if (s.length() == 0) { return defaultMessage; } return s; }).orElse(defaultMessage); } writeDocs("Deprecated: " + message); } return hasDocs; } private boolean isTargetDeprecated(Model model, MemberShape member) { return model.expectShape(member.getTarget()).getTrait(DeprecatedTrait.class).isPresent() // don't consider deprecated prelude shapes (like PrimitiveBoolean) && !Prelude.isPreludeShape(member.getTarget()); } @Override public String toString() { String contents = super.toString(); if (innerWriter) { return contents; } String[] packageParts = fullPackageName.split("/"); String header = String.format("// Code generated by smithy-go-codegen DO NOT EDIT.%n%n"); String packageName = packageParts[packageParts.length - 1]; if (packageName.startsWith("v") && packageParts.length >= 2) { String remaining = packageName.substring(1); try { int value = Integer.parseInt(remaining); packageName = packageParts[packageParts.length - 2]; if (value == 0 || value == 1) { throw new CodegenException("module paths vN version component must only be N >= 2"); } } catch (NumberFormatException ne) { // Do nothing } } String packageDocs = this.packageDocs.toString(); String packageStatement = String.format("package %s%n%n", packageName); String importString = imports.toString(); String strippedContents = StringUtils.stripStart(contents, null); String strippedImportString = StringUtils.strip(importString, null); // Don't add an additional new line between explicit imports and managed imports. if (!strippedImportString.isEmpty() && strippedContents.startsWith("import ")) { return header + strippedImportString + "\n" + strippedContents; } return header + packageDocs + packageStatement + importString + contents; } /** * Implements Go symbol formatting for the {@code $T} formatter. */ private class GoSymbolFormatter implements BiFunction<Object, String, String> { @Override public String apply(Object type, String indent) { if (type instanceof Symbol) { Symbol resolvedSymbol = (Symbol) type; String literal = resolvedSymbol.getName(); boolean isSlice = resolvedSymbol.getProperty(SymbolUtils.GO_SLICE, Boolean.class).orElse(false); boolean isMap = resolvedSymbol.getProperty(SymbolUtils.GO_MAP, Boolean.class).orElse(false); if (isSlice || isMap) { resolvedSymbol = resolvedSymbol.getProperty(SymbolUtils.GO_ELEMENT_TYPE, Symbol.class) .orElseThrow(() -> new CodegenException("Expected go element type property to be defined")); literal = new PointableGoSymbolFormatter().apply(resolvedSymbol, "nested"); } else if (!SymbolUtils.isUniverseType(resolvedSymbol) && isExternalNamespace(resolvedSymbol.getNamespace())) { literal = formatWithNamespace(resolvedSymbol); } addUseImports(resolvedSymbol); if (isSlice) { return "[]" + literal; } else if (isMap) { return "map[string]" + literal; } else { return literal; } } else if (type instanceof SymbolReference) { SymbolReference typeSymbol = (SymbolReference) type; addImport(typeSymbol.getSymbol(), typeSymbol.getAlias(), SymbolReference.ContextOption.USE); return typeSymbol.getAlias(); } else { throw new CodegenException( "Invalid type provided to $T. Expected a Symbol, but found `" + type + "`"); } } private String formatWithNamespace(Symbol symbol) { if (StringUtils.isEmpty(symbol.getNamespace())) { return symbol.getName(); } return String.format("%s.%s", CodegenUtils.getSymbolNamespaceAlias(symbol), symbol.getName()); } } /** * Implements Go symbol formatting for the {@code $P} formatter. This is identical to the $T * formatter, except that it will add a * to symbols that can be pointers. */ private class PointableGoSymbolFormatter extends GoSymbolFormatter { @Override public String apply(Object type, String indent) { String formatted = super.apply(type, indent); if (isPointer(type)) { formatted = "*" + formatted; } return formatted; } private boolean isPointer(Object type) { if (type instanceof Symbol) { Symbol typeSymbol = (Symbol) type; return typeSymbol.getProperty(SymbolUtils.POINTABLE, Boolean.class).orElse(false); } else if (type instanceof SymbolReference) { SymbolReference typeSymbol = (SymbolReference) type; return typeSymbol.getProperty(SymbolUtils.POINTABLE, Boolean.class).orElse(false) || typeSymbol.getSymbol().getProperty(SymbolUtils.POINTABLE, Boolean.class).orElse(false); } else { throw new CodegenException( "Invalid type provided to $P. Expected a Symbol, but found `" + type + "`"); } } } class GoWritableInjector extends GoSymbolFormatter { @Override public String apply(Object type, String indent) { if (!(type instanceof Writable)) { throw new CodegenException( "expect Writable for GoWriter W injector, but got " + type); } var innerWriter = new GoWriter(fullPackageName, true); ((Writable) type).accept(innerWriter); addImports(innerWriter); addDependencies(innerWriter); return innerWriter.toString().trim(); } } public interface Writable extends Consumer<GoWriter> { } /** * Chains together multiple Writables that can be composed into one Writable. */ public static final class ChainWritable { private final List<GoWriter.Writable> writables; public ChainWritable() { writables = new ArrayList<>(); } public ChainWritable add(GoWriter.Writable writable) { writables.add(writable); return this; } public <T> ChainWritable add(Optional<T> value, Function<T, Writable> fn) { value.ifPresent(t -> writables.add(fn.apply(t))); return this; } public ChainWritable add(boolean include, GoWriter.Writable writable) { if (!include) { writables.add(writable); } return this; } public GoWriter.Writable compose() { return (GoWriter writer) -> { var hasPrevious = false; for (GoWriter.Writable writable : writables) { if (hasPrevious) { writer.write(""); } hasPrevious = true; writer.write("$W", writable); } }; } } }
8,966
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/GoModGenerator.java
/* * Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Map; import java.util.logging.Logger; import software.amazon.smithy.build.FileManifest; import software.amazon.smithy.codegen.core.CodegenException; /** * Generates a go.mod file for the project. * * <p>See here for more information on the format: https://github.com/golang/go/wiki/Modules#gomod */ final class GoModGenerator { private static final Logger LOGGER = Logger.getLogger(GoModGenerator.class.getName()); private GoModGenerator() {} static void writeGoMod( GoSettings settings, FileManifest manifest, GoModuleInfo goModuleInfo ) { Boolean generateGoMod = settings.getGenerateGoMod(); if (!generateGoMod) { return; } Path goModFile = manifest.getBaseDir().resolve("go.mod"); LOGGER.fine("Generating go.mod file at path " + goModFile.toString()); // `go mod init` will fail if the `go.mod` already exists, so this deletes // it if it's present in the output. While it's technically possible // to simply edit the file, it's easier to just start fresh. if (Files.exists(goModFile)) { try { Files.delete(goModFile); } catch (IOException e) { throw new CodegenException("Failed to delete existing go.mod file", e); } } manifest.addFile(goModFile); CodegenUtils.runCommand("go mod init " + settings.getModuleName(), manifest.getBaseDir()); for (Map.Entry<String, String> dependency : goModuleInfo.getMinimumNonStdLibDependencies().entrySet()) { CodegenUtils.runCommand( String.format("go mod edit -require=%s@%s", dependency.getKey(), dependency.getValue()), manifest.getBaseDir()); } CodegenUtils.runCommand( String.format("go mod edit -go=%s", goModuleInfo.getGoDirective()), manifest.getBaseDir()); } }
8,967
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/GoCodegenPlugin.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen; import java.util.logging.Logger; import software.amazon.smithy.build.PluginContext; import software.amazon.smithy.build.SmithyBuildPlugin; import software.amazon.smithy.codegen.core.SymbolProvider; import software.amazon.smithy.model.Model; /** * Plugin to trigger Go code generation. */ public final class GoCodegenPlugin implements SmithyBuildPlugin { private static final Logger LOGGER = Logger.getLogger(GoCodegenPlugin.class.getName()); @Override public String getName() { return "go-codegen"; } @Override public void execute(PluginContext context) { String onlyBuild = System.getenv("SMITHY_GO_BUILD_API"); if (onlyBuild != null && !onlyBuild.isEmpty()) { String targetServiceId = GoSettings.from(context.getSettings()).getService().toString(); boolean found = false; for (String includeServiceId : onlyBuild.split(",")) { if (targetServiceId.startsWith(includeServiceId)) { found = true; break; } } if (!found) { LOGGER.info("skipping " + targetServiceId); return; } } new CodegenVisitor(context).execute(); } /** * Creates a Go symbol provider. * * @param model The model to generate symbols for. * @param settings The Gosettings to use to create symbol provider * @return Returns the created provider. */ public static SymbolProvider createSymbolProvider(Model model, GoSettings settings) { return new SymbolVisitor(model, settings); } }
8,968
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/ServiceGenerator.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.codegen.core.SymbolProvider; import software.amazon.smithy.go.codegen.integration.ClientMember; import software.amazon.smithy.go.codegen.integration.ClientMemberResolver; import software.amazon.smithy.go.codegen.integration.ConfigField; import software.amazon.smithy.go.codegen.integration.ConfigFieldResolver; import software.amazon.smithy.go.codegen.integration.GoIntegration; import software.amazon.smithy.go.codegen.integration.RuntimeClientPlugin; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.ServiceShape; /** * Generates a service client and configuration. */ final class ServiceGenerator implements Runnable { public static final String CONFIG_NAME = "Options"; private final GoSettings settings; private final Model model; private final SymbolProvider symbolProvider; private final GoWriter writer; private final ServiceShape service; private final List<GoIntegration> integrations; private final List<RuntimeClientPlugin> runtimePlugins; private final ApplicationProtocol applicationProtocol; ServiceGenerator( GoSettings settings, Model model, SymbolProvider symbolProvider, GoWriter writer, ServiceShape service, List<GoIntegration> integrations, List<RuntimeClientPlugin> runtimePlugins, ApplicationProtocol applicationProtocol ) { this.settings = settings; this.model = model; this.symbolProvider = symbolProvider; this.writer = writer; this.service = service; this.integrations = integrations; this.runtimePlugins = runtimePlugins; this.applicationProtocol = applicationProtocol; } @Override public void run() { String serviceId = settings.getService().toString(); for (GoIntegration integration : integrations) { serviceId = integration.processServiceId(settings, model, serviceId); } writer.write("const ServiceID = $S", serviceId); writer.write("const ServiceAPIVersion = $S", service.getVersion()); writer.write(""); Symbol serviceSymbol = symbolProvider.toSymbol(service); writer.writeDocs(String.format("%s provides the API client to make operations call for %s.", serviceSymbol.getName(), CodegenUtils.getServiceTitle(service, "the API"))); writer.openBlock("type $T struct {", "}", serviceSymbol, () -> { writer.write("options $L", CONFIG_NAME); // Add client members resolved from runtime plugins to the client struct. for (ClientMember clientMember : getAllClientMembers()) { writer.write(""); clientMember.getDocumentation().ifPresent(writer::writeDocs); writer.write("$L $P", clientMember.getName(), clientMember.getType()); } }); generateConstructor(serviceSymbol); generateConfig(); generateClientInvokeOperation(); } private void writeClientMemberResolvers( GoWriter writer, RuntimeClientPlugin plugin, Predicate<ClientMemberResolver> predicate ) { plugin.getClientMemberResolvers().stream().filter(predicate) .forEach(resolver -> { writer.write("$T(client)", resolver.getResolver()); writer.write(""); }); } private void writeConfigFieldResolvers( GoWriter writer, RuntimeClientPlugin plugin, Predicate<ConfigFieldResolver> predicate ) { plugin.getConfigFieldResolvers().stream().filter(predicate) .forEach(resolver -> { writer.writeInline("$T(&options", resolver.getResolver()); if (resolver.isWithOperationName()) { writer.writeInline(", opID"); } if (resolver.isWithClientInput()) { if (resolver.getLocation() == ConfigFieldResolver.Location.CLIENT) { writer.writeInline(", client"); } else { writer.writeInline(", *c"); } } writer.write(")"); writer.write(""); }); } private void generateConstructor(Symbol serviceSymbol) { writer.writeDocs(String.format("New returns an initialized %s based on the functional options. " + "Provide additional functional options to further configure the behavior " + "of the client, such as changing the client's endpoint or adding custom " + "middleware behavior.", serviceSymbol.getName())); Symbol optionsSymbol = SymbolUtils.createPointableSymbolBuilder(CONFIG_NAME).build(); writer.openBlock("func New(options $T, optFns ...func($P)) $P {", "}", optionsSymbol, optionsSymbol, serviceSymbol, () -> { writer.write("options = options.Copy()").write(""); List<RuntimeClientPlugin> plugins = runtimePlugins.stream().filter(plugin -> plugin.matchesService(model, service)) .collect(Collectors.toList()); // Run any config initialization functions registered by runtime plugins. for (RuntimeClientPlugin plugin : plugins) { writeConfigFieldResolvers(writer, plugin, resolver -> resolver.getLocation() == ConfigFieldResolver.Location.CLIENT && resolver.getTarget() == ConfigFieldResolver.Target.INITIALIZATION); } writer.openBlock("for _, fn := range optFns {", "}", () -> writer.write("fn(&options)")); writer.write(""); writer.openBlock("client := &$T{", "}", serviceSymbol, () -> { writer.write("options: options,"); }).write(""); // Run any config finalization functions registered by runtime plugins. for (RuntimeClientPlugin plugin : plugins) { writeConfigFieldResolvers(writer, plugin, resolver -> resolver.getLocation() == ConfigFieldResolver.Location.CLIENT && resolver.getTarget() == ConfigFieldResolver.Target.FINALIZATION); } // Run any client member resolver functions registered by runtime plugins. for (RuntimeClientPlugin plugin : plugins) { writeClientMemberResolvers(writer, plugin, resolver -> true); } writer.write("return client"); }); } private void generateConfig() { writer.openBlock("type $L struct {", "}", CONFIG_NAME, () -> { writer.writeDocs("Set of options to modify how an operation is invoked. These apply to all operations " + "invoked for this client. Use functional options on operation call to modify this " + "list for per operation behavior." ); Symbol stackSymbol = SymbolUtils.createPointableSymbolBuilder("Stack", SmithyGoDependency.SMITHY_MIDDLEWARE) .build(); writer.write("APIOptions []func($P) error", stackSymbol).write(""); // Add config fields to the options struct. for (ConfigField configField : getAllConfigFields()) { configField.getDocumentation().ifPresent(writer::writeDocs); configField.getDeprecated().ifPresent(s -> { if (configField.getDocumentation().isPresent()) { writer.writeDocs(""); } writer.writeDocs(String.format("Deprecated: %s", s)); }); writer.write("$L $P", configField.getName(), configField.getType()); writer.write(""); } generateApplicationProtocolConfig(); }).write(""); writer.writeDocs("WithAPIOptions returns a functional option for setting the Client's APIOptions option."); writer.openBlock("func WithAPIOptions(optFns ...func(*middleware.Stack) error) func(*Options) {", "}", () -> { writer.openBlock("return func(o *Options) {", "}", () -> { writer.write("o.APIOptions = append(o.APIOptions, optFns...)"); }); }); getAllConfigFields().stream().filter(ConfigField::getWithHelper).filter(ConfigField::isDeprecated) .forEach(configField -> { writer.writeDocs(configField.getDeprecated().get()); writeWithHelperFunction(writer, configField); }); getAllConfigFields().stream().filter(ConfigField::getWithHelper).filter( Predicate.not(ConfigField::isDeprecated)) .forEach(configField -> { writer.writeDocs( String.format( "With%s returns a functional option for setting the Client's %s option.", configField.getName(), configField.getName())); writeWithHelperFunction(writer, configField); }); generateApplicationProtocolTypes(); writer.writeDocs("Copy creates a clone where the APIOptions list is deep copied."); writer.openBlock("func (o $L) Copy() $L {", "}", CONFIG_NAME, CONFIG_NAME, () -> { writer.write("to := o"); Symbol stackSymbol = SymbolUtils.createPointableSymbolBuilder("Stack", SmithyGoDependency.SMITHY_MIDDLEWARE) .build(); writer.write("to.APIOptions = make([]func($P) error, len(o.APIOptions))", stackSymbol); writer.write("copy(to.APIOptions, o.APIOptions)").write(""); writer.write("return to"); }); } private void writeWithHelperFunction(GoWriter writer, ConfigField configField) { writer.openBlock("func With$L(v $P) func(*Options) {", "}", configField.getName(), configField.getType(), () -> { writer.openBlock("return func(o *Options) {", "}", () -> { writer.write("o.$L = v", configField.getName()); }); }).write(""); } private List<ConfigField> getAllConfigFields() { List<ConfigField> configFields = new ArrayList<>(); for (RuntimeClientPlugin runtimeClientPlugin : runtimePlugins) { if (!runtimeClientPlugin.matchesService(model, service)) { continue; } configFields.addAll(runtimeClientPlugin.getConfigFields()); } return configFields.stream() .distinct() .sorted(Comparator.comparing(ConfigField::getName)) .collect(Collectors.toList()); } private List<ClientMember> getAllClientMembers() { List<ClientMember> clientMembers = new ArrayList<>(); for (RuntimeClientPlugin runtimeClientPlugin : runtimePlugins) { if (!runtimeClientPlugin.matchesService(model, service)) { continue; } clientMembers.addAll(runtimeClientPlugin.getClientMembers()); } return clientMembers.stream() .distinct() .sorted(Comparator.comparing(ClientMember::getName)) .collect(Collectors.toList()); } private void generateApplicationProtocolConfig() { ensureSupportedProtocol(); writer.writeDocs( "The HTTP client to invoke API calls with. Defaults to client's default HTTP implementation if nil."); writer.write("HTTPClient HTTPClient").write(""); } private void generateApplicationProtocolTypes() { ensureSupportedProtocol(); writer.addUseImports(SmithyGoDependency.NET_HTTP); writer.openBlock("type HTTPClient interface {", "}", () -> { writer.write("Do(*http.Request) (*http.Response, error)"); }).write(""); } private void generateClientInvokeOperation() { writer.addUseImports(SmithyGoDependency.CONTEXT); writer.addUseImports(SmithyGoDependency.SMITHY); writer.openBlock("func (c *Client) invokeOperation(" + "ctx context.Context, " + "opID string, " + "params interface{}, " + "optFns []func(*Options), " + "stackFns ...func(*middleware.Stack, Options) error" + ") " + "(result interface{}, metadata middleware.Metadata, err error) {", "}", () -> { writer.addUseImports(SmithyGoDependency.SMITHY_MIDDLEWARE); writer.addUseImports(SmithyGoDependency.SMITHY_HTTP_TRANSPORT); // Ensure operation stack invocations start with clean set of stack values. writer.write("ctx = middleware.ClearStackValues(ctx)"); generateConstructStack(); writer.write("options := c.options.Copy()"); List<RuntimeClientPlugin> plugins = runtimePlugins.stream().filter(plugin -> plugin.matchesService(model, service)) .collect(Collectors.toList()); for (RuntimeClientPlugin plugin : plugins) { writeConfigFieldResolvers(writer, plugin, resolver -> resolver.getLocation() == ConfigFieldResolver.Location.OPERATION && resolver.getTarget() == ConfigFieldResolver.Target.INITIALIZATION); } writer.write("for _, fn := range optFns { fn(&options) }"); writer.write(""); for (RuntimeClientPlugin plugin : plugins) { writeConfigFieldResolvers(writer, plugin, resolver -> resolver.getLocation() == ConfigFieldResolver.Location.OPERATION && resolver.getTarget() == ConfigFieldResolver.Target.FINALIZATION); } writer.openBlock("for _, fn := range stackFns {", "}", () -> { writer.write("if err := fn(stack, options); err != nil { return nil, metadata, err }"); }); writer.write(""); writer.openBlock("for _, fn := range options.APIOptions {", "}", () -> { writer.write("if err := fn(stack); err != nil { return nil, metadata, err }"); }); writer.write(""); generateConstructStackHandler(); writer.write("result, metadata, err = handler.Handle(ctx, params)"); writer.openBlock("if err != nil {", "}", () -> { writer.openBlock("err = &smithy.OperationError{", "}", () -> { writer.write("ServiceID: ServiceID,"); writer.write("OperationName: opID,"); writer.write("Err: err,"); }); }); writer.write("return result, metadata, err"); }); } private void generateConstructStack() { ensureSupportedProtocol(); Symbol newStack = SymbolUtils.createValueSymbolBuilder( "NewStack", SmithyGoDependency.SMITHY_MIDDLEWARE).build(); Symbol newStackRequest = SymbolUtils.createValueSymbolBuilder( "NewStackRequest", SmithyGoDependency.SMITHY_HTTP_TRANSPORT).build(); writer.write("stack := $T(opID, $T)", newStack, newStackRequest); } private void generateConstructStackHandler() { ensureSupportedProtocol(); Symbol decorateHandler = SymbolUtils.createValueSymbolBuilder( "DecorateHandler", SmithyGoDependency.SMITHY_MIDDLEWARE).build(); Symbol newClientHandler = SymbolUtils.createValueSymbolBuilder( "NewClientHandler", SmithyGoDependency.SMITHY_HTTP_TRANSPORT).build(); writer.write("handler := $T($T(options.HTTPClient), stack)", decorateHandler, newClientHandler); } private void ensureSupportedProtocol() { if (!applicationProtocol.isHttpProtocol()) { throw new UnsupportedOperationException( "Protocols other than HTTP are not yet implemented: " + applicationProtocol); } } }
8,969
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/TriConsumer.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen; import java.util.Objects; @FunctionalInterface public interface TriConsumer<T, U, V> { /** * Performs the operation on the given inputs. * * @param t is the first argument * @param u is the second argument * @param v is the third argument */ void accept(T t, U u, V v); /** * Returns a composed {@link TriConsumer} that performs, in sequence, this * operation followed by the {@code after} operation. * * @param after the operation to perform after this operation * @return a composed {@link TriConsumer} * @throws NullPointerException if {@code after} is null */ default TriConsumer<T, U, V> andThen(TriConsumer<? super T, ? super U, ? super V> after) { Objects.requireNonNull(after); return (x, y, z) -> { accept(x, y, z); after.accept(x, y, z); }; } }
8,970
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/Synthetic.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen; import java.util.Optional; import software.amazon.smithy.codegen.core.CodegenException; import software.amazon.smithy.model.node.Node; import software.amazon.smithy.model.shapes.ShapeId; import software.amazon.smithy.model.traits.AbstractTrait; import software.amazon.smithy.model.traits.AbstractTraitBuilder; import software.amazon.smithy.utils.SmithyBuilder; import software.amazon.smithy.utils.ToSmithyBuilder; /** * Defines a shape as being a clone of another modeled shape. * <p> * Must only be used as a runtime trait-only applied to shapes based on model processing */ public final class Synthetic extends AbstractTrait implements ToSmithyBuilder<Synthetic> { public static final ShapeId ID = ShapeId.from("smithy.go.traits#Synthetic"); private static final String ARCHETYPE = "archetype"; private final Optional<ShapeId> archetype; private Synthetic(Builder builder) { super(ID, builder.getSourceLocation()); this.archetype = builder.archetype; } /** * Get the archetype shape that this clone is based on. * * @return the original archetype shape */ public Optional<ShapeId> getArchetype() { return archetype; } @Override protected Node createNode() { throw new CodegenException("attempted to serialize runtime only trait"); } @Override public boolean equals(Object other) { if (other == this) { return true; } else if (!(other instanceof Synthetic)) { return false; } else { Synthetic b = (Synthetic) other; return toShapeId().equals(b.toShapeId()) && archetype.equals(b.getArchetype()); } } @Override public int hashCode() { return toShapeId().hashCode() * 17 + Node.objectNode() .withOptionalMember(ARCHETYPE, archetype.map(ShapeId::toString).map(Node::from)) .hashCode(); } @Override public SmithyBuilder<Synthetic> toBuilder() { Builder builder = builder(); getArchetype().ifPresent(builder::archetype); return builder; } /** * @return Returns a builder used to create {@link Synthetic}. */ public static Builder builder() { return new Builder(); } /** * Builder for {@link Synthetic}. */ public static final class Builder extends AbstractTraitBuilder<Synthetic, Builder> { private Optional<ShapeId> archetype = Optional.empty(); private Builder() { } @Override public Synthetic build() { return new Synthetic(this); } public Builder archetype(ShapeId archetype) { this.archetype = Optional.ofNullable(archetype); return this; } public Builder removeArchetype() { this.archetype = Optional.empty(); return this; } } }
8,971
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/GoDependency.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.TreeSet; import software.amazon.smithy.codegen.core.CodegenException; import software.amazon.smithy.codegen.core.SymbolDependency; import software.amazon.smithy.codegen.core.SymbolDependencyContainer; import software.amazon.smithy.utils.SetUtils; import software.amazon.smithy.utils.SmithyBuilder; /** * */ public final class GoDependency implements SymbolDependencyContainer, Comparable<GoDependency> { private final Type type; private final String sourcePath; private final String importPath; private final String alias; private final String version; private final Set<GoDependency> dependencies; private final SymbolDependency symbolDependency; private GoDependency(Builder builder) { this.type = SmithyBuilder.requiredState("type", builder.type); this.sourcePath = !this.type.equals(Type.STANDARD_LIBRARY) ? SmithyBuilder.requiredState("sourcePath", builder.sourcePath) : ""; this.importPath = SmithyBuilder.requiredState("importPath", builder.importPath); this.alias = builder.alias; this.version = SmithyBuilder.requiredState("version", builder.version); this.dependencies = builder.dependencies; this.symbolDependency = SymbolDependency.builder() .dependencyType(this.type.toString()) .packageName(this.sourcePath) .version(this.version) .build(); } /** * Given two {@link SymbolDependency} referring to the same package, return the minimum dependency version using * minimum version selection. The version strings must be semver compatible. * * @param dx the first dependency * @param dy the second dependency * @return the minimum dependency */ public static SymbolDependency mergeByMinimumVersionSelection(SymbolDependency dx, SymbolDependency dy) { SemanticVersion sx = SemanticVersion.parseVersion(dx.getVersion()); SemanticVersion sy = SemanticVersion.parseVersion(dy.getVersion()); // This *shouldn't* happen in Go since the Go module import path must end with the major version component. // Exception is the case where the major version is 0 or 1. if (sx.getMajor() != sy.getMajor() && !(sx.getMajor() == 0 || sy.getMajor() == 0)) { throw new CodegenException(String.format("Dependency %s has conflicting major versions", dx.getPackageName())); } int cmp = sx.compareTo(sy); if (cmp < 0) { return dy; } else if (cmp > 0) { return dx; } return dx; } /** * Get the the set of {@link GoDependency} required by this dependency. * * @return the set of dependencies */ public Set<GoDependency> getGoDependencies() { return this.dependencies; } /** * Get the symbol dependency representing the dependency. * * @return the symbol dependency */ public SymbolDependency getSymbolDependency() { return symbolDependency; } /** * Get the type of dependency. * * @return the dependency type */ public Type getType() { return type; } /** * Get the source code path of the dependency. * * @return the dependency source code path */ public String getSourcePath() { return sourcePath; } /** * Get the import path of the dependency. * * @return the import path of the dependency */ public String getImportPath() { return importPath; } /** * Get the alias of the module to use. * * @return the alias */ public String getAlias() { return alias; } /** * Get the version of the dependency. * * @return the version */ public String getVersion() { return version; } @Override public List<SymbolDependency> getDependencies() { Set<SymbolDependency> symbolDependencySet = new TreeSet<>(SetUtils.of(getSymbolDependency())); symbolDependencySet.addAll(resolveDependencies(getGoDependencies(), new TreeSet<>(SetUtils.of(this)))); return new ArrayList<>(symbolDependencySet); } private Set<SymbolDependency> resolveDependencies(Set<GoDependency> goDependencies, Set<GoDependency> processed) { Set<SymbolDependency> symbolDependencies = new TreeSet<>(); if (goDependencies.size() == 0) { return symbolDependencies; } Set<GoDependency> dependenciesToResolve = new TreeSet<>(); for (GoDependency dependency : goDependencies) { if (processed.contains(dependency)) { continue; } processed.add(dependency); symbolDependencies.add(dependency.getSymbolDependency()); dependenciesToResolve.addAll(dependency.getGoDependencies()); } symbolDependencies.addAll(resolveDependencies(dependenciesToResolve, processed)); return symbolDependencies; } public static Builder builder() { return new Builder(); } @Override public boolean equals(Object o) { if (this == o) { return true; } else if (!(o instanceof GoDependency)) { return false; } GoDependency other = (GoDependency) o; return this.type.equals(other.type) && this.sourcePath.equals(other.sourcePath) && this.importPath.equals(other.importPath) && this.alias.equals(other.alias) && this.version.equals(other.version) && this.dependencies.equals(other.dependencies); } @Override public int hashCode() { return Objects.hash(type, sourcePath, importPath, alias, version, dependencies); } @Override public int compareTo(GoDependency o) { if (equals(o)) { return 0; } int importPathCompare = importPath.compareTo(o.importPath); if (importPathCompare != 0) { return importPathCompare; } if (alias != null) { int aliasCompare = alias.compareTo(o.alias); if (aliasCompare != 0) { return aliasCompare; } } return version.compareTo(o.version); } /** * Represents a dependency type. */ public enum Type { STANDARD_LIBRARY, DEPENDENCY; @Override public String toString() { switch (this) { case STANDARD_LIBRARY: return "stdlib"; case DEPENDENCY: return "dependency"; default: return "unknown"; } } } /** * Get {@link GoDependency} representing the provided module description. * * @param sourcePath the root source path for the given code * @param importPath the import path of the package * @param version the version of source module * @param alias a default alias to use when importing the package, can be null * @return the dependency */ public static GoDependency moduleDependency(String sourcePath, String importPath, String version, String alias) { GoDependency.Builder builder = GoDependency.builder() .type(GoDependency.Type.DEPENDENCY) .sourcePath(sourcePath) .importPath(importPath) .version(version); if (alias != null) { builder.alias(alias); } return builder.build(); } /** * Get {@link GoDependency} representing the standard library import description. * * @param importPath the import path of the package * @param version the version of source module * @return the dependency */ public static GoDependency standardLibraryDependency(String importPath, String version) { return GoDependency.builder() .type(GoDependency.Type.STANDARD_LIBRARY) .importPath(importPath) .version(version) .build(); } /** * Get {@link GoDependency} representing the standard library import description. * * @param importPath the import path of the package * @param version the version of source module * @param alias the alias for stdlib dependency * @return the dependency */ public static GoDependency standardLibraryDependency(String importPath, String version, String alias) { GoDependency.Builder builder = GoDependency.builder() .type(GoDependency.Type.STANDARD_LIBRARY) .importPath(importPath) .version(version); if (alias != null) { builder.alias(alias); } return builder.build(); } /** * Builder for {@link GoDependency}. */ public static final class Builder implements SmithyBuilder<GoDependency> { private Type type; private String sourcePath; private String importPath; private String alias; private String version; private final Set<GoDependency> dependencies = new TreeSet<>(); private Builder() { } /** * Set the dependency type. * * @param type dependency type * @return the builder */ public Builder type(Type type) { this.type = type; return this; } /** * Set the source path. * * @param sourcePath the source path root * @return the builder */ public Builder sourcePath(String sourcePath) { this.sourcePath = sourcePath; return this; } /** * Set the import path. * * @param importPath the import path * @return the builder */ public Builder importPath(String importPath) { this.importPath = importPath; return this; } /** * Set the dependency alias. * * @param alias the alias * @return the builder */ public Builder alias(String alias) { this.alias = alias; return this; } /** * Set the dependency version. * * @param version the version * @return the builder */ public Builder version(String version) { this.version = version; return this; } /** * Set the collection of {@link GoDependency} required by this dependency. * * @param dependencies a collection of dependencies * @return the builder */ public Builder dependencies(Collection<GoDependency> dependencies) { this.dependencies.clear(); this.dependencies.addAll(dependencies); return this; } /** * Add a dependency on another {@link GoDependency}. * * @param dependency the dependency * @return the builder */ public Builder addDependency(GoDependency dependency) { this.dependencies.add(dependency); return this; } /** * Remove a dependency on another {@link GoDependency}. * * @param dependency the dependency * @return the builder */ public Builder removeDependency(GoDependency dependency) { this.dependencies.remove(dependency); return this; } @Override public GoDependency build() { return new GoDependency(this); } } }
8,972
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/endpoints/FnProvider.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen.endpoints; import software.amazon.smithy.codegen.core.Symbol; /* * FnProvider is the means by which generator consumers * can provide custom library functions to be invoked by * by Endpoint resolution. */ public interface FnProvider { Symbol fnFor(String name); }
8,973
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/endpoints/ExpressionGenerator.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen.endpoints; import static software.amazon.smithy.go.codegen.GoWriter.goBlockTemplate; import static software.amazon.smithy.go.codegen.GoWriter.goTemplate; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Stream; import software.amazon.smithy.go.codegen.GoWriter; import software.amazon.smithy.go.codegen.SmithyGoDependency; import software.amazon.smithy.go.codegen.SymbolUtils; import software.amazon.smithy.model.SourceLocation; import software.amazon.smithy.rulesengine.language.syntax.Identifier; import software.amazon.smithy.rulesengine.language.syntax.expressions.Expression; import software.amazon.smithy.rulesengine.language.syntax.expressions.ExpressionVisitor; import software.amazon.smithy.rulesengine.language.syntax.expressions.Reference; import software.amazon.smithy.rulesengine.language.syntax.expressions.Template; import software.amazon.smithy.rulesengine.language.syntax.expressions.TemplateVisitor; import software.amazon.smithy.rulesengine.language.syntax.expressions.functions.FunctionDefinition; import software.amazon.smithy.rulesengine.language.syntax.expressions.functions.GetAttr; import software.amazon.smithy.rulesengine.language.syntax.expressions.literal.Literal; import software.amazon.smithy.rulesengine.language.syntax.expressions.literal.LiteralVisitor; import software.amazon.smithy.utils.MapUtils; import software.amazon.smithy.utils.StringUtils; final class ExpressionGenerator { private final Scope scope; private final FnProvider fnProvider; ExpressionGenerator(Scope scope, FnProvider fnProvider) { this.scope = scope; this.fnProvider = fnProvider; } public GoWriter.Writable generate(Expression expr) { var exprOrRef = expr; var optExprIdent = scope.getIdent(expr); if (optExprIdent.isPresent()) { exprOrRef = new Reference(Identifier.of(optExprIdent.get()), SourceLocation.NONE); } return exprOrRef.accept(new ExpressionGeneratorVisitor(scope, fnProvider)); } private record ExpressionGeneratorVisitor(Scope scope, FnProvider fnProvider) implements ExpressionVisitor<GoWriter.Writable> { @Override public GoWriter.Writable visitLiteral(Literal literal) { return literal.accept(new LiteralGeneratorVisitor(scope, fnProvider)); } @Override public GoWriter.Writable visitRef(Reference ref) { return goTemplate(ref.getName().toString()); } @Override public GoWriter.Writable visitGetAttr(GetAttr getAttr) { var target = new ExpressionGenerator(scope, fnProvider).generate(getAttr.getTarget()); var path = (GoWriter.Writable) (GoWriter w) -> { getAttr.getPath().stream().toList().forEach((part) -> { if (part instanceof GetAttr.Part.Key) { w.writeInline(".$L", getBuiltinMemberName(((GetAttr.Part.Key) part).key())); } else if (part instanceof GetAttr.Part.Index) { w.writeInline(".Get($L)", ((GetAttr.Part.Index) part).index()); } }); }; return (GoWriter w) -> w.writeInline("$W$W", target, path); } @Override public GoWriter.Writable visitIsSet(Expression expr) { return (GoWriter w) -> { w.write("$W != nil", new ExpressionGenerator(scope, fnProvider).generate(expr)); }; } @Override public GoWriter.Writable visitNot(Expression expr) { return (GoWriter w) -> { w.write("!($W)", new ExpressionGenerator(scope, fnProvider).generate(expr)); }; } @Override public GoWriter.Writable visitBoolEquals(Expression left, Expression right) { return (GoWriter w) -> { var generator = new ExpressionGenerator(scope, fnProvider); w.write("$W == $W", generator.generate(left), generator.generate(right)); }; } @Override public GoWriter.Writable visitStringEquals(Expression left, Expression right) { return (GoWriter w) -> { var generator = new ExpressionGenerator(scope, fnProvider); w.write("$W == $W", generator.generate(left), generator.generate(right)); }; } @Override public GoWriter.Writable visitLibraryFunction(FunctionDefinition fnDef, List<Expression> args) { return new FnGenerator(scope, fnProvider).generate(fnDef, args); } } private record LiteralGeneratorVisitor(Scope scope, FnProvider fnProvider) implements LiteralVisitor<GoWriter.Writable> { @Override public GoWriter.Writable visitBoolean(boolean b) { return goTemplate(String.valueOf(b)); } @Override public GoWriter.Writable visitString(Template value) { Stream<GoWriter.Writable> parts = value.accept( new TemplateGeneratorVisitor((expr) -> new ExpressionGenerator(scope, fnProvider).generate(expr))); return (GoWriter w) -> { parts.forEach((p) -> w.write("$W", p)); }; } @Override public GoWriter.Writable visitRecord(Map<Identifier, Literal> members) { return goBlockTemplate("map[string]interface{}{", "}", (w) -> { members.forEach((k, v) -> { w.write("$S: $W,", k.getName().toString(), new ExpressionGenerator(scope, fnProvider).generate(v)); }); }); } @Override public GoWriter.Writable visitTuple(List<Literal> members) { return goBlockTemplate("[]interface{}{", "}", (w) -> { members.forEach((v) -> w.write("$W,", new ExpressionGenerator(scope, fnProvider).generate(v))); }); } @Override public GoWriter.Writable visitInteger(int i) { return goTemplate(String.valueOf(i)); } } private record TemplateGeneratorVisitor( Function<Expression, GoWriter.Writable> generator) implements TemplateVisitor<GoWriter.Writable> { @Override public GoWriter.Writable visitStaticTemplate(String s) { return (GoWriter w) -> w.write("$S", s); } @Override public GoWriter.Writable visitSingleDynamicTemplate(Expression expr) { return this.generator.apply(expr); } @Override public GoWriter.Writable visitStaticElement(String s) { return (GoWriter w) -> { w.write("out.WriteString($S)", s); }; } @Override public GoWriter.Writable visitDynamicElement(Expression expr) { return (GoWriter w) -> { w.write("out.WriteString($W)", this.generator.apply(expr)); }; } @Override public GoWriter.Writable startMultipartTemplate() { return goTemplate(""" func() string { var out $stringsBuilder:T """, MapUtils.of( "stringsBuilder", SymbolUtils.createValueSymbolBuilder("Builder", SmithyGoDependency.STRINGS).build())); } @Override public GoWriter.Writable finishMultipartTemplate() { return goTemplate(""" return out.String() }() """); } } private static String getBuiltinMemberName(Identifier ident) { return StringUtils.capitalize(ident.getName().toString()); } }
8,974
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/endpoints/EndpointBuiltInHandler.java
/* * Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen.endpoints; import software.amazon.smithy.go.codegen.GoWriter; import software.amazon.smithy.rulesengine.language.syntax.parameters.Parameters; /** * Used by integrations to provide BuiltIn value resolution * functionality during endpoint resolution. * */ public interface EndpointBuiltInHandler { /** * Used by integrations to set a member on the endpoints resolution * middleware object. * * @param writer Settings used to generate. */ default void renderEndpointBuiltInField(GoWriter writer) { // pass } /** * Used by integrations to set invoke BuiltIn resolution during Endpoint * resolution. * * @param writer Settings used to generate. */ default void renderEndpointBuiltInInvocation(GoWriter writer) { // pass } /** * Used by integrations to set initialize BuiltIn values on the Endpoint * resolution object. * * @param writer Settings used to generate. */ default void renderEndpointBuiltInInitialization(GoWriter writer, Parameters parameters) { // pass } }
8,975
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/endpoints/EndpointParametersGenerator.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen.endpoints; import static software.amazon.smithy.go.codegen.GoWriter.emptyGoTemplate; import static software.amazon.smithy.go.codegen.GoWriter.goBlockTemplate; import static software.amazon.smithy.go.codegen.GoWriter.goDocTemplate; import static software.amazon.smithy.go.codegen.GoWriter.goTemplate; import java.io.Serializable; import java.util.Comparator; import java.util.Iterator; import java.util.Map; import java.util.Optional; import java.util.stream.Stream; import java.util.stream.StreamSupport; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.go.codegen.GoWriter; import software.amazon.smithy.go.codegen.SmithyGoDependency; import software.amazon.smithy.go.codegen.SymbolUtils; import software.amazon.smithy.model.node.StringNode; import software.amazon.smithy.rulesengine.language.EndpointRuleSet; import software.amazon.smithy.rulesengine.language.evaluation.value.Value; import software.amazon.smithy.rulesengine.language.syntax.parameters.Parameter; import software.amazon.smithy.rulesengine.language.syntax.parameters.Parameters; import software.amazon.smithy.utils.MapUtils; import software.amazon.smithy.utils.SmithyBuilder; import software.amazon.smithy.utils.StringUtils; public final class EndpointParametersGenerator { public static final String VALIDATE_REQUIRED_FUNC_NAME = "ValidateRequired"; public static final String DEFAULT_VALUE_FUNC_NAME = "WithDefaults"; public static final String LOGGER_MEMBER_NAME = "SDKClientLogger"; public static final String ENABLE_LOGGING_MEMBER_NAME = "LogRuleFuncErrors"; private final Map<String, Object> commonCodegenArgs; private EndpointParametersGenerator(Builder builder) { var parametersType = SmithyBuilder.requiredState("parametersType", builder.parametersType); commonCodegenArgs = MapUtils.of( "parametersType", parametersType, "fmtErrorf", SymbolUtils.createValueSymbolBuilder("Errorf", SmithyGoDependency.FMT).build()); } public GoWriter.Writable generate(Optional<EndpointRuleSet> ruleset) { if (ruleset.isPresent()) { var parameters = ruleset.get().getParameters(); return generateParameters(MapUtils.of( "parametersMembers", generateParametersMembers(parameters), "parametersValidationMethod", generateValidationMethod(parameters), "parametersDefaultValueMethod", generateDefaultsMethod(parameters))); } else { return generateParameters(MapUtils.of( "parametersMembers", emptyGoTemplate(), "parametersValidationMethod", emptyGoTemplate(), "parametersDefaultValueMethod", emptyGoTemplate())); } } private GoWriter.Writable generateParameters(Map<String, Object> overriddenArgs) { return goTemplate(""" $parametersTypeDocs:W type $parametersType:T struct { $parametersMembers:W } $parametersValidationMethod:W $parametersDefaultValueMethod:W """, commonCodegenArgs, MapUtils.of( "parametersTypeDocs", generateParametersTypeDocs()), overriddenArgs); } private GoWriter.Writable generateParametersTypeDocs() { return goDocTemplate(""" $parametersType:T provides the parameters that influence how endpoints are resolved. """, commonCodegenArgs); } private GoWriter.Writable generateParametersMembers(Parameters parameters) { return (GoWriter w) -> { w.indent(); parameters.forEach((parameter) -> { var writeChain = new GoWriter.ChainWritable() .add(parameter.getDocumentation(), GoWriter::goTemplate) // TODO[GH-25977529]: fix incorrect wrapping in generated comment .add(parameter.isRequired(), goTemplate("Parameter is required.")) .add(parameter.getDefault(), (defaultValue) -> { return goTemplate("Defaults to " + defaultValue + " if no value is provided."); }) .add(parameter.getBuiltIn(), GoWriter::goTemplate) .add(parameter.getDeprecated(), (deprecated) -> { return goTemplate("Deprecated: " + deprecated.getMessage()); }); w.writeRenderedDocs(writeChain.compose()); w.write("$L $P", getExportedParameterName(parameter), parameterAsSymbol(parameter)); w.write(""); }); }; } private GoWriter.Writable generateDefaultsMethod(Parameters parameters) { return goTemplate(""" $methodDocs:W func (p $parametersType:T) $funcName:L() $parametersType:T { $setDefaults:W return p } """, commonCodegenArgs, MapUtils.of( "funcName", DEFAULT_VALUE_FUNC_NAME, "methodDocs", goDocTemplate("$funcName:L returns a shallow copy of $parametersType:T" + "with default values applied to members where applicable.", commonCodegenArgs, MapUtils.of( "funcName", DEFAULT_VALUE_FUNC_NAME)), "setDefaults", (GoWriter.Writable) (GoWriter w) -> { sortParameters(parameters).forEach((parameter) -> { parameter.getDefault().ifPresent(defaultValue -> { w.writeGoTemplate(""" if p.$memberName:L == nil { p.$memberName:L = $defaultValue:W } """, MapUtils.of( "memberName", getExportedParameterName(parameter), "defaultValue", generateDefaultValue(parameter, defaultValue) )); }); }); })); } private GoWriter.Writable generateDefaultValue(Parameter parameter, Value defaultValue) { return switch (parameter.getType()) { case STRING -> goTemplate("$ptrString:T($value:S)", MapUtils.of( "ptrString", SymbolUtils.createValueSymbolBuilder("String", SmithyGoDependency.SMITHY_PTR).build(), "value", defaultValue.expectStringValue())); case BOOLEAN -> goTemplate("$ptrBool:T($value:L)", MapUtils.of( "ptrBool", SymbolUtils.createValueSymbolBuilder("Bool", SmithyGoDependency.SMITHY_PTR).build(), "value", defaultValue.expectBooleanValue())); }; } private GoWriter.Writable generateValidationMethod(Parameters parameters) { if (!haveRequiredParameters(parameters)) { return emptyGoTemplate(); } return goBlockTemplate(""" $methodDocs:W func (p $parametersType:T) $funcName:L() error { """, "}", commonCodegenArgs, MapUtils.of( "funcName", VALIDATE_REQUIRED_FUNC_NAME, "methodDocs", goDocTemplate(""" $funcName:L validates required parameters are set. """, MapUtils.of( "funcName", VALIDATE_REQUIRED_FUNC_NAME))), (w) -> { sortParameters(parameters).forEach((parameter) -> { if (!parameter.isRequired()) { return; } w.writeGoTemplate(""" if p.$memberName:L == nil { return $fmtErrorf:T("parameter $memberName:L is required") } """, commonCodegenArgs, MapUtils.of( "memberName", getExportedParameterName(parameter))); }); w.write("return nil"); }); } public static Symbol parameterAsSymbol(Parameter parameter) { return switch (parameter.getType()) { case STRING -> SymbolUtils.createPointableSymbolBuilder("string") .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true).build(); case BOOLEAN -> SymbolUtils.createPointableSymbolBuilder("bool") .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true).build(); }; } public static boolean haveRequiredParameters(Parameters parameters) { for (Iterator<Parameter> iter = parameters.iterator(); iter.hasNext();) { if (iter.next().isRequired()) { return true; } } return false; } public static String getExportedParameterName(Parameter parameter) { return StringUtils.capitalize(parameter.getName().getName().getValue()); } public static String getExportedParameterName(StringNode name) { return StringUtils.capitalize(name.getValue()); } public static Builder builder() { return new Builder(); } public static final class Builder implements SmithyBuilder<EndpointParametersGenerator> { private Symbol parametersType; private Builder() { } public Builder parametersType(Symbol parametersType) { this.parametersType = parametersType; return this; } @Override public EndpointParametersGenerator build() { return new EndpointParametersGenerator(this); } } public static Stream<Parameter> sortParameters(Parameters parameters) { return StreamSupport .stream(parameters.spliterator(), false) .sorted(new Sorted()); } public static final class Sorted implements Comparator<Parameter>, Serializable { /** * Initializes the SortedMembers. */ @Override public int compare(Parameter a, Parameter b) { // first compare if the options are required or not, whichever option is // required should win. If both // options are required or not required, continue on to alphabetic search. // If a is required but b isn't return -1 so a is sorted before b // If b is required but a isn't, return 1 so a is sorted after b // If both a and b are required or optional, use alphabetic sorting of a and b's // member name. int requiredOption = 0; if (a.isRequired()) { requiredOption -= 1; } if (b.isRequired()) { requiredOption += 1; } if (requiredOption != 0) { return requiredOption; } return a.getName().getName().getValue().compareTo(b.getName().getName().getValue()); } } }
8,976
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/endpoints/FnGenerator.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen.endpoints; import static software.amazon.smithy.go.codegen.GoWriter.goTemplate; import static software.amazon.smithy.go.codegen.GoWriter.joinWritables; import java.util.ArrayList; import java.util.List; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.go.codegen.GoWriter; import software.amazon.smithy.go.codegen.SmithyGoDependency; import software.amazon.smithy.go.codegen.SymbolUtils; import software.amazon.smithy.rulesengine.language.syntax.expressions.Expression; import software.amazon.smithy.rulesengine.language.syntax.expressions.functions.FunctionDefinition; import software.amazon.smithy.utils.MapUtils; public class FnGenerator { private final Scope scope; private final FnProvider fnProvider; public FnGenerator(Scope scope, FnProvider fnProvider) { this.scope = scope; this.fnProvider = fnProvider; } GoWriter.Writable generate(FunctionDefinition fnDef, List<Expression> fnArgs) { Symbol goFn; if (this.fnProvider.fnFor(fnDef.getId()) == null) { var defaultFnProvider = new DefaultFnProvider(); goFn = defaultFnProvider.fnFor(fnDef.getId()); } else { goFn = this.fnProvider.fnFor(fnDef.getId()); } List<GoWriter.Writable> writableFnArgs = new ArrayList<>(); fnArgs.forEach((expr) -> { writableFnArgs.add(new ExpressionGenerator(scope, this.fnProvider).generate(expr)); }); return goTemplate("$fn:T($args:W)", MapUtils.of( "fn", goFn, "args", joinWritables(writableFnArgs, ", "))); } public static class DefaultFnProvider implements FnProvider { @Override public Symbol fnFor(String name) { return switch (name) { case "isValidHostLabel" -> SymbolUtils.createValueSymbolBuilder("IsValidHostLabel", SmithyGoDependency.SMITHY_ENDPOINT_RULESFN).build(); case "parseURL" -> SymbolUtils.createValueSymbolBuilder("ParseURL", SmithyGoDependency.SMITHY_ENDPOINT_RULESFN).build(); case "substring" -> SymbolUtils.createValueSymbolBuilder("SubString", SmithyGoDependency.SMITHY_ENDPOINT_RULESFN).build(); case "uriEncode" -> SymbolUtils.createValueSymbolBuilder("URIEncode", SmithyGoDependency.SMITHY_ENDPOINT_RULESFN).build(); default -> null; }; } } static boolean isFnResultOptional(FunctionDefinition fn) { return switch (fn.getId()) { case "isValidHostLabel" -> true; case "parseURL" -> true; case "substring" -> true; case "uriEncode" -> false; default -> false; }; } }
8,977
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/endpoints/EndpointTestsGenerator.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen.endpoints; import static software.amazon.smithy.go.codegen.GoWriter.emptyGoTemplate; import static software.amazon.smithy.go.codegen.GoWriter.goBlockTemplate; import static software.amazon.smithy.go.codegen.GoWriter.goDocTemplate; import static software.amazon.smithy.go.codegen.GoWriter.goTemplate; import static software.amazon.smithy.go.codegen.GoWriter.joinWritables; import static software.amazon.smithy.go.codegen.endpoints.EndpointParametersGenerator.getExportedParameterName; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.TreeSet; import software.amazon.smithy.codegen.core.CodegenException; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.go.codegen.GoWriter; import software.amazon.smithy.go.codegen.SmithyGoDependency; import software.amazon.smithy.go.codegen.SymbolUtils; import software.amazon.smithy.model.node.ArrayNode; import software.amazon.smithy.model.node.BooleanNode; import software.amazon.smithy.model.node.Node; import software.amazon.smithy.model.node.NodeVisitor; import software.amazon.smithy.model.node.NullNode; import software.amazon.smithy.model.node.NumberNode; import software.amazon.smithy.model.node.ObjectNode; import software.amazon.smithy.model.node.StringNode; import software.amazon.smithy.rulesengine.language.EndpointRuleSet; import software.amazon.smithy.rulesengine.language.syntax.parameters.Parameters; import software.amazon.smithy.rulesengine.traits.EndpointTestCase; import software.amazon.smithy.rulesengine.traits.ExpectedEndpoint; import software.amazon.smithy.utils.MapUtils; import software.amazon.smithy.utils.SmithyBuilder; public final class EndpointTestsGenerator { private final Map<String, Object> commonCodegenArgs; private EndpointTestsGenerator(Builder builder) { var newResolverFn = SmithyBuilder.requiredState("newResolverFn", builder.newResolverFn); var parametersType = SmithyBuilder.requiredState("parametersType", builder.parametersType); var endpointType = SmithyBuilder.requiredState("endpointType", builder.endpointType); var resolveEndpointMethodName = SmithyBuilder.requiredState("resolveEndpointMethodName", builder.resolveEndpointMethodName); commonCodegenArgs = MapUtils.of( "parametersType", parametersType, "endpointType", endpointType, "newResolverFn", newResolverFn, "resolveEndpointMethodName", resolveEndpointMethodName, "fmtErrorf", SymbolUtils.createValueSymbolBuilder("Errorf", SmithyGoDependency.FMT).build()); } public GoWriter.Writable generate(Optional<EndpointRuleSet> ruleset, List<EndpointTestCase> testCases) { if (!ruleset.isPresent()) { return emptyGoTemplate(); } var parameters = ruleset.get().getParameters(); List<GoWriter.Writable> writables = new ArrayList<>(); for (int i = 0; i < testCases.size(); i++) { var testCase = testCases.get(i); writables.add(goTemplate(""" $testCaseDocs:W func TestEndpointCase$caseIdx:L(t *$testingT:T) { $testBody:W } """, commonCodegenArgs, MapUtils.of( "caseIdx", i, "testingT", SymbolUtils.createValueSymbolBuilder("T", SmithyGoDependency.TESTING).build(), "testCaseDocs", generateTestCaseDocs(testCase), "testBody", generateTestCase(parameters, testCase)))); } return joinWritables(writables, "\n\n"); } private GoWriter.Writable generateTestCaseDocs(EndpointTestCase testCase) { if (testCase.getDocumentation().isPresent()) { return goDocTemplate(testCase.getDocumentation().get()); } return emptyGoTemplate(); } private GoWriter.Writable generateTestCase(Parameters parameters, EndpointTestCase testCase) { return goTemplate(""" var params = $parametersType:T{ $parameterValues:W } resolver := $newResolverFn:T() result, err := resolver.$resolveEndpointMethodName:L($contextBG:T(), params) _, _ = result, err $expectErr:W $expectEndpoint:W """, commonCodegenArgs, MapUtils.of( "contextBG", SymbolUtils.createValueSymbolBuilder("Background", SmithyGoDependency.CONTEXT).build(), "parameterValues", generateParameterValues(parameters, testCase), "expectErr", generateExpectError(testCase.getExpect().getError()), "expectEndpoint", generateExpectEndpoint(testCase.getExpect().getEndpoint()))); } private GoWriter.Writable generateParameterValues(Parameters parameters, EndpointTestCase testCase) { List<GoWriter.Writable> writables = new ArrayList<>(); // TODO filter keys based on actual modeled parameters Set<String> parameterNames = new TreeSet<>(); parameters.forEach((p) -> { parameterNames.add(getExportedParameterName(p)); }); testCase.getParams().getMembers().forEach((key, value) -> { var exportedName = getExportedParameterName(key); if (parameterNames.contains(exportedName)) { writables.add((GoWriter w) -> { w.write("$L: $W,", getExportedParameterName(key), generateParameterValue(value)); }); } }); return joinWritables(writables, "\n"); } private GoWriter.Writable generateParameterValue(Node value) { return switch (value.getType()) { case STRING -> (GoWriter w) -> { w.write("$T($S)", SymbolUtils.createValueSymbolBuilder("String", SmithyGoDependency.SMITHY_PTR).build(), value.expectStringNode().getValue()); }; case BOOLEAN -> (GoWriter w) -> { w.write("$T($L)", SymbolUtils.createValueSymbolBuilder("Bool", SmithyGoDependency.SMITHY_PTR).build(), value.expectBooleanNode().getValue()); }; default -> throw new CodegenException("Unhandled member type: " + value.getType()); }; } GoWriter.Writable generateExpectError(Optional<String> expectErr) { if (expectErr.isEmpty()) { return goTemplate(""" if err != nil { t.Fatalf("expect no error, got %v", err) } """); } return goTemplate(""" if err == nil { t.Fatalf("expect error, got none") } if e, a := $expect:S, err.Error(); !$stringsContains:T(a, e) { t.Errorf("expect %v error in %v", e, a) } """, MapUtils.of( "expect", expectErr.get(), "stringsContains", SymbolUtils.createValueSymbolBuilder("Contains", SmithyGoDependency.STRINGS).build())); } GoWriter.Writable generateExpectEndpoint(Optional<ExpectedEndpoint> expectEndpoint) { if (expectEndpoint.isEmpty()) { return emptyGoTemplate(); } var endpoint = expectEndpoint.get(); return goTemplate(""" uri, _ := $urlParse:T($expectURL:S) expectEndpoint := $endpointType:T{ URI: *uri, $headers:W $properties:W } if e, a := expectEndpoint.URI, result.URI; e != a{ t.Errorf("expect %v URI, got %v", e, a) } $assertFields:W $assertProperties:W """, commonCodegenArgs, MapUtils.of( "urlParse", SymbolUtils.createValueSymbolBuilder("Parse", SmithyGoDependency.NET_URL).build(), "cmpDiff", SymbolUtils.createPointableSymbolBuilder("Diff", SmithyGoDependency.GO_CMP).build(), "expectURL", endpoint.getUrl(), "headers", generateHeaders(endpoint.getHeaders()), "properties", generateProperties(endpoint.getProperties()), "assertFields", generateAssertFields(), "assertProperties", generateAssertProperties())); } GoWriter.Writable generateHeaders(Map<String, List<String>> headers) { Map<String, Object> commonArgs = MapUtils.of( "memberName", "Headers", "headerType", SymbolUtils.createPointableSymbolBuilder("Header", SmithyGoDependency.NET_HTTP).build(), "newHeaders", SymbolUtils.createValueSymbolBuilder("Header{}", SmithyGoDependency.NET_HTTP).build()); if (headers.isEmpty()) { return goTemplate("Headers: $newHeaders:T,", commonArgs); } return goBlockTemplate(""" $memberName:L: func() $headerType:T { headers := $newHeaders:T """, """ return headers }(), """, commonArgs, (w) -> { headers.forEach((key, values) -> { List<GoWriter.Writable> valueWritables = new ArrayList<>(); values.forEach((value) -> { valueWritables.add((GoWriter ww) -> ww.write("$S", value)); }); w.writeGoTemplate("headers.Set($key:S, $values:W)", commonArgs, MapUtils.of( "key", key, "values", joinWritables(valueWritables, ", "))); }); }); } GoWriter.Writable generateAssertFields() { return goTemplate(""" if diff := $cmpDiff:T(expectEndpoint.Headers, result.Headers); diff != "" { t.Errorf("expect headers to match\\n%s", diff) } """, MapUtils.of( "cmpDiff", SymbolUtils.createPointableSymbolBuilder("Diff", SmithyGoDependency.GO_CMP).build(), "cmpAllowUnexported", SymbolUtils.createPointableSymbolBuilder("AllowUnexported", SmithyGoDependency.GO_CMP).build())); } GoWriter.Writable generateProperties(Map<String, Node> properties) { Map<String, Object> commonArgs = MapUtils.of( "propertiesType", SymbolUtils.createValueSymbolBuilder("Properties", SmithyGoDependency.SMITHY).build()); if (properties.isEmpty()) { return goTemplate("Properties: $propertiesType:T{},", commonArgs); } return goBlockTemplate(""" Properties: func() $propertiesType:T { var properties $propertiesType:T """, """ return properties }(), """, commonArgs, (w) -> { properties.forEach((key, value) -> { w.writeGoTemplate("properties.Set($key:S, $value:W)", commonArgs, MapUtils.of( "key", key, "value", generateNodeValue(value))); }); }); } GoWriter.Writable generateNodeValue(Node value) { return value.accept(new NodeVisitor<>() { @Override public GoWriter.Writable arrayNode(ArrayNode arrayNode) { List<GoWriter.Writable> elements = new ArrayList<>(); arrayNode.getElements().forEach((e) -> { elements.add((GoWriter w) -> w.write("$W,", e.accept(this))); }); return (GoWriter w) -> { w.write(""" []interface{}{ $W } """, joinWritables(elements, "\n")); }; } @Override public GoWriter.Writable booleanNode(BooleanNode booleanNode) { return (GoWriter w) -> w.write("$L", booleanNode.getValue()); } @Override public GoWriter.Writable nullNode(NullNode nullNode) { return (GoWriter w) -> w.write("nil"); } @Override public GoWriter.Writable numberNode(NumberNode numberNode) { return (GoWriter w) -> w.write("$L", numberNode.toString()); } @Override public GoWriter.Writable objectNode(ObjectNode objectNode) { List<GoWriter.Writable> members = new ArrayList<>(); objectNode.getMembers().forEach((k, v) -> { members.add((GoWriter w) -> w.write("$S: $W,", k.getValue(), v.accept(this))); }); return (GoWriter w) -> { w.write(""" map[string]interface{}{ $W } """, joinWritables(members, "\n")); }; } @Override public GoWriter.Writable stringNode(StringNode stringNode) { return (GoWriter w) -> w.write("$S", stringNode.getValue()); } }); } GoWriter.Writable generateAssertProperties() { return goTemplate(""" if diff := $cmpDiff:T(expectEndpoint.Properties, result.Properties, $cmpAllowUnexported:T($propertiesType:T{}), ); diff != "" { t.Errorf("expect properties to match\\n%s", diff) } """, MapUtils.of( "cmpDiff", SymbolUtils.createPointableSymbolBuilder("Diff", SmithyGoDependency.GO_CMP).build(), "cmpAllowUnexported", SymbolUtils.createPointableSymbolBuilder("AllowUnexported", SmithyGoDependency.GO_CMP).build(), "propertiesType", SymbolUtils.createValueSymbolBuilder("Properties", SmithyGoDependency.SMITHY).build())); } public static Builder builder() { return new Builder(); } public static final class Builder implements SmithyBuilder<EndpointTestsGenerator> { private Symbol newResolverFn; private Symbol parametersType; private Symbol endpointType; private String resolveEndpointMethodName; private Builder() { } public Builder endpointType(Symbol endpointType) { this.endpointType = endpointType; return this; } public Builder newResolverFn(Symbol newResolverFn) { this.newResolverFn = newResolverFn; return this; } public Builder parametersType(Symbol parametersType) { this.parametersType = parametersType; return this; } public Builder resolveEndpointMethodName(String resolveEndpointMethodName) { this.resolveEndpointMethodName = resolveEndpointMethodName; return this; } @Override public EndpointTestsGenerator build() { return new EndpointTestsGenerator(this); } } }
8,978
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/endpoints/EndpointClientPluginsGenerator.java
/* * Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen.endpoints; import java.util.ArrayList; import java.util.List; import java.util.Optional; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.codegen.core.SymbolProvider; import software.amazon.smithy.go.codegen.GoCodegenPlugin; import software.amazon.smithy.go.codegen.GoSettings; import software.amazon.smithy.go.codegen.SymbolUtils; import software.amazon.smithy.go.codegen.integration.ConfigField; import software.amazon.smithy.go.codegen.integration.GoIntegration; import software.amazon.smithy.go.codegen.integration.MiddlewareRegistrar; import software.amazon.smithy.go.codegen.integration.RuntimeClientPlugin; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.knowledge.TopDownIndex; import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.ToShapeId; import software.amazon.smithy.rulesengine.language.EndpointRuleSet; import software.amazon.smithy.rulesengine.language.syntax.parameters.Parameter; import software.amazon.smithy.rulesengine.traits.ClientContextParamsTrait; import software.amazon.smithy.rulesengine.traits.EndpointRuleSetTrait; import software.amazon.smithy.utils.ListUtils; import software.amazon.smithy.utils.StringUtils; /** * Class responsible for registering client config fields that * are modeled in endpoint rulesets. */ public class EndpointClientPluginsGenerator implements GoIntegration { private final List<RuntimeClientPlugin> runtimeClientPlugins = new ArrayList<>(); private static String getAddEndpointMiddlewareFuncName(String operationName) { return String.format("add%sResolveEndpointMiddleware", operationName); } private static String getExportedParameterName(Parameter parameter) { return StringUtils.capitalize(parameter.getName().getName().getValue()); } private static Symbol parameterAsSymbol(Parameter parameter) { return switch (parameter.getType()) { case STRING -> SymbolUtils.createPointableSymbolBuilder("string") .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true).build(); case BOOLEAN -> SymbolUtils.createPointableSymbolBuilder("bool") .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true).build(); }; } @Override public List<RuntimeClientPlugin> getClientPlugins() { runtimeClientPlugins.add(RuntimeClientPlugin.builder() .configFields(ListUtils.of( ConfigField.builder() .name("BaseEndpoint") .type(SymbolUtils.createPointableSymbolBuilder("string") .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true).build()) .documentation( """ This endpoint will be given as input to an EndpointResolverV2. It is used for providing a custom base endpoint that is subject to modifications by the processing EndpointResolverV2. """ ) .build() )) .build()); return runtimeClientPlugins; } @Override public void processFinalizedModel(GoSettings settings, Model model) { ServiceShape service = settings.getService(model); var rulesetTrait = service.getTrait(EndpointRuleSetTrait.class); Optional<EndpointRuleSet> rulesetOpt = (rulesetTrait.isPresent()) ? Optional.of(EndpointRuleSet.fromNode(rulesetTrait.get().getRuleSet())) : Optional.empty(); var clientContextParamsTrait = service.getTrait(ClientContextParamsTrait.class); if (!rulesetOpt.isPresent()) { return; } var topDownIndex = TopDownIndex.of(model); for (ToShapeId operationId : topDownIndex.getContainedOperations(service)) { OperationShape operationShape = model.expectShape(operationId.toShapeId(), OperationShape.class); SymbolProvider symbolProvider = GoCodegenPlugin.createSymbolProvider(model, settings); String inputHelperFuncName = getAddEndpointMiddlewareFuncName( symbolProvider.toSymbol(operationShape).getName() ); runtimeClientPlugins.add(RuntimeClientPlugin.builder() .operationPredicate((m, s, o) -> { return o.equals(operationShape); }) .registerMiddleware(MiddlewareRegistrar.builder() .resolvedFunction(SymbolUtils.createValueSymbolBuilder(inputHelperFuncName) .build()) .useClientOptions() .build()) .build()); if (clientContextParamsTrait.isPresent()) { if (rulesetOpt.isPresent()) { var clientContextParams = clientContextParamsTrait.get(); var parameters = rulesetOpt.get().getParameters(); parameters.forEach(param -> { if ( clientContextParams.getParameters().containsKey(param.getName().getName().getValue()) && !param.getBuiltIn().isPresent() ) { var documentation = param.getDocumentation().isPresent() ? param.getDocumentation().get() : ""; runtimeClientPlugins.add(RuntimeClientPlugin.builder() .configFields(ListUtils.of( ConfigField.builder() .name(getExportedParameterName(param)) .type(parameterAsSymbol(param)) .documentation(documentation) .build() )) .build()); } }); } } } } }
8,979
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/endpoints/EndpointResolverGenerator.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen.endpoints; import static software.amazon.smithy.go.codegen.GoWriter.emptyGoTemplate; import static software.amazon.smithy.go.codegen.GoWriter.goBlockTemplate; import static software.amazon.smithy.go.codegen.GoWriter.goDocTemplate; import static software.amazon.smithy.go.codegen.GoWriter.goTemplate; import static software.amazon.smithy.go.codegen.GoWriter.joinWritables; import static software.amazon.smithy.go.codegen.endpoints.EndpointParametersGenerator.VALIDATE_REQUIRED_FUNC_NAME; import static software.amazon.smithy.go.codegen.endpoints.EndpointParametersGenerator.getExportedParameterName; import static software.amazon.smithy.go.codegen.endpoints.EndpointParametersGenerator.haveRequiredParameters; import static software.amazon.smithy.go.codegen.endpoints.FnGenerator.isFnResultOptional; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.TreeMap; import java.util.logging.Logger; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.go.codegen.GoWriter; import software.amazon.smithy.go.codegen.SmithyGoDependency; import software.amazon.smithy.go.codegen.SymbolUtils; import software.amazon.smithy.model.SourceException; import software.amazon.smithy.model.SourceLocation; import software.amazon.smithy.rulesengine.language.Endpoint; import software.amazon.smithy.rulesengine.language.EndpointRuleSet; import software.amazon.smithy.rulesengine.language.error.RuleError; import software.amazon.smithy.rulesengine.language.evaluation.type.OptionalType; import software.amazon.smithy.rulesengine.language.syntax.Identifier; import software.amazon.smithy.rulesengine.language.syntax.expressions.Expression; import software.amazon.smithy.rulesengine.language.syntax.expressions.ExpressionVisitor; import software.amazon.smithy.rulesengine.language.syntax.expressions.Reference; import software.amazon.smithy.rulesengine.language.syntax.expressions.functions.FunctionDefinition; import software.amazon.smithy.rulesengine.language.syntax.expressions.functions.IsSet; import software.amazon.smithy.rulesengine.language.syntax.expressions.literal.Literal; import software.amazon.smithy.rulesengine.language.syntax.parameters.Parameter; import software.amazon.smithy.rulesengine.language.syntax.parameters.Parameters; import software.amazon.smithy.rulesengine.language.syntax.rule.Condition; import software.amazon.smithy.rulesengine.language.syntax.rule.Rule; import software.amazon.smithy.rulesengine.language.syntax.rule.RuleValueVisitor; import software.amazon.smithy.utils.MapUtils; import software.amazon.smithy.utils.SmithyBuilder; public final class EndpointResolverGenerator { private static final String PARAMS_ARG_NAME = "params"; private static final String REALIZED_URL_VARIABLE_NAME = "uri"; private static final String ERROR_MESSAGE_ENDOFTREE = "Endpoint resolution failed. Invalid operation or environment input."; private static final Logger LOGGER = Logger.getLogger(EndpointResolverGenerator.class.getName()); private final Map<String, Object> commonCodegenArgs; private final FnProvider fnProvider; private int conditionIdentCounter = 0; private EndpointResolverGenerator(Builder builder) { var parametersType = SmithyBuilder.requiredState("parametersType", builder.parametersType); var resolverInterfaceType = SmithyBuilder.requiredState("resolverInterfaceType", builder.resolverInterfaceType); var resolverImplementationType = SmithyBuilder.requiredState("resolverImplementationType", builder.resolverImplementationType); var newResolverFn = SmithyBuilder.requiredState("newResolverFn", builder.newResolverFn); var endpointType = SmithyBuilder.requiredState("endpointType", builder.endpointType); var resolveEndpointMethodName = SmithyBuilder.requiredState("resolveEndpointMethodName", builder.resolveEndpointMethodName); this.fnProvider = SmithyBuilder.requiredState("fnProvider", builder.fnProvider); this.commonCodegenArgs = MapUtils.of( "paramArgName", PARAMS_ARG_NAME, "parametersType", parametersType, "endpointType", endpointType, "resolverInterfaceType", resolverInterfaceType, "resolverImplementationType", resolverImplementationType, "newResolverFn", newResolverFn, "resolveEndpointMethodName", resolveEndpointMethodName, "fmtErrorf", SymbolUtils.createValueSymbolBuilder("Errorf", SmithyGoDependency.FMT).build()); } public GoWriter.Writable generate(Optional<EndpointRuleSet> ruleset) { if (ruleset.isPresent()) { return generateResolverType(generateResolveMethodBody(ruleset.get())); } else { LOGGER.warning("service does not have modeled endpoint rules"); return generateEmptyRules(); } } public GoWriter.Writable generateEmptyRules() { return generateResolverType(generateEmptyResolveMethodBody()); } private GoWriter.Writable generateResolverType(GoWriter.Writable resolveMethodBody) { return goTemplate(""" // $resolverInterfaceType:T provides the interface for resolving service endpoints. type $resolverInterfaceType:T interface { $resolveEndpointMethodDocs:W $resolveEndpointMethodName:L(ctx $context:T, $paramArgName:L $parametersType:T) ( $endpointType:T, error, ) } $resolverTypeDocs:W type $resolverImplementationType:T struct{} func $newResolverFn:T() $resolverInterfaceType:T { return &$resolverImplementationType:T{} } $resolveEndpointMethodDocs:W func (r *$resolverImplementationType:T) $resolveEndpointMethodName:L( ctx $context:T, $paramArgName:L $parametersType:T, ) ( endpoint $endpointType:T, err error, ) { $resolveMethodBody:W } """, commonCodegenArgs, MapUtils.of( "context", SymbolUtils.createValueSymbolBuilder("Context", SmithyGoDependency.CONTEXT).build(), "resolverTypeDocs", generateResolverTypeDocs(), "resolveEndpointMethodDocs", generateResolveEndpointMethodDocs(), "resolveMethodBody", resolveMethodBody)); } private static String getLocalVarParameterName(Parameter p) { return "_" + p.getName().toString(); } private static String getMemberParameterName(Parameter p) { return PARAMS_ARG_NAME + "." + getExportedParameterName(p); } private GoWriter.Writable generateResolveMethodBody(EndpointRuleSet ruleset) { var scope = Scope.empty(); for (Iterator<Parameter> iter = ruleset.getParameters().iterator(); iter.hasNext();) { // Required parameters can be dereferenced directly so that read access are // always by value. // Optional parameters will be dereferenced via conditional checks. String identName; Parameter p = iter.next(); if (p.isRequired()) { identName = getLocalVarParameterName(p); } else { identName = getMemberParameterName(p); } scope = scope.withIdent(p.toExpression(), identName); } ruleset.typeCheck(); return goTemplate(""" $paramsWithDefaults:W $validateParams:W $paramVars:W $rules:W """, commonCodegenArgs, MapUtils.of( "logPrintln", SymbolUtils.createValueSymbolBuilder("Println", SmithyGoDependency.LOG).build(), "validateParams", generateValidateParams(ruleset.getParameters()), "paramsWithDefaults", generateParamsWithDefaults(), "paramVars", (GoWriter.Writable) (GoWriter w) -> { for (Iterator<Parameter> iter = ruleset.getParameters().iterator(); iter.hasNext();) { Parameter param = iter.next(); if (!param.isRequired()) { continue; } w.write("$L := *$L", getLocalVarParameterName(param), getMemberParameterName(param)); } }, "rules", generateRulesList(ruleset.getRules(), scope))); } private GoWriter.Writable generateParamsWithDefaults() { return goTemplate("$paramArgName:L = $paramArgName:L.$withDefaults:L()", commonCodegenArgs, MapUtils.of( "withDefaults", EndpointParametersGenerator.DEFAULT_VALUE_FUNC_NAME)); } private GoWriter.Writable generateEmptyResolveMethodBody() { return goTemplate("return endpoint, $fmtErrorf:T(\"no endpoint rules defined\")", commonCodegenArgs); } private GoWriter.Writable generateResolverTypeDocs() { return goDocTemplate("$resolverImplementationType:T provides the implementation for resolving endpoints.", commonCodegenArgs); } private GoWriter.Writable generateResolveEndpointMethodDocs() { return goDocTemplate("$resolveEndpointMethodName:L attempts to resolve the endpoint with the provided options," + " returning the endpoint if found. Otherwise an error is returned.", commonCodegenArgs); } private GoWriter.Writable generateValidateParams(Parameters parameters) { if (!haveRequiredParameters(parameters)) { return emptyGoTemplate(); } return goTemplate(""" if err = $paramArgName:L.$paramsValidateMethod:L(); err != nil { return endpoint, $fmtErrorf:T("endpoint parameters are not valid, %w", err) } """, commonCodegenArgs, MapUtils.of( "paramsValidateMethod", VALIDATE_REQUIRED_FUNC_NAME)); } private GoWriter.Writable generateRulesList(List<Rule> rules, Scope scope) { return (w) -> { rules.forEach(rule -> { rule.getDocumentation().ifPresent(w::writeDocs); w.write("$W", generateRule(rule, rule.getConditions(), scope)); }); if (!rules.isEmpty()) { Rule lastRule = rules.get(rules.size() - 1); // Trees are terminal, so we must ensure there's a final fallback condition at // the end of each one. // Generally we know we need to insert one when the final rule in a tree is not // "static" i.e. it has // conditions that might mean it is not selected. Since it may not be chosen // (its set of conditions may // evaluate to false) we MUST put a fallback error return after which we know // will get executed. // // However, assignment statements are conflated with conditions in the rules // language, and while certain // assignments DO have a condition associated with them (basically, checking // that the result of the // assignment is not nil), some do not. Therefore, remove "static" // condition/assignments from // consideration. boolean needsFallback = !lastRule.getConditions().stream().filter( condition -> { // You can't assert into a FunctionDefinition from an Expression - we have to // inspect the fn // member of the node directly. String fn = condition.toNode().expectObjectNode().expectStringMember("fn").getValue(); // the only static assignment condition, as of this writing... return !fn.equals("uriEncode"); }).toList().isEmpty(); if (needsFallback) { w.writeGoTemplate( "return endpoint, $fmtErrorf:T(\"" + ERROR_MESSAGE_ENDOFTREE + "\")", commonCodegenArgs); } } }; } private GoWriter.Writable generateRule(Rule rule, List<Condition> conditions, Scope scope) { if (conditions.isEmpty()) { return rule.accept(new RuleVisitor(scope, this.fnProvider)); } var condition = conditions.get(0); var remainingConditions = conditions.subList(1, conditions.size()); var generator = new ExpressionGenerator(scope, this.fnProvider); var fn = conditionalFunc(condition); String conditionIdentifier; if (condition.getResult().isPresent()) { var ident = condition.getResult().get(); conditionIdentifier = "_" + ident.getName().getValue(); // Store the condition result so that it can be referenced in the future by the // result identifier. scope = scope.withIdent(new Reference(ident, SourceLocation.NONE), conditionIdentifier); } else { conditionIdentifier = nameForExpression(fn); } if (fn.type() instanceof OptionalType || isConditionalFnResultOptional(condition, fn)) { return goTemplate(""" if exprVal := $target:W; exprVal != nil { $conditionIdent:L := *exprVal _ = $conditionIdent:L $next:W } """, MapUtils.of( "conditionIdent", conditionIdentifier, "target", generator.generate(fn), "next", generateRule( rule, remainingConditions, scope.withMember(fn, conditionIdentifier)))); } if (condition.getResult().isPresent()) { return goTemplate(""" $conditionIdent:L := $target:W _ = $conditionIdent:L $next:W """, MapUtils.of( "conditionIdent", conditionIdentifier, "target", generator.generate(fn), "next", generateRule( rule, remainingConditions, scope.withMember(fn, conditionIdentifier)))); } return goTemplate(""" if $target:W { $next:W } """, MapUtils.of( "target", generator.generate(fn), "next", generateRule(rule, remainingConditions, scope))); } private static Expression conditionalFunc(Condition condition) { var fn = condition.getFunction(); if (fn instanceof IsSet) { var setFn = ((IsSet) fn); List<Expression> argv = setFn.getArguments(); if (argv.size() == 1) { return argv.get(0); } throw new RuleError(new SourceException("expected 1 argument but found " + argv.size(), setFn)); } return fn; } private String nameForExpression(Expression expr) { conditionIdentCounter++; if (expr instanceof Reference) { return nameForRef((Reference) expr); } return String.format("_var_%d", conditionIdentCounter); } /** * Returns a name for a reference. * * @param ref reference to get name for * @return name */ private static String nameForRef(Reference ref) { return "_" + ref.getName(); } private GoWriter.Writable generateEndpoint(Endpoint endpoint, Scope scope) { return goTemplate(""" $endpointType:T{ URI: *$uriVariableName:L, $headers:W $properties:W } """, commonCodegenArgs, MapUtils.of( "uriVariableName", REALIZED_URL_VARIABLE_NAME, "headers", generateEndpointHeaders(endpoint.getHeaders(), scope), "properties", generateEndpointProperties(endpoint.getProperties(), scope))); } private GoWriter.Writable generateEndpointHeaders(Map<String, List<Expression>> headers, Scope scope) { Map<String, Object> args = MapUtils.of( "memberName", "Headers", "headerType", SymbolUtils.createPointableSymbolBuilder("Header", SmithyGoDependency.NET_HTTP).build(), "newHeaders", SymbolUtils.createValueSymbolBuilder("Header{}", SmithyGoDependency.NET_HTTP).build()); // TODO: consider removing this line (letting it default to nil init) // rather than generating empty headers // https://github.com/aws/aws-sdk-go-v2/pull/2110/files#r1186193501 if (headers.isEmpty()) { return goTemplate("Headers: $newHeaders:T,", args); } var writableHeaders = new TreeMap<String, List<GoWriter.Writable>>(); var generator = new ExpressionGenerator(scope, this.fnProvider); headers.forEach((k, vs) -> { var writables = new ArrayList<GoWriter.Writable>(); vs.forEach(v -> writables.add(generator.generate(v))); writableHeaders.put(k, writables); }); return goBlockTemplate("$memberName:L: func() $headerType:T {", "}(),", args, (w) -> { w.writeGoTemplate("headers := $newHeaders:T", args); writableHeaders.forEach((k, vs) -> { w.write("headers.Set($W)", generateNewHeaderValue(k, vs)); }); w.write("return headers"); }); } private GoWriter.Writable generateNewHeaderValue(String headerName, List<GoWriter.Writable> headerValues) { Map<String, Object> args = MapUtils.of( "headerName", headerName, "headerValues", joinWritables(headerValues, ", ")); if (headerValues.isEmpty()) { return goTemplate("$headerName:W", args); } return goTemplate("$headerName:S, $headerValues:W", args); } private GoWriter.Writable generateEndpointProperties(Map<Identifier, Literal> properties, Scope scope) { Map<String, Object> propertyTypeArg = MapUtils.of( "memberName", "Properties", "propertyType", SymbolUtils.createValueSymbolBuilder("Properties", SmithyGoDependency.SMITHY).build()); if (properties.isEmpty()) { return emptyGoTemplate(); } var writableProperties = new TreeMap<String, GoWriter.Writable>(); var generator = new ExpressionGenerator(scope, this.fnProvider); properties.forEach((k, v) -> { writableProperties.put(k.toString(), generator.generate(v)); }); return goBlockTemplate( """ $memberName:L: func() $propertyType:T{ var out $propertyType:T """, """ return out }(), """, propertyTypeArg, (w) -> { writableProperties.forEach((k, v) -> { // TODO these properties should be typed, and ignore properties that are // unknown. w.write("out.Set($S, $W)", k, v); }); }); } class RuleVisitor implements RuleValueVisitor<GoWriter.Writable> { final Scope scope; final FnProvider fnProvider; RuleVisitor(Scope scope, FnProvider fnProvider) { this.scope = scope; this.fnProvider = fnProvider; } @Override public GoWriter.Writable visitTreeRule(List<Rule> rules) { return generateRulesList(rules, scope); } @Override public GoWriter.Writable visitErrorRule(Expression errorExpr) { return goTemplate(""" return endpoint, $fmtErrorf:T("endpoint rule error, %s", $errorExpr:W) """, commonCodegenArgs, MapUtils.of( "errorExpr", new ExpressionGenerator(scope, fnProvider).generate(errorExpr))); } @Override public GoWriter.Writable visitEndpointRule(Endpoint endpoint) { return goTemplate(""" uriString := $url:W $uriVariableName:L, err := url.Parse(uriString) if err != nil { return endpoint, fmt.Errorf(\"Failed to parse uri: %s\", uriString) } return $endpoint:W, nil """, MapUtils.of( // TODO: consider simplifying how the URI string is built // look into strings.Join "uriVariableName", REALIZED_URL_VARIABLE_NAME, "url", new ExpressionGenerator(scope, this.fnProvider).generate(endpoint.getUrl()), "endpoint", generateEndpoint(endpoint, scope))); } } private static boolean isConditionalFnResultOptional(Condition condition, Expression fn) { if (condition.getResult().isEmpty()) { return false; } final boolean[] isOptionalResult = {false}; fn.accept(new ExpressionVisitor.Default<Void>() { @Override public Void getDefault() { return null; } @Override public Void visitLibraryFunction(FunctionDefinition fn, List<Expression> args) { isOptionalResult[0] = isFnResultOptional(fn); return null; } }); return isOptionalResult[0]; } public static Builder builder() { return new Builder(); } public static final class Builder implements SmithyBuilder<EndpointResolverGenerator> { private Symbol resolverInterfaceType; private Symbol resolverImplementationType; private Symbol newResolverFn; private Symbol parametersType; private Symbol endpointType; private String resolveEndpointMethodName; private FnProvider fnProvider; private Builder() { } public Builder endpointType(Symbol endpointType) { this.endpointType = endpointType; return this; } public Builder resolverInterfaceType(Symbol resolverInterfaceType) { this.resolverInterfaceType = resolverInterfaceType; return this; } public Builder resolverImplementationType(Symbol resolverImplementationType) { this.resolverImplementationType = resolverImplementationType; return this; } public Builder newResolverFn(Symbol newResolverFn) { this.newResolverFn = newResolverFn; return this; } public Builder resolveEndpointMethodName(String resolveEndpointMethodName) { this.resolveEndpointMethodName = resolveEndpointMethodName; return this; } public Builder parametersType(Symbol parametersType) { this.parametersType = parametersType; return this; } public Builder fnProvider(FnProvider fnProvider) { this.fnProvider = fnProvider; return this; } @Override public EndpointResolverGenerator build() { return new EndpointResolverGenerator(this); } } }
8,980
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/endpoints/Scope.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen.endpoints; import java.util.HashMap; import java.util.Map; import java.util.Optional; import software.amazon.smithy.rulesengine.language.syntax.expressions.Expression; /* * Provides contextualized scope down the call tree to inform generator of expression origin. */ class Scope { private final Map<Expression, String> mapping; Scope(Map<Expression, String> mapping) { this.mapping = mapping; } static Scope empty() { return new Scope(new HashMap<>()); } Optional<String> getIdent(Expression expr) { if (!mapping.containsKey(expr)) { return Optional.empty(); } return Optional.of(mapping.get(expr)); } Scope withMember(Expression expr, String name) { Map<Expression, String> newMapping = new HashMap<>(mapping); newMapping.put(expr, name); return new Scope(newMapping); } Scope withIdent(Expression expr, String name) { var newMapping = new HashMap<>(mapping); newMapping.put(expr, name); return new Scope(newMapping); } }
8,981
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/endpoints/EndpointMiddlewareGenerator.java
/* * Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen.endpoints; import static software.amazon.smithy.go.codegen.GoWriter.goTemplate; import java.util.Iterator; import java.util.List; import java.util.Optional; import software.amazon.smithy.codegen.core.CodegenException; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.codegen.core.SymbolProvider; import software.amazon.smithy.go.codegen.GoDelegator; import software.amazon.smithy.go.codegen.GoSettings; import software.amazon.smithy.go.codegen.GoWriter; import software.amazon.smithy.go.codegen.MiddlewareIdentifier; import software.amazon.smithy.go.codegen.SmithyGoDependency; import software.amazon.smithy.go.codegen.SymbolUtils; import software.amazon.smithy.go.codegen.integration.GoIntegration; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.knowledge.OperationIndex; import software.amazon.smithy.model.knowledge.TopDownIndex; import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.ToShapeId; import software.amazon.smithy.rulesengine.language.EndpointRuleSet; import software.amazon.smithy.rulesengine.language.syntax.parameters.Parameter; import software.amazon.smithy.rulesengine.language.syntax.parameters.ParameterType; import software.amazon.smithy.rulesengine.language.syntax.parameters.Parameters; import software.amazon.smithy.rulesengine.traits.ClientContextParamsTrait; import software.amazon.smithy.rulesengine.traits.ContextParamTrait; import software.amazon.smithy.rulesengine.traits.EndpointRuleSetTrait; import software.amazon.smithy.rulesengine.traits.StaticContextParamsTrait; import software.amazon.smithy.utils.MapUtils; import software.amazon.smithy.utils.SmithyBuilder; import software.amazon.smithy.utils.StringUtils; /** * Class responsible for generating middleware * that will be used during endpoint resolution. */ public final class EndpointMiddlewareGenerator { // TODO(ep20): remove existing v1 "ResolveEndpoint" and rename public static final String MIDDLEWARE_ID = "ResolveEndpointV2"; List<GoIntegration> integrations; private EndpointMiddlewareGenerator(Builder builder) { this.integrations = SmithyBuilder.requiredState("integrations", builder.integrations); } public void generate(GoSettings settings, Model model, SymbolProvider symbolProvider, GoDelegator goDelegator) { var serviceShape = settings.getService(model); var rulesetTrait = serviceShape.getTrait(EndpointRuleSetTrait.class); var clientContextParamsTrait = serviceShape.getTrait(ClientContextParamsTrait.class); Optional<EndpointRuleSet> rulesetOpt = (rulesetTrait.isPresent()) ? Optional.of(EndpointRuleSet.fromNode(rulesetTrait.get().getRuleSet())) : Optional.empty(); TopDownIndex topDownIndex = TopDownIndex.of(model); for (ToShapeId operation : topDownIndex.getContainedOperations(serviceShape)) { OperationShape operationShape = model.expectShape(operation.toShapeId(), OperationShape.class); goDelegator.useShapeWriter(operationShape, writer -> { if (rulesetOpt.isPresent()) { var parameters = rulesetOpt.get().getParameters(); Symbol operationSymbol = symbolProvider.toSymbol(operationShape); String operationName = operationSymbol.getName(); writer.write( """ $W $W $W """, generateMiddlewareType(parameters, clientContextParamsTrait, operationName), generateMiddlewareMethods( parameters, settings, clientContextParamsTrait, symbolProvider, operationShape, model), generateMiddlewareAdder(parameters, operationName, clientContextParamsTrait) ); } }); } } private GoWriter.Writable generateMiddlewareType( Parameters parameters, Optional<ClientContextParamsTrait> clientContextParamsTrait, String operationName) { return (GoWriter w) -> { w.openBlock("type $L struct {", "}", getMiddlewareObjectName(operationName), () -> { w.write("EndpointResolver $T", SymbolUtils.createValueSymbolBuilder("EndpointResolverV2").build()); for (Iterator<Parameter> iter = parameters.iterator(); iter.hasNext();) { if (iter.next().getBuiltIn().isPresent()) { for (GoIntegration integration : this.integrations) { var builtInHandlerOpt = integration.getEndpointBuiltinHandler(); if (builtInHandlerOpt.isPresent()) { builtInHandlerOpt.get().renderEndpointBuiltInField(w); } } break; } } if (clientContextParamsTrait.isPresent()) { var clientContextParams = clientContextParamsTrait.get(); parameters.forEach(param -> { if (clientContextParams.getParameters().containsKey(param.getName().getName().getValue()) && !param.getBuiltIn().isPresent()) { w.write("$L $P", getExportedParameterName(param), parameterAsSymbol(param)); } }); } }); }; } private GoWriter.Writable generateMiddlewareMethods( Parameters parameters, GoSettings settings, Optional<ClientContextParamsTrait> clientContextParamsTrait, SymbolProvider symbolProvider, OperationShape operationShape, Model model) { Symbol operationSymbol = symbolProvider.toSymbol(operationShape); String operationName = operationSymbol.getName(); String middlewareName = getMiddlewareObjectName(operationName); Symbol middlewareSymbol = SymbolUtils.createPointableSymbolBuilder(middlewareName).build(); return (GoWriter writer) -> { writer.openBlock("func ($P) ID() string {", "}", middlewareSymbol, () -> { writer.writeInline("return "); MiddlewareIdentifier.string(MIDDLEWARE_ID).writeInline(writer); writer.write(""); }); writer.write(""); String handleMethodName = "HandleSerialize"; Symbol contextType = SymbolUtils.createValueSymbolBuilder("Context", SmithyGoDependency.CONTEXT).build(); Symbol metadataType = SymbolUtils.createValueSymbolBuilder("Metadata", SmithyGoDependency.SMITHY_MIDDLEWARE).build(); var inputType = SymbolUtils.createValueSymbolBuilder("SerializeInput", SmithyGoDependency.SMITHY_MIDDLEWARE).build(); var outputType = SymbolUtils.createValueSymbolBuilder("SerializeOutput", SmithyGoDependency.SMITHY_MIDDLEWARE).build(); var handlerType = SymbolUtils.createValueSymbolBuilder("SerializeHandler", SmithyGoDependency.SMITHY_MIDDLEWARE).build(); writer.openBlock("func (m $P) $L(ctx $T, in $T, next $T) (\n" + "\tout $T, metadata $T, err error,\n" + ") {", "}", new Object[]{ middlewareSymbol, handleMethodName, contextType, inputType, handlerType, outputType, metadataType, }, () -> { writer.write("$W", generateMiddlewareResolverBody( operationShape, model, parameters, clientContextParamsTrait, settings) ); }); }; } private GoWriter.Writable generateMiddlewareResolverBody( OperationShape operationShape, Model model, Parameters parameters, Optional<ClientContextParamsTrait> clientContextParamsTrait, GoSettings settings) { return goTemplate( """ $preEndpointResolutionHook:W $requestValidator:W $inputValidator:W $legacyResolverValidator:W params := $endpointParametersType:L{} $builtInResolverInvocation:W $clientContextBinding:W $contextBinding:W $staticContextBinding:W $endpointResolution:W $postEndpointResolution:W return next.HandleSerialize(ctx, in) """, MapUtils.of( "preEndpointResolutionHook", generatePreEndpointResolutionHook(settings, model) ), MapUtils.of( "requestValidator", generateRequestValidator(), "inputValidator", generateInputValidator(model, operationShape), "legacyResolverValidator", generateLegacyResolverValidator(), "endpointParametersType", EndpointResolutionGenerator.PARAMETERS_TYPE_NAME, "builtInResolverInvocation", generateBuiltInResolverInvocation(parameters), "clientContextBinding", generateClientContextParamBinding(parameters, clientContextParamsTrait), "contextBinding", generateContextParamBinding(operationShape, model), "staticContextBinding", generateStaticContextParamBinding(parameters, operationShape), "endpointResolution", generateEndpointResolution(), "postEndpointResolution", generatePostEndpointResolutionHook(settings, model, operationShape) ) ); } private GoWriter.Writable generatePreEndpointResolutionHook(GoSettings settings, Model model) { return (GoWriter writer) -> { for (GoIntegration integration : this.integrations) { integration.renderPreEndpointResolutionHook(settings, writer, model); } }; } private GoWriter.Writable generateRequestValidator() { return (GoWriter writer) -> { writer.write( """ req, ok := in.Request.($P) if !ok { return out, metadata, $T(\"unknown transport type %T\", in.Request) } """, SymbolUtils.createPointableSymbolBuilder("Request", SmithyGoDependency.SMITHY_HTTP_TRANSPORT).build(), SymbolUtils.createValueSymbolBuilder("Errorf", SmithyGoDependency.FMT).build() ); }; } private GoWriter.Writable generateInputValidator(Model model, OperationShape operationShape) { var opIndex = OperationIndex.of(model); var inputOpt = opIndex.getInput(operationShape); GoWriter.Writable inputValidator = (GoWriter writer) -> { writer.write(""); }; if (inputOpt.isPresent()) { var input = inputOpt.get(); for (var inputMember : input.getAllMembers().values()) { var contextParamTraitOpt = inputMember.getTrait(ContextParamTrait.class); if (contextParamTraitOpt.isPresent()) { inputValidator = (GoWriter writer) -> { writer.write( """ input, ok := in.Parameters.($P) if !ok { return out, metadata, $T(\"unknown transport type %T\", in.Request) } """, SymbolUtils.createPointableSymbolBuilder(operationShape.getInput().get().getName()).build(), SymbolUtils.createValueSymbolBuilder("Errorf", SmithyGoDependency.FMT).build() ); }; } } } return inputValidator; } private GoWriter.Writable generateLegacyResolverValidator() { return (GoWriter writer) -> { writer.write( """ if m.EndpointResolver == nil { return out, metadata, $T(\"expected endpoint resolver to not be nil\") } """, SymbolUtils.createValueSymbolBuilder("Errorf", SmithyGoDependency.FMT).build() ); }; } private GoWriter.Writable generateBuiltInResolverInvocation(Parameters parameters) { return (GoWriter writer) -> { for (Iterator<Parameter> iter = parameters.iterator(); iter.hasNext();) { if (iter.next().getBuiltIn().isPresent()) { for (GoIntegration integration : this.integrations) { var builtInHandlerOpt = integration.getEndpointBuiltinHandler(); if (builtInHandlerOpt.isPresent()) { builtInHandlerOpt.get().renderEndpointBuiltInInvocation(writer); } } break; } } }; } private GoWriter.Writable generateClientContextParamBinding( Parameters parameters, Optional<ClientContextParamsTrait> clientContextParamsTrait) { return (GoWriter writer) -> { if (clientContextParamsTrait.isPresent()) { var clientContextParams = clientContextParamsTrait.get(); parameters.forEach(param -> { if (clientContextParams.getParameters().containsKey(param.getName().getName().getValue()) && !param.getBuiltIn().isPresent() ) { var name = getExportedParameterName(param); writer.write("params.$L = m.$L", name, name); } }); } }; } private GoWriter.Writable generateContextParamBinding(OperationShape operationShape, Model model) { return (GoWriter writer) -> { var opIndex = OperationIndex.of(model); var inputOpt = opIndex.getInput(operationShape); if (inputOpt.isPresent()) { var input = inputOpt.get(); input.getAllMembers().values().forEach(inputMember -> { var contextParamTraitOpt = inputMember.getTrait(ContextParamTrait.class); if (contextParamTraitOpt.isPresent()) { var contextParamTrait = contextParamTraitOpt.get(); writer.write( """ params.$L = input.$L """, contextParamTrait.getName(), inputMember.getMemberName() ); writer.write(""); } }); } writer.write(""); }; } private GoWriter.Writable generateStaticContextParamBinding(Parameters parameters, OperationShape operationShape) { var staticContextParamTraitOpt = operationShape.getTrait(StaticContextParamsTrait.class); return (GoWriter writer) -> { parameters.forEach(param -> { if (staticContextParamTraitOpt.isPresent()) { var paramName = param.getName().getName().getValue(); var staticParam = staticContextParamTraitOpt .get() .getParameters() .get(paramName); if (staticParam != null) { Symbol valueWrapper; if (param.getType() == ParameterType.BOOLEAN) { valueWrapper = SymbolUtils.createValueSymbolBuilder( "Bool", SmithyGoDependency.SMITHY_PTR).build(); writer.write( "params.$L = $T($L)", paramName, valueWrapper, staticParam.getValue()); } else if (param.getType() == ParameterType.STRING) { valueWrapper = SymbolUtils.createValueSymbolBuilder( "String", SmithyGoDependency.SMITHY_PTR).build(); writer.write( "params.$L = $T($L)", paramName, valueWrapper, String.format( "\"%s\"", staticParam.getValue() )); } else { throw new CodegenException( String.format("unexpected static context param type: %s", param.getType())); } } } }); writer.write(""); }; } private GoWriter.Writable generateEndpointResolution() { return goTemplate( """ var resolvedEndpoint $endpointType:T resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) if err != nil { return out, metadata, $errorType:T(\"failed to resolve service endpoint, %w\", err) } req.URL = &resolvedEndpoint.URI for k := range resolvedEndpoint.Headers { req.Header.Set( k, resolvedEndpoint.Headers.Get(k), ) } """, MapUtils.of( "endpointType", SymbolUtils.createValueSymbolBuilder( "Endpoint", SmithyGoDependency.SMITHY_ENDPOINTS ).build(), "errorType", SymbolUtils.createValueSymbolBuilder("Errorf", SmithyGoDependency.FMT).build() ) ); } private GoWriter.Writable generatePostEndpointResolutionHook( GoSettings settings, Model model, OperationShape operation ) { return (GoWriter writer) -> { for (GoIntegration integration : this.integrations) { integration.renderPostEndpointResolutionHook(settings, writer, model, Optional.of(operation)); } }; } private GoWriter.Writable generateMiddlewareAdder( Parameters parameters, String operationName, Optional<ClientContextParamsTrait> clientContextParamsTrait) { return (GoWriter writer) -> { writer.write( """ func $L(stack $P, options Options) error { return stack.Serialize.Insert(&$L{ EndpointResolver: options.EndpointResolverV2, $W $W }, \"ResolveEndpoint\", middleware.After) } """, SymbolUtils.createValueSymbolBuilder(getAddEndpointMiddlewareFuncName(operationName)).build(), SymbolUtils.createPointableSymbolBuilder("Stack", SmithyGoDependency.SMITHY_MIDDLEWARE).build(), SymbolUtils.createValueSymbolBuilder(getMiddlewareObjectName(operationName)).build(), generateBuiltInInitialization(parameters), generateClientContextParamInitialization(parameters, clientContextParamsTrait) ); }; } private GoWriter.Writable generateBuiltInInitialization(Parameters parameters) { return (GoWriter writer) -> { for (Iterator<Parameter> iter = parameters.iterator(); iter.hasNext();) { if (iter.next().getBuiltIn().isPresent()) { for (GoIntegration integration : this.integrations) { var builtInHandlerOpt = integration.getEndpointBuiltinHandler(); if (builtInHandlerOpt.isPresent()) { builtInHandlerOpt.get().renderEndpointBuiltInInitialization(writer, parameters); } } break; } } }; } private GoWriter.Writable generateClientContextParamInitialization( Parameters parameters, Optional<ClientContextParamsTrait> clientContextParamsTrait) { return (GoWriter writer) -> { if (clientContextParamsTrait.isPresent()) { var clientContextParams = clientContextParamsTrait.get(); parameters.forEach(param -> { if ( clientContextParams.getParameters().containsKey(param.getName().getName().getValue()) && !param.getBuiltIn().isPresent() ) { var name = getExportedParameterName(param); writer.write("$L: options.$L,", name, name); } }); } }; } public static String getAddEndpointMiddlewareFuncName(String operationName) { return String.format("add%sResolveEndpointMiddleware", operationName); } public static String getMiddlewareObjectName(String operationName) { return String.format("op%sResolveEndpointMiddleware", operationName); } public static String getExportedParameterName(Parameter parameter) { return StringUtils.capitalize(parameter.getName().getName().getValue()); } public static Symbol parameterAsSymbol(Parameter parameter) { return switch (parameter.getType()) { case STRING -> SymbolUtils.createPointableSymbolBuilder("string") .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true).build(); case BOOLEAN -> SymbolUtils.createPointableSymbolBuilder("bool") .putProperty(SymbolUtils.GO_UNIVERSE_TYPE, true).build(); }; } public static Builder builder() { return new Builder(); } public static final class Builder implements SmithyBuilder<EndpointMiddlewareGenerator> { List<GoIntegration> integrations; private Builder() { } public Builder integrations(List<GoIntegration> integrations) { this.integrations = integrations; return this; } @Override public EndpointMiddlewareGenerator build() { return new EndpointMiddlewareGenerator(this); } } }
8,982
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/endpoints/EndpointResolutionGenerator.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen.endpoints; import java.util.ArrayList; import java.util.List; import java.util.Optional; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.go.codegen.SmithyGoDependency; import software.amazon.smithy.go.codegen.SymbolUtils; import software.amazon.smithy.go.codegen.integration.ProtocolGenerator; import software.amazon.smithy.rulesengine.language.EndpointRuleSet; import software.amazon.smithy.rulesengine.traits.EndpointRuleSetTrait; import software.amazon.smithy.rulesengine.traits.EndpointTestCase; import software.amazon.smithy.rulesengine.traits.EndpointTestsTrait; /** * Generates all components required for Smithy Ruleset Endpoint Resolution. * These components include a Provider, Parameters, and Tests. */ public class EndpointResolutionGenerator { public static final String FEATURE_NAME = "V2"; public static final String PARAMETERS_TYPE_NAME = "EndpointParameters"; public static final String RESOLVER_INTERFACE_NAME = "Endpoint" + "Resolver" + FEATURE_NAME; public static final String RESOLVER_IMPLEMENTATION_NAME = "resolver"; public static final String RESOLVER_ENDPOINT_METHOD_NAME = "ResolveEndpoint"; public static final String NEW_RESOLVER_FUNC_NAME = "NewDefault" + RESOLVER_INTERFACE_NAME; private final FnProvider fnProvider; private final Symbol endpointType; private final Symbol parametersType; private final Symbol resolverInterfaceType; private final Symbol resolverImplementationType; private final Symbol newResolverFn; public EndpointResolutionGenerator(FnProvider fnProvider) { this.fnProvider = fnProvider; this.endpointType = SymbolUtils.createValueSymbolBuilder("Endpoint", SmithyGoDependency.SMITHY_ENDPOINTS).build(); this.parametersType = SymbolUtils.createValueSymbolBuilder(PARAMETERS_TYPE_NAME).build(); this.resolverInterfaceType = SymbolUtils.createValueSymbolBuilder(RESOLVER_INTERFACE_NAME).build(); this.resolverImplementationType = SymbolUtils.createValueSymbolBuilder(RESOLVER_IMPLEMENTATION_NAME).build(); this.newResolverFn = SymbolUtils.createValueSymbolBuilder(NEW_RESOLVER_FUNC_NAME).build(); } public void generate(ProtocolGenerator.GenerationContext context) { var serviceShape = context.getService(); var parametersGenerator = EndpointParametersGenerator.builder() .parametersType(parametersType) .build(); var resolverGenerator = EndpointResolverGenerator.builder() .parametersType(parametersType) .resolverInterfaceType(resolverInterfaceType) .resolverImplementationType(resolverImplementationType) .newResolverFn(newResolverFn) .endpointType(endpointType) .resolveEndpointMethodName(RESOLVER_ENDPOINT_METHOD_NAME) .fnProvider(this.fnProvider) .build(); var middlewareGenerator = EndpointMiddlewareGenerator.builder() .integrations(context.getIntegrations()) .build(); Optional<EndpointRuleSet> ruleset = serviceShape.getTrait(EndpointRuleSetTrait.class) .map( (trait) -> EndpointRuleSet.fromNode(trait.getRuleSet()) ); context.getWriter() .map( (writer) -> writer.write("$W", parametersGenerator.generate(ruleset)) ); context.getWriter() .map( (writer) -> writer.write("$W", resolverGenerator.generate(ruleset)) ); middlewareGenerator.generate( context.getSettings(), context.getModel(), context.getSymbolProvider(), context.getDelegator()); } public void generateTests(ProtocolGenerator.GenerationContext context) { var serviceShape = context.getService(); Optional<EndpointRuleSet> ruleset = serviceShape.getTrait(EndpointRuleSetTrait.class) .map( (trait) -> EndpointRuleSet.fromNode(trait.getRuleSet()) ); var testsGenerator = EndpointTestsGenerator.builder() .parametersType(parametersType) .newResolverFn(newResolverFn) .endpointType(endpointType) .resolveEndpointMethodName(RESOLVER_ENDPOINT_METHOD_NAME) .build(); final List<EndpointTestCase> testCases = new ArrayList<>(); var endpointTestTrait = serviceShape.getTrait(EndpointTestsTrait.class); endpointTestTrait.ifPresent(trait -> testCases.addAll(trait.getTestCases())); context.getWriter() .map( (writer) -> { return writer.write("$W", testsGenerator.generate(ruleset, testCases)); } ); } }
8,983
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/integration/RuntimeClientPlugin.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen.integration; import java.util.Collection; import java.util.HashSet; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.BiPredicate; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.utils.SmithyBuilder; import software.amazon.smithy.utils.ToSmithyBuilder; /** * Represents a runtime plugin for a client that hooks into various aspects * of Go code generation, including adding configuration settings * to clients and middleware plugins to both clients and commands. * * <p>These runtime client plugins are registered through the * {@link GoIntegration} SPI and applied to the code generator at * build-time. */ public final class RuntimeClientPlugin implements ToSmithyBuilder<RuntimeClientPlugin> { private final BiPredicate<Model, ServiceShape> servicePredicate; private final OperationPredicate operationPredicate; private final Set<ConfigField> configFields; private final Set<ConfigFieldResolver> configFieldResolvers; private final Set<ClientMember> clientMembers; private final Set<ClientMemberResolver> clientMemberResolvers; private final MiddlewareRegistrar registerMiddleware; private RuntimeClientPlugin(Builder builder) { operationPredicate = builder.operationPredicate; servicePredicate = builder.servicePredicate; configFields = builder.configFields; registerMiddleware = builder.registerMiddleware; clientMembers = builder.clientMembers; clientMemberResolvers = builder.clientMemberResolvers; configFieldResolvers = builder.configFieldResolvers; } @FunctionalInterface public interface OperationPredicate { /** * Tests if middleware is applied to an individual operation. * * @param model Model the operation belongs to. * @param service Service the operation belongs to. * @param operation Operation to test. * @return Returns true if middleware should be applied to the operation. */ boolean test(Model model, ServiceShape service, OperationShape operation); } /** * Gets the config fields that will be added to the client config by this plugin. * @return the config field resolvers. */ public Set<ConfigFieldResolver> getConfigFieldResolvers() { return configFieldResolvers; } /** * Gets the client members that will be added to the client structure by this plugin. * @return the client member resolvers. */ public Set<ClientMemberResolver> getClientMemberResolvers() { return clientMemberResolvers; } /** * Gets the optionally present middleware registrar object that resolves to middleware registering function. * * @return Returns the optionally present MiddlewareRegistrar object. */ public Optional<MiddlewareRegistrar> registerMiddleware() { return Optional.ofNullable(registerMiddleware); } /** * Returns true if this plugin applies to the given service. * * <p>By default, a plugin applies to all services but not to specific * commands. You an configure a plugin to apply only to a subset of * services (for example, only apply to a known service or a service * with specific traits) or to no services at all (for example, if * the plugin is meant to by command-specific and not on every * command executed by the service). * * @param model The model the service belongs to. * @param service Service shape to test against. * @return Returns true if the plugin is applied to the given service. * @see #matchesOperation(Model, ServiceShape, OperationShape) */ public boolean matchesService(Model model, ServiceShape service) { return servicePredicate.test(model, service); } /** * Returns true if this plugin applies to the given operation. * * @param model Model the operation belongs to. * @param service Service the operation belongs to. * @param operation Operation to test against. * @return Returns true if the plugin is applied to the given operation. * @see #matchesService(Model, ServiceShape) */ public boolean matchesOperation(Model model, ServiceShape service, OperationShape operation) { return operationPredicate.test(model, service, operation); } /** * Gets the config fields that will be added to the client config by this plugin. * * <p>Each config field will be added to the client's Config object and will * result in a corresponding getter method being added to the config. E.g.: * <p> * type ClientOptions struct { * // My docs. * MyField string * } * <p> * func (o ClientOptions) GetMyField() string { * return o.MyField * } * * @return Returns the config fields to add to the client config. */ public Set<ConfigField> getConfigFields() { return configFields; } /** * Gets the client member fields that will be added to the client structure by this plugin. * * <p>Each client member field will be added to the client's structure. * E.g.: * <p> * type Client struct { * * options Options * * // My cache. * cache map[string]string * } * <p> * * @return Returns the client members to add to the client structure. */ public Set<ClientMember> getClientMembers() { return clientMembers; } public static Builder builder() { return new Builder(); } @Override public SmithyBuilder<RuntimeClientPlugin> toBuilder() { return builder() .clientMemberResolvers(clientMemberResolvers) .configFieldResolvers(configFieldResolvers) .servicePredicate(servicePredicate) .operationPredicate(operationPredicate) .registerMiddleware(registerMiddleware); } /** * Builds a {@code RuntimeClientPlugin}. */ public static final class Builder implements SmithyBuilder<RuntimeClientPlugin> { private BiPredicate<Model, ServiceShape> servicePredicate = (model, service) -> true; private OperationPredicate operationPredicate = (model, service, operation) -> false; private Set<ConfigField> configFields = new HashSet<>(); private Set<ConfigFieldResolver> configFieldResolvers = new HashSet<>(); private Set<ClientMember> clientMembers = new HashSet<>(); private Set<ClientMemberResolver> clientMemberResolvers = new HashSet<>(); private MiddlewareRegistrar registerMiddleware; @Override public RuntimeClientPlugin build() { return new RuntimeClientPlugin(this); } /** * Registers middleware into the operation middleware stack. * * @param registerMiddleware resolved middleware registrar to set. * @return Returns the builder. */ public Builder registerMiddleware(MiddlewareRegistrar registerMiddleware) { this.registerMiddleware = registerMiddleware; return this; } /** * Sets a predicate that determines if the plugin applies to a * specific operation. * * <p>When this method is called, the {@code servicePredicate} is * automatically configured to return false for every service. * * <p>By default, a plugin applies globally to a service, which thereby * applies to every operation when the middleware stack is copied. * * @param operationPredicate Operation matching predicate. * @return Returns the builder. * @see #servicePredicate(BiPredicate) */ public Builder operationPredicate(OperationPredicate operationPredicate) { this.operationPredicate = Objects.requireNonNull(operationPredicate); servicePredicate = (model, service) -> false; return this; } /** * Configures a predicate that makes a plugin only apply to a set of * operations that match one or more of the set of given shape names, * and ensures that the plugin is not applied globally to services. * * <p>By default, a plugin applies globally to a service, which thereby * applies to every operation when the middleware stack is copied. * * @param operationNames Set of operation names. * @return Returns the builder. */ public Builder appliesOnlyToOperations(Set<String> operationNames) { operationPredicate((model, service, operation) -> operationNames.contains(operation.getId().getName())); return servicePredicate((model, service) -> false); } /** * Configures a predicate that applies the plugin to a service if the * predicate matches a given model and service. * * <p>When this method is called, the {@code operationPredicate} is * automatically configured to return false for every operation, * causing the plugin to only apply to services and not to individual * operations. * * <p>By default, a plugin applies globally to a service, which * thereby applies to every operation when the middleware stack is * copied. Setting a custom service predicate is useful for plugins * that should only be applied to specific services or only applied * at the operation level. * * @param servicePredicate Service predicate. * @return Returns the builder. */ public Builder servicePredicate(BiPredicate<Model, ServiceShape> servicePredicate) { this.servicePredicate = Objects.requireNonNull(servicePredicate); operationPredicate = (model, service, operation) -> false; return this; } /** * Sets the config fields that will be added to the client config by this plugin. * * <p>Each config field will be added to the client's Config object and will * result in a corresponding getter method being added to the config. E.g.: * <p> * type ClientOptions struct { * // My docs. * MyField string * } * <p> * func (o ClientOptions) GetMyField() string { * return o.MyField * } * * @param configFields The config fields to add to the client config. * @return Returns the builder. */ public Builder configFields(Collection<ConfigField> configFields) { this.configFields = new HashSet<>(configFields); return this; } /** * Adds a config field that will be added to the client config by this plugin. * * <p>Each config field will be added to the client's Config object and will * result in a corresponding getter method being added to the config. E.g.: * <p> * type ClientOptions struct { * // My docs. * MyField string * } * <p> * func (o ClientOptions) GetMyField() string { * return o.MyField * } * * @param configField The config field to add to the client config. * @return Returns the builder. */ public Builder addConfigField(ConfigField configField) { this.configFields.add(configField); return this; } /** * Sets the config field resolvers that will be added to the client by this plugin. * * @param configFieldResolvers The config field resolvers. * @return Returns the builder. */ public Builder configFieldResolvers(Collection<ConfigFieldResolver> configFieldResolvers) { this.configFieldResolvers = new HashSet<>(configFieldResolvers); return this; } /** * Adds a config field resolver that will be added to the client by this plugin. * * @param configFieldResolver The config field resolver. * @return Returns the builder. */ public Builder addConfigFieldResolver(ConfigFieldResolver configFieldResolver) { this.configFieldResolvers.add(configFieldResolver); return this; } /** * Sets the client member fields that will be added to the client struct * by this plugin. * * <p>Each client member field will be added to the client's struct. * E.g.: * <p> * type Client struct { * option Options * * // My cache added using plugin * cache map[string]string * } * <p> * * @param clientMembers The client members to add on the client. * @return Returns the builder. */ public Builder clientMembers(Collection<ClientMember> clientMembers) { this.clientMembers = new HashSet<>(clientMembers); return this; } /** * Adds a client member that will be added to the client structure by this plugin. * * <p>Each client member field will be added to the client's structure. * E.g.: * <p> * type Client struct { * option Options * * // my cache added using plugin * cache map[string]string * } * * @param clientMember The clientMember to add to the client structure. * @return Returns the builder. */ public Builder addClientMember(ClientMember clientMember) { this.clientMembers.add(clientMember); return this; } /** * Sets the client member resolvers that will be added to the client by this plugin. * * @param clientMemberResolvers The client member resolvers. * @return Returns the builder. */ public Builder clientMemberResolvers(Collection<ClientMemberResolver> clientMemberResolvers) { this.clientMemberResolvers = new HashSet<>(clientMemberResolvers); return this; } /** * Adds a client member resolver that will be added to the client by this plugin. * * @param clientMemberResolver The client member resolver. * @return Returns the builder. */ public Builder addClientMemberResolver(ClientMemberResolver clientMemberResolver) { this.clientMemberResolvers.add(clientMemberResolver); return this; } } }
8,984
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/integration/DocumentShapeDeserVisitor.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen.integration; import java.util.Collections; import java.util.Map; import java.util.function.BiConsumer; import java.util.stream.Collectors; import software.amazon.smithy.codegen.core.CodegenException; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.codegen.core.SymbolProvider; import software.amazon.smithy.go.codegen.GoWriter; import software.amazon.smithy.go.codegen.SmithyGoDependency; import software.amazon.smithy.go.codegen.integration.ProtocolGenerator.GenerationContext; import software.amazon.smithy.model.shapes.CollectionShape; import software.amazon.smithy.model.shapes.DocumentShape; import software.amazon.smithy.model.shapes.ListShape; import software.amazon.smithy.model.shapes.MapShape; import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.ResourceShape; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.SetShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeVisitor; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.shapes.UnionShape; /** * Visitor to generate deserialization functions for shapes in protocol document bodies. * <p> * Visitor methods for aggregate types except maps and collections are final and will * generate functions that dispatch their loading from the body to the matching abstract method. * <p> * Visitor methods for all other types will default to not generating deserialization * functions. This may be overwritten by downstream implementations if the protocol requires * more complex deserialization strategies for those types. * <p> * The standard implementation is as follows; no assumptions are made about the protocol * being generated for. * * <ul> * <li>Service, Operation, Resource: no function generated. <b>Not overridable.</b></li> * <li>Document, List, Map, Set, Structure, Union: generates a deserialization function. * <b>Not overridable.</b></li> * <li>All other types: no function generated. <b>May be overridden.</b></li> * </ul> */ public abstract class DocumentShapeDeserVisitor extends ShapeVisitor.Default<Void> { public interface DeserializerNameProvider { String getName(Shape shape, ServiceShape service, String protocol); } private final GenerationContext context; private final DeserializerNameProvider deserializerNameProvider; public DocumentShapeDeserVisitor(GenerationContext context) { this(context, null); } public DocumentShapeDeserVisitor(GenerationContext context, DeserializerNameProvider deserializerNameProvider) { this.context = context; this.deserializerNameProvider = deserializerNameProvider; } /** * Gets the generation context. * * @return The generation context. */ protected final GenerationContext getContext() { return context; } @Override protected Void getDefault(Shape shape) { return null; } /** * Writes the code needed to deserialize a collection in the document of a response. * * <p>Implementations of this method are expected to generate a function body that * returns the type generated for the CollectionShape {@code shape} parameter. * * <p>For example, given the following Smithy model: * * <pre>{@code * list ParameterList { * member: Parameter * } * }</pre> * * <p>The function signature for this body will return only {@code error} and have at * least one parameter in scope: * <ul> * <li>{@code v *[]*string}: a pointer to the location the resulting list should be deserialized to.</li> * </ul> * * <p>It will also have any parameters in scope as defined by {@code getAdditionalArguments}. * For json, for instance, you may want to pass around a {@code *json.Decoder} to handle parsing * the json. * * <p>The function could end up looking like: * * <pre>{@code * func myProtocol_deserializeDocumentParameterList(v *[]*types.Parameter, decoder *json.Decoder) error { * if v == nil { * return fmt.Errorf("unexpected nil of type %T", v) * } * startToken, err := decoder.Token() * if err == io.EOF { * return nil * } * if err != nil { * return err * } * if startToken == nil { * return nil * } * if t, ok := startToken.(json.Delim); !ok || t != '[' { * return fmt.Errorf("expect `[` as start token") * } * * var cv []*types.Parameter * if *v == nil { * cv = []*types.Parameter{} * } else { * cv = *v * } * * for decoder.More() { * var col *types.Parameter * if err := myProtocol_deserializeDocumentParameter(&col, decoder); err != nil { * return err * } * cv = append(cv, col) * } * * endToken, err := decoder.Token() * if err != nil { * return err * } * if t, ok := endToken.(json.Delim); !ok || t != ']' { * return fmt.Errorf("expect `]` as end token") * } * * *v = cv * return nil * } * }</pre> * * @param context The generation context. * @param shape The collection shape being generated. */ protected abstract void deserializeCollection(GenerationContext context, CollectionShape shape); /** * Writes the code needed to deserialize a document shape in the document of a response. * * <p>Implementations of this method are expected to generate a function body that * returns the type generated for the DocumentShape {@code shape} parameter. * * <p>For example, given the following Smithy model: * * <pre>{@code * document FooDocument * }</pre> * * <p>The function signature for this body will return only {@code error} and have at * least one parameter in scope: * <ul> * <li>{@code v *Document}: a pointer to the location the resulting document should be deserialized to.</li> * </ul> * * <p>It will also have any parameters in scope as defined by {@code getAdditionalArguments}. * For json, for instance, you may want to pass around a {@code *json.Decoder} to handle parsing * the json. * * @param context The generation context. * @param shape The document shape being generated. */ protected abstract void deserializeDocument(GenerationContext context, DocumentShape shape); /** * Writes the code needed to deserialize a map in the document of a response. * * <p>Implementations of this method are expected to generate a function body that * returns the type generated for the MapShape {@code shape} parameter. * * <p>For example, given the following Smithy model: * * <pre>{@code * map c { * key: String, * value: Field * } * }</pre> * * <p>The function signature for this body will return only {@code error} and have at * least one parameter in scope: * <ul> * <li>{@code v *map[string]*types.FieldMap}: a pointer to the location the resulting map should * be deserialized to.</li> * </ul> * * <p>It will also have any parameters in scope as defined by {@code getAdditionalArguments}. * For json, for instance, you may want to pass around a {@code *json.Decoder} to handle parsing * the json. * * <p>The function could end up looking like: * * <pre>{@code * func myProtocol_deserializeDocumentFieldMap(v *map[string]*types.FieldMap, decoder *json.Decoder) error { * if v == nil { * return fmt.Errorf("unexpected nil of type %T", v) * } * startToken, err := decoder.Token() * if err == io.EOF { * return nil * } * if err != nil { * return err * } * if startToken == nil { * return nil * } * if t, ok := startToken.(json.Delim); !ok || t != '{' { * return fmt.Errorf("expect `{` as start token") * } * * var mv map[string]*types.FieldMap * if *v == nil { * mv = map[string]*types.FieldMap{} * } else { * mv = *v * } * * for decoder.More() { * token, err := decoder.Token() * if err != nil { * return err * } * * key, ok := token.(string) * if !ok { * return fmt.Errorf("expected map-key of type string, found type %T", token) * } * * var parsedVal *types.FieldMap * if err := myProtocol_deserializeDocumentFieldMap(&parsedVal, decoder); err != nil { * return err * } * mv[key] = parsedVal * * } * endToken, err := decoder.Token() * if err != nil { * return err * } * if t, ok := endToken.(json.Delim); !ok || t != '}' { * return fmt.Errorf("expect `}` as end token") * } * * *v = mv * return nil * } * }</pre> * * @param context The generation context. * @param shape The map shape being generated. */ protected abstract void deserializeMap(GenerationContext context, MapShape shape); /** * Writes the code needed to deserialize a structure in the document of a response. * * <p>Implementations of this method are expected to generate a function body that * returns the type generated for the StructureShape {@code shape} parameter. * * <p>For example, given the following Smithy model: * * <pre>{@code * structure Field { * FooValue: Foo, * BarValue: String, * } * }</pre> * * <p>The function signature for this body will return only {@code error} and have at * least one parameter in scope: * <ul> * <li>{@code v **types.Field}: a pointer to the location the resulting structure should be deserialized to.</li> * </ul> * * <p>It will also have any parameters in scope as defined by {@code getAdditionalArguments}. * For json, for instance, you may want to pass around a {@code *json.Decoder} to handle parsing * the json. * * <p>The function could end up looking like: * * <pre>{@code * func myProtocol_deserializeDocumentField(v **types.Field, decoder *json.Decoder) error { * if v == nil { * return fmt.Errorf("unexpected nil of type %T", v) * } * startToken, err := decoder.Token() * if err == io.EOF { * return nil * } * if err != nil { * return err * } * if startToken == nil { * return nil * } * if t, ok := startToken.(json.Delim); !ok || t != '{' { * return fmt.Errorf("expect `{` as start token") * } * * var sv *types.KitchenSink * if *v == nil { * sv = &types.KitchenSink{} * } else { * sv = *v * } * * for decoder.More() { * t, err := decoder.Token() * if err != nil { * return err * } * switch t { * case "FooValue": * if err := myProtocol_deserializeDocumentFoo(&sv.FooValue, decoder); err != nil { * return err * } * case "BarValue": * val, err := decoder.Token() * if err != nil { * return err * } * if val != nil { * jtv, ok := val.(string) * if !ok { * return fmt.Errorf("expected String to be of type string, got %T instead", val) * } * sv.BarValue = &jtv * } * default: * // Discard the unknown * } * } * endToken, err := decoder.Token() * if err != nil { * return err * } * if t, ok := endToken.(json.Delim); !ok || t != '}' { * return fmt.Errorf("expect `}` as end token") * } * *v = sv * return nil * } * }</pre> * * @param context The generation context. * @param shape The structure shape being generated. */ protected abstract void deserializeStructure(GenerationContext context, StructureShape shape); /** * Writes the code needed to deserialize a union in the document of a response. * * <p>Implementations of this method are expected to generate a function body that * returns the type generated for the UnionShape {@code shape} parameter. * * <pre>{@code * union Field { * fooValue: Foo, * barValue: String, * } * }</pre> * * <p>The function signature for this body will return only {@code error} and have at * least one parameter in scope: * <ul> * <li>{@code v *Field}: a pointer to the location the resulting union should be deserialized to.</li> * </ul> * * <p>It will also have any parameters in scope as defined by {@code getAdditionalArguments}. * For json, for instance, you may want to pass around a {@code *json.Decoder} to handle parsing * the json. * * @param context The generation context. * @param shape The union shape being generated. */ protected abstract void deserializeUnion(GenerationContext context, UnionShape shape); /** * Generates a function for deserializing the output shape, dispatching body handling * to the supplied function. * * @param shape The shape to generate a deserializer for. * @param functionBody An implementation that will generate a function body to * deserialize the shape. */ protected final void generateDeserFunction( Shape shape, BiConsumer<GenerationContext, Shape> functionBody ) { SymbolProvider symbolProvider = context.getSymbolProvider(); GoWriter writer = context.getWriter().get(); Symbol symbol = symbolProvider.toSymbol(shape); final String functionName; if (this.deserializerNameProvider != null) { functionName = deserializerNameProvider.getName(shape, context.getService(), context.getProtocolName()); } else { functionName = ProtocolGenerator.getDocumentDeserializerFunctionName( shape, context.getService(), context.getProtocolName()); } String additionalArguments = getAdditionalArguments().entrySet().stream() .map(entry -> String.format(", %s %s", entry.getKey(), entry.getValue())) .collect(Collectors.joining()); writer.openBlock("func $L(v *$P$L) error {", "}", functionName, symbol, additionalArguments, () -> { writer.addUseImports(SmithyGoDependency.FMT); writer.openBlock("if v == nil {", "}", () -> { writer.write("return fmt.Errorf(\"unexpected nil of type %T\", v)"); }); functionBody.accept(context, shape); }).write(""); } /** * Gets any additional arguments needed for every deserializer function. * * @return a map of argument name to argument type. */ protected Map<String, String> getAdditionalArguments() { return Collections.emptyMap(); } @Override public final Void operationShape(OperationShape shape) { throw new CodegenException("Operation shapes cannot be bound to documents."); } @Override public final Void resourceShape(ResourceShape shape) { throw new CodegenException("Resource shapes cannot be bound to documents."); } @Override public final Void serviceShape(ServiceShape shape) { throw new CodegenException("Service shapes cannot be bound to documents."); } /** * Dispatches to create the body of document shape deserilization functions. * * @param shape The document shape to generate deserialization for. * @return null */ @Override public final Void documentShape(DocumentShape shape) { generateDeserFunction(shape, (c, s) -> deserializeDocument(c, s.asDocumentShape().get())); return null; } /** * Dispatches to create the body of list shape deserilization functions. * * @param shape The list shape to generate deserialization for. * @return null */ @Override public Void listShape(ListShape shape) { generateDeserFunction(shape, (c, s) -> deserializeCollection(c, s.asListShape().get())); return null; } /** * Dispatches to create the body of map shape deserilization functions. * * @param shape The map shape to generate deserialization for. * @return null */ @Override public Void mapShape(MapShape shape) { generateDeserFunction(shape, (c, s) -> deserializeMap(c, s.asMapShape().get())); return null; } /** * Dispatches to create the body of set shape deserilization functions. * * @param shape The set shape to generate deserialization for. * @return null */ @Override public Void setShape(SetShape shape) { generateDeserFunction(shape, (c, s) -> deserializeCollection(c, s.asSetShape().get())); return null; } /** * Dispatches to create the body of structure shape deserilization functions. * * @param shape The structure shape to generate deserialization for. * @return null */ @Override public final Void structureShape(StructureShape shape) { generateDeserFunction(shape, (c, s) -> deserializeStructure(c, s.asStructureShape().get())); return null; } /** * Dispatches to create the body of union shape deserilization functions. * * @param shape The union shape to generate deserialization for. * @return null */ @Override public final Void unionShape(UnionShape shape) { generateDeserFunction(shape, (c, s) -> deserializeUnion(c, s.asUnionShape().get())); return null; } }
8,985
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/integration/AddChecksumRequiredMiddleware.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen.integration; import java.util.List; import software.amazon.smithy.go.codegen.SmithyGoDependency; import software.amazon.smithy.go.codegen.SymbolUtils; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.traits.HttpChecksumRequiredTrait; import software.amazon.smithy.utils.ListUtils; /** * Adds middleware supporting httpChecksumRequired trait behavior. */ public class AddChecksumRequiredMiddleware implements GoIntegration { @Override public byte getOrder() { return 0; } @Override public List<RuntimeClientPlugin> getClientPlugins() { return ListUtils.of( RuntimeClientPlugin.builder() .operationPredicate(this::hasChecksumRequiredTrait) .registerMiddleware(MiddlewareRegistrar.builder() .resolvedFunction(SymbolUtils.createValueSymbolBuilder( "AddContentChecksumMiddleware", SmithyGoDependency.SMITHY_HTTP_TRANSPORT).build()) .build()) .build() ); } // return true if operation shape is decorated with `httpChecksumRequired` trait. private boolean hasChecksumRequiredTrait(Model model, ServiceShape service, OperationShape operation) { return operation.hasTrait(HttpChecksumRequiredTrait.class); } }
8,986
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/integration/ConfigFieldResolver.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen.integration; import java.util.Objects; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.utils.SmithyBuilder; /** * Represent symbol that points to a function that operates * on the client options during client construction or operation invocation. * <p> * Can target options prior customer mutation (Initialization), or after customer mutation (Finalization). * <p> * Any configuration that a plugin requires in order to function should be * checked in this function, either setting a default value if possible or * returning an error if not. */ public final class ConfigFieldResolver { private final Location location; private final Target target; private final Symbol resolver; private final boolean withOperationName; private final boolean withClientInput; private ConfigFieldResolver(Builder builder) { location = SmithyBuilder.requiredState("location", builder.location); target = SmithyBuilder.requiredState("target", builder.target); resolver = SmithyBuilder.requiredState("resolver", builder.resolver); withOperationName = builder.withOperationName; withClientInput = builder.withClientInput; } public Location getLocation() { return location; } public Target getTarget() { return target; } public Symbol getResolver() { return resolver; } public boolean isWithOperationName() { return withOperationName && location == Location.OPERATION; } public boolean isWithClientInput() { return withClientInput; } public static Builder builder() { return new Builder(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ConfigFieldResolver that = (ConfigFieldResolver) o; return location == that.location && target == that.target && resolver.equals(that.resolver) && withOperationName == that.withOperationName && withClientInput == that.withClientInput; } /** * Returns a hash code value for the object. * * @return the hash code. */ @Override public int hashCode() { return Objects.hash(location, target, resolver); } /** * The location where the resolver is executed. */ public enum Location { /** * Indicates that the resolver is executed in the client constructor. */ CLIENT, /** * Indicates that the resolver is executed during operation invocation. */ OPERATION } /** * Indicates the target of the resolver. */ public enum Target { /** * Indicates that the resolver targets config fields prior to customer mutation. */ INITIALIZATION, /** * Indicates that the resolver targets config fields after customer mutation. */ FINALIZATION } public static class Builder implements SmithyBuilder<ConfigFieldResolver> { private Location location; private Target target; private Symbol resolver; private boolean withOperationName = false; private boolean withClientInput = false; public Builder location(Location location) { this.location = location; return this; } public Builder target(Target target) { this.target = target; return this; } public Builder resolver(Symbol resolver) { this.resolver = resolver; return this; } public Builder withOperationName(boolean withOperationName) { this.withOperationName = withOperationName; return this; } public Builder withClientInput(boolean withClientInput) { this.withClientInput = withClientInput; return this; } @Override public ConfigFieldResolver build() { return new ConfigFieldResolver(this); } } }
8,987
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/integration/HttpBindingProtocolGenerator.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen.integration; import static software.amazon.smithy.go.codegen.integration.ProtocolUtils.requiresDocumentSerdeFunction; import java.util.Collection; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.TreeSet; import java.util.function.BiConsumer; import java.util.logging.Logger; import java.util.stream.Collectors; import software.amazon.smithy.codegen.core.CodegenException; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.codegen.core.SymbolProvider; import software.amazon.smithy.go.codegen.ApplicationProtocol; import software.amazon.smithy.go.codegen.CodegenUtils; import software.amazon.smithy.go.codegen.GoEventStreamIndex; import software.amazon.smithy.go.codegen.GoStackStepMiddlewareGenerator; import software.amazon.smithy.go.codegen.GoValueAccessUtils; import software.amazon.smithy.go.codegen.GoWriter; import software.amazon.smithy.go.codegen.SmithyGoDependency; import software.amazon.smithy.go.codegen.SymbolUtils; import software.amazon.smithy.go.codegen.knowledge.GoPointableIndex; import software.amazon.smithy.go.codegen.trait.NoSerializeTrait; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.knowledge.EventStreamIndex; import software.amazon.smithy.model.knowledge.EventStreamInfo; import software.amazon.smithy.model.knowledge.HttpBinding; import software.amazon.smithy.model.knowledge.HttpBindingIndex; import software.amazon.smithy.model.knowledge.TopDownIndex; import software.amazon.smithy.model.shapes.CollectionShape; import software.amazon.smithy.model.shapes.MapShape; import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; import software.amazon.smithy.model.shapes.ShapeType; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.shapes.ToShapeId; import software.amazon.smithy.model.shapes.UnionShape; import software.amazon.smithy.model.traits.EnumTrait; import software.amazon.smithy.model.traits.HttpTrait; import software.amazon.smithy.model.traits.MediaTypeTrait; import software.amazon.smithy.model.traits.StreamingTrait; import software.amazon.smithy.model.traits.TimestampFormatTrait; import software.amazon.smithy.model.traits.TimestampFormatTrait.Format; import software.amazon.smithy.utils.OptionalUtils; /** * Abstract implementation useful for all protocols that use HTTP bindings. */ public abstract class HttpBindingProtocolGenerator implements ProtocolGenerator { private static final Logger LOGGER = Logger.getLogger(HttpBindingProtocolGenerator.class.getName()); private final boolean isErrorCodeInBody; private final Set<Shape> serializeDocumentBindingShapes = new TreeSet<>(); private final Set<Shape> deserializeDocumentBindingShapes = new TreeSet<>(); private final Set<StructureShape> deserializingErrorShapes = new TreeSet<>(); /** * Creates a Http binding protocol generator. * * @param isErrorCodeInBody A boolean that indicates if the error code for the implementing protocol is located in * the error response body, meaning this generator will parse the body before attempting to * load an error code. */ public HttpBindingProtocolGenerator(boolean isErrorCodeInBody) { this.isErrorCodeInBody = isErrorCodeInBody; } @Override public ApplicationProtocol getApplicationProtocol() { return ApplicationProtocol.createDefaultHttpApplicationProtocol(); } @Override public void generateSharedSerializerComponents(GenerationContext context) { serializeDocumentBindingShapes.addAll(ProtocolUtils.resolveRequiredDocumentShapeSerde( context.getModel(), serializeDocumentBindingShapes)); generateDocumentBodyShapeSerializers(context, serializeDocumentBindingShapes); } /** * Get the operations with HTTP Bindings. * * @param context the generation context * @return the list of operation shapes */ public Set<OperationShape> getHttpBindingOperations(GenerationContext context) { TopDownIndex topDownIndex = context.getModel().getKnowledge(TopDownIndex.class); Set<OperationShape> containedOperations = new TreeSet<>(); for (OperationShape operation : topDownIndex.getContainedOperations(context.getService())) { OptionalUtils.ifPresentOrElse( operation.getTrait(HttpTrait.class), httpTrait -> containedOperations.add(operation), () -> LOGGER.warning(String.format( "Unable to fetch %s protocol request bindings for %s because it does not have an " + "http binding trait", getProtocol(), operation.getId())) ); } return containedOperations; } @Override public void generateRequestSerializers(GenerationContext context) { Set<OperationShape> operations = getHttpBindingOperations(context); for (OperationShape operation : operations) { generateOperationSerializer(context, operation); } GoEventStreamIndex goEventStreamIndex = GoEventStreamIndex.of(context.getModel()); goEventStreamIndex.getInputEventStreams(context.getService()).ifPresent(shapeIdSetMap -> shapeIdSetMap.forEach((shapeId, eventStreamInfos) -> { generateEventStreamSerializers(context, context.getModel().expectShape(shapeId, UnionShape.class), eventStreamInfos); })); } /** * Generate the event stream serializers for the given event stream target and associated operations. * * @param context the generation context * @param eventUnion the event stream union * @param eventStreamInfos the event stream infos */ protected abstract void generateEventStreamSerializers( GenerationContext context, UnionShape eventUnion, Set<EventStreamInfo> eventStreamInfos ); /** * Generate the event stream deserializers for the given event stream target and asscioated operations. * * @param context the generation context * @param eventUnion the event stream union * @param eventStreamInfos the event stream infos */ protected abstract void generateEventStreamDeserializers( GenerationContext context, UnionShape eventUnion, Set<EventStreamInfo> eventStreamInfos ); /** * Gets the default serde format for timestamps. * * @return Returns the default format. */ protected abstract Format getDocumentTimestampFormat(); /** * Gets the default content-type when a document is synthesized in the body. * * @return Returns the default content-type. */ protected abstract String getDocumentContentType(); private void generateOperationSerializer(GenerationContext context, OperationShape operation) { generateOperationSerializerMiddleware(context, operation); generateOperationHttpBindingSerializer(context, operation); Optional<EventStreamInfo> streamInfo = EventStreamIndex.of(context.getModel()).getInputInfo(operation); if (!CodegenUtils.isStubSynthetic(ProtocolUtils.expectInput(context.getModel(), operation)) && streamInfo.isEmpty()) { generateOperationDocumentSerializer(context, operation); addOperationDocumentShapeBindersForSerializer(context, operation); } } /** * Generates the operation document serializer function. * * @param context the generation context * @param operation the operation shape being generated */ protected abstract void generateOperationDocumentSerializer(GenerationContext context, OperationShape operation); /** * Adds the top-level shapes from the operation that bind to the body document that require serializer functions. * * @param context the generator context * @param operation the operation to add document binders from */ private void addOperationDocumentShapeBindersForSerializer(GenerationContext context, OperationShape operation) { Model model = context.getModel(); // Walk and add members shapes to the list that will require serializer functions Collection<HttpBinding> bindings = HttpBindingIndex.of(model) .getRequestBindings(operation).values(); for (HttpBinding binding : bindings) { MemberShape memberShape = binding.getMember(); Shape targetShape = model.expectShape(memberShape.getTarget()); // Check if the input shape has a members that target the document or payload and require serializers. // If an operation has an input event stream it will have seperate serializers generated. if (requiresDocumentSerdeFunction(targetShape) && (binding.getLocation() == HttpBinding.Location.DOCUMENT || binding.getLocation() == HttpBinding.Location.PAYLOAD)) { serializeDocumentBindingShapes.add(targetShape); } } } private void generateOperationSerializerMiddleware(GenerationContext context, OperationShape operation) { SymbolProvider symbolProvider = context.getSymbolProvider(); Model model = context.getModel(); ServiceShape service = context.getService(); Shape inputShape = model.expectShape(operation.getInput() .orElseThrow(() -> new CodegenException("expect input shape for operation: " + operation.getId()))); Symbol inputSymbol = symbolProvider.toSymbol(inputShape); ApplicationProtocol applicationProtocol = getApplicationProtocol(); Symbol requestType = applicationProtocol.getRequestType(); HttpTrait httpTrait = operation.expectTrait(HttpTrait.class); GoStackStepMiddlewareGenerator middleware = GoStackStepMiddlewareGenerator.createSerializeStepMiddleware( ProtocolGenerator.getSerializeMiddlewareName(operation.getId(), service, getProtocolName()), ProtocolUtils.OPERATION_SERIALIZER_MIDDLEWARE_ID); middleware.writeMiddleware(context.getWriter().get(), (generator, writer) -> { writer.addUseImports(SmithyGoDependency.FMT); writer.addUseImports(SmithyGoDependency.SMITHY); writer.addUseImports(SmithyGoDependency.SMITHY_HTTP_BINDING); // cast input request to smithy transport type, check for failures writer.write("request, ok := in.Request.($P)", requestType); writer.openBlock("if !ok {", "}", () -> { writer.write("return out, metadata, " + "&smithy.SerializationError{Err: fmt.Errorf(\"unknown transport type %T\", in.Request)}" ); }); writer.write(""); // cast input parameters type to the input type of the operation writer.write("input, ok := in.Parameters.($P)", inputSymbol); writer.write("_ = input"); writer.openBlock("if !ok {", "}", () -> { writer.write("return out, metadata, " + "&smithy.SerializationError{Err: fmt.Errorf(\"unknown input parameters type %T\"," + " in.Parameters)}"); }); writer.write(""); writer.write("opPath, opQuery := httpbinding.SplitURI($S)", httpTrait.getUri()); writer.write("request.URL.Path = smithyhttp.JoinPath(request.URL.Path, opPath)"); writer.write("request.URL.RawQuery = smithyhttp.JoinRawQuery(request.URL.RawQuery, opQuery)"); writer.write("request.Method = $S", httpTrait.getMethod()); writer.write( """ var restEncoder $P if request.URL.RawPath == "" { restEncoder, err = $T(request.URL.Path, request.URL.RawQuery, request.Header) } else { request.URL.RawPath = $T(request.URL.RawPath, opPath) restEncoder, err = $T(request.URL.Path, request.URL.RawPath, request.URL.RawQuery, request.Header) } """, SymbolUtils.createPointableSymbolBuilder( "Encoder", SmithyGoDependency.SMITHY_HTTP_BINDING).build(), SymbolUtils.createValueSymbolBuilder( "NewEncoder", SmithyGoDependency.SMITHY_HTTP_BINDING).build(), SymbolUtils.createValueSymbolBuilder( "JoinPath", SmithyGoDependency.SMITHY_HTTP_TRANSPORT).build(), SymbolUtils.createValueSymbolBuilder( "NewEncoderWithRawPath", SmithyGoDependency.SMITHY_HTTP_BINDING).build() ); writer.openBlock("if err != nil {", "}", () -> { writer.write("return out, metadata, &smithy.SerializationError{Err: err}"); }); writer.write(""); // we only generate an operations http bindings function if there are bindings if (isOperationWithRestRequestBindings(model, operation)) { String serFunctionName = ProtocolGenerator.getOperationHttpBindingsSerFunctionName( inputShape, service, getProtocolName()); writer.openBlock("if err := $L(input, restEncoder); err != nil {", "}", serFunctionName, () -> { writer.write("return out, metadata, &smithy.SerializationError{Err: err}"); }); writer.write(""); } // Don't consider serializing the body if the input shape is a stubbed synthetic clone, without an // archetype. if (!CodegenUtils.isStubSynthetic(ProtocolUtils.expectInput(model, operation))) { Optional<EventStreamInfo> eventStreamInfo = EventStreamIndex.of(model).getInputInfo(operation); // document bindings vs payload bindings vs event streams HttpBindingIndex httpBindingIndex = HttpBindingIndex.of(model); boolean hasDocumentBindings = httpBindingIndex .getRequestBindings(operation, HttpBinding.Location.DOCUMENT) .stream().anyMatch(httpBinding -> eventStreamInfo.map(streamInfo -> !streamInfo.getEventStreamMember().equals(httpBinding.getMember())).orElse(true)); Optional<HttpBinding> payloadBinding = httpBindingIndex.getRequestBindings(operation, HttpBinding.Location.PAYLOAD).stream() .filter(httpBinding -> eventStreamInfo.map(streamInfo -> !streamInfo.getEventStreamMember().equals(httpBinding.getMember())).orElse(true)) .findFirst(); if (eventStreamInfo.isPresent() && (hasDocumentBindings || payloadBinding.isPresent())) { throw new CodegenException("HTTP Binding Protocol unexpected document or payload bindings with " + "input event stream"); } if (eventStreamInfo.isPresent()) { writeOperationSerializerMiddlewareEventStreamSetup(context, eventStreamInfo.get()); } else if (hasDocumentBindings) { // delegate the setup and usage of the document serializer function for the protocol writeMiddlewareDocumentSerializerDelegator(context, operation, generator); } else if (payloadBinding.isPresent()) { // delegate the setup and usage of the payload serializer function for the protocol MemberShape memberShape = payloadBinding.get().getMember(); writeMiddlewarePayloadSerializerDelegator(context, memberShape); } writer.write(""); } // Serialize HTTP request with payload, if set. writer.openBlock("if request.Request, err = restEncoder.Encode(request.Request); err != nil {", "}", () -> { writer.write("return out, metadata, &smithy.SerializationError{Err: err}"); }); writer.write("in.Request = request"); writer.write(""); writer.write("return next.$L(ctx, in)", generator.getHandleMethodName()); }); } protected abstract void writeOperationSerializerMiddlewareEventStreamSetup( GenerationContext context, EventStreamInfo eventStreamInfo ); // Generates operation deserializer middleware that delegates to appropriate deserializers for the error, // output shapes for the operation. private void generateOperationDeserializerMiddleware(GenerationContext context, OperationShape operation) { SymbolProvider symbolProvider = context.getSymbolProvider(); Model model = context.getModel(); ServiceShape service = context.getService(); ApplicationProtocol applicationProtocol = getApplicationProtocol(); Symbol responseType = applicationProtocol.getResponseType(); GoWriter goWriter = context.getWriter().get(); GoStackStepMiddlewareGenerator middleware = GoStackStepMiddlewareGenerator.createDeserializeStepMiddleware( ProtocolGenerator.getDeserializeMiddlewareName(operation.getId(), service, getProtocolName()), ProtocolUtils.OPERATION_DESERIALIZER_MIDDLEWARE_ID); String errorFunctionName = ProtocolGenerator.getOperationErrorDeserFunctionName( operation, service, context.getProtocolName()); middleware.writeMiddleware(goWriter, (generator, writer) -> { writer.addUseImports(SmithyGoDependency.FMT); writer.write("out, metadata, err = next.$L(ctx, in)", generator.getHandleMethodName()); writer.write("if err != nil { return out, metadata, err }"); writer.write(""); writer.write("response, ok := out.RawResponse.($P)", responseType); writer.openBlock("if !ok {", "}", () -> { writer.addUseImports(SmithyGoDependency.SMITHY); writer.write(String.format("return out, metadata, &smithy.DeserializationError{Err: %s}", "fmt.Errorf(\"unknown transport type %T\", out.RawResponse)")); }); writer.write(""); writer.openBlock("if response.StatusCode < 200 || response.StatusCode >= 300 {", "}", () -> { writer.write("return out, metadata, $L(response, &metadata)", errorFunctionName); }); Shape outputShape = model.expectShape(operation.getOutput() .orElseThrow(() -> new CodegenException("expect output shape for operation: " + operation.getId())) ); Symbol outputSymbol = symbolProvider.toSymbol(outputShape); // initialize out.Result as output structure shape writer.write("output := &$T{}", outputSymbol); writer.write("out.Result = output"); writer.write(""); // Output shape HTTP binding middleware generation if (isShapeWithRestResponseBindings(model, operation)) { String deserFuncName = ProtocolGenerator.getOperationHttpBindingsDeserFunctionName( outputShape, service, getProtocolName()); writer.write("err= $L(output, response)", deserFuncName); writer.openBlock("if err != nil {", "}", () -> { writer.addUseImports(SmithyGoDependency.SMITHY); writer.write(String.format("return out, metadata, &smithy.DeserializationError{Err: %s}", "fmt.Errorf(\"failed to decode response with invalid Http bindings, %w\", err)")); }); writer.write(""); } Optional<EventStreamInfo> streamInfoOptional = EventStreamIndex.of(model).getOutputInfo(operation); // Discard without deserializing the response if the input shape is a stubbed synthetic clone // without an archetype. if (CodegenUtils.isStubSynthetic(ProtocolUtils.expectOutput(model, operation)) && streamInfoOptional.isEmpty()) { writer.addUseImports(SmithyGoDependency.IOUTIL); writer.openBlock("if _, err = io.Copy(ioutil.Discard, response.Body); err != nil {", "}", () -> { writer.openBlock("return out, metadata, &smithy.DeserializationError{", "}", () -> { writer.write("Err: fmt.Errorf(\"failed to discard response body, %w\", err),"); }); }); } else { boolean hasBodyBinding = HttpBindingIndex.of(model).getResponseBindings(operation).values().stream() .filter(httpBinding -> httpBinding.getLocation() == HttpBinding.Location.DOCUMENT || httpBinding.getLocation() == HttpBinding.Location.PAYLOAD) .anyMatch(httpBinding -> streamInfoOptional.map(esi -> !esi.getEventStreamMember() .equals(httpBinding.getMember())).orElse(true)); if (hasBodyBinding && streamInfoOptional.isPresent()) { throw new CodegenException("HTTP Binding Protocol unexpected document or payload bindings with " + "output event stream"); } if (hasBodyBinding) { // Output Shape Document Binding middleware generation writeMiddlewareDocumentDeserializerDelegator(context, operation, generator); } } writer.write(""); writer.write("return out, metadata, err"); }); goWriter.write(""); Set<StructureShape> errorShapes = HttpProtocolGeneratorUtils.generateErrorDispatcher( context, operation, responseType, this::writeErrorMessageCodeDeserializer, this::getOperationErrors); deserializingErrorShapes.addAll(errorShapes); deserializeDocumentBindingShapes.addAll(errorShapes); } /** * Writes a code snippet that gets the error code and error message. * * <p>Four parameters will be available in scope: * <ul> * <li>{@code response: smithyhttp.HTTPResponse}: the HTTP response received.</li> * <li>{@code errorBody: bytes.BytesReader}: the HTTP response body.</li> * <li>{@code errorMessage: string}: the error message initialized to a default value.</li> * <li>{@code errorCode: string}: the error code initialized to a default value.</li> * </ul> * * @param context the generation context. */ protected abstract void writeErrorMessageCodeDeserializer(GenerationContext context); /** * Generate the document serializer logic for the serializer middleware body. * * @param context the generation context * @param operation the operation * @param generator middleware generator definition */ protected abstract void writeMiddlewareDocumentSerializerDelegator( GenerationContext context, OperationShape operation, GoStackStepMiddlewareGenerator generator ); /** * Writes a payload content-type header setter. * * @param writer the {@link GoWriter}. * @param payloadShape the payload shape. */ protected void writeSetPayloadShapeHeader(GoWriter writer, Shape payloadShape) { writer.pushState(); writer.putContext("withIsDefaultContentType", SymbolUtils.createValueSymbolBuilder( "SetIsContentTypeDefaultValue", SmithyGoDependency.SMITHY_HTTP_TRANSPORT).build()); writer.putContext("payloadMediaType", getPayloadShapeMediaType(payloadShape)); writer.write(""" if !restEncoder.HasHeader("Content-Type") { ctx = $withIsDefaultContentType:T(ctx, true) restEncoder.SetHeader("Content-Type").String($payloadMediaType:S) } """); writer.popState(); } /** * Writes the stream setter that set the operand as the HTTP body. * * @param writer the {@link GoWriter}. * @param operand the operand for the value to be set as the HTTP body. */ protected void writeSetStream(GoWriter writer, String operand) { writer.write(""" if request, err = request.SetStream($L); err != nil { return out, metadata, &smithy.SerializationError{Err: err} }""", operand); } /** * Generate the payload serializer logic for the serializer middleware body. * * @param context the generation context * @param memberShape the payload target member */ protected void writeMiddlewarePayloadSerializerDelegator( GenerationContext context, MemberShape memberShape ) { GoWriter writer = context.getWriter().get(); Model model = context.getModel(); Shape payloadShape = model.expectShape(memberShape.getTarget()); if (payloadShape.hasTrait(StreamingTrait.class)) { writeSetPayloadShapeHeader(writer, payloadShape); GoValueAccessUtils.writeIfNonZeroValueMember(context.getModel(), context.getSymbolProvider(), writer, memberShape, "input", (s) -> { writer.write("payload := $L", s); writeSetStream(writer, "payload"); }); } else if (payloadShape.isBlobShape()) { writeSetPayloadShapeHeader(writer, payloadShape); GoValueAccessUtils.writeIfNonZeroValueMember(context.getModel(), context.getSymbolProvider(), writer, memberShape, "input", (s) -> { writer.addUseImports(SmithyGoDependency.BYTES); writer.write("payload := bytes.NewReader($L)", s); writeSetStream(writer, "payload"); }); } else if (payloadShape.isStringShape()) { writeSetPayloadShapeHeader(writer, payloadShape); GoValueAccessUtils.writeIfNonZeroValueMember(context.getModel(), context.getSymbolProvider(), writer, memberShape, "input", (s) -> { writer.addUseImports(SmithyGoDependency.STRINGS); if (payloadShape.hasTrait(EnumTrait.class)) { writer.write("payload := strings.NewReader(string($L))", s); } else { writer.write("payload := strings.NewReader(*$L)", s); } writeSetStream(writer, "payload"); }); } else { writeMiddlewarePayloadAsDocumentSerializerDelegator(context, memberShape, "input"); } } /** * Returns the MediaType for the payload shape derived from the MediaTypeTrait, shape type, or * document content type. * * @param payloadShape shape bound to the payload. * @return string for media type. */ private String getPayloadShapeMediaType(Shape payloadShape) { Optional<MediaTypeTrait> mediaTypeTrait = payloadShape.getTrait(MediaTypeTrait.class); if (mediaTypeTrait.isPresent()) { return mediaTypeTrait.get().getValue(); } if (payloadShape.isBlobShape()) { return "application/octet-stream"; } if (payloadShape.isStringShape()) { return "text/plain"; } return getDocumentContentType(); } /** * Generate the payload serializers with document serializer logic for the serializer middleware body. * * @param context the generation context * @param memberShape the payload target member * @param operand the operand that is used to access the member value */ protected abstract void writeMiddlewarePayloadAsDocumentSerializerDelegator( GenerationContext context, MemberShape memberShape, String operand ); /** * Generate the document deserializer logic for the deserializer middleware body. * * @param context the generation context * @param operation the operation * @param generator middleware generator definition */ protected abstract void writeMiddlewareDocumentDeserializerDelegator( GenerationContext context, OperationShape operation, GoStackStepMiddlewareGenerator generator ); private boolean isRestBinding(HttpBinding.Location location) { return location == HttpBinding.Location.HEADER || location == HttpBinding.Location.PREFIX_HEADERS || location == HttpBinding.Location.LABEL || location == HttpBinding.Location.QUERY || location == HttpBinding.Location.QUERY_PARAMS || location == HttpBinding.Location.RESPONSE_CODE; } // returns whether an operation shape has Rest Request Bindings private boolean isOperationWithRestRequestBindings(Model model, OperationShape operationShape) { Collection<HttpBinding> bindings = HttpBindingIndex.of(model) .getRequestBindings(operationShape).values(); for (HttpBinding binding : bindings) { if (isRestBinding(binding.getLocation())) { return true; } } return false; } /** * Returns whether a shape has rest response bindings. * The shape can be an operation shape, error shape or an output shape. * * @param model the model * @param shape the shape with possible presence of rest response bindings * @return boolean indicating presence of rest response bindings in the shape */ protected boolean isShapeWithRestResponseBindings(Model model, Shape shape) { Collection<HttpBinding> bindings = HttpBindingIndex.of(model).getResponseBindings(shape).values(); for (HttpBinding binding : bindings) { if (isRestBinding(binding.getLocation())) { return true; } } return false; } private void generateOperationHttpBindingSerializer(GenerationContext context, OperationShape operation) { SymbolProvider symbolProvider = context.getSymbolProvider(); Model model = context.getModel(); GoWriter writer = context.getWriter().get(); Shape inputShape = model.expectShape(operation.getInput() .orElseThrow(() -> new CodegenException("missing input shape for operation: " + operation.getId()))); HttpBindingIndex bindingIndex = model.getKnowledge(HttpBindingIndex.class); List<HttpBinding> bindings = bindingIndex.getRequestBindings(operation).values().stream() .filter(httpBinding -> isRestBinding(httpBinding.getLocation())) .sorted(Comparator.comparing(HttpBinding::getMember)) .collect(Collectors.toList()); Symbol httpBindingEncoder = getHttpBindingEncoderSymbol(); Symbol inputSymbol = symbolProvider.toSymbol(inputShape); String functionName = ProtocolGenerator.getOperationHttpBindingsSerFunctionName( inputShape, context.getService(), getProtocolName()); writer.addUseImports(SmithyGoDependency.FMT); writer.openBlock("func $L(v $P, encoder $P) error {", "}", functionName, inputSymbol, httpBindingEncoder, () -> { writer.openBlock("if v == nil {", "}", () -> { writer.write("return fmt.Errorf(\"unsupported serialization of nil %T\", v)"); }); writer.write(""); for (HttpBinding binding : bindings.stream() .filter(NoSerializeTrait.excludeNoSerializeHttpBindingMembers()) .collect(Collectors.toList())) { writeHttpBindingMember(context, binding); writer.write(""); } writer.write("return nil"); }); writer.write(""); } private Symbol getHttpBindingEncoderSymbol() { return SymbolUtils.createPointableSymbolBuilder("Encoder", SmithyGoDependency.SMITHY_HTTP_BINDING).build(); } private void generateHttpBindingTimestampSerializer( Model model, GoWriter writer, MemberShape memberShape, HttpBinding.Location location, String operand, BiConsumer<GoWriter, String> locationEncoder ) { writer.addUseImports(SmithyGoDependency.SMITHY_TIME); TimestampFormatTrait.Format format = model.getKnowledge(HttpBindingIndex.class).determineTimestampFormat( memberShape, location, getDocumentTimestampFormat()); switch (format) { case DATE_TIME: locationEncoder.accept(writer, "String(smithytime.FormatDateTime(" + operand + "))"); break; case HTTP_DATE: locationEncoder.accept(writer, "String(smithytime.FormatHTTPDate(" + operand + "))"); break; case EPOCH_SECONDS: locationEncoder.accept(writer, "Double(smithytime.FormatEpochSeconds(" + operand + "))"); break; default: throw new CodegenException("Unknown timestamp format"); } } private boolean isHttpDateTimestamp(Model model, HttpBinding.Location location, MemberShape memberShape) { Shape targetShape = model.expectShape(memberShape.getTarget().toShapeId()); if (targetShape.getType() != ShapeType.TIMESTAMP) { return false; } TimestampFormatTrait.Format format = HttpBindingIndex.of(model).determineTimestampFormat( memberShape, location, getDocumentTimestampFormat()); return format == Format.HTTP_DATE; } private void writeHttpBindingSetter( GenerationContext context, GoWriter writer, MemberShape memberShape, HttpBinding.Location location, String operand, BiConsumer<GoWriter, String> locationEncoder ) { Model model = context.getModel(); Shape targetShape = model.expectShape(memberShape.getTarget()); // We only need to dereference if we pass the shape around as reference in Go. // Note we make two exceptions here: big.Int and big.Float should still be passed as reference to the helper // method as they can be arbitrarily large. operand = CodegenUtils.getAsValueIfDereferencable(GoPointableIndex.of(context.getModel()), memberShape, operand); switch (targetShape.getType()) { case BOOLEAN: locationEncoder.accept(writer, "Boolean(" + operand + ")"); break; case STRING: operand = targetShape.hasTrait(EnumTrait.class) ? "string(" + operand + ")" : operand; locationEncoder.accept(writer, "String(" + operand + ")"); break; case ENUM: operand = "string(" + operand + ")"; locationEncoder.accept(writer, "String(" + operand + ")"); break; case TIMESTAMP: generateHttpBindingTimestampSerializer(model, writer, memberShape, location, operand, locationEncoder); break; case BYTE: locationEncoder.accept(writer, "Byte(" + operand + ")"); break; case SHORT: locationEncoder.accept(writer, "Short(" + operand + ")"); break; case INTEGER: case INT_ENUM: locationEncoder.accept(writer, "Integer(" + operand + ")"); break; case LONG: locationEncoder.accept(writer, "Long(" + operand + ")"); break; case FLOAT: locationEncoder.accept(writer, "Float(" + operand + ")"); break; case DOUBLE: locationEncoder.accept(writer, "Double(" + operand + ")"); break; case BIG_INTEGER: locationEncoder.accept(writer, "BigInteger(" + operand + ")"); break; case BIG_DECIMAL: locationEncoder.accept(writer, "BigDecimal(" + operand + ")"); break; default: throw new CodegenException("unexpected shape type " + targetShape.getType()); } } private void writeHttpBindingMember( GenerationContext context, HttpBinding binding ) { GoWriter writer = context.getWriter().get(); Model model = context.getModel(); MemberShape memberShape = binding.getMember(); Shape targetShape = model.expectShape(memberShape.getTarget()); HttpBinding.Location location = binding.getLocation(); // return an error if member shape targets location label, but is unset. if (location.equals(HttpBinding.Location.LABEL)) { // labels must always be set to be serialized on URI, and non empty strings, GoValueAccessUtils.writeIfZeroValueMember(context.getModel(), context.getSymbolProvider(), writer, memberShape, "v", false, true, operand -> { writer.addUseImports(SmithyGoDependency.SMITHY); writer.write("return &smithy.SerializationError { " + "Err: fmt.Errorf(\"input member $L must not be empty\")}", memberShape.getMemberName()); }); } boolean allowZeroStrings = location != HttpBinding.Location.HEADER; GoValueAccessUtils.writeIfNonZeroValueMember(context.getModel(), context.getSymbolProvider(), writer, memberShape, "v", allowZeroStrings, memberShape.isRequired(), (operand) -> { final String locationName = binding.getLocationName().isEmpty() ? memberShape.getMemberName() : binding.getLocationName(); switch (location) { case HEADER: writer.write("locationName := $S", getCanonicalHeader(locationName)); writeHeaderBinding(context, memberShape, operand, location, "locationName", "encoder"); break; case PREFIX_HEADERS: MemberShape valueMemberShape = model.expectShape(targetShape.getId(), MapShape.class).getValue(); Shape valueMemberTarget = model.expectShape(valueMemberShape.getTarget()); if (targetShape.getType() != ShapeType.MAP) { throw new CodegenException("Unexpected prefix headers target shape " + valueMemberTarget.getType() + ", " + valueMemberShape.getId()); } writer.write("hv := encoder.Headers($S)", getCanonicalHeader(locationName)); writer.addUseImports(SmithyGoDependency.NET_HTTP); writer.openBlock("for mapKey, mapVal := range $L {", "}", operand, () -> { GoValueAccessUtils.writeIfNonZeroValue(context.getModel(), writer, valueMemberShape, "mapVal", false, false, () -> { writeHeaderBinding(context, valueMemberShape, "mapVal", location, "http.CanonicalHeaderKey(mapKey)", "hv"); }); }); break; case LABEL: writeHttpBindingSetter(context, writer, memberShape, location, operand, (w, s) -> { w.openBlock("if err := encoder.SetURI($S).$L; err != nil {", "}", locationName, s, () -> { w.write("return err"); }); }); break; case QUERY: writeQueryBinding(context, memberShape, targetShape, operand, location, locationName, "encoder", false); break; case QUERY_PARAMS: MemberShape queryMapValueMemberShape = CodegenUtils.expectMapShape(targetShape).getValue(); Shape queryMapValueTargetShape = model.expectShape(queryMapValueMemberShape.getTarget()); MemberShape queryMapKeyMemberShape = CodegenUtils.expectMapShape(targetShape).getKey(); writer.openBlock("for qkey, qvalue := range $L {", "}", operand, () -> { writer.write("if encoder.HasQuery(qkey) { continue }"); writeQueryBinding(context, queryMapKeyMemberShape, queryMapValueTargetShape, "qvalue", location, "qkey", "encoder", true); }); break; default: throw new CodegenException("unexpected http binding found"); } }); } /** * Writes query bindings, as per the target shape. This method is shared * between members modeled with Location.Query and Location.QueryParams. * Precedence across Location.Query and Location.QueryParams is handled * outside the scope of this function. * * @param context is the generation context * @param memberShape is the member shape for which query is serialized * @param targetShape is the target shape of the query member. * This can either be string, or a list/set of string. * @param operand is the member value accessor . * @param location is the location of the member - can be Location.Query * or Location.QueryParams. * @param locationName is the key for which query is encoded. * @param dest is the query encoder destination. * @param isQueryParams boolean representing if Location used for query binding is * QUERY_PARAMS. */ private void writeQueryBinding( GenerationContext context, MemberShape memberShape, Shape targetShape, String operand, HttpBinding.Location location, String locationName, String dest, boolean isQueryParams ) { GoWriter writer = context.getWriter().get(); if (targetShape instanceof CollectionShape) { MemberShape collectionMember = CodegenUtils.expectCollectionShape(targetShape) .getMember(); writer.openBlock("for i := range $L {", "}", operand, () -> { GoValueAccessUtils.writeIfZeroValue(context.getModel(), writer, collectionMember, operand + "[i]", () -> writer.write("continue")); String addQuery = String.format("$L.AddQuery(%s).$L", isQueryParams ? "$L" : "$S"); writeHttpBindingSetter(context, writer, collectionMember, location, operand + "[i]", (w, s) -> w.writeInline(addQuery, dest, locationName, s)); }); return; } String setQuery = String.format("$L.SetQuery(%s).$L", isQueryParams ? "$L" : "$S"); writeHttpBindingSetter(context, writer, memberShape, location, operand, (w, s) -> w.writeInline(setQuery, dest, locationName, s)); } private void writeHeaderBinding( GenerationContext context, MemberShape memberShape, String operand, HttpBinding.Location location, String locationName, String dest ) { GoWriter writer = context.getWriter().get(); Model model = context.getModel(); Shape targetShape = model.expectShape(memberShape.getTarget()); if (!(targetShape instanceof CollectionShape)) { String op = conditionallyBase64Encode(context, writer, targetShape, operand); writeHttpBindingSetter(context, writer, memberShape, location, op, (w, s) -> { w.writeInline("$L.SetHeader($L).$L", dest, locationName, s); }); return; } MemberShape collectionMemberShape = CodegenUtils.expectCollectionShape(targetShape).getMember(); writer.openBlock("for i := range $L {", "}", operand, () -> { // Only set non-empty non-nil header values String indexedOperand = operand + "[i]"; GoValueAccessUtils.writeIfNonZeroValue(context.getModel(), writer, collectionMemberShape, indexedOperand, false, false, () -> { String op = conditionallyEscapeHeader(context, writer, collectionMemberShape, indexedOperand); writeHttpBindingSetter(context, writer, collectionMemberShape, location, op, (w, s) -> { w.writeInline("$L.AddHeader($L).$L", dest, locationName, s); }); }); }); } private String conditionallyEscapeHeader( GenerationContext context, GoWriter writer, MemberShape memberShape, String operand ) { var targetShape = context.getModel().expectShape(memberShape.getTarget()); if (!targetShape.isStringShape()) { return operand; } if (targetShape.hasTrait(MediaTypeTrait.class)) { return conditionallyBase64Encode(context, writer, targetShape, operand); } writer.pushState(); var returnVar = "escaped"; var pointableIndex = GoPointableIndex.of(context.getModel()); var shouldDereference = pointableIndex.isDereferencable(memberShape); if (shouldDereference) { operand = CodegenUtils.getAsValueIfDereferencable(pointableIndex, memberShape, operand); writer.putContext("escapedVar", "escapedVal"); returnVar = "escapedPtr"; } else { writer.putContext("escapedVar", returnVar); } writer.putContext("returnVar", returnVar); if (targetShape.hasTrait(EnumTrait.class)) { operand = "string(" + operand + ")"; } writer.putContext("value", operand); writer.putContext("quoteValue", SymbolUtils.createValueSymbolBuilder( "Quote", SmithyGoDependency.STRCONV).build()); writer.putContext("indexOf", SymbolUtils.createValueSymbolBuilder( "Index", SmithyGoDependency.STRINGS).build()); writer.putContext("ptrString", SymbolUtils.createValueSymbolBuilder( "String", SmithyGoDependency.SMITHY_PTR).build()); writer.write(""" $escapedVar:L := $value:L if $indexOf:T($value:L, `,`) != -1 || $indexOf:T($value:L, `"`) != -1 { $escapedVar:L = $quoteValue:T($value:L) } """); if (shouldDereference) { writer.write("$returnVar:L := $ptrString:T($escapedVar:L)"); } writer.popState(); return returnVar; } private String conditionallyBase64Encode( GenerationContext context, GoWriter writer, Shape targetShape, String operand ) { // MediaType strings written to headers must be base64 encoded if (!targetShape.isStringShape() || !targetShape.hasTrait(MediaTypeTrait.class)) { return operand; } writer.pushState(); var returnVar = "encoded"; var pointableIndex = GoPointableIndex.of(context.getModel()); var shouldDereference = pointableIndex.isDereferencable(targetShape); if (shouldDereference) { operand = CodegenUtils.getAsValueIfDereferencable(pointableIndex, targetShape, operand); writer.putContext("encodedVar", "encodedVal"); returnVar = "encodedPtr"; } else { writer.putContext("encodedVar", returnVar); } writer.putContext("returnVar", returnVar); writer.putContext("value", operand); writer.putContext("ptrString", SymbolUtils.createValueSymbolBuilder( "String", SmithyGoDependency.SMITHY_PTR).build()); writer.putContext("encodeToString", SymbolUtils.createValueSymbolBuilder( "StdEncoding.EncodeToString", SmithyGoDependency.BASE64).build()); writer.write("$encodedVar:L := $encodeToString:T([]byte($value:L))"); if (shouldDereference) { writer.write("$returnVar:L := $ptrString:T($encodedVar:L)"); } writer.popState(); return returnVar; } /** * Generates serialization functions for shapes in the passed set. These functions * should return a value that can then be serialized by the implementation of * {@code serializeInputDocument}. * * @param context The generation context. * @param shapes The shapes to generate serialization for. */ protected abstract void generateDocumentBodyShapeSerializers(GenerationContext context, Set<Shape> shapes); @Override public void generateResponseDeserializers(GenerationContext context) { EventStreamIndex streamIndex = EventStreamIndex.of(context.getModel()); for (OperationShape operation : getHttpBindingOperations(context)) { generateOperationDeserializerMiddleware(context, operation); generateHttpBindingDeserializer(context, operation); Optional<EventStreamInfo> streamInfo = streamIndex.getOutputInfo(operation); if (!CodegenUtils.isStubSynthetic(ProtocolUtils.expectOutput(context.getModel(), operation)) && streamInfo.isEmpty()) { generateOperationDocumentDeserializer(context, operation); addOperationDocumentShapeBindersForDeserializer(context, operation); } } GoEventStreamIndex goEventStreamIndex = GoEventStreamIndex.of(context.getModel()); goEventStreamIndex.getOutputEventStreams(context.getService()).ifPresent(shapeIdSetMap -> shapeIdSetMap.forEach((shapeId, eventStreamInfos) -> { generateEventStreamDeserializers(context, context.getModel().expectShape(shapeId, UnionShape.class), eventStreamInfos); })); for (StructureShape error : deserializingErrorShapes) { generateHttpBindingDeserializer(context, error); } } // Generates Http Binding shape deserializer function. private void generateHttpBindingDeserializer(GenerationContext context, Shape shape) { SymbolProvider symbolProvider = context.getSymbolProvider(); Model model = context.getModel(); GoWriter writer = context.getWriter().get(); HttpBindingIndex bindingIndex = model.getKnowledge(HttpBindingIndex.class); List<HttpBinding> bindings = bindingIndex.getResponseBindings(shape).values().stream() .filter(binding -> isRestBinding(binding.getLocation())) .sorted(Comparator.comparing(HttpBinding::getMember)) .collect(Collectors.toList()); // Don't generate anything if there are no bindings. if (bindings.size() == 0) { return; } Shape targetShape = shape; if (shape.isOperationShape()) { targetShape = ProtocolUtils.expectOutput(model, shape.asOperationShape().get()); } Symbol targetSymbol = symbolProvider.toSymbol(targetShape); Symbol smithyHttpResponsePointableSymbol = SymbolUtils.createPointableSymbolBuilder( "Response", SmithyGoDependency.SMITHY_HTTP_TRANSPORT).build(); writer.addUseImports(SmithyGoDependency.FMT); String functionName = ProtocolGenerator.getOperationHttpBindingsDeserFunctionName( targetShape, context.getService(), getProtocolName()); writer.openBlock("func $L(v $P, response $P) error {", "}", functionName, targetSymbol, smithyHttpResponsePointableSymbol, () -> { writer.openBlock("if v == nil {", "}", () -> { writer.write("return fmt.Errorf(\"unsupported deserialization for nil %T\", v)"); }); writer.write(""); for (HttpBinding binding : bindings) { writeRestDeserializerMember(context, writer, binding); writer.write(""); } writer.write("return nil"); }); } private String generateHttpHeaderValue( GenerationContext context, GoWriter writer, MemberShape memberShape, HttpBinding binding, String operand ) { Shape targetShape = context.getModel().expectShape(memberShape.getTarget()); if (targetShape.getType() != ShapeType.LIST && targetShape.getType() != ShapeType.SET) { writer.addUseImports(SmithyGoDependency.STRINGS); writer.write("$L = strings.TrimSpace($L)", operand, operand); } String value = ""; switch (targetShape.getType()) { case STRING: if (targetShape.hasTrait(EnumTrait.class)) { value = String.format("types.%s(%s)", targetShape.getId().getName(), operand); return value; } // MediaType strings must be base-64 encoded when sent in headers. if (targetShape.hasTrait(MediaTypeTrait.class)) { writer.addUseImports(SmithyGoDependency.BASE64); writer.write("b, err := base64.StdEncoding.DecodeString($L)", operand); writer.write("if err != nil { return err }"); return "string(b)"; } return operand; case ENUM: value = String.format("types.%s(%s)", targetShape.getId().getName(), operand); return value; case BOOLEAN: writer.addUseImports(SmithyGoDependency.STRCONV); writer.write("vv, err := strconv.ParseBool($L)", operand); writer.write("if err != nil { return err }"); return "vv"; case TIMESTAMP: writer.addUseImports(SmithyGoDependency.SMITHY_TIME); HttpBindingIndex bindingIndex = context.getModel().getKnowledge(HttpBindingIndex.class); TimestampFormatTrait.Format format = bindingIndex.determineTimestampFormat( memberShape, binding.getLocation(), Format.HTTP_DATE ); switch (format) { case EPOCH_SECONDS: writer.addUseImports(SmithyGoDependency.STRCONV); writer.write("f, err := strconv.ParseFloat($L, 64)", operand); writer.write("if err != nil { return err }"); writer.write("t := smithytime.ParseEpochSeconds(f)"); break; case HTTP_DATE: writer.write("t, err := smithytime.ParseHTTPDate($L)", operand); writer.write("if err != nil { return err }"); break; case DATE_TIME: writer.write("t, err := smithytime.ParseDateTime($L)", operand); writer.write("if err != nil { return err }"); break; default: throw new CodegenException("Unexpected timestamp format " + format); } return "t"; case BYTE: writer.addUseImports(SmithyGoDependency.STRCONV); writer.write("vv, err := strconv.ParseInt($L, 0, 8)", operand); writer.write("if err != nil { return err }"); return "int8(vv)"; case SHORT: writer.addUseImports(SmithyGoDependency.STRCONV); writer.write("vv, err := strconv.ParseInt($L, 0, 16)", operand); writer.write("if err != nil { return err }"); return "int16(vv)"; case INTEGER: case INT_ENUM: writer.addUseImports(SmithyGoDependency.STRCONV); writer.write("vv, err := strconv.ParseInt($L, 0, 32)", operand); writer.write("if err != nil { return err }"); return "int32(vv)"; case LONG: writer.addUseImports(SmithyGoDependency.STRCONV); writer.write("vv, err := strconv.ParseInt($L, 0, 64)", operand); writer.write("if err != nil { return err }"); return "vv"; case FLOAT: writer.addUseImports(SmithyGoDependency.STRCONV); writer.write("vv, err := strconv.ParseFloat($L, 32)", operand); writer.write("if err != nil { return err }"); return "float32(vv)"; case DOUBLE: writer.addUseImports(SmithyGoDependency.STRCONV); writer.write("vv, err := strconv.ParseFloat($L, 64)", operand); writer.write("if err != nil { return err }"); return "vv"; case BIG_INTEGER: writer.addUseImports(SmithyGoDependency.BIG); writer.write("i := big.NewInt(0)"); writer.write("bi, ok := i.SetString($L,0)", operand); writer.openBlock("if !ok {", "}", () -> { writer.write( "return fmt.Error($S)", "Incorrect conversion from string to BigInteger type" ); }); return "*bi"; case BIG_DECIMAL: writer.addUseImports(SmithyGoDependency.BIG); writer.write("f := big.NewFloat(0)"); writer.write("bd, ok := f.SetString($L,0)", operand); writer.openBlock("if !ok {", "}", () -> { writer.write( "return fmt.Error($S)", "Incorrect conversion from string to BigDecimal type" ); }); return "*bd"; case BLOB: writer.addUseImports(SmithyGoDependency.BASE64); writer.write("b, err := base64.StdEncoding.DecodeString($L)", operand); writer.write("if err != nil { return err }"); return "b"; case SET: case LIST: // handle list/Set as target shape MemberShape targetValueListMemberShape = CodegenUtils.expectCollectionShape(targetShape).getMember(); return getHttpHeaderCollectionDeserializer(context, writer, targetValueListMemberShape, binding, operand); default: throw new CodegenException("unexpected shape type " + targetShape.getType()); } } private String getHttpHeaderCollectionDeserializer( GenerationContext context, GoWriter writer, MemberShape memberShape, HttpBinding binding, String operand ) { writer.write("var list []$P", context.getSymbolProvider().toSymbol(memberShape)); String operandValue = operand + "Val"; writer.openBlock("for _, $L := range $L {", "}", operandValue, operand, () -> { String value = generateHttpHeaderValue(context, writer, memberShape, binding, operandValue); writer.write("list = append(list, $L)", CodegenUtils.getAsPointerIfPointable(context.getModel(), writer, GoPointableIndex.of(context.getModel()), memberShape, value)); }); return "list"; } private void writeRestDeserializerMember( GenerationContext context, GoWriter writer, HttpBinding binding ) { MemberShape memberShape = binding.getMember(); Shape targetShape = context.getModel().expectShape(memberShape.getTarget()); String memberName = context.getSymbolProvider().toMemberName(memberShape); switch (binding.getLocation()) { case HEADER: writeHeaderDeserializerFunction(context, writer, memberName, memberShape, binding); break; case PREFIX_HEADERS: if (!targetShape.isMapShape()) { throw new CodegenException("unexpected prefix-header shape type found in Http bindings"); } writePrefixHeaderDeserializerFunction(context, writer, memberName, memberShape, binding); break; case RESPONSE_CODE: writer.addUseImports(SmithyGoDependency.SMITHY_PTR); writer.write("v.$L = $L", memberName, CodegenUtils.getAsPointerIfPointable(context.getModel(), writer, GoPointableIndex.of(context.getModel()), memberShape, "int32(response.StatusCode)")); break; default: throw new CodegenException("unexpected http binding found"); } } private void writeHeaderDeserializerFunction( GenerationContext context, GoWriter writer, String memberName, MemberShape memberShape, HttpBinding binding ) { writer.openBlock("if headerValues := response.Header.Values($S); len(headerValues) != 0 {", "}", binding.getLocationName(), () -> { Shape targetShape = context.getModel().expectShape(memberShape.getTarget()); String operand = "headerValues"; operand = writeHeaderValueAccessor(context, writer, targetShape, binding, operand); String value = generateHttpHeaderValue(context, writer, memberShape, binding, operand); writer.write("v.$L = $L", memberName, CodegenUtils.getAsPointerIfPointable(context.getModel(), writer, GoPointableIndex.of(context.getModel()), memberShape, value)); }); } private void writePrefixHeaderDeserializerFunction( GenerationContext context, GoWriter writer, String memberName, MemberShape memberShape, HttpBinding binding ) { String prefix = binding.getLocationName(); Shape targetShape = context.getModel().expectShape(memberShape.getTarget()); MemberShape valueMemberShape = targetShape.asMapShape() .orElseThrow(() -> new CodegenException("prefix headers must target map shape")) .getValue(); writer.openBlock("for headerKey, headerValues := range response.Header {", "}", () -> { writer.addUseImports(SmithyGoDependency.STRINGS); Symbol targetSymbol = context.getSymbolProvider().toSymbol(targetShape); writer.openBlock( "if lenPrefix := len($S); " + "len(headerKey) >= lenPrefix && strings.EqualFold(headerKey[:lenPrefix], $S) {", "}", prefix, prefix, () -> { writer.openBlock("if v.$L == nil {", "}", memberName, () -> { writer.write("v.$L = $P{}", memberName, targetSymbol); }); String operand = "headerValues"; operand = writeHeaderValueAccessor(context, writer, targetShape, binding, operand); String value = generateHttpHeaderValue(context, writer, valueMemberShape, binding, operand); writer.write("v.$L[strings.ToLower(headerKey[lenPrefix:])] = $L", memberName, CodegenUtils.getAsPointerIfPointable(context.getModel(), writer, GoPointableIndex.of(context.getModel()), valueMemberShape, value)); }); }); } /** * Returns the header value accessor operand, and also if the target shape is a list/set will write the splitting * of the header values by comma(,) utility helper. * * @param context generation context * @param writer writer * @param targetShape target shape * @param binding http binding location * @param operand operand of the header values. * @return returns operand for accessing the header values */ private String writeHeaderValueAccessor( GenerationContext context, GoWriter writer, Shape targetShape, HttpBinding binding, String operand ) { switch (targetShape.getType()) { case LIST: case SET: writerHeaderListValuesSplit(context, writer, CodegenUtils.expectCollectionShape(targetShape), binding, operand); break; default: // Always use first element in header, ignores if there are multiple headers with this key. operand += "[0]"; break; } return operand; } /** * Writes the utility to split split comma separate header values into a single list for consistent iteration. Also * has special case handling for HttpDate timestamp format when serialized as a header list. Assigns the split * header values back to the same operand name. * * @param context generation context * @param writer writer * @param shape target collection shape * @param binding http binding location * @param operand operand of the header values. */ private void writerHeaderListValuesSplit( GenerationContext context, GoWriter writer, CollectionShape shape, HttpBinding binding, String operand ) { writer.openBlock("{", "}", () -> { writer.write("var err error"); writer.addUseImports(SmithyGoDependency.SMITHY_HTTP_TRANSPORT); if (isHttpDateTimestamp(context.getModel(), binding.getLocation(), shape.getMember())) { writer.write("$L, err = smithyhttp.SplitHTTPDateTimestampHeaderListValues($L)", operand, operand); } else { writer.write("$L, err = smithyhttp.SplitHeaderListValues($L)", operand, operand); } writer.openBlock("if err != nil {", "}", () -> { writer.write("return err"); }); }); } @Override public void generateSharedDeserializerComponents(GenerationContext context) { deserializingErrorShapes.forEach(error -> generateErrorDeserializer(context, error)); deserializeDocumentBindingShapes.addAll(ProtocolUtils.resolveRequiredDocumentShapeSerde( context.getModel(), deserializeDocumentBindingShapes)); generateDocumentBodyShapeDeserializers(context, deserializeDocumentBindingShapes); } /** * Adds the top-level shapes from the operation that bind to the body document that require deserializer functions. * * @param context the generator context * @param operation the operation to add document binders from */ private void addOperationDocumentShapeBindersForDeserializer(GenerationContext context, OperationShape operation) { Model model = context.getModel(); HttpBindingIndex httpBindingIndex = HttpBindingIndex.of(model); addDocumentDeserializerBindingShapes(model, httpBindingIndex, operation); for (ShapeId errorShapeId : operation.getErrors()) { addDocumentDeserializerBindingShapes(model, httpBindingIndex, errorShapeId); } } /** * Adds shapes from provided shape that require document deserializer functions to be generated. * * @param model the smithy model. * @param index the http binding index * @param shape the shape to enumerate member shapes for document deserializers */ private void addDocumentDeserializerBindingShapes(Model model, HttpBindingIndex index, ToShapeId shape) { // Walk and add members shapes to the list that will require deserializer functions for (HttpBinding binding : index.getResponseBindings(shape).values()) { MemberShape memberShape = binding.getMember(); Shape targetShape = model.expectShape(memberShape.getTarget()); // Event Stream Member should not immediately generate a document deserializer // and is handled via generateOperationEventMessageDeserializers. if (StreamingTrait.isEventStream(model, memberShape)) { continue; } // Add deserializer helpers for document and payload shape bindings if the operation does not have // any output event streams. if (requiresDocumentSerdeFunction(targetShape) && (binding.getLocation() == HttpBinding.Location.DOCUMENT || binding.getLocation() == HttpBinding.Location.PAYLOAD)) { deserializeDocumentBindingShapes.add(targetShape); } } } /** * Generates the operation document deserializer function. * * @param context the generation context * @param operation the operation shape being generated */ protected abstract void generateOperationDocumentDeserializer(GenerationContext context, OperationShape operation); /** * Generates deserialization functions for shapes in the provided set. These functions * should return a value that can then be deserialized by the implementation of * {@code deserializeOutputDocument}. * * @param context The generation context. * @param shapes The shapes to generate deserialization for. */ protected abstract void generateDocumentBodyShapeDeserializers(GenerationContext context, Set<Shape> shapes); private void generateErrorDeserializer(GenerationContext context, StructureShape shape) { GoWriter writer = context.getWriter().get(); String functionName = ProtocolGenerator.getErrorDeserFunctionName( shape, context.getService(), context.getProtocolName()); Symbol responseType = getApplicationProtocol().getResponseType(); writer.addUseImports(SmithyGoDependency.BYTES); writer.openBlock("func $L(response $P, errorBody *bytes.Reader) error {", "}", functionName, responseType, () -> deserializeError(context, shape)); writer.write(""); } /** * Writes a function body that deserializes the given error. * * <p>Two parameters will be available in scope: * <ul> * <li>{@code response: smithyhttp.HTTPResponse}: the HTTP response received.</li> * <li>{@code errorBody: bytes.BytesReader}: the HTTP response body.</li> * </ul> * * @param context The generation context. * @param shape The error shape. */ protected abstract void deserializeError(GenerationContext context, StructureShape shape); /** * Converts the first letter and any letter following a hyphen to upper case. The remaining letters are lower cased. * * @param key the header * @return the canonical header */ private String getCanonicalHeader(String key) { char[] chars = key.toCharArray(); boolean upper = true; for (int i = 0; i < chars.length; i++) { char c = chars[i]; c = upper ? Character.toUpperCase(c) : Character.toLowerCase(c); chars[i] = c; upper = c == '-'; } return new String(chars); } }
8,988
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/integration/HttpProtocolUnitTestResponseErrorGenerator.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * * */ package software.amazon.smithy.go.codegen.integration; import java.util.List; import java.util.Set; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.codegen.core.SymbolProvider; import software.amazon.smithy.go.codegen.GoWriter; import software.amazon.smithy.go.codegen.SmithyGoDependency; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.protocoltests.traits.HttpResponseTestCase; /** * Generates HTTP protocol unit tests for HTTP response API error test cases. */ public class HttpProtocolUnitTestResponseErrorGenerator extends HttpProtocolUnitTestResponseGenerator { protected final StructureShape errorShape; protected final Symbol errorSymbol; /** * Initializes the protocol test generator. * * @param builder the builder initializing the generator. */ protected HttpProtocolUnitTestResponseErrorGenerator(Builder builder) { super(builder); this.errorShape = builder.error; this.errorSymbol = symbolProvider.toSymbol(errorShape); } /** * Provides the unit test function's format string. * * @return returns format string paired with unitTestFuncNameArgs */ @Override protected String unitTestFuncNameFormat() { return "TestClient_$L_$L_$LDeserialize"; } /** * Provides the unit test function name's format string arguments. * * @return returns a list of arguments used to format the unitTestFuncNameFormat returned format string. */ @Override protected Object[] unitTestFuncNameArgs() { return new Object[]{opSymbol.getName(), errorSymbol.getName(), protocolName}; } /** * Hook to generate the parameter declarations as struct parameters into the test case's struct definition. * Must generate all test case parameters before returning. * * @param writer writer to write generated code with. */ @Override protected void generateTestCaseParams(GoWriter writer) { writer.write("StatusCode int"); // TODO authScheme writer.addUseImports(SmithyGoDependency.NET_HTTP); writer.write("Header http.Header"); // TODO why do these exist? // writer.write("RequireHeaders []string"); // writer.write("ForbidHeaders []string"); writer.write("BodyMediaType string"); writer.write("Body []byte"); // TODO vendorParams for requestID writer.write("ExpectError $P", errorSymbol); } /** * Hook to generate all the test case parameters as struct member values for a single test case. * Must generate all test case parameter values before returning. * * @param writer writer to write generated code with. * @param testCase definition of a single test case. */ @Override protected void generateTestCaseValues(GoWriter writer, HttpResponseTestCase testCase) { writeStructField(writer, "StatusCode", testCase.getCode()); writeHeaderStructField(writer, "Header", testCase.getHeaders()); testCase.getBodyMediaType().ifPresent(mediaType -> { writeStructField(writer, "BodyMediaType", "$S", mediaType); }); testCase.getBody().ifPresent(body -> { writeStructField(writer, "Body", "[]byte(`$L`)", body); }); writeStructField(writer, "ExpectError", errorShape, testCase.getParams()); } /** * Hook to generate the body of the test that will be invoked for all test cases of this operation. Should not * do any assertions. * * @param writer writer to write generated code with. */ @Override protected void generateTestAssertions(GoWriter writer) { writeAssertNotNil(writer, "err"); writeAssertNil(writer, "result"); // Operation Metadata writer.openBlock("var opErr interface{", "}", () -> { writer.write("Service() string"); writer.write("Operation() string"); }); writer.addUseImports(SmithyGoDependency.ERRORS); writer.openBlock("if !errors.As(err, &opErr) {", "}", () -> { writer.write("t.Fatalf(\"expect $P operation error, got %T\", err)", errorSymbol); }); writer.openBlock("if e, a := ServiceID, opErr.Service(); e != a {", "}", () -> { writer.write("t.Errorf(\"expect %v operation service name, got %v\", e, a)"); }); writer.openBlock("if e, a := $S, opErr.Operation(); e != a {", "}", opSymbol.getName(), () -> { writer.write("t.Errorf(\"expect %v operation service name, got %v\", e, a)"); }); // Smithy API error writer.write("var actualErr $P", errorSymbol); writer.openBlock("if !errors.As(err, &actualErr) {", "}", () -> { writer.write("t.Fatalf(\"expect $P result error, got %T\", err)", errorSymbol); }); writeAssertComplexEqual(writer, "c.ExpectError", "actualErr", new String[]{"middleware.Metadata{}"}); // TODO assertion for protocol metadata } public static class Builder extends HttpProtocolUnitTestResponseGenerator.Builder { protected StructureShape error; // TODO should be a way not to define these override methods since they are all defined in the base Builder. // the return type breaks this though since this builder adds a new builder field. @Override public Builder model(Model model) { super.model(model); return this; } @Override public Builder symbolProvider(SymbolProvider symbolProvider) { super.symbolProvider(symbolProvider); return this; } @Override public Builder protocolName(String protocolName) { super.protocolName(protocolName); return this; } @Override public Builder service(ServiceShape service) { super.service(service); return this; } @Override public Builder operation(OperationShape operation) { super.operation(operation); return this; } public Builder error(StructureShape error) { this.error = error; return this; } @Override public Builder testCases(List<HttpResponseTestCase> testCases) { super.testCases(testCases); return this; } @Override public Builder addTestCases(List<HttpResponseTestCase> testCases) { super.addTestCases(testCases); return this; } @Override public Builder clientConfigValue(ConfigValue configValue) { super.clientConfigValue(configValue); return this; } @Override public Builder clientConfigValues(Set<ConfigValue> clientConfigValues) { super.clientConfigValues(clientConfigValues); return this; } @Override public Builder addClientConfigValues(Set<ConfigValue> clientConfigValues) { super.addClientConfigValues(clientConfigValues); return this; } @Override public Builder skipTest(SkipTest skipTest) { super.skipTest(skipTest); return this; } @Override public Builder skipTests(Set<SkipTest> skipTests) { super.skipTests(skipTests); return this; } @Override public Builder addSkipTests(Set<SkipTest> skipTests) { super.addSkipTests(skipTests); return this; } @Override public HttpProtocolUnitTestResponseErrorGenerator build() { return new HttpProtocolUnitTestResponseErrorGenerator(this); } } }
8,989
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/integration/ClientMemberResolver.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen.integration; import java.util.Objects; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.utils.SmithyBuilder; /** * Represent symbol that points to a function that operates * on the client member fields during client construction. * * Any configuration that a plugin requires in order to function should be * checked in this function, either setting a default value if possible or * returning an error if not. */ public final class ClientMemberResolver { private final Symbol resolver; private ClientMemberResolver(Builder builder) { resolver = SmithyBuilder.requiredState("resolver", builder.resolver); } public Symbol getResolver() { return resolver; } public static Builder builder() { return new Builder(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ClientMemberResolver that = (ClientMemberResolver) o; return resolver.equals(that.resolver); } /** * Returns a hash code value for the object. * @return the hash code. */ @Override public int hashCode() { return Objects.hash(resolver); } public static class Builder implements SmithyBuilder<ClientMemberResolver> { private Symbol resolver; public Builder resolver(Symbol resolver) { this.resolver = resolver; return this; } @Override public ClientMemberResolver build() { return new ClientMemberResolver(this); } } }
8,990
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/integration/MiddlewareRegistrar.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen.integration; import java.util.ArrayList; import java.util.Collection; import java.util.Objects; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.go.codegen.SmithyGoDependency; import software.amazon.smithy.go.codegen.SymbolUtils; import software.amazon.smithy.utils.SmithyBuilder; import software.amazon.smithy.utils.ToSmithyBuilder; public class MiddlewareRegistrar implements ToSmithyBuilder<MiddlewareRegistrar> { private final Symbol resolvedFunction; private final Collection<Symbol> functionArguments; private final String inlineRegisterMiddlewareStatement; private final Symbol inlineRegisterMiddlewarePosition; public MiddlewareRegistrar(Builder builder) { this.resolvedFunction = builder.resolvedFunction; this.functionArguments = builder.functionArguments; this.inlineRegisterMiddlewareStatement = builder.inlineRegisterMiddlewareStatement; this.inlineRegisterMiddlewarePosition = builder.inlineRegisterMiddlewarePosition; } /** * @return symbol that resolves to a function. */ public Symbol getResolvedFunction() { return resolvedFunction; } /** * @return collection of symbols denoting the arguments of the resolved function. */ public Collection<Symbol> getFunctionArguments() { return functionArguments; } /** * @return string denoting inline middleware registration in the stack */ public String getInlineRegisterMiddlewareStatement() { return inlineRegisterMiddlewareStatement; } /** * @return symbol used to define the middleware position in the stack */ public Symbol getInlineRegisterMiddlewarePosition() { return inlineRegisterMiddlewarePosition; } @Override public SmithyBuilder<MiddlewareRegistrar> toBuilder() { return builder().functionArguments(functionArguments).resolvedFunction(resolvedFunction); } public static MiddlewareRegistrar.Builder builder() { return new MiddlewareRegistrar.Builder(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } MiddlewareRegistrar that = (MiddlewareRegistrar) o; return Objects.equals(getResolvedFunction(), that.getResolvedFunction()) && Objects.equals(getFunctionArguments(), that.getFunctionArguments()); } @Override public int hashCode() { return Objects.hash(getResolvedFunction(), getFunctionArguments()); } /** * Builds a MiddlewareRegistrar. */ public static class Builder implements SmithyBuilder<MiddlewareRegistrar> { private Symbol resolvedFunction; private Collection<Symbol> functionArguments; private String inlineRegisterMiddlewareStatement; private Symbol inlineRegisterMiddlewarePosition; @Override public MiddlewareRegistrar build() { return new MiddlewareRegistrar(this); } /** * Set the name of the MiddlewareRegistrar function. * * @param resolvedFunction a symbol that resolves to the function . * @return Returns the builder. */ public Builder resolvedFunction(Symbol resolvedFunction) { this.resolvedFunction = resolvedFunction; return this; } /** * Sets the function Arguments for the MiddlewareRegistrar function. * * @param functionArguments A collection of symbols representing the arguments * to the middleware register function. * @return Returns the builder. */ public Builder functionArguments(Collection<Symbol> functionArguments) { this.functionArguments = new ArrayList<>(functionArguments); return this; } /** * Sets symbol that resolves to options as an argument for the resolved function. * * @return Returns the builder. */ public Builder useClientOptions() { Collection<Symbol> args = new ArrayList<>(); args.add(SymbolUtils.createValueSymbolBuilder("options").build()); this.functionArguments = args; return this; } /** * Adds a middleware to the middleware stack at relative position of After. * @param stackStep Stack step. * @return Returns the Builder. */ public Builder registerAfter(MiddlewareStackStep stackStep) { this.inlineRegisterMiddlewareStatement = String.format("%s.Add(", stackStep); this.inlineRegisterMiddlewarePosition = getMiddlewareAfterPositionSymbol(); return this; } /** * Adds the middleware to the middleware stack at relative position of Before. * @param stackStep Stack step at which the middleware is to be register. * @return Returns the Builder. */ public Builder registerBefore(MiddlewareStackStep stackStep) { this.inlineRegisterMiddlewareStatement = String.format("%s.Add(", stackStep); this.inlineRegisterMiddlewarePosition = getMiddlewareBeforePositionSymbol(); return this; } private Symbol getMiddlewareAfterPositionSymbol() { return SymbolUtils.createValueSymbolBuilder("After", SmithyGoDependency.SMITHY_MIDDLEWARE).build(); } private Symbol getMiddlewareBeforePositionSymbol() { return SymbolUtils.createValueSymbolBuilder("Before", SmithyGoDependency.SMITHY_MIDDLEWARE).build(); } } }
8,991
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/integration/IdempotencyTokenMiddlewareGenerator.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen.integration; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.codegen.core.SymbolProvider; import software.amazon.smithy.go.codegen.GoDelegator; import software.amazon.smithy.go.codegen.GoSettings; import software.amazon.smithy.go.codegen.GoStackStepMiddlewareGenerator; import software.amazon.smithy.go.codegen.GoWriter; import software.amazon.smithy.go.codegen.MiddlewareIdentifier; import software.amazon.smithy.go.codegen.SmithyGoDependency; import software.amazon.smithy.go.codegen.SymbolUtils; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.knowledge.OperationIndex; import software.amazon.smithy.model.knowledge.TopDownIndex; import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; import software.amazon.smithy.model.traits.IdempotencyTokenTrait; import software.amazon.smithy.utils.ListUtils; public class IdempotencyTokenMiddlewareGenerator implements GoIntegration { public static final String IDEMPOTENCY_CONFIG_NAME = "IdempotencyTokenProvider"; public static final MiddlewareIdentifier OPERATION_IDEMPOTENCY_TOKEN_MIDDLEWARE_ID = MiddlewareIdentifier .string("OperationIdempotencyTokenAutoFill"); List<RuntimeClientPlugin> runtimeClientPlugins = new ArrayList<>(); private void execute( Model model, GoWriter writer, SymbolProvider symbolProvider, OperationShape operation, MemberShape idempotencyTokenMemberShape ) { GoStackStepMiddlewareGenerator middlewareGenerator = GoStackStepMiddlewareGenerator.createInitializeStepMiddleware( getIdempotencyTokenMiddlewareName(operation), OPERATION_IDEMPOTENCY_TOKEN_MIDDLEWARE_ID ); Shape inputShape = model.expectShape(operation.getInput().get()); Symbol inputSymbol = symbolProvider.toSymbol(inputShape); String memberName = symbolProvider.toMemberName(idempotencyTokenMemberShape); middlewareGenerator.writeMiddleware(writer, (generator, middlewareWriter) -> { // if token provider is nil, skip this middleware middlewareWriter.openBlock("if m.tokenProvider == nil {", "}", () -> { middlewareWriter.write("return next.$L(ctx, in)", middlewareGenerator.getHandleMethodName()); }); writer.write(""); middlewareWriter.write("input, ok := in.Parameters.($P)", inputSymbol); middlewareWriter.write("if !ok { return out, metadata, " + "fmt.Errorf(\"expected middleware input to be of type $P \")}", inputSymbol); middlewareWriter.addUseImports(SmithyGoDependency.FMT); writer.write(""); middlewareWriter.openBlock("if input.$L == nil {", "}", memberName, () -> { middlewareWriter.write("t, err := m.tokenProvider.GetIdempotencyToken()"); middlewareWriter.write(" if err != nil { return out, metadata, err }"); middlewareWriter.write("input.$L = &t", memberName); }); middlewareWriter.write("return next.$L(ctx, in)", middlewareGenerator.getHandleMethodName()); }, ((generator, memberWriter) -> { memberWriter.write("tokenProvider IdempotencyTokenProvider"); })); } @Override public void processFinalizedModel(GoSettings settings, Model model) { ServiceShape serviceShape = settings.getService(model); Map<ShapeId, MemberShape> map = getOperationsWithIdempotencyToken(model, serviceShape); if (map.isEmpty()) { return; } runtimeClientPlugins.add( RuntimeClientPlugin.builder() .configFields(ListUtils.of(ConfigField.builder() .name(IDEMPOTENCY_CONFIG_NAME) .type(SymbolUtils.createValueSymbolBuilder("IdempotencyTokenProvider").build()) .documentation("Provides idempotency tokens values " + "that will be automatically populated into idempotent API operations.") .build())) .build() ); for (Map.Entry<ShapeId, MemberShape> entry : map.entrySet()) { ShapeId operationShapeId = entry.getKey(); OperationShape operation = model.expectShape(operationShapeId, OperationShape.class); String getMiddlewareHelperName = getIdempotencyTokenMiddlewareHelperName(operation); RuntimeClientPlugin runtimeClientPlugin = RuntimeClientPlugin.builder() .operationPredicate((predicateModel, predicateService, predicateOperation) -> { return operation.equals(predicateOperation); }) .registerMiddleware(MiddlewareRegistrar.builder() .resolvedFunction(SymbolUtils.createValueSymbolBuilder(getMiddlewareHelperName).build()) .useClientOptions() .build()) .build(); runtimeClientPlugins.add(runtimeClientPlugin); } } /** * Gets the sort order of the customization from -128 to 127, with lowest * executed first. * * @return Returns the sort order, defaults to 10. */ @Override public byte getOrder() { return 10; } @Override public void writeAdditionalFiles( GoSettings settings, Model model, SymbolProvider symbolProvider, GoDelegator delegator ) { ServiceShape serviceShape = settings.getService(model); Map<ShapeId, MemberShape> map = getOperationsWithIdempotencyToken(model, serviceShape); if (map.size() == 0) { return; } delegator.useShapeWriter(serviceShape, (writer) -> { writer.write("// IdempotencyTokenProvider interface for providing idempotency token"); writer.openBlock("type IdempotencyTokenProvider interface {", "}", () -> { writer.write("GetIdempotencyToken() (string, error)"); }); writer.write(""); }); for (Map.Entry<ShapeId, MemberShape> entry : map.entrySet()) { ShapeId operationShapeId = entry.getKey(); OperationShape operation = model.expectShape(operationShapeId, OperationShape.class); delegator.useShapeWriter(operation, (writer) -> { // Generate idempotency token middleware MemberShape memberShape = map.get(operationShapeId); execute(model, writer, symbolProvider, operation, memberShape); // Generate idempotency token middleware registrar function writer.addUseImports(SmithyGoDependency.SMITHY_MIDDLEWARE); String middlewareHelperName = getIdempotencyTokenMiddlewareHelperName(operation); writer.openBlock("func $L(stack *middleware.Stack, cfg Options) error {", "}", middlewareHelperName, () -> { writer.write("return stack.Initialize.Add(&$L{tokenProvider: cfg.$L}, middleware.Before)", getIdempotencyTokenMiddlewareName(operation), IDEMPOTENCY_CONFIG_NAME); }); }); } } @Override public List<RuntimeClientPlugin> getClientPlugins() { return runtimeClientPlugins; } /** * Get Idempotency Token Middleware name. * * @param operationShape Operation shape for which middleware is defined. * @return name of the idempotency token middleware. */ private String getIdempotencyTokenMiddlewareName(OperationShape operationShape) { return String.format("idempotencyToken_initializeOp%s", operationShape.getId().getName()); } /** * Get Idempotency Token Middleware Helper name. * * @param operationShape Operation shape for which middleware is defined. * @return name of the idempotency token middleware. */ private String getIdempotencyTokenMiddlewareHelperName(OperationShape operationShape) { return String.format("addIdempotencyToken_op%sMiddleware", operationShape.getId().getName()); } /** * Gets a map with key as OperationId and Member shape as value for member shapes of an operation * decorated with the Idempotency token trait. * * @param model Model used for generation. * @param service Service for which idempotency token map is retrieved. * @return map of operation shapeId as key, member shape as value. */ public static Map<ShapeId, MemberShape> getOperationsWithIdempotencyToken(Model model, ServiceShape service) { Map<ShapeId, MemberShape> map = new TreeMap<>(); TopDownIndex.of(model).getContainedOperations(service).stream().forEach((operationShape) -> { MemberShape memberShape = getMemberWithIdempotencyToken(model, operationShape); if (memberShape != null) { map.put(operationShape.getId(), memberShape); } }); return map; } /** * Returns if there are any operations within the service that use idempotency token auto fill trait. * * @param model Model used for generation. * @param service Service for which idempotency token map is retrieved. * @return if operations use idempotency token auto fill trait. */ public static boolean hasOperationsWithIdempotencyToken(Model model, ServiceShape service) { return !getOperationsWithIdempotencyToken(model, service).isEmpty(); } /** * Returns member shape which gets members decorated with Idempotency Token trait. * * @param model Model used for generation. * @param operation Operation shape consisting of member decorated with idempotency token trait. * @return member shape decorated with Idempotency token trait. */ private static MemberShape getMemberWithIdempotencyToken(Model model, OperationShape operation) { OperationIndex operationIndex = model.getKnowledge(OperationIndex.class); Shape inputShape = operationIndex.getInput(operation).get(); for (MemberShape member : inputShape.members()) { if (member.hasTrait(IdempotencyTokenTrait.class)) { return member; } } return null; } }
8,992
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/integration/MiddlewareStackStep.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen.integration; /** * Represents the middleware stack step. */ public enum MiddlewareStackStep { INITIALIZE, BUILD, SERIALIZE, DESERIALIZE, FINALIZE; @Override public String toString() { switch (this) { case INITIALIZE: return "Initialize"; case BUILD: return "Build"; case SERIALIZE: return "Serialize"; case DESERIALIZE: return "Deserialize"; case FINALIZE: return "Finalize"; default: return "Unknown"; } } }
8,993
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/integration/ClientMember.java
/* * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen.integration; import java.util.Objects; import java.util.Optional; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.utils.SmithyBuilder; import software.amazon.smithy.utils.ToSmithyBuilder; /** * Represents a member field on a client struct. */ public class ClientMember implements ToSmithyBuilder<ClientMember> { private final String name; private final Symbol type; private final String documentation; public ClientMember(Builder builder) { this.name = Objects.requireNonNull(builder.name); this.type = Objects.requireNonNull(builder.type); this.documentation = builder.documentation; } /** * @return Returns the name of the client member field. */ public String getName() { return name; } /** * @return Returns the type Symbol for the member field. */ public Symbol getType() { return type; } /** * @return Gets the optional documentation for the member field. */ public Optional<String> getDocumentation() { return Optional.ofNullable(documentation); } @Override public SmithyBuilder<ClientMember> toBuilder() { return builder().type(type).name(name).documentation(documentation); } public static Builder builder() { return new Builder(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ClientMember that = (ClientMember) o; return Objects.equals(getName(), that.getName()) && Objects.equals(getType(), that.getType()) && Objects.equals(getDocumentation(), that.getDocumentation()); } @Override public int hashCode() { return Objects.hash(getName(), getType(), getDocumentation()); } /** * Builds a ClientMember. */ public static class Builder implements SmithyBuilder<ClientMember> { private String name; private Symbol type; private String documentation; @Override public ClientMember build() { return new ClientMember(this); } /** * Set the name of the member field on client. * * @param name is the name of the field on the client. * @return Returns the builder. */ public Builder name(String name) { this.name = name; return this; } /** * Sets the type of the client field. * * @param type A Symbol representing the type of the client field. * @return Returns the builder. */ public Builder type(Symbol type) { this.type = type; return this; } /** * Sets the documentation for the client field. * * @param documentation The documentation for the client field. * @return Returns the builder. */ public Builder documentation(String documentation) { this.documentation = documentation; return this; } } }
8,994
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/integration/Waiters.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen.integration; import java.util.Map; import java.util.Optional; import software.amazon.smithy.codegen.core.CodegenException; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.codegen.core.SymbolProvider; import software.amazon.smithy.go.codegen.GoDelegator; import software.amazon.smithy.go.codegen.GoSettings; import software.amazon.smithy.go.codegen.GoWriter; import software.amazon.smithy.go.codegen.SmithyGoDependency; import software.amazon.smithy.go.codegen.SymbolUtils; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.knowledge.TopDownIndex; import software.amazon.smithy.model.shapes.ListShape; import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; import software.amazon.smithy.model.shapes.SimpleShape; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.utils.StringUtils; import software.amazon.smithy.waiters.Acceptor; import software.amazon.smithy.waiters.Matcher; import software.amazon.smithy.waiters.PathComparator; import software.amazon.smithy.waiters.WaitableTrait; import software.amazon.smithy.waiters.Waiter; /** * Implements support for WaitableTrait. */ public class Waiters implements GoIntegration { private static final String WAITER_INVOKER_FUNCTION_NAME = "Wait"; private static final String WAITER_INVOKER_WITH_OUTPUT_FUNCTION_NAME = "WaitForOutput"; @Override public void writeAdditionalFiles( GoSettings settings, Model model, SymbolProvider symbolProvider, GoDelegator goDelegator ) { ServiceShape serviceShape = settings.getService(model); TopDownIndex topDownIndex = TopDownIndex.of(model); topDownIndex.getContainedOperations(serviceShape).stream() .forEach(operation -> { if (!operation.hasTrait(WaitableTrait.ID)) { return; } Map<String, Waiter> waiters = operation.expectTrait(WaitableTrait.class).getWaiters(); goDelegator.useShapeWriter(operation, writer -> { generateOperationWaiter(model, symbolProvider, writer, serviceShape, operation, waiters); }); }); } /** * Generates all waiter components used for the operation. */ private void generateOperationWaiter( Model model, SymbolProvider symbolProvider, GoWriter writer, ServiceShape service, OperationShape operation, Map<String, Waiter> waiters ) { // generate waiter function waiters.forEach((name, waiter) -> { // write waiter options generateWaiterOptions(model, symbolProvider, writer, operation, name, waiter); // write waiter client generateWaiterClient(model, symbolProvider, writer, operation, name, waiter); // write waiter specific invoker generateWaiterInvoker(model, symbolProvider, writer, operation, name, waiter); // write waiter specific invoker with output generateWaiterInvokerWithOutput(model, symbolProvider, writer, operation, name, waiter); // write waiter state mutator for each waiter generateRetryable(model, symbolProvider, writer, service, operation, name, waiter); }); } /** * Generates waiter options to configure a waiter client. */ private void generateWaiterOptions( Model model, SymbolProvider symbolProvider, GoWriter writer, OperationShape operationShape, String waiterName, Waiter waiter ) { String optionsName = generateWaiterOptionsName(waiterName); String waiterClientName = generateWaiterClientName(waiterName); StructureShape inputShape = model.expectShape( operationShape.getInput().get(), StructureShape.class ); StructureShape outputShape = model.expectShape( operationShape.getOutput().get(), StructureShape.class ); Symbol inputSymbol = symbolProvider.toSymbol(inputShape); Symbol outputSymbol = symbolProvider.toSymbol(outputShape); writer.write(""); writer.writeDocs( String.format("%s are waiter options for %s", optionsName, waiterClientName) ); writer.openBlock("type $L struct {", "}", optionsName, () -> { writer.addUseImports(SmithyGoDependency.TIME); writer.write(""); writer.writeDocs( "Set of options to modify how an operation is invoked. These apply to all operations " + "invoked for this client. Use functional options on operation call to modify " + "this list for per operation behavior." ); Symbol stackSymbol = SymbolUtils.createPointableSymbolBuilder("Stack", SmithyGoDependency.SMITHY_MIDDLEWARE) .build(); writer.write("APIOptions []func($P) error", stackSymbol); writer.write(""); writer.writeDocs( String.format("MinDelay is the minimum amount of time to delay between retries. " + "If unset, %s will use default minimum delay of %s seconds. " + "Note that MinDelay must resolve to a value lesser than or equal " + "to the MaxDelay.", waiterClientName, waiter.getMinDelay()) ); writer.write("MinDelay time.Duration"); writer.write(""); writer.writeDocs( String.format("MaxDelay is the maximum amount of time to delay between retries. " + "If unset or set to zero, %s will use default max delay of %s seconds. " + "Note that MaxDelay must resolve to value greater than or equal " + "to the MinDelay.", waiterClientName, waiter.getMaxDelay()) ); writer.write("MaxDelay time.Duration"); writer.write(""); writer.writeDocs("LogWaitAttempts is used to enable logging for waiter retry attempts"); writer.write("LogWaitAttempts bool"); writer.write(""); writer.writeDocs( "Retryable is function that can be used to override the " + "service defined waiter-behavior based on operation output, or returned error. " + "This function is used by the waiter to decide if a state is retryable " + "or a terminal state.\n\nBy default service-modeled logic " + "will populate this option. This option can thus be used to define a custom " + "waiter state with fall-back to service-modeled waiter state mutators." + "The function returns an error in case of a failure state. " + "In case of retry state, this function returns a bool value of true and " + "nil error, while in case of success it returns a bool value of false and " + "nil error." ); writer.write( "Retryable func(context.Context, $P, $P, error) " + "(bool, error)", inputSymbol, outputSymbol); } ); writer.write(""); } /** * Generates waiter client used to invoke waiter function. The waiter client is specific to a modeled waiter. * Each waiter client is unique within a enclosure of a service. * This function also generates a waiter client constructor that takes in a API client interface, and waiter options * to configure a waiter client. */ private void generateWaiterClient( Model model, SymbolProvider symbolProvider, GoWriter writer, OperationShape operationShape, String waiterName, Waiter waiter ) { Symbol operationSymbol = symbolProvider.toSymbol(operationShape); String clientName = generateWaiterClientName(waiterName); writer.write(""); writer.writeDocs( String.format("%s defines the waiters for %s", clientName, waiterName) ); writer.openBlock("type $L struct {", "}", clientName, () -> { writer.write(""); writer.write("client $L", OperationInterfaceGenerator.getApiClientInterfaceName(operationSymbol)); writer.write(""); writer.write("options $L", generateWaiterOptionsName(waiterName)); }); writer.write(""); String constructorName = String.format("New%s", clientName); Symbol waiterOptionsSymbol = SymbolUtils.createPointableSymbolBuilder( generateWaiterOptionsName(waiterName) ).build(); Symbol clientSymbol = SymbolUtils.createPointableSymbolBuilder( clientName ).build(); writer.writeDocs( String.format("%s constructs a %s.", constructorName, clientName) ); writer.openBlock("func $L(client $L, optFns ...func($P)) $P {", "}", constructorName, OperationInterfaceGenerator.getApiClientInterfaceName(operationSymbol), waiterOptionsSymbol, clientSymbol, () -> { writer.write("options := $T{}", waiterOptionsSymbol); writer.addUseImports(SmithyGoDependency.TIME); // set defaults writer.write("options.MinDelay = $L * time.Second", waiter.getMinDelay()); writer.write("options.MaxDelay = $L * time.Second", waiter.getMaxDelay()); writer.write("options.Retryable = $L", generateRetryableName(waiterName)); writer.write(""); writer.openBlock("for _, fn := range optFns {", "}", () -> { writer.write("fn(&options)"); }); writer.openBlock("return &$T {", "}", clientSymbol, () -> { writer.write("client: client, "); writer.write("options: options, "); }); }); } /** * Generates waiter invoker functions to call specific operation waiters * These waiter invoker functions is defined on each modeled waiter client. * The invoker function takes in a context, along with operation input, and * optional functional options for the waiter. */ private void generateWaiterInvoker( Model model, SymbolProvider symbolProvider, GoWriter writer, OperationShape operationShape, String waiterName, Waiter waiter ) { StructureShape inputShape = model.expectShape( operationShape.getInput().get(), StructureShape.class ); Symbol inputSymbol = symbolProvider.toSymbol(inputShape); Symbol waiterOptionsSymbol = SymbolUtils.createPointableSymbolBuilder( generateWaiterOptionsName(waiterName) ).build(); Symbol clientSymbol = SymbolUtils.createPointableSymbolBuilder( generateWaiterClientName(waiterName) ).build(); writer.write(""); writer.addUseImports(SmithyGoDependency.CONTEXT); writer.addUseImports(SmithyGoDependency.TIME); writer.writeDocs( String.format( "%s calls the waiter function for %s waiter. The maxWaitDur is the maximum wait duration " + "the waiter will wait. The maxWaitDur is required and must be greater than zero.", WAITER_INVOKER_FUNCTION_NAME, waiterName) ); writer.openBlock( "func (w $P) $L(ctx context.Context, params $P, maxWaitDur time.Duration, optFns ...func($P)) error {", "}", clientSymbol, WAITER_INVOKER_FUNCTION_NAME, inputSymbol, waiterOptionsSymbol, () -> { writer.write( "_, err := w.$L(ctx, params, maxWaitDur, optFns...)", WAITER_INVOKER_WITH_OUTPUT_FUNCTION_NAME ); writer.write("return err"); }); } /** * Generates waiter invoker functions to call specific operation waiters * and return the output of the successful operation. * These waiter invoker functions is defined on each modeled waiter client. * The invoker function takes in a context, along with operation input, and * optional functional options for the waiter. */ private void generateWaiterInvokerWithOutput( Model model, SymbolProvider symbolProvider, GoWriter writer, OperationShape operationShape, String waiterName, Waiter waiter ) { StructureShape inputShape = model.expectShape( operationShape.getInput().get(), StructureShape.class ); StructureShape outputShape = model.expectShape( operationShape.getOutput().get(), StructureShape.class ); Symbol operationSymbol = symbolProvider.toSymbol(operationShape); Symbol inputSymbol = symbolProvider.toSymbol(inputShape); Symbol outputSymbol = symbolProvider.toSymbol(outputShape); Symbol waiterOptionsSymbol = SymbolUtils.createPointableSymbolBuilder( generateWaiterOptionsName(waiterName) ).build(); Symbol clientSymbol = SymbolUtils.createPointableSymbolBuilder( generateWaiterClientName(waiterName) ).build(); writer.write(""); writer.addUseImports(SmithyGoDependency.CONTEXT); writer.addUseImports(SmithyGoDependency.TIME); writer.writeDocs( String.format( "%s calls the waiter function for %s waiter and returns the output of the successful " + "operation. The maxWaitDur is the maximum wait duration the waiter will wait. The " + "maxWaitDur is required and must be greater than zero.", WAITER_INVOKER_WITH_OUTPUT_FUNCTION_NAME, waiterName) ); writer.openBlock( "func (w $P) $L(ctx context.Context, params $P, maxWaitDur time.Duration, optFns ...func($P)) " + "($P, error) {", "}", clientSymbol, WAITER_INVOKER_WITH_OUTPUT_FUNCTION_NAME, inputSymbol, waiterOptionsSymbol, outputSymbol, () -> { writer.openBlock("if maxWaitDur <= 0 {", "}", () -> { writer.addUseImports(SmithyGoDependency.FMT); writer.write( "return nil, fmt.Errorf(\"maximum wait time for waiter must be greater than zero\")" ); }).write(""); writer.write("options := w.options"); writer.openBlock("for _, fn := range optFns {", "}", () -> { writer.write("fn(&options)"); }); writer.write(""); // validate values for MaxDelay from options writer.openBlock("if options.MaxDelay <= 0 {", "}", () -> { writer.write("options.MaxDelay = $L * time.Second", waiter.getMaxDelay()); }); writer.write(""); // validate that MinDelay is lesser than or equal to resolved MaxDelay writer.openBlock("if options.MinDelay > options.MaxDelay {", "}", () -> { writer.addUseImports(SmithyGoDependency.FMT); writer.write("return nil, fmt.Errorf(\"minimum waiter delay %v must be lesser than or equal to " + "maximum waiter delay of %v.\", options.MinDelay, options.MaxDelay)"); }).write(""); writer.addUseImports(SmithyGoDependency.CONTEXT); writer.write("ctx, cancelFn := context.WithTimeout(ctx, maxWaitDur)"); writer.write("defer cancelFn()"); writer.write(""); Symbol loggerMiddleware = SymbolUtils.createValueSymbolBuilder( "Logger", SmithyGoDependency.SMITHY_WAITERS ).build(); writer.write("logger := $T{}", loggerMiddleware); writer.write("remainingTime := maxWaitDur").write(""); writer.write("var attempt int64"); writer.openBlock("for {", "}", () -> { writer.write(""); writer.write("attempt++"); writer.write("apiOptions := options.APIOptions"); writer.write("start := time.Now()").write(""); // add waiter logger middleware to log an attempt, if LogWaitAttempts is enabled. writer.openBlock("if options.LogWaitAttempts {", "}", () -> { writer.write("logger.Attempt = attempt"); writer.write( "apiOptions = append([]func(*middleware.Stack) error{}, options.APIOptions...)"); writer.write("apiOptions = append(apiOptions, logger.AddLogger)"); }).write(""); // make a request writer.openBlock("out, err := w.client.$T(ctx, params, func (o *Options) { ", "})", operationSymbol, () -> { writer.write("o.APIOptions = append(o.APIOptions, apiOptions...)"); }); writer.write(""); // handle response and identify waiter state writer.write("retryable, err := options.Retryable(ctx, params, out, err)"); writer.write("if err != nil { return nil, err }"); writer.write("if !retryable { return out, nil }").write(""); // update remaining time writer.write("remainingTime -= time.Since(start)"); // check if next iteration is possible writer.openBlock("if remainingTime < options.MinDelay || remainingTime <= 0 {", "}", () -> { writer.write("break"); }); writer.write(""); // handle retry delay computation, sleep. Symbol computeDelaySymbol = SymbolUtils.createValueSymbolBuilder( "ComputeDelay", SmithyGoDependency.SMITHY_WAITERS ).build(); writer.writeDocs("compute exponential backoff between waiter retries"); writer.openBlock("delay, err := $T(", ")", computeDelaySymbol, () -> { writer.write("attempt, options.MinDelay, options.MaxDelay, remainingTime,"); }); writer.addUseImports(SmithyGoDependency.FMT); writer.write( "if err != nil { return nil, fmt.Errorf(\"error computing waiter delay, %w\", err)}"); writer.write(""); // update remaining time as per computed delay writer.write("remainingTime -= delay"); // sleep for delay Symbol sleepWithContextSymbol = SymbolUtils.createValueSymbolBuilder( "SleepWithContext", SmithyGoDependency.SMITHY_TIME ).build(); writer.writeDocs("sleep for the delay amount before invoking a request"); writer.openBlock("if err := $T(ctx, delay); err != nil {", "}", sleepWithContextSymbol, () -> { writer.write( "return nil, fmt.Errorf(\"request cancelled while waiting, %w\", err)"); }); }); writer.write("return nil, fmt.Errorf(\"exceeded max wait time for $L waiter\")", waiterName); }); } /** * Generates a waiter state mutator function which is used by the waiter retrier Middleware to mutate * waiter state as per the defined logic and returned operation response. * * @param model the smithy model * @param symbolProvider symbol provider * @param writer the Gowriter * @param serviceShape service shape for which operation waiter is modeled * @param operationShape operation shape on which the waiter is modeled * @param waiterName the waiter name * @param waiter the waiter structure that contains info on modeled waiter */ private void generateRetryable( Model model, SymbolProvider symbolProvider, GoWriter writer, ServiceShape serviceShape, OperationShape operationShape, String waiterName, Waiter waiter ) { StructureShape inputShape = model.expectShape( operationShape.getInput().get(), StructureShape.class ); StructureShape outputShape = model.expectShape( operationShape.getOutput().get(), StructureShape.class ); Symbol inputSymbol = symbolProvider.toSymbol(inputShape); Symbol outputSymbol = symbolProvider.toSymbol(outputShape); writer.write(""); writer.openBlock("func $L(ctx context.Context, input $P, output $P, err error) (bool, error) {", "}", generateRetryableName(waiterName), inputSymbol, outputSymbol, () -> { waiter.getAcceptors().forEach(acceptor -> { writer.write(""); // scope each acceptor to avoid name collisions Matcher matcher = acceptor.getMatcher(); switch (matcher.getMemberName()) { case "output": writer.addUseImports(SmithyGoDependency.GO_JMESPATH); writer.addUseImports(SmithyGoDependency.FMT); Matcher.OutputMember outputMember = (Matcher.OutputMember) matcher; String path = outputMember.getValue().getPath(); String expectedValue = outputMember.getValue().getExpected(); PathComparator comparator = outputMember.getValue().getComparator(); writer.openBlock("if err == nil {", "}", () -> { writer.write("pathValue, err := jmespath.Search($S, output)", path); writer.openBlock("if err != nil {", "}", () -> { writer.write( "return false, " + "fmt.Errorf(\"error evaluating waiter state: %w\", err)"); }).write(""); writer.write("expectedValue := $S", expectedValue); if (comparator == PathComparator.BOOLEAN_EQUALS) { writeWaiterComparator(writer, acceptor, comparator, null, "pathValue", "expectedValue"); } else { String[] pathMembers = path.split("\\."); Shape targetShape = outputShape; for (int i = 0; i < pathMembers.length; i++) { MemberShape member = getComparedMember(model, targetShape, pathMembers[i]); if (member == null) { targetShape = null; break; } targetShape = model.expectShape(member.getTarget()); } if (targetShape == null) { writeWaiterComparator(writer, acceptor, comparator, null, "pathValue", "expectedValue"); } else { Symbol targetSymbol = symbolProvider.toSymbol(targetShape); writeWaiterComparator(writer, acceptor, comparator, targetSymbol, "pathValue", "expectedValue"); } } }); break; case "inputOutput": writer.addUseImports(SmithyGoDependency.GO_JMESPATH); writer.addUseImports(SmithyGoDependency.FMT); Matcher.InputOutputMember ioMember = (Matcher.InputOutputMember) matcher; path = ioMember.getValue().getPath(); expectedValue = ioMember.getValue().getExpected(); comparator = ioMember.getValue().getComparator(); writer.openBlock("if err == nil {", "}", () -> { writer.openBlock("pathValue, err := jmespath.Search($S, &struct{", "})", path, () -> { writer.write("Input $P \n Output $P \n }{", inputSymbol, outputSymbol); writer.write("Input: input, \n Output: output, \n"); }); writer.openBlock("if err != nil {", "}", () -> { writer.write( "return false, " + "fmt.Errorf(\"error evaluating waiter state: %w\", err)"); }); writer.write(""); writer.write("expectedValue := $S", expectedValue); writeWaiterComparator(writer, acceptor, comparator, outputSymbol, "pathValue", "expectedValue"); }); break; case "success": Matcher.SuccessMember successMember = (Matcher.SuccessMember) matcher; writer.openBlock("if err == nil {", "}", () -> { writeMatchedAcceptorReturn(writer, acceptor); }); break; case "errorType": Matcher.ErrorTypeMember errorTypeMember = (Matcher.ErrorTypeMember) matcher; String errorType = errorTypeMember.getValue(); writer.openBlock("if err != nil {", "}", () -> { // identify if this is a modeled error shape Optional<ShapeId> errorShapeId = operationShape.getErrors().stream().filter( shapeId -> { return shapeId.getName(serviceShape).equalsIgnoreCase(errorType); }).findFirst(); // if modeled error shape if (errorShapeId.isPresent()) { Shape errorShape = model.expectShape(errorShapeId.get()); Symbol modeledErrorSymbol = symbolProvider.toSymbol(errorShape); writer.addUseImports(SmithyGoDependency.ERRORS); writer.write("var errorType *$T", modeledErrorSymbol); writer.openBlock("if errors.As(err, &errorType) {", "}", () -> { writeMatchedAcceptorReturn(writer, acceptor); }); } else { // fall back to un-modeled error shape matching writer.addUseImports(SmithyGoDependency.SMITHY); writer.addUseImports(SmithyGoDependency.ERRORS); // assert unmodeled error to smithy's API error writer.write("var apiErr smithy.APIError"); writer.write("ok := errors.As(err, &apiErr)"); writer.openBlock("if !ok {", "}", () -> { writer.write("return false, " + "fmt.Errorf(\"expected err to be of type smithy.APIError, " + "got %w\", err)"); }); writer.write(""); writer.openBlock("if $S == apiErr.ErrorCode() {", "}", errorType, () -> { writeMatchedAcceptorReturn(writer, acceptor); }); } }); break; default: throw new CodegenException( String.format("unknown waiter state : %v", matcher.getMemberName()) ); } }); writer.write(""); writer.write("return true, nil"); }); } /** * writes comparators for a given waiter. The comparators are defined within the waiter acceptor. * * @param writer the Gowriter * @param acceptor the waiter acceptor that defines the comparator and acceptor states * @param comparator the comparator * @param targetSymbol the shape symbol of the compared type. * @param actual the variable carrying the actual value obtained. * This may be computed via a jmespath expression or operation response status (success/failure) * @param expected the variable carrying the expected value. This value is as per the modeled waiter. */ private void writeWaiterComparator( GoWriter writer, Acceptor acceptor, PathComparator comparator, Symbol targetSymbol, String actual, String expected ) { if (targetSymbol == null) { targetSymbol = SymbolUtils.createValueSymbolBuilder("string").build(); } String valueAccessor = "string(value)"; Optional<Boolean> isPointable = targetSymbol.getProperty(SymbolUtils.POINTABLE, Boolean.class); if (isPointable.isPresent() && isPointable.get().booleanValue()) { valueAccessor = "string(*value)"; } switch (comparator) { case STRING_EQUALS: writer.write("value, ok := $L.($P)", actual, targetSymbol); writer.write("if !ok {"); writer.write("return false, fmt.Errorf(\"waiter comparator expected $P value, got %T\", $L)}", targetSymbol, actual); writer.write(""); writer.openBlock("if $L == $L {", "}", valueAccessor, expected, () -> { writeMatchedAcceptorReturn(writer, acceptor); }); break; case BOOLEAN_EQUALS: writer.addUseImports(SmithyGoDependency.STRCONV); writer.write("bv, err := strconv.ParseBool($L)", expected); writer.write( "if err != nil { return false, " + "fmt.Errorf(\"error parsing boolean from string %w\", err)}"); writer.write("value, ok := $L.(bool)", actual); writer.openBlock(" if !ok {", "}", () -> { writer.write("return false, " + "fmt.Errorf(\"waiter comparator expected bool value got %T\", $L)", actual); }); writer.write(""); writer.openBlock("if value == bv {", "}", () -> { writeMatchedAcceptorReturn(writer, acceptor); }); break; case ALL_STRING_EQUALS: writer.write("var match = true"); writer.write("listOfValues, ok := $L.([]interface{})", actual); writer.openBlock(" if !ok {", "}", () -> { writer.write("return false, " + "fmt.Errorf(\"waiter comparator expected list got %T\", $L)", actual); }); writer.write(""); writer.write("if len(listOfValues) == 0 { match = false }"); String allStringValueAccessor = valueAccessor; Symbol allStringTargetSymbol = targetSymbol; writer.openBlock("for _, v := range listOfValues {", "}", () -> { writer.write("value, ok := v.($P)", allStringTargetSymbol); writer.write("if !ok {"); writer.write("return false, fmt.Errorf(\"waiter comparator expected $P value, got %T\", $L)}", allStringTargetSymbol, actual); writer.write(""); writer.write("if $L != $L { match = false }", allStringValueAccessor, expected); }); writer.write(""); writer.openBlock("if match {", "}", () -> { writeMatchedAcceptorReturn(writer, acceptor); }); break; case ANY_STRING_EQUALS: writer.write("listOfValues, ok := $L.([]interface{})", actual); writer.openBlock(" if !ok {", "}", () -> { writer.write("return false, " + "fmt.Errorf(\"waiter comparator expected list got %T\", $L)", actual); }); writer.write(""); String anyStringValueAccessor = valueAccessor; Symbol anyStringTargetSymbol = targetSymbol; writer.openBlock("for _, v := range listOfValues {", "}", () -> { writer.write("value, ok := v.($P)", anyStringTargetSymbol); writer.write("if !ok {"); writer.write("return false, fmt.Errorf(\"waiter comparator expected $P value, got %T\", $L)}", anyStringTargetSymbol, actual); writer.write(""); writer.openBlock("if $L == $L {", "}", anyStringValueAccessor, expected, () -> { writeMatchedAcceptorReturn(writer, acceptor); }); }); break; default: throw new CodegenException( String.format("Found unknown waiter path comparator, %s", comparator.toString())); } } /** * Writes return statement for state where a waiter's acceptor state is a match. * * @param writer the Go writer * @param acceptor the waiter acceptor who's state is used to write an appropriate return statement. */ private void writeMatchedAcceptorReturn(GoWriter writer, Acceptor acceptor) { switch (acceptor.getState()) { case SUCCESS: writer.write("return false, nil"); break; case FAILURE: writer.addUseImports(SmithyGoDependency.FMT); writer.write("return false, fmt.Errorf(\"waiter state transitioned to Failure\")"); break; case RETRY: writer.write("return true, nil"); break; default: throw new CodegenException("unknown acceptor state defined for the waiter"); } } private String generateWaiterOptionsName( String waiterName ) { waiterName = StringUtils.capitalize(waiterName); return String.format("%sWaiterOptions", waiterName); } private String generateWaiterClientName( String waiterName ) { waiterName = StringUtils.capitalize(waiterName); return String.format("%sWaiter", waiterName); } private String generateRetryableName( String waiterName ) { waiterName = StringUtils.uncapitalize(waiterName); return String.format("%sStateRetryable", waiterName); } /** * Returns the MemberShape wrt to the provided Shape and name. * For eg, If shape `A` has MemberShape `B`, and the name provided is `B` as string. * We return the MemberShape `B`. * * @param model the generation model. * @param shape the shape that is walked to retreive the shape matching provided name. * @param name name is a single scope path string, and should only match to one or less shapes. * @return MemberShape matching the name. */ private MemberShape getComparedMember(Model model, Shape shape, String name) { name = name.replaceAll("\\[\\]", ""); // if shape is a simple shape, just return shape as member shape if (shape instanceof SimpleShape) { return shape.asMemberShape().get(); } switch (shape.getType()) { case STRUCTURE: StructureShape st = shape.asStructureShape().get(); for (MemberShape memberShape : st.getAllMembers().values()) { if (name.equalsIgnoreCase(memberShape.getMemberName())) { return memberShape; } } break; case LIST: ListShape listShape = shape.asListShape().get(); MemberShape listMember = listShape.getMember(); Shape listTarget = model.expectShape(listMember.getTarget()); return getComparedMember(model, listTarget, name); default: // TODO: add support for * usage with jmespath expression. return null; } // TODO: add support for * usage with jmespath expression. // return null if no shape type matched (this would happen in case of * usage with jmespath expression). return null; } }
8,995
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/integration/EndpointHostPrefixMiddleware.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * * */ package software.amazon.smithy.go.codegen.integration; import java.util.ArrayList; import java.util.List; import software.amazon.smithy.codegen.core.SymbolProvider; import software.amazon.smithy.go.codegen.GoDelegator; import software.amazon.smithy.go.codegen.GoSettings; import software.amazon.smithy.go.codegen.GoStackStepMiddlewareGenerator; import software.amazon.smithy.go.codegen.GoWriter; import software.amazon.smithy.go.codegen.MiddlewareIdentifier; import software.amazon.smithy.go.codegen.SmithyGoDependency; import software.amazon.smithy.go.codegen.SymbolUtils; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.knowledge.TopDownIndex; import software.amazon.smithy.model.pattern.SmithyPattern; import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.traits.EndpointTrait; /** * EndpointHostPrefixMiddleware adds middlewares to identify * a host prefix and mutate the request URL host if permitted. **/ public class EndpointHostPrefixMiddleware implements GoIntegration { private static final MiddlewareIdentifier MIDDLEWARE_ID = MiddlewareIdentifier.string("EndpointHostPrefix"); final List<RuntimeClientPlugin> runtimeClientPlugins = new ArrayList<>(); final List<OperationShape> endpointPrefixOperations = new ArrayList<>(); @Override public void processFinalizedModel(GoSettings settings, Model model) { ServiceShape service = settings.getService(model); endpointPrefixOperations.addAll(getOperationsWithEndpointPrefix(model, service)); endpointPrefixOperations.forEach((operation) -> { String middlewareHelperName = getMiddlewareHelperName(operation); runtimeClientPlugins.add(RuntimeClientPlugin.builder() .operationPredicate((m, s, o) -> o.equals(operation)) .registerMiddleware(MiddlewareRegistrar.builder() .resolvedFunction(SymbolUtils.createValueSymbolBuilder(middlewareHelperName).build()) .build()) .build() ); }); } @Override public List<RuntimeClientPlugin> getClientPlugins() { return runtimeClientPlugins; } @Override public void writeAdditionalFiles( GoSettings settings, Model model, SymbolProvider symbolProvider, GoDelegator delegator ) { endpointPrefixOperations.forEach((operation) -> { delegator.useShapeWriter(operation, (writer) -> { SmithyPattern pattern = operation.expectTrait(EndpointTrait.class).getHostPrefix(); writeMiddleware(writer, model, symbolProvider, operation, pattern); String middlewareName = getMiddlewareName(operation); String middlewareHelperName = getMiddlewareHelperName(operation); writer.addUseImports(SmithyGoDependency.SMITHY_MIDDLEWARE); writer.openBlock("func $L(stack *middleware.Stack) error {", "}", middlewareHelperName, () -> { writer.write( "return stack.Serialize.Insert(&$L{}, `OperationSerializer`, middleware.After)", middlewareName); }); }); }); } private static void writeMiddleware( GoWriter writer, Model model, SymbolProvider symbolProvider, OperationShape operation, SmithyPattern pattern ) { GoStackStepMiddlewareGenerator middlewareGenerator = GoStackStepMiddlewareGenerator.createSerializeStepMiddleware( getMiddlewareName(operation), MIDDLEWARE_ID ); middlewareGenerator.writeMiddleware(writer, (generator, w) -> { writer.addUseImports(SmithyGoDependency.SMITHY_HTTP_TRANSPORT); writer.addUseImports(SmithyGoDependency.FMT); w.openBlock("if smithyhttp.GetHostnameImmutable(ctx) || " + "smithyhttp.IsEndpointHostPrefixDisabled(ctx) {", "}", () -> { w.write("return next.$L(ctx, in)", generator.getHandleMethodName()); }).write(""); w.write("req, ok := in.Request.(*smithyhttp.Request)"); w.openBlock("if !ok {", "}", () -> { writer.write("return out, metadata, fmt.Errorf(\"unknown transport type %T\", in.Request)"); }).write(""); if (pattern.getLabels().isEmpty()) { w.write("req.URL.Host = $S + req.URL.Host", pattern.toString()); } else { // If the pattern has labels, we need to build up the host prefix using a string builder. writer.addUseImports(SmithyGoDependency.STRINGS); writer.addUseImports(SmithyGoDependency.SMITHY); StructureShape input = ProtocolUtils.expectInput(model, operation); writer.write("input, ok := in.Parameters.($P)", symbolProvider.toSymbol(input)); w.openBlock("if !ok {", "}", () -> { writer.write("return out, metadata, fmt.Errorf(\"unknown input type %T\", in.Parameters)"); }).write(""); w.write("var prefix strings.Builder"); for (SmithyPattern.Segment segment : pattern.getSegments()) { if (!segment.isLabel()) { w.write("prefix.WriteString($S)", segment.toString()); } else { MemberShape member = input.getMember(segment.getContent()).get(); String memberName = symbolProvider.toMemberName(member); String memberReference = "input." + memberName; // Theoretically this should never be nil or empty by this point unless validation has // been disabled. w.write("if $L == nil {", memberReference).indent(); w.write("return out, metadata, &smithy.SerializationError{Err: " + "fmt.Errorf(\"$L forms part of the endpoint host and so may not be nil\")}", memberName); w.dedent().write("} else if !smithyhttp.ValidHostLabel(*$L) {", memberReference).indent(); w.write("return out, metadata, &smithy.SerializationError{Err: " + "fmt.Errorf(\"$L forms part of the endpoint host and so must match " + "\\\"[a-zA-Z0-9-]{1,63}\\\"" + ", but was \\\"%s\\\"\", *$L)}", memberName, memberReference); w.dedent().openBlock("} else {", "}", () -> { w.write("prefix.WriteString(*$L)", memberReference); }); } } w.write("req.URL.Host = prefix.String() + req.URL.Host"); } w.write(""); w.write("return next.$L(ctx, in)", generator.getHandleMethodName()); }); } /** * Gets a list of the operations decorated with the EndpointTrait. * * @param model Model used for generation. * @param service Service for getting list of operations. * @return list of operations decorated with the EndpointTrait. */ public static List<OperationShape> getOperationsWithEndpointPrefix(Model model, ServiceShape service) { List<OperationShape> operations = new ArrayList<>(); TopDownIndex.of(model).getContainedOperations(service).stream().forEach((operation) -> { if (!operation.hasTrait(EndpointTrait.ID)) { return; } operations.add(operation); }); return operations; } private static String getMiddlewareName(OperationShape operation) { return String.format("endpointPrefix_op%sMiddleware", operation.getId().getName()); } private static String getMiddlewareHelperName(OperationShape operation) { return String.format("addEndpointPrefix_op%sMiddleware", operation.getId().getName()); } }
8,996
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/integration/HttpProtocolTestGenerator.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen.integration; import static java.lang.String.format; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.TreeSet; import java.util.logging.Logger; import software.amazon.smithy.codegen.core.SymbolProvider; import software.amazon.smithy.go.codegen.GoDelegator; import software.amazon.smithy.go.codegen.GoSettings; import software.amazon.smithy.go.codegen.GoWriter; import software.amazon.smithy.go.codegen.ShapeValueGenerator; import software.amazon.smithy.go.codegen.integration.ProtocolGenerator.GenerationContext; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.knowledge.OperationIndex; import software.amazon.smithy.model.knowledge.TopDownIndex; import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.protocoltests.traits.HttpMessageTestCase; import software.amazon.smithy.protocoltests.traits.HttpRequestTestCase; import software.amazon.smithy.protocoltests.traits.HttpRequestTestsTrait; import software.amazon.smithy.protocoltests.traits.HttpResponseTestCase; import software.amazon.smithy.protocoltests.traits.HttpResponseTestsTrait; import software.amazon.smithy.utils.IoUtils; /** * Generates protocol unit tests for the HTTP protocol from smithy models. */ public class HttpProtocolTestGenerator { private static final Logger LOGGER = Logger.getLogger(HttpProtocolTestGenerator.class.getName()); private final SymbolProvider symbolProvider; private final GoSettings settings; private final GoWriter writer; private final GoDelegator delegator; private final Model model; private final ServiceShape service; private final String protocolName; private final Set<String> additionalStubs = new TreeSet<>(); private final HttpProtocolUnitTestRequestGenerator.Builder requestTestBuilder; private final HttpProtocolUnitTestResponseGenerator.Builder responseTestBuilder; private final HttpProtocolUnitTestResponseErrorGenerator.Builder responseErrorTestBuilder; /** * Initializes the protocol generator. * * @param context Protocol generation context. * @param requestTestBuilder builder that will create a request test generator. * @param responseTestBuilder build that will create a response test generator. * @param responseErrorTestBuilder builder that will create a response API error test generator. */ public HttpProtocolTestGenerator( GenerationContext context, HttpProtocolUnitTestRequestGenerator.Builder requestTestBuilder, HttpProtocolUnitTestResponseGenerator.Builder responseTestBuilder, HttpProtocolUnitTestResponseErrorGenerator.Builder responseErrorTestBuilder ) { this.settings = context.getSettings(); this.model = context.getModel(); this.service = context.getService(); this.protocolName = context.getProtocolName(); this.symbolProvider = context.getSymbolProvider(); this.writer = context.getWriter().get(); this.delegator = context.getDelegator(); this.requestTestBuilder = requestTestBuilder; this.responseTestBuilder = responseTestBuilder; this.responseErrorTestBuilder = responseErrorTestBuilder; } /** * Generates the API HTTP protocol tests defined in the smithy model. */ public void generateProtocolTests() { OperationIndex operationIndex = model.getKnowledge(OperationIndex.class); TopDownIndex topDownIndex = model.getKnowledge(TopDownIndex.class); for (OperationShape operation : new TreeSet<>(topDownIndex.getContainedOperations(service))) { if (operation.hasTag("server-only")) { continue; } // 1. Generate test cases for each request. operation.getTrait(HttpRequestTestsTrait.class).ifPresent(trait -> { final List<HttpRequestTestCase> testCases = filterProtocolTestCases(trait.getTestCases()); if (testCases.isEmpty()) { return; } delegator.useShapeTestWriter(operation, (writer) -> { LOGGER.fine(() -> format("Generating request protocol test case for %s", operation.getId())); requestTestBuilder.model(model) .symbolProvider(symbolProvider) .protocolName(protocolName) .service(service) .operation(operation) .testCases(trait.getTestCases()) .build() .generateTestFunction(writer); }); }); // 2. Generate test cases for each response. operation.getTrait(HttpResponseTestsTrait.class).ifPresent(trait -> { final List<HttpResponseTestCase> testCases = filterProtocolTestCases(trait.getTestCases()); if (testCases.isEmpty()) { return; } delegator.useShapeTestWriter(operation, (writer) -> { LOGGER.fine(() -> format("Generating response protocol test case for %s", operation.getId())); responseTestBuilder.model(model) .symbolProvider(symbolProvider) .protocolName(protocolName) .service(service) .operation(operation) .testCases(trait.getTestCases()) .shapeValueGeneratorConfig(ShapeValueGenerator.Config.builder() .normalizeHttpPrefixHeaderKeys(true).build()) .build() .generateTestFunction(writer); }); }); // 3. Generate test cases for each error on each operation. for (StructureShape error : operationIndex.getErrors(operation)) { if (error.hasTag("server-only")) { continue; } error.getTrait(HttpResponseTestsTrait.class).ifPresent(trait -> { final List<HttpResponseTestCase> testCases = filterProtocolTestCases(trait.getTestCases()); if (testCases.isEmpty()) { return; } delegator.useShapeTestWriter(operation, (writer) -> { LOGGER.fine(() -> format("Generating response error protocol test case for %s", operation.getId())); responseErrorTestBuilder.model(model) .symbolProvider(symbolProvider) .protocolName(protocolName) .service(service) .operation(operation) .error(error) .testCases(trait.getTestCases()) .build() .generateTestFunction(writer); }); }); } } // Include any additional stubs required. for (String additionalStub : additionalStubs) { writer.write(IoUtils.readUtf8Resource(getClass(), additionalStub)); } } private <T extends HttpMessageTestCase> List<T> filterProtocolTestCases(List<T> testCases) { List<T> filtered = new ArrayList<>(); for (T testCase : testCases) { if (testCase.getProtocol().equals(settings.getProtocol())) { filtered.add(testCase); } } return filtered; } }
8,997
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/integration/GoIntegration.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.go.codegen.integration; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.function.Consumer; import software.amazon.smithy.codegen.core.SymbolProvider; import software.amazon.smithy.go.codegen.GoDelegator; import software.amazon.smithy.go.codegen.GoSettings; import software.amazon.smithy.go.codegen.GoWriter; import software.amazon.smithy.go.codegen.TriConsumer; import software.amazon.smithy.go.codegen.endpoints.EndpointBuiltInHandler; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.Shape; /** * Java SPI for customizing Go code generation, registering * new protocol code generators, renaming shapes, modifying the model, * adding custom code, etc. */ public interface GoIntegration { /** * Gets the sort order of the customization from -128 to 127. * * <p>Customizations are applied according to this sort order. Lower values * are executed before higher values (for example, -128 comes before 0, * comes before 127). Customizations default to 0, which is the middle point * between the minimum and maximum order values. The customization * applied later can override the runtime configurations that provided * by customizations applied earlier. * * @return Returns the sort order, defaulting to 0. */ default byte getOrder() { return 0; } /** * Preprocess the model before code generation. * * <p>This can be used to remove unsupported features, remove traits * from shapes (e.g., make members optional), etc. * * @param model model definition. * @param settings Setting used to generate. * @return Returns the updated model. */ default Model preprocessModel(Model model, GoSettings settings) { return model; } /** * Updates the {@link SymbolProvider} used when generating code. * * <p>This can be used to customize the names of shapes, the package * that code is generated into, add dependencies, add imports, etc. * * @param settings Setting used to generate. * @param model Model being generated. * @param symbolProvider The original {@code SymbolProvider}. * @return The decorated {@code SymbolProvider}. */ default SymbolProvider decorateSymbolProvider( GoSettings settings, Model model, SymbolProvider symbolProvider ) { return symbolProvider; } /** * Writes additional files. * * Called each time a writer is used that defines a shape. * * <p>Any mutations made on the writer (for example, adding * section interceptors) are removed after the callback has completed; * the callback is invoked in between pushing and popping state from * the writer. * * @param settings Settings used to generate. * @param model Model to generate from. * @param symbolProvider Symbol provider used for codegen. * @param writer Writer that will be used. * @param definedShape Shape that is being defined in the writer. */ default void onShapeWriterUse( GoSettings settings, Model model, SymbolProvider symbolProvider, GoWriter writer, Shape definedShape ) { // pass } /** * Writes additional files. * * @param settings Settings used to generate. * @param model Model to generate from. * @param symbolProvider Symbol provider used for codegen. * @param writerFactory A factory function that takes the name of a file * to write and a {@code Consumer} that receives a * {@link GoSettings} to perform the actual writing to the file. */ default void writeAdditionalFiles( GoSettings settings, Model model, SymbolProvider symbolProvider, TriConsumer<String, String, Consumer<GoWriter>> writerFactory ) { // pass } /** * Writes additional files. * * @param settings Settings used to generate. * @param model Model to generate from. * @param symbolProvider Symbol provider used for codegen. * @param goDelegator GoDelegator used to manage writer for the file. */ default void writeAdditionalFiles( GoSettings settings, Model model, SymbolProvider symbolProvider, GoDelegator goDelegator ) { // pass } /** * Gets a list of protocol generators to register. * * @return Returns the list of protocol generators to register. */ default List<ProtocolGenerator> getProtocolGenerators() { return Collections.emptyList(); } /** * Processes the finalized model before runtime plugins are consumed and * code generation starts. This plugin can be used to add RuntimeClientPlugins * to the integration's list of plugin. * * @param settings Settings used to generate. * @param model Model to generate from. */ default void processFinalizedModel(GoSettings settings, Model model) { // pass } /** * Gets a list of plugins to apply to the generated client. * * @return Returns the list of RuntimePlugins to apply to the client. */ default List<RuntimeClientPlugin> getClientPlugins() { return Collections.emptyList(); } /** * Processes the given serviceId and may return a unmodified, modified, or replacement value. * * @param settings Settings used to generate * @param model model to generate from * @param serviceId the serviceId * @return the new serviceId */ default String processServiceId(GoSettings settings, Model model, String serviceId) { return serviceId; } /** * Used by integrations to provide an EndpointBuiltInHandler * that allows endpoint resolution middleware generation * to resolve BuiltIn values. */ default Optional<EndpointBuiltInHandler> getEndpointBuiltinHandler() { return Optional.empty(); } default void renderPreEndpointResolutionHook(GoSettings settings, GoWriter writer, Model model) { // pass } default void renderPostEndpointResolutionHook( GoSettings settings, GoWriter writer, Model model, Optional<OperationShape> operation) { // pass } }
8,998
0
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen
Create_ds/smithy-go/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/integration/HttpProtocolUnitTestResponseGenerator.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * * */ package software.amazon.smithy.go.codegen.integration; import java.util.function.Consumer; import java.util.logging.Logger; import software.amazon.smithy.go.codegen.GoWriter; import software.amazon.smithy.go.codegen.SmithyGoDependency; import software.amazon.smithy.protocoltests.traits.HttpResponseTestCase; /** * Generates HTTP protocol unit tests for HTTP response test cases. */ public class HttpProtocolUnitTestResponseGenerator extends HttpProtocolUnitTestGenerator<HttpResponseTestCase> { private static final Logger LOGGER = Logger.getLogger(HttpProtocolUnitTestResponseGenerator.class.getName()); /** * Initializes the protocol test generator. * * @param builder the builder initializing the generator. */ protected HttpProtocolUnitTestResponseGenerator(Builder builder) { super(builder); } /** * Provides the unit test function's format string. * * @return returns format string paired with unitTestFuncNameArgs */ @Override protected String unitTestFuncNameFormat() { return "TestClient_$L_$LDeserialize"; } /** * Provides the unit test function name's format string arguments. * * @return returns a list of arguments used to format the unitTestFuncNameFormat returned format string. */ @Override protected Object[] unitTestFuncNameArgs() { return new Object[]{opSymbol.getName(), protocolName}; } /** * Hook to generate the parameter declarations as struct parameters into the test case's struct definition. * Must generate all test case parameters before returning. * * @param writer writer to write generated code with. */ @Override protected void generateTestCaseParams(GoWriter writer) { writer.write("StatusCode int"); // TODO authScheme writer.addUseImports(SmithyGoDependency.NET_HTTP); writer.write("Header http.Header"); // TODO why do these exist? // writer.write("RequireHeaders []string"); // writer.write("ForbidHeaders []string"); writer.write("BodyMediaType string"); writer.write("Body []byte"); writer.write("ExpectResult $P", outputSymbol); } /** * Hook to generate all the test case parameters as struct member values for a single test case. * Must generate all test case parameter values before returning. * * @param writer writer to write generated code with. * @param testCase definition of a single test case. */ @Override protected void generateTestCaseValues(GoWriter writer, HttpResponseTestCase testCase) { writeStructField(writer, "StatusCode", testCase.getCode()); writeHeaderStructField(writer, "Header", testCase.getHeaders()); testCase.getBodyMediaType().ifPresent(mediaType -> { writeStructField(writer, "BodyMediaType", "$S", mediaType); }); testCase.getBody().ifPresent(body -> { writeStructField(writer, "Body", "[]byte(`$L`)", body); }); writeStructField(writer, "ExpectResult", outputShape, testCase.getParams()); } @Override protected void generateTestClient(GoWriter writer, String clientName) { writer.openBlock("$L := New(Options{", "})", clientName, () -> { writer.addUseImports(SmithyGoDependency.SMITHY_HTTP_TRANSPORT); writer.openBlock("HTTPClient: smithyhttp.ClientDoFunc(func(r *http.Request) (*http.Response, error) {", "}),", () -> generateResponse(writer)); for (ConfigValue value : clientConfigValues) { writeStructField(writer, value.getName(), value.getValue()); } }); } @Override protected void generateTestServer(GoWriter writer, String name, Consumer<GoWriter> handler) { // We aren't using a test server, but we do need a URL to set. writer.write("serverURL := \"http://localhost:8888/\""); } /** * Generates a Response object to return for testing. * * @param writer The writer to write generated code with. */ protected void generateResponse(GoWriter writer) { writer.addUseImports(SmithyGoDependency.NET_HTTP); writer.write("headers := http.Header{}"); writer.openBlock("for k, vs := range c.Header {", "}", () -> { writer.openBlock("for _, v := range vs {", "}", () -> { writer.write("headers.Add(k, v)"); }); }); writer.openBlock("if len(c.BodyMediaType) != 0 && len(headers.Values(\"Content-Type\")) == 0 {", "}", () -> { writer.write("headers.Set(\"Content-Type\", c.BodyMediaType)"); }); writer.openBlock("response := &http.Response{", "}", () -> { writer.write("StatusCode: c.StatusCode,"); writer.write("Header: headers,"); writer.write("Request: r,"); }); writer.addUseImports(SmithyGoDependency.BYTES); writer.addUseImports(SmithyGoDependency.IOUTIL); writer.openBlock("if len(c.Body) != 0 {", "} else {", () -> { writer.write("response.ContentLength = int64(len(c.Body))"); writer.write("response.Body = ioutil.NopCloser(bytes.NewReader(c.Body))"); }); writer.openBlock("", "}", () -> { // We have to set this special sentinel value for no body, or anything that relies on there being // a value set will panic. writer.write("response.Body = http.NoBody"); }); writer.write("return response, nil"); } /** * Hook to generate the body of the test that will be invoked for all test cases of this operation. Should not * do any assertions. * * @param writer writer to write generated code with. */ @Override protected void generateTestInvokeClientOperation(GoWriter writer, String clientName) { writer.addUseImports(SmithyGoDependency.CONTEXT); writer.write("var params $T", inputSymbol); writer.write("result, err := $L.$T(context.Background(), &params)", clientName, opSymbol); } /** * Hook to generate the assertions for the operation's test cases. Will be in the same scope as the test body. * * @param writer writer to write generated code with. */ @Override protected void generateTestAssertions(GoWriter writer) { writeAssertNil(writer, "err"); writeAssertNotNil(writer, "result"); writer.addUseImports(SmithyGoDependency.SMITHY_MIDDLEWARE); writeAssertComplexEqual(writer, "c.ExpectResult", "result", new String[]{"middleware.Metadata{}"}); // TODO assertion for protocol metadata } public static class Builder extends HttpProtocolUnitTestGenerator.Builder<HttpResponseTestCase> { @Override public HttpProtocolUnitTestResponseGenerator build() { return new HttpProtocolUnitTestResponseGenerator(this); } } }
8,999