branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep>import styled from "styled-components" const AllProjectsHolder = styled.div` margin: 1.5em 0 0 0; width: 100%; display: flex; flex-direction: column; ` const SingleProjectHolder = styled.div` display: inherit; transition: all 0.25s linear; @media (max-width: 850px) { flex-direction: column !important; } ` const ImageHolder = styled.div` width: 50%; height: 24em; overflow: hidden; display: flex; @media (max-width: 850px) { width: 100%; } @media (min-width: 2880px) { width: max-content; height: 34em; } ` const Image = styled.img` width: 100%; ` const InfoHolder = styled.div` padding: 0 4em; display: inherit; flex-direction: column; justify-content: center; align-items: center; flex: 1; text-align: center; @media (max-width: 850px) { margin: 0 0 3em 0; } @media (min-width: 2000px) { font-size: 0.9vw; } ` const Title = styled.h2` border-bottom-width: 0.05em; border-bottom-style: solid; a { text-decoration: none; } ` const Role = styled.em` margin: 0 0 0.25em 0; ` const Description = styled.p` font-family: "EB Garamond", serif; ` export { AllProjectsHolder, SingleProjectHolder, ImageHolder, Image, InfoHolder, Title, Role, Description, } <file_sep>import React from "react" const Context = React.createContext() const { Provider } = Context export default Context export { Provider } <file_sep>import fola from "./fola.png"; import folaMobile from "./folaMobile.png"; // import FPCHackathon from "./FPCHackathon.png" import homeUniteUs from "./homeUniteUs.png"; import portfolio from "./portfolio.png"; import sirvy from "./sirvy.png"; // import columnGenerator from "./columnGenerator.png" // import columnGeneratorMobile from "./columnGeneratorMobile.png" import bagOfHolding from "./bagOfHolding.png"; // import bulletinBored from "./bulletinBored.png" // import bulletinBoredMobile from "./bulletinBoredMobile.png" import nightIn from "./nightIn.png"; // import flashLights from "./flashLights.png" // import sbreentry from "./sbreentry.png" // import sbreentryMobile from "./sbreentry-mobile.png" import thrivesbc from "./thrivesbc.png"; import thrivesbcMobile from "./thrivesbc-mobile.png"; const folioProjects = [ // { // title: "Santa Barbara Reentry", // fullImage: sbreentry, // mobileImage: sbreentryMobile, // link: "https://santabarbarareentry.netlify.app/", // github: "https://github.com/codeforamerica/sb_reentry_app", // role: "Software Engineer", // description: // "Currently In Progress: Santa Barbara Reentry is an app to help justice impacted residents of Santa Barbara County more easily access public resources after a jail or prison stay.", // center: true, // }, { title: "ThriveSBC", fullImage: thrivesbc, mobileImage: thrivesbcMobile, link: "https://www.thrivesbc.com/", github: "https://github.com/sbpublicdefendersoffice/sb_reentry_app", role: "Software Engineer, Designer and Primary Architect", description: "ThriveSBC is an app to help all residents of Santa Barbara who identify as justice impacted more easily access public and other helpful resources.", center: false, }, { title: "Food Oasis Los Angeles", fullImage: fola, mobileImage: folaMobile, link: "https://foodoasis.la/", github: "https://github.com/hackforla/food-oasis", role: "Front End Developer", description: "Find Food Pantries, Food Banks and Meal Programs in Los Angeles County. Food For All!", center: true, }, // { // title: "LAFPC Dashboard", // fullImage: FPCHackathon, // mobileImage: false, // link: "https://lafpc-hackathon-dashboard.herokuapp.com/", // github: "https://github.com/timmalstead/LAFPC_Hackathon_Final_Deployed", // role: "Full Stack Developer", // description: // "Winner of first prize and audience favorite at the Los Angeles Food Policy Council x General Assembly hackathon, LAFPC dashboard is an easy way to view, manage and visualize facts about food policy in Los Angeles County.", // center: false, // }, { title: "Home Unite Us", fullImage: homeUniteUs, mobileImage: false, link: "https://lacommunity.site/hosthome/", github: "https://github.com/hackforla/HomeUniteUs", role: "Lead Front End Developer", description: "A web application that matches homeless and at-risk youth with short term host housing and job training to help transition into a more stable life. Created with the team at Hack for LA, it feels great to work on something that makes a real difference.", center: false, }, { title: "Portfolio Site", fullImage: portfolio, mobileImage: "", link: "https://timmalstead.com/", github: "https://github.com/timmalstead/custom_portfolio", role: "Sole Designer and Developer", description: "My newest portfolio and the very site you are on right now. Some of the most concise React I've written to date.", center: true, }, { title: "Sirvy", fullImage: sirvy, mobileImage: false, link: "https://sirvy.herokuapp.com/", github: "https://github.com/timmalstead/sirvy", role: "Full Stack Developer & UI Designer", description: "Sirvy allows users to send surveys via SMS, and then visualize the data in graph form.", center: false, }, // { // title: "The Thomas Friedman Column Generator", // fullImage: columnGenerator, // mobileImage: columnGeneratorMobile, // link: "https://veryimportantcolumngenerator.herokuapp.com/", // github: "https://github.com/timmalstead/Very_Important_Column_Generator", // role: "Full Stack Developer & Designer", // description: // "A Madlib style random word generator in the style of New York Times columnist <NAME>.", // center: false, // }, // { // title: "<NAME>", // fullImage: bulletinBored, // mobileImage: bulletinBoredMobile, // link: "https://bulletinbored.herokuapp.com/", // github: "https://github.com/timmalstead/bulletinbored", // role: "Full Stack Developer & UI Designer", // description: // "A note taking app created to further my understanding of React Hooks and GraphQL", // center: false, // }, { title: "Night In", fullImage: nightIn, mobileImage: false, link: "https://night-in.herokuapp.com/", github: "https://github.com/timmalstead/Night_in_front_end", role: "Lead Front End Developer & UI Designer", description: "The perfect dinner and a movie, every time. Select recipes and public domain movies based on user preferences.", center: true, }, { title: "Bag of Holding", fullImage: bagOfHolding, mobileImage: false, link: "https://timmalstead.github.io/bagofholding/", github: "https://github.com/timmalstead/bagofholding", role: "Front End Developer, Writer & Illustrator", description: "A text based adventure game played in the browser console. A long term project, first level playable now!", center: false, }, // { // title: "Flash.Lights.", // fullImage: flashLights, // mobileImage: false, // link: "https://timmalstead.github.io/flash_lights/", // github: "https://github.com/timmalstead/flash_lights", // role: "Front End Developer & Designer", // description: // "A fun and colorful browser based game that tests your ability to remember sequences of colors.", // center: true, // }, ]; export default folioProjects; <file_sep>import styled from "styled-components" const Main = styled.main` width: 100%; padding: 3.5em 0 0 0; display: flex; flex-direction: column; align-items: center; justify-content: space-between; min-height: inherit; @media (max-width: 850px) { padding: 4.5em 0 0 0; } ` export default Main <file_sep>import React from "react" import * as Style from "./style" import Context from "../../ThemeContext" import ProfilePic from "./profilePic.jpg" const parOne = ` I am a full stack software engineer and designer seeking to help make the world a more just and equitable place through the use of beautiful, intuitive and helpful software. My goal is to create software that helps solve tough problems for real people. I approach each project with a careful eye toward design, ease of use and performance. ` const parTwo = ` I hope you'll take a look at my work and reach out. Together we can make something that matters. ` const About = () => { const { secondaryColor, contrastTwo } = React.useContext(Context).styles const [spinClick, setToSpin] = React.useState(false) const spinThenDelay = () => { setToSpin(true) setTimeout(() => { setToSpin(false) }, 500) } return ( <Style.AboutHolder> <Style.Profile src={ProfilePic} alt="Profile Pic" onClick={() => spinThenDelay()} style={{ animation: spinClick ? "spin 0.5s ease-in-out" : null }} /> <Style.Blurb> <h1> Let's Make Something That <em style={{ color: contrastTwo }}> Matters</em> </h1> <span style={{ borderTopColor: secondaryColor, }} /> <p>Hello, I'm <NAME></p> <p>{parOne}</p> <p>{parTwo}</p> </Style.Blurb> </Style.AboutHolder> ) } export default About <file_sep>import React from "react" const Writing = () => <h1>this will be writing</h1> export default Writing <file_sep>import React from "react" import Footer from "./style" const date = new Date().getFullYear() const SiteFooter = () => ( <Footer>Copyright &copy; <NAME> 2019-{date}</Footer> ) export default SiteFooter <file_sep>import styled from "styled-components" const Footer = styled.footer` font-family: "EB Garamond", serif; margin: 1em 0; cursor: default; @media (min-width: 1500px) { font-size: 1vw; } ` export default Footer <file_sep>import styled from "styled-components" const PickerHolder = styled.div` position: absolute; left: 0; top: 0; height: 100vh; width: 100vw; display: flex; justify-content: center; align-items: center; div { color: #000; position: relative; z-index: 1; } ` const ArrowUp = styled.div` position: relative; left: 0.25em; height: 0; width: 0; border-left: 1em solid transparent; border-right: 1em solid transparent; border-bottom-width: 1em; border-bottom-style: solid; ` const ArrowLeft = styled.div` height: 0; width: 0; border-top: 0.7em solid transparent; border-bottom: 0.7em solid transparent; border-right-width: 0.7em; border-right-style: solid; ` const ArrowRight = styled.div` height: 0; width: 0; border-top: 0.7em solid transparent; border-bottom: 0.7em solid transparent; border-left-width: 0.7em; border-left-style: solid; ` const PopUp = styled.div` main { position: relative; padding: 1em; min-height: 20em; width: 16em; border-radius: 0.5em; display: flex; flex-direction: column; align-items: center; text-align: center; } @media (min-height: 2000px) { main { transform: scale(2); transform-origin: right top 0; } } ` const ThemeComponentTitle = styled.span` width: min-content; font-size: 1.7em; ` const ThemeTitle = styled.div` min-width: 70%; font-size: 1.2em; margin: 0.4em 0; display: flex; justify-content: space-between; align-items: center; ` const ColorInfoHolder = styled.div` width: 90%; display: inherit; justify-content: space-between; margin: 0 0 0.5em 0; font-family: "EB Garamond", serif; ` const ColorHolder = styled.div` width: 3em; height: 3em; border-width: 0.03em; border-style: solid; border-radius: 50%; ` const ColorInfo = styled.div` width: 70%; display: inherit; flex-direction: column; justify-content: center; align-items: center; ` export { ArrowUp, ArrowLeft, ArrowRight, PopUp, PickerHolder, ThemeComponentTitle, ThemeTitle, ColorInfoHolder, ColorHolder, ColorInfo, } <file_sep>import React from "react" import * as Style from "./style" import themes from "./themes" import { PhotoshopPicker } from "react-color" import Context from "../../ThemeContext" const ThemeSelector = () => { const { styles, changeStyle } = React.useContext(Context) const { name, imgKey, mainColor, headerSecondary, selector, contrastOne, contrastTwo, } = styles const initialPopUpLocation = window.innerWidth > 850 ? false : true const [popUpLocation, shiftPopUp] = React.useState(initialPopUpLocation) const [pickerVisible, switchPickerVisible] = React.useState(false) const [selectedColor, selectCurrentColor] = React.useState({ colorName: "Color Picker", hex: "#FF0000", }) React.useEffect(() => { const adjustPopUp = () => { window.innerWidth > 850 ? shiftPopUp(false) : shiftPopUp(true) } window.addEventListener("resize", adjustPopUp) return () => window.removeEventListener("resize", adjustPopUp) }) // const callColorPicker = (colorTitle, color, setPickerVisibility) => { // selectCurrentColor({ colorName: colorTitle, hex: color }) // setPickerVisibility() // } const setColor = (setPickerVisibility) => { changeStyle({ ...styles, [selectedColor.colorName]: selectedColor.hex, }) setPickerVisibility() } const shiftTheme = (increment) => { if (increment) { themes[imgKey + 1] ? changeStyle(themes[imgKey + 1]) : changeStyle(themes[0]) } else { themes[imgKey - 1] ? changeStyle(themes[imgKey - 1]) : changeStyle(themes[themes.length - 1]) } } React.useEffect(() => { const storage = window.localStorage for (const prop in styles) { storage[prop] = styles[prop] } }, [styles]) React.useEffect(() => { const favicon = document.getElementById("favicon") favicon.href = `./${name}.ico` }, [name]) const themeDisplay = () => { const colorArr = [] for (const str in styles) { if (str !== "imgKey" && str !== "blendMode") { if (str !== "name") { const nameSplit = str .split(/(?=[A-Z])/) .map((word) => `${word[0].toUpperCase()}${word.substring(1)}`) .join(" ") colorArr.push( <Style.ColorInfoHolder key={str}> <Style.ColorHolder onClick={ () => console.log( "this is where the color picker is called when not commented out" ) /* callColorPicker(str, styles[str], () => switchPickerVisible(true) ) */ } style={{ borderColor: styles[str] === selector ? contrastTwo : "transparent", backgroundColor: styles[str], }} /> <Style.ColorInfo> <span>{nameSplit}</span> <span>{styles[str]}</span> </Style.ColorInfo> </Style.ColorInfoHolder> ) } else { colorArr.push( <Style.ThemeTitle key={str}> <Style.ArrowLeft onClick={() => shiftTheme(false)} style={{ borderRightColor: contrastOne, }} /> <em>{styles[str]}</em> <Style.ArrowRight onClick={() => shiftTheme(true)} style={{ borderLeftColor: contrastOne, }} /> </Style.ThemeTitle> ) } } } return colorArr } return ( <React.Fragment> {pickerVisible ? ( <Style.PickerHolder> <PhotoshopPicker color={selectedColor.hex} onChange={(e) => selectCurrentColor({ ...selectedColor, hex: e.hex }) } onAccept={() => setColor(() => switchPickerVisible(false))} onCancel={() => switchPickerVisible(false)} /> </Style.PickerHolder> ) : null} <Style.PopUp> <Style.ArrowUp style={{ borderBottomColor: selector, }} /> <main style={{ backgroundColor: selector, right: popUpLocation ? ".5em" : "12em", border: mainColor === selector ? `.07em solid ${headerSecondary}` : null, }} > <Style.ThemeComponentTitle style={{ borderBottom: `.03em solid ${contrastOne}`, }} > Themes </Style.ThemeComponentTitle> {themeDisplay()} </main> </Style.PopUp> </React.Fragment> ) } export default ThemeSelector <file_sep>const themes = [ { name: "Sleek", imgKey: 0, mainColor: "#212123", secondaryColor: "#585b60", textColor: "#eceff5", headerColor: "#212123", headerSecondary: "#585b60", headerText: "#eceff5", selector: "#585b60", contrastOne: "#d7d950", contrastTwo: "#68c2c8", blendMode: "normal", }, { name: "Greyscale", imgKey: 1, mainColor: "#bebebe", secondaryColor: "#7b7b7b", textColor: "#4b4b4b", headerColor: "#262626", headerSecondary: "#ffffff", headerText: "#ffffff", selector: "#ffffff", contrastOne: "#e9e9e9", contrastTwo: "#646464", blendMode: "color-dodge", }, { name: "Light", imgKey: 2, mainColor: "#ffffff", secondaryColor: "#ffffff", textColor: "#000000", headerColor: "#ffffff", headerSecondary: "#000000", headerText: "#000000", selector: "#ffffff", contrastOne: "#000000", contrastTwo: "#000000", blendMode: "normal", }, { name: "Dark", imgKey: 3, mainColor: "#000000", secondaryColor: "#000000", textColor: "#ffffff", headerColor: "#000000", headerSecondary: "#ffffff", headerText: "#ffffff", selector: "#000000", contrastOne: "#ffffff", contrastTwo: "#ffffff", blendMode: "normal", }, { name: "Beast_Mode", imgKey: 4, mainColor: "#f0f2f1", secondaryColor: "#ff4848", textColor: "#484040", headerColor: "#ff4848", headerSecondary: "#3f2c2c", headerText: "#ffffff", selector: "#ff8080", contrastOne: "#64565b", contrastTwo: "#64565b", blendMode: "multiply", }, { name: "Boutique", imgKey: 5, mainColor: "#2f416c", secondaryColor: "#111b59", textColor: "#ffc2c2", headerColor: "#fffff6", headerSecondary: "#ffc2c2", headerText: "#ffc2c2", selector: "#fffff6", contrastOne: "#ffb220", contrastTwo: "#f4c2ff", blendMode: "screen", }, ] export default themes <file_sep>import React from "react" import ThemeSelector from "../ThemeSelector" import Gear from "./gear" import GearHolder from "./style" import Context from "../../ThemeContext" const ThemeGear = () => { const { headerSecondary } = React.useContext(Context).styles const [showThemeSelector, toggleThemeSelector] = React.useState(false) return ( <GearHolder title="theme-popup" onClick={(e) => { return e.target.attributes.title?.nodeValue === "theme-popup" ? toggleThemeSelector(!showThemeSelector) : null }} > {Gear(headerSecondary)} {showThemeSelector ? <ThemeSelector /> : null} </GearHolder> ) } export default ThemeGear <file_sep>import React from "react" import fullIcons from "./fullSizeIcons" import mobileIcons from "./mobileIcons" import * as Style from "./style" import Context from "../../ThemeContext" const Links = () => { const { headerText, contrastOne } = React.useContext(Context).styles const initialIcons = window.innerWidth > 850 ? fullIcons : mobileIcons const [iconsToRender, changeIcons] = React.useState(initialIcons) React.useEffect(() => { const changeMobileIcons = () => { window.innerWidth <= 850 ? changeIcons(mobileIcons) : changeIcons(fullIcons) } window.addEventListener("resize", changeMobileIcons) }) const [hovering, changeHover] = React.useState( initialIcons.reduce((object, icon) => { object[icon.key] = false return object }, {}) ) return ( <Style.Icons> {iconsToRender.map((link) => ( <a key={link.key} href={link.url} target="_blank" rel="noopener noreferrer" > <Style.Icon> <svg viewBox={link.viewBox} fill-rule="evenodd" style={{ fill: hovering[link.key] ? contrastOne : headerText, }} onMouseOver={() => changeHover({ ...hovering, [link.key]: true })} onMouseOut={() => changeHover({ ...hovering, [link.key]: false })} > {link.path} </svg> </Style.Icon> </a> ))} </Style.Icons> ) } export default Links <file_sep>import styled from "styled-components" const GearHolder = styled.div` grid-area: themes; height: 2.5em; width: 2.5em; :hover { svg { animation: spin 0.5s ease-in-out; } @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } } ` export default GearHolder <file_sep>import styled from "styled-components" const TechHolder = styled.div` padding: 1em 0; margin: 1.5em 0 0 0; width: 98%; display: flex; flex-wrap: wrap; justify-content: center; ` const IconHolder = styled.div` position: relative; margin: 0.5em; width: 8em; height: 8em; display: inherit; flex-direction: column; justify-content: space-around; align-items: center; text-align: center; svg { width: 10vw; position: relative; z-index: -1; } @media (max-width: 800px) { width: 5em; height: 6em; } @media (max-width: 515px) { width: 4em; } @media (min-width: 1900px) { width: 11em; height: 11em; svg { width: 28vw; } } @media (min-width: 2400px) { width: 13em; height: 13em; svg { width: 30vw; } } @media (min-width: 3000px) { width: 22em; height: 22em; svg { width: 35vw; } } ` const PopUp = styled.div` position: absolute; flex-direction: column; top: 5em; left: 2em; z-index: 2; div { position: relative; left: 1em; height: 0; width: 0; border-left: 1em solid transparent; border-right: 1em solid transparent; border-bottom-width: 1em; border-bottom-style: solid; } article { position: relative; font-family: "EB Garamond", serif; padding: 1em; display: inherit; flex-direction: inherit; justify-content: space-between; align-items: center; min-height: 10em; width: 15em; border-radius: 0.5em; p { margin: 0; } a { margin: 0.5em 0 0 0; } } @media (max-width: 800px) { top: 3.5em; left: 0.5em; } @media (min-width: 1900px) { font-size: 1.2vw; article { width: 15vw; } } @media (min-width: 2300px) { article { width: 18vw; } } ` export { TechHolder, IconHolder, PopUp } <file_sep>import codeBg from "./codeBg.jpg" import keyboardAndMouse from "./keyboardAndMouse.jpg" import lines from "./lines.jpg" import lines2 from "./lines2.jpg" import business from "./business.jpg" import dresses from "./dresses.jpg" const splashPhotos = [ codeBg, lines, keyboardAndMouse, lines2, business, dresses, ] export default splashPhotos <file_sep>import React from "react" import splashPhotos from "./splashPhotos" import NavRoutes from "../../navRoutes" import folioProjects from "../Projects/projects" import TechIcons from "../Techs/techIcons" import profilePic from "../About/profilePic.jpg" import { Link } from "react-router-dom" import * as Style from "./style" import Context from "../../ThemeContext" const Splash = () => { const { imgKey, mainColor, secondaryColor, textColor, contrastOne, contrastTwo, blendMode, } = React.useContext(Context).styles const [hoverEffects, changeHoverEffects] = React.useState( NavRoutes.reduce((hoverObj, route) => { hoverObj[route.key] = false return hoverObj }, {}) ) const loadingEffect = (route) => { switch (route) { case "Projects": const randNum = Math.floor(Math.random() * folioProjects.length) const randProject = folioProjects[randNum] return ( <Style.ProjectImg style={{ backgroundImage: `url(${randProject.fullImage})`, backgroundPosition: randProject.center ? "center" : "top", left: hoverEffects[route] ? "0em" : "75vw", }} /> ) case "Tools": const iconCopy = [...TechIcons] const iconBundle = [] let screenDivisor = window.innerWidth >= 3000 ? Math.floor(window.innerWidth / 625) : window.innerWidth >= 2200 ? Math.floor(window.innerWidth / 400) : window.innerWidth >= 1500 ? Math.floor(window.innerWidth / 300) : window.innerWidth >= 1000 ? Math.floor(window.innerWidth / 250) : Math.ceil(window.innerWidth / 250) if (screenDivisor > TechIcons.length) screenDivisor = TechIcons.length for (let i = 0; i < screenDivisor; i++) { const randomNum = Math.floor(Math.random() * iconCopy.length) iconBundle.push(iconCopy[randomNum]) iconCopy.splice(randomNum, 1) } return iconBundle.map((icon, i) => ( <Style.EffectSvg key={i} viewBox="0 0 51 72" style={{ left: hoverEffects[route] ? "0em" : "75vw", transition: `left ${0.075 * i + 0.5}s linear`, }} > {icon.path} </Style.EffectSvg> )) default: return ( <Style.ProfileImg src={profilePic} alt="Profile Pic" style={{ left: hoverEffects[route] ? "0em" : "75vw" }} /> ) } } return ( <Style.SplashHolder> <Style.ImageHolder style={{ backgroundImage: `linear-gradient(${mainColor}00 50%, ${mainColor}FF), url(${splashPhotos[imgKey]})`, }} > <div> <Style.NameHolder style={{ borderBottom: `.09em solid ${secondaryColor}`, }} > <Style.Name style={{ mixBlendMode: blendMode }}> <NAME> </Style.Name> </Style.NameHolder> <Style.TypeEffect style={{ mixBlendMode: blendMode }} /> </div> <Style.MadeWithLove> Made with{" "} <span role="img" aria-label="red-heart"> ❤️ </span>{" "} in React.JS </Style.MadeWithLove> </Style.ImageHolder> <Style.ProjectLinksHolder> {NavRoutes.map((route) => ( <Style.RouteHolder key={route.key}> <Link key={route.key} to={route.path} style={{ color: hoverEffects[route.key] ? contrastTwo : textColor, borderBottom: hoverEffects[route.key] ? `.25em solid ${contrastOne}` : ".1em solid transparent", }} onMouseOver={() => changeHoverEffects({ ...hoverEffects, [route.key]: true }) } onMouseOut={() => changeHoverEffects({ ...hoverEffects, [route.key]: false }) } > {route.key} </Link> <Style.EffectHolder style={{ visibility: hoverEffects[route.key] ? "visible" : "hidden", }} > {loadingEffect(route.key)} </Style.EffectHolder> </Style.RouteHolder> ))} </Style.ProjectLinksHolder> </Style.SplashHolder> ) } export default Splash <file_sep>import styled from "styled-components" const AboutHolder = styled.div` min-height: 90vh; margin: 1.5em 0 0 0; width: 100%; display: grid; grid-template-columns: auto min-content auto 45% auto; grid-template-rows: 25% max-content auto; grid-template-areas: ". . . . ." ". profile . article ." ". . . . ."; @media (max-width: 950px) { grid-template-rows: 15% max-content auto; } @media (max-width: 800px) { display: flex; flex-direction: column; align-items: center; } ` const Profile = styled.img` grid-area: profile; width: 25vw; border-radius: 50%; :active { animation: spin 0.5s ease-in-out; } @media (max-width: 800px) { width: 40vw; margin-top: 2em; } @media (max-width: 550px) { width: 14em; } ` const Blurb = styled.article` padding: 0 2em; grid-area: article; display: flex; flex-direction: column; justify-content: center; h1 { font-size: Max(2em, 2vw); margin-bottom: 0.2em; } em { font-size: 1.2em; } span { width: 75%; border-top-width: 0.09em; border-top-style: solid; } p { margin: 0.5em 0 0.25em 0; font-family: "EB Garamond", serif; font-size: Max(1.1em, 1.1vw); } @media (max-width: 800px) { h1, p { text-align: center; } span { margin: 0 auto; } } ` export { AboutHolder, Profile, Blurb } <file_sep>## <NAME>'s Software Portfolio -- Please contact me at <EMAIL> <file_sep>import React from "react" import folioProjects from "./projects" import * as Style from "./style" import Context from "../../ThemeContext" const Projects = () => { const { mainColor, secondaryColor, contrastOne } = React.useContext( Context ).styles const [projectHover, changeProjectHover] = React.useState( folioProjects.reduce((hoverHolder, project) => { hoverHolder[project.title] = false return hoverHolder }, {}) ) const fullPics = folioProjects.reduce((arr, val) => { arr.push(val.fullImage) return arr }, []) const mobilePics = folioProjects.reduce((arr, val) => { arr.push(val.mobileImage || val.fullImage) return arr }, []) const [picturesToRender, changePictureSet] = React.useState( window.innerWidth > 800 ? fullPics : mobilePics ) React.useEffect(() => { const firePictureChange = () => { window.innerWidth > 800 ? changePictureSet(fullPics) : changePictureSet(mobilePics) } window.addEventListener("resize", firePictureChange) return () => window.removeEventListener("resize", firePictureChange) }) const linkMaker = (link, content) => ( <a href={link} target="_blank" rel="noopener noreferrer"> {content} </a> ) return ( <Style.AllProjectsHolder> {folioProjects.map((project, i) => ( <Style.SingleProjectHolder key={project.title} style={{ flexDirection: i % 2 === 0 ? "row" : "row-reverse", backgroundColor: projectHover[project.title] ? secondaryColor : mainColor, }} onMouseOver={() => changeProjectHover({ ...projectHover, [project.title]: true }) } onMouseOut={() => changeProjectHover({ ...projectHover, [project.title]: false }) } > <Style.ImageHolder style={{ alignItems: project.center ? "center" : "flex-start" }} > {linkMaker( project.link, <Style.Image alt={project.title} src={picturesToRender[i]} /> )} </Style.ImageHolder> <Style.InfoHolder> <Style.Title style={{ borderBottomColor: secondaryColor }}> {linkMaker(project.link, project.title)} </Style.Title> <Style.Role style={{ color: contrastOne }}> {project.role} </Style.Role> <Style.Description>{project.description}</Style.Description> {linkMaker(project.github, `View ${project.title} on GitHub`)} </Style.InfoHolder> </Style.SingleProjectHolder> ))} </Style.AllProjectsHolder> ) } export default Projects <file_sep>import React from "react" import About from "./components/About" import Projects from "./components/Projects" import Tools from "./components/Techs" // import Writing from "./components/Writing" // prettier-ignore const NavRoutes = [ { key: "Projects", path: "/projects", comp: <Projects />, }, { key: "Tools", path: "/tools", comp: <Tools /> }, { key: "About Me", path: "/about", comp: <About />, }, // { // key: "Writing", // path: "/writing", // comp: <Writing />, // }, ] export default NavRoutes <file_sep>//PROJECTS //change bulletin bored centering? fill up with things instead? //refactor sirvy to resize graph better? //PRINT, ILLO AND OTHER CREATIVE WORK //THEMES //dynamic favicons //svgs for routes //different pic for greyscale? //break into smaller components? //change header to look better on 4k //bigger pics for splash page, want to design for up to 4k //another set of project pics for splash page? <file_sep>import React from "react" import Loader from "./components/Loader" import SiteFooter from "./components/Footer" import Splash from "./components/SplashPage" import NavBar from "./components/NavBar" import NavRoutes from "./navRoutes" import * as Router from "react-router-dom" import Main from "./style" import { createGlobalStyle } from "styled-components" import { Provider } from "./ThemeContext" const SiteHeader = React.lazy(() => Promise.all([ import("./components/Header"), new Promise((resolve) => setTimeout(resolve, 2000)), ]).then(([moduleExports]) => moduleExports) ) const App = () => { const storage = window.localStorage const [styles, changeStyle] = React.useState({ name: storage.name || "Sleek", imgKey: parseInt(storage.imgKey) || 0, mainColor: storage.mainColor || "#212123", secondaryColor: storage.secondaryColor || "#585b60", textColor: storage.textColor || "#eceff5", headerColor: storage.headerColor || "#212123", headerSecondary: storage.headerSecondary || "#585b60", headerText: storage.headerText || "#eceff5", selector: storage.selector || "#585b60", contrastOne: storage.contrastOne || "#d7d950", contrastTwo: storage.contrastTwo || "#68c2c8", blendMode: storage.blendMode || "normal", }) React.useEffect(() => { const favicon = document.getElementById("favicon") favicon.href = `./${styles.name}.ico` }) const [headerBorder, changeHeaderBorder] = React.useState(true) const [borderBounce, toggleBorderBounce] = React.useState(true) const Global = createGlobalStyle` * { box-sizing:border-box; } *::selection { background-color : ${styles.contrastTwo} } body { margin:0; overflow-x:hidden; overflow-y:scroll; min-height:50em; width: 100vw; background-color: ${styles.mainColor}; color: ${styles.textColor}; font-family: 'Lato', sans-serif; } a, .active::before { color: ${styles.textColor} } #root { min-height:inherit; } ` return ( <Provider value={{ styles, changeStyle }}> <React.Suspense fallback={<Loader />}> <SiteHeader headerBorder={headerBorder} toggleBorderBounce={toggleBorderBounce} /> <Main> <Router.Switch> <Router.Route exact path="/" render={() => <Splash />} /> {NavRoutes.map((route) => ( <Router.Route key={route.key} exact path={route.path} render={() => ( <React.Fragment> <NavBar changeHeaderBorder={changeHeaderBorder} borderBounce={borderBounce} toggleBorderBounce={toggleBorderBounce} /> {route.comp} </React.Fragment> )} /> ))} </Router.Switch> <SiteFooter /> </Main> </React.Suspense> <Global /> </Provider> ) } export default App
67b5ff66faf2304757f1ab1c6b1d5549fb74a2cb
[ "JavaScript", "Markdown" ]
23
JavaScript
timmalstead/custom_portfolio
d3b863cd803932b48697f7c16ac9ad314cabc75c
4e0cb9a60794c7a2adea73818b927e6cf9b7b70d
refs/heads/master
<repo_name>lisacopeland/wikipediaviewer<file_sep>/src/app/search.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import {switchMap, distinctUntilChanged, debounceTime} from 'rxjs/operators'; @Injectable() export class SearchService { baseUrl = 'https://en.wikipedia.org/w/api.php?action=opensearch&format=json&search='; searchUrl = ''; constructor(private http: HttpClient) { } search(terms: Observable<string>) { return terms.pipe(debounceTime(400), distinctUntilChanged(), switchMap(term => this.searchEntries(term)) ); } searchEntries(term) { return this.http.get(this.baseUrl + term); } } <file_sep>/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { MatButtonModule, MatCardModule, MatCheckboxModule, MatDatepickerModule, MatNativeDateModule, MatDialogModule, MatGridListModule, MatIconModule, MatInputModule, MatListModule, MatMenuModule, MatPaginatorModule, MatRadioModule, MatSortModule, MatSelectModule, MatSidenavModule, MatSlideToggleModule, MatSnackBarModule, MatTableModule, MatTabsModule, MatToolbarModule, MatTooltipModule, MatFormFieldModule } from '@angular/material'; import { AppComponent } from './app.component'; import { SearchService } from './search.service'; /** * App module for the application * * @export * @class AppModule */ @NgModule({ declarations: [AppComponent], imports: [ BrowserModule, BrowserAnimationsModule, HttpClientModule, MatInputModule, MatIconModule, MatListModule ], providers: [ SearchService ], bootstrap: [AppComponent] }) export class AppModule {} <file_sep>/src/app/app.component.spec.ts import { TestBed, async, ComponentFixture } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { AppComponent } from './app.component'; describe('AppComponent', () => { let myComponent: AppComponent; let myFixture: ComponentFixture<AppComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ AppComponent ], }).compileComponents().then(() => { myFixture = TestBed.createComponent(AppComponent); myComponent = myFixture.componentInstance; }); })); it('should create the app', async(() => { expect(myComponent).toBeTruthy(); })); it(`should have as title 'app'`, async(() => { expect(myComponent.title).toEqual('app'); })); it('should render title in a h1 tag', async(() => { myFixture.detectChanges(); const compiled = myFixture.debugElement.nativeElement; expect(compiled.querySelector('h1').textContent).toContain('Welcome to app!'); })); it('should render an h2 tag', async(() => { myFixture.detectChanges(); const compiled = myFixture.debugElement.nativeElement; expect(compiled.querySelector('.h2tag').textContent).toContain('Here are some links to help you start:'); })); it('should click button and change ptag', async(() => { myFixture.detectChanges(); const compiled = myFixture.debugElement.nativeElement; expect(compiled.querySelector('.ptag').textContent).toContain('false'); spyOn(myComponent, 'onClick').and.callThrough(); const myButton = myFixture.debugElement.query(By.css('.myButton')); myButton.triggerEventHandler('click', null); myFixture.detectChanges(); expect(myComponent.onClick).toHaveBeenCalled(); expect(compiled.querySelector('.ptag').textContent).toContain('true'); expect(compiled.querySelector('.orange').textContent).toContain('Orange Kitty'); })); }); <file_sep>/src/app/app.component.ts import { Component, OnInit } from '@angular/core'; import { MatInputModule, MatIconModule, MatListModule } from '@angular/material'; import { Subject , Subscription } from 'rxjs'; import { SearchService } from './search.service'; /** * the app component * * @export * @class AppComponent * @implements {OnInit} */ @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { title = 'app'; buttonClicked = false; results: Object; subscription: Subscription; linksArray = []; searchTerm$ = new Subject<string>(); constructor(private searchService: SearchService) { this.searchService.search(this.searchTerm$) .subscribe(results => { // console.log('hi from app component searchservice.search, got back'); // console.log(results); this.linksArray = results[3]; // console.log('linksArray = ' + this.linksArray); }); } ngOnInit() { } }
83c2ba1b8c3c474aecbbe77e9ba2443eb8ad640a
[ "TypeScript" ]
4
TypeScript
lisacopeland/wikipediaviewer
d59cb9b37126c9b6edbbcd83ef7ca3eb84cdec20
acf2544bf25eeaa67ecf4c718aec663372335084
refs/heads/master
<repo_name>yuriymos/Money-under-control<file_sep>/AddWindow.java import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; /** * Created by Y on 12.08.2017. * This class create a window to add information about spending money */ public class AddWindow extends JDialog implements ActionListener { // value for set up maximum amount of money you could enter private final static Integer MAX_MONEY = 20000; // value for year private final static Integer SINCE_YEAR = 2000; // arrays with data to form any date private String[] dayString; private String[] monthsString; private String[] yearString; // data to create all panels private JPanel gridForDate; private JPanel gridForBoxes; private JPanel gridForMoney; private JPanel gridForButtons; // to get data from comboBoxes and textField private JComboBox day, month, year; private JComboBox moneyComboBox, categoriesComboBox; private JTextField textFieldForNote; // for information about the button OK, it was pressed or not. private boolean buttonOkPressed; /** * Constructor - creating a new window. */ public AddWindow() { this.setResizable(false); this.setModal(true); this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); // create panel for date createPanelForDate(); // create panel for labels and comboBoxes createPanelForLabelsAndComboBoxes(); // create panel for components witch needs to enter money createPanelForMoney(); // create panel for buttons Ok and Cancel createPanelForButtonsOkCancel(); // create panel to group all panels JPanel flow = new JPanel(new FlowLayout(FlowLayout.RIGHT)); flow.add(gridForButtons); // create panel to group all panels JPanel grid = new JPanel(new GridLayout(2, 1, 5, 0)); grid.add(gridForBoxes); grid.add(gridForMoney); // add all panels to the frame Container container = getContentPane(); container.add(gridForDate, BorderLayout.NORTH); container.add(grid, BorderLayout.CENTER); container.add(flow, BorderLayout.SOUTH); // set an optimal size of the window this.pack(); // set the main window on the center this.setLocationRelativeTo(null); this.setVisible(true); } /** * The createDataForDate method is private, it needs to create data for date */ private void createDataForDate() { dayString = new String[31]; // where 31 is maximum days possible in a month for (Integer value = 1; value <= dayString.length; value++) { dayString[value - 1] = value.toString(); } monthsString = new String[]{ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; yearString = new String[100]; // how many years? of course 100 years for (Integer index = SINCE_YEAR; index < yearString.length + SINCE_YEAR; index++) { yearString[index - SINCE_YEAR] = index.toString(); } } /** * The createPanelForDate method is private, * it needs to add data about date */ private void createPanelForDate() { gridForDate = new JPanel(new GridLayout(2, 3, 5, 0)); gridForDate.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(), "Enter date"), BorderFactory.createEmptyBorder(0, 10, 10, 10))); createDataForDate(); for (String labelTitle : new String[]{"Day:", "Month:", "Year:"}) { gridForDate.add(new JLabel(labelTitle, JLabel.CENTER)); } day = new JComboBox(dayString); month = new JComboBox(monthsString); year = new JComboBox(yearString); this.setCurrentDate(); gridForDate.add(day); gridForDate.add(month); gridForDate.add(year); } /** * The setCurrentDate method is private, * it needs to set current data to the add window */ private void setCurrentDate() { Date currentDate = new Date(System.currentTimeMillis()); SimpleDateFormat sdfDay = new SimpleDateFormat("dd"); SimpleDateFormat sdfMonth = new SimpleDateFormat("MMMM", Locale.ENGLISH); SimpleDateFormat sdfYear = new SimpleDateFormat("yyyy"); int currentDay = Integer.parseInt(sdfDay.format(currentDate)); String currentMonth = sdfMonth.format(currentDate); int currentYear = Integer.parseInt(sdfYear.format(currentDate)); day.setSelectedItem((String.valueOf(currentDay))); month.setSelectedItem(currentMonth); year.setSelectedItem((String.valueOf(currentYear))); } /** * The createPanelForLabelsAndComboBoxes method is private, * it needs to set current data to the add window */ private void createPanelForLabelsAndComboBoxes() { gridForBoxes = new JPanel(new GridLayout(1, 0, 5, 0)); gridForBoxes.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(), "Enter description of your spendings"), BorderFactory.createEmptyBorder(5, 10, 10, 10))); // these are possible categories, you could add more String[] someCategories = {"Food", "Clothes", "Wife", "Rent", "Adventures", "Car", "Children", "Public transport", "Other"}; categoriesComboBox = new JComboBox(someCategories); gridForBoxes.add(categoriesComboBox); textFieldForNote = new JTextField("note", JTextField.CENTER); gridForBoxes.add(textFieldForNote); } /** * The createPanelForMoney method is private, * it needs to add data about your money spending * You should chose one number from combo box * from 0 to MAX_MONEY */ private void createPanelForMoney() { gridForMoney = new JPanel(new GridLayout(1, 2, 5, 0)); gridForMoney.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(), "How much money have you spent?"), BorderFactory.createEmptyBorder(5, 10, 10, 10))); String[] moneyString = new String[MAX_MONEY]; for (Integer value = 0; value < moneyString.length; value++) { moneyString[value] = value.toString(); } moneyComboBox = new JComboBox(moneyString); gridForMoney.add(moneyComboBox); } /** * The createPanelForButtonsOkCancel method is private, * it needs to add buttons to the add window */ private void createPanelForButtonsOkCancel() { gridForButtons = new JPanel(new GridLayout(1, 2, 5, 0)); for (String buttonName : new String[]{"Ok", "Cancel"}) { JButton button = new JButton(buttonName); gridForButtons.add(button); button.addActionListener(this); // ActionListener } } /** * This method needs to send entered data * @return String [] */ public DataString sendData() throws ParseException { //String string = "January 2, 2010"; String string = new String(month.getSelectedItem().toString() + " " + day.getSelectedItem().toString() + ", " + year.getSelectedItem().toString()); DateFormat format = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH); Date date = format.parse(string); DataString dString = new DataString(date, categoriesComboBox.getSelectedItem().toString(), textFieldForNote.getText(), moneyComboBox.getSelectedItem().toString()); return dString; } /** * This method needs to send information about button "Ok", * @return boolean This returns the button "Ok" was pressed or not. */ public boolean isPressedOk() { return buttonOkPressed; } /** * This is an overloaded method * @param ae is an object-event */ @Override public void actionPerformed(ActionEvent ae) { if (ae.getActionCommand().equals("Ok")) { buttonOkPressed = true; this.dispose(); } else { buttonOkPressed = false; this.dispose(); } } }
2c70bf61ed86dcdc5c40f6cd220bfa5afbca6b67
[ "Java" ]
1
Java
yuriymos/Money-under-control
de69ffa1d732626ea70cb24c2384dc536f88676e
157ace311bc1d6f7a44ba0be077964e801cba783
refs/heads/master
<file_sep>package com.github.stokito.jsmallmap; import org.openjdk.jol.info.ClassLayout; import org.openjdk.jol.info.GraphLayout; import org.openjdk.jol.vm.VM; import java.io.PrintWriter; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import static java.lang.System.out; public class Jol { private static final Integer I_1 = 1; private static final Integer I_2 = 2; private static final Integer I_3 = 3; private static final Integer I_4 = 4; private static final Integer I_5 = 5; public static void main(String[] args) throws Exception { out.println(VM.current().details()); //JDK10 Map mapN = Map.of(I_1, I_1, I_2, I_2, I_3, I_3, I_4, I_4, I_5, I_5); Map mapN = new MapN(I_1, I_1, I_2, I_2, I_3, I_3, I_4, I_4, I_5, I_5); out.println(ClassLayout.parseInstance(mapN).toPrintable()); out.println(GraphLayout.parseInstance(mapN).toFootprint()); HashMap hashMap = new HashMap(5, 1.0F); put5Enries(hashMap); out.println(ClassLayout.parseInstance(hashMap).toPrintable()); out.println(GraphLayout.parseInstance(hashMap).toFootprint()); SmallMap smallMap = new SmallMap(mapN); put5Enries(hashMap); out.println(ClassLayout.parseInstance(smallMap).toPrintable()); out.println(GraphLayout.parseInstance(smallMap).toFootprint()); SmallMap2 smallMap2 = SmallMap2.of(I_1, I_1, I_2, I_2, I_3, I_3, I_4, I_4, I_5, I_5); out.println(ClassLayout.parseInstance(smallMap2).toPrintable()); out.println(GraphLayout.parseInstance(smallMap2).toFootprint()); LinkedHashMap linkedHashMap = new LinkedHashMap(5, 1.0F); put5Enries(linkedHashMap); out.println(ClassLayout.parseInstance(linkedHashMap).toPrintable()); out.println(GraphLayout.parseInstance(linkedHashMap).toFootprint()); /* * In this example, we see that under collisions, HashMap * degrades to the linked list. With JDK 8, we can also see * it further "degrades" to the tree. */ PrintWriter pw = new PrintWriter(System.out, true); Map<Dummy, Void> map = new HashMap<Dummy, Void>(); map.put(new Dummy(1), null); map.put(new Dummy(2), null); System.gc(); pw.println(GraphLayout.parseInstance(map).toPrintable()); map.put(new Dummy(2), null); map.put(new Dummy(2), null); map.put(new Dummy(2), null); map.put(new Dummy(2), null); System.gc(); pw.println(GraphLayout.parseInstance(map).toPrintable()); for (int c = 0; c < 6; c++) { map.put(new Dummy(2), null); } pw.println(map.size());//=>12 System.gc(); pw.println(GraphLayout.parseInstance(map).toPrintable()); pw.close(); } private static void put5Enries(Map map) { map.put(I_1, I_1); map.put(I_2, I_2); map.put(I_3, I_3); map.put(I_4, I_4); map.put(I_5, I_5); } /** * Dummy class which controls the hashcode and is decently Comparable. */ public static class Dummy implements Comparable<Dummy> { static int ID; final int id = ID++; final int hc; public Dummy(int hc) { this.hc = hc; } @Override public boolean equals(Object o) { return (this == o); } @Override public int hashCode() { return hc; } @Override public int compareTo(Dummy o) { return Integer.compare(id, o.id); } } }<file_sep># jsmallmap - POC of simplest as possible Java Map Proof of Concept (POC, experiment) of implementing of fastest Map class for small amount of entries. You can call it "SimpleMap" or "SmallMap" or "TupleMap" or "Vals" (see bellow why). Java's standard `HashMap` is just great: it is fast and memory efficient. It's so smart that on big elements number it internally switches to `TreeMap`. It's genius but not as this `SmallMap`. It works quite stupid: each key and each value are stored in... fields `key1`, `val1`, `key2`, `val2`... `key5`, `val5`: ```java public final class SmallMap<K, V> implements Map<K, V> { private K key1; private V val1; private K key2; private V val2; private K key3; private V val3; private K key4; private V val4; private K key5; private V val5; public boolean containsKey(Object key) { return key.equals(key1) || key.equals(key2) || key.equals(key3) || key.equals(key4) || key.equals(key5); } ... } ``` Yes, it is possible to store only five entries in ten fields. And if you try to put more entries you'll get an exception (sic!). Not so much to be honest, but in practice this is enough for most cases: * When map is created to pass or return multiple values into a method i.e. the map is used as [tuple](https://docs.microsoft.com/en-us/dotnet/api/system.tuple?view=netframework-4.7.1). * As imitation of object when you don't want to create a separate class. * To pass placeholder variables to formatters * it's enough to store params of most HTTP requests * Almost all unit tests uses few entries. The SmallMap is intended to be fast (but not *fastest*) but to have smallest memory consumption (about 56 bytes per instance). You can say: "Who cares? HashMap is already fast and with reasonably small memory footprint. Today we have gibibytes of memory". And you are partially right: we do have gibibytes of RAM but we have only about 256kb or processor cache. E.g. on my computer: $ lscpu | grep "Cache" L1d Cache: 32K L1i Cache: 32K L2 Cache: 256K L3 Cache: 6144K To understand how this is very important see [Latency Numbers Every Programmer Should Know](https://gist.github.com/jboner/2841832). But what is more important is that data is transferred between memory and CPU cache in blocks of fixed size, called **cache lines** with [typical size 64 bytes](https://www.7-cpu.com/cpu/Haswell.html). When you try to fetch one byte actually it will also fetch next 63 bytes. This called [Cache Prefetching](https://en.wikipedia.org/wiki/Cache_prefetching) and has a big impact on performance. If the object is shared between threads this can cause a [False Sharing problem](https://robsjava.blogspot.com/2014/03/what-is-false-sharing.html). What is also we had to keep in mind that today enterprise applications contains thousands of instances of hash map and it becomes a problem because it takes more time to collect a garbage with stop the world pauses. So a main idea is to make so small map so it can fit into CPU cache and all it's entries are tied together to be prefetched. I expect that this can be especially useful in conjunction with [compact objects](http://objectlayout.github.io/ObjectLayout/) that are still not added to JDK :( # Design principles ### Why only 5 entries? We have two main usages: 1. As temporary map to pass or return few values to/from a method i.e. in eden memory. 2. As row in a container (list) to represent few fields during processing or . #### To fit into cache line In both cases the map should be smaller that 64 bytes i.e. 64 - 12 bytes for an object header = 52 bytes. Both key and value are object's references by 4 bytes (on x64 without reference compression 8 bytes). 52 / (4 bytes per key + 4 bytes per value) = 6 entries + 4 free bytes. So we can use up to 6 entries to fit into the requirement. In fact, this is the only one clear requirement/wish. The HashMap with one element takes already 120 bytes so if we double the size to 128 (14 entries) it will be ok in comparision with HashMap. But on a big count of fields linear search can work slower. #### To use less memory This is not so important when using the map as temp object in method return or param but it may be expensive when map is used as row container. Imagine you have 1000 map instances then each new entry ads (4 bytes of key + 4 bytes of value) * 1000 = &000 bytes. 1 entry * 1000 maps = &000 2 entries * 1000 maps = 16000 3 entries * 1000 maps = 24000 4 entries * 1000 maps = 32000 5 entries * 1000 maps = 40000 6 entries * 1000 maps = 48000 The main problem is that you'll reserve all 48 bytes for 6 entries even if you use only 3 entries with 24 bytes. This can me solved by creation of another classes with specific arity like `Map3`, `Map4`, `Map5`, `Map6` or even `Map14`. #### To be fast The map uses a simplest linear search. For small entries count it's even faster then search by hash. The methods `put()` and `get()` should be as fast as they can. The method `put()` depends on on entries count linearly. The method `get()` also depends on on entries count linearly but if entry by key is not present it will make full scan. Each new entry makes `putAll()` working longer. But here is another important metric: methods size. If method less than 35 bytecodes it will be inlined. If method less that 325 bytecodes and is hot then it will be also inlined in runtime. Currently method get() is 132 and put() is 233 which is near to limit 235. Method `size()` is 64 and `isEmpty()` is 13. ### Most frequntly methods Here is some trade-off which method should be fast and which can be slow. Since the class will be used as tuple I chose the following priority: 1. `put()` and `get()` should be fastest methods because are used the most: this is achieved. 2. `putAll()` and copy constructor: current implementation can be faster 3. iteration by entry set: current implementation is dramatically slow. 4. `toString()` but current implementation is too slow. 5. `equals()` and `hashCode()` 6. `size()` and `isEmpty()` current implementation is fastest as possible. 7. `remove()` is fast enough and `clean()` makes immediately (just set size = 0) but can cause memory leaks because it don't nulls fields and references are alive. 8. get keys set and values list: current implementation is too slow and returns inline class (can cause memory leak). Also I think to return just usual ArrayList. # Benchmark result It's hard to benchmark SimpleMap because it's overhead is too small to measure. Also it is hard to compare it with HashMap. Usually maps are benchmarked on large amounts of entries while here we should do opposite. Especially it's hard to imitate the main usage of SimpleMap: as tuple returned from methods. I made a synthetic test to roughly estimate allocation of 2000000 maps in **old memory** with putting and getting 5 entries: hash map Spent time: 3249.609999ms Consumed mem: 503_633.734375kb ![Screenshot of VisualVM for HashMap](hashmap.png "Screenshot of VisualVM for HashMap") simple map Spent time: 119.958241ms Consumed mem: 115_456.5703125kb ![Screenshot of VisualVM for SmallMap](smallmap.png "Screenshot of VisualVM for SmallMap") Simple map consumed 4 less memory and worked 16 times fast. And when I tried 4000000 entries HashMap test just died with OOM. To reproduce it run Main class with -Xms2G -Xmx2G vm options. Looks impressive but don't trust this results it doesn't count a lot of things. So here is a [JMH](http://openjdk.java.net/projects/code-tools/jmh/) benchmark. To compile and run it use: mvn clean isntall java -jar target/benchmarks.jar -gc true Example on my machine: ``` $ java -jar target/benchmarks.jar -wi 1 -wf 1 -tu ms -i 1 -foe true -gc true Benchmark Mode Cnt Score Error Units MapGetBenchmarkHashMap.testGetExistingKey thrpt 5 96545.632 ± 4223.053 ops/ms MapGetBenchmarkSmallMap.testGetExistingKey thrpt 5 102397.779 ± 3472.132 ops/ms MapPutBenchmarkHashMap.testPutNonExistingKey thrpt 5 47219.787 ± 713.935 ops/ms MapPutBenchmarkSmallMap.testPutNonExistingKey thrpt 5 94985.959 ± 3306.885 ops/ms ``` `get()` works twice faster while `put()` is just slightly faster. Here maps was created in **eden (new) memory**. Also due to some weird bug inside JMH when `instanceof` doesn't work the test for `putAll()` when it justs copies fields is not working properly. Even if other map is SmallMap it will iterate and execute `put()` for each entry and this is much heavier. But with some hacks I got some near to real data: ``` Benchmark Mode Cnt Score Error Units SmallMap.putAll() from other SimpleMap thrpt 5 98251.151 ± 4336.348 ops/ms SmallMap.putAll() from other HashMap thrpt 5 89048.174 ± 74724.720 ops/ms ``` # Memory footprint The instance of `SmallMap` takes 56 bytes see [jol](http://openjdk.java.net/projects/code-tools/jol/) output: ``` # Running 64-bit HotSpot VM. # Using compressed oop with 0-bit shift. # Using compressed klass with 3-bit shift. # Objects are 8 bytes aligned. # Field sizes by type: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes] # Array element sizes: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes] com.github.stokito.jsmallmap.SmallMap object internals: OFFSET SIZE TYPE DESCRIPTION VALUE 0 12 (object header) N/A 12 1 byte SmallMap.size N/A 13 3 (alignment/padding gap) 16 4 java.lang.Object SmallMap.key1 N/A 20 4 java.lang.Object SmallMap.val1 N/A 24 4 java.lang.Object SmallMap.key2 N/A 28 4 java.lang.Object SmallMap.val2 N/A 32 4 java.lang.Object SmallMap.key3 N/A 36 4 java.lang.Object SmallMap.val3 N/A 40 4 java.lang.Object SmallMap.key4 N/A 44 4 java.lang.Object SmallMap.val4 N/A 48 4 java.lang.Object SmallMap.key5 N/A 52 4 java.lang.Object SmallMap.val5 N/A Instance size: 56 bytes Space losses: 3 bytes internal + 0 bytes external = 3 bytes total ``` Note that `byte size` was padded to int but I still wan't to use byte just for feature test with compact objects. From heap dump the size of instance SmallMap<Integer,Integer> is 97. The empty HashMap is smaller and consumes only 48 bytes but with five values it becomes much bigger. From heap dump the size is 64 and retained: 372 i.e. more in 3 times than SmallMap. Empty MapN 48 bytes. MapN 1 entry 80 bytes. MapN 2 entries 112 bytes. MapN 3 entries 144 bytes. MapN 5 entries retained 228. 2000000 Spent time: 706.55321ms Consumed mem: 277506.0kb # Vals: simple and universal collection But what is more interesting for me is to try to create an universal class which can be used as Tuple as Map, as List and Set and call it Vals. The similar conception is used in dynamic languages where object is just a map and you can use it as array. Thus you can easily write everywhere something like: ```java // use as list List<String> usernames = Vals.listOf("admin", "user", "guest")); assert usernames.val1 == "admin"; assert usernames.val2 == "user"; assert usernames.val3 == "guest"; // use as set: duplicated removed on creation Set<String> goods = Vals.setOf("beer", "vodka", "beer")); assert goods.val1 == "beer"; assert goods.val2 == "vodka"; assert goods.val3 == null; // try to add duplicate goods.add("beer"); assert goods.size() == 2; // still no dups ``` # Related works and discussions * JDK9 has internal class `MapN` which uses an array where keys and values are pairwised. Also it lookups a value by hash. to I copied the class into sources so we can benchmark it. * https://www.nayuki.io/page/compact-hash-map-java * https://github.com/OpenHFT/SmoothieMap * See [Which implementation of Map<K,V> should I use if my map needs to be small more than fast?](https://stackoverflow.com/questions/8835928/which-implementation-of-mapk-v-should-i-use-if-my-map-needs-to-be-small-more-t) * https://github.com/Zteve/SmallCollections * https://developer.android.com/reference/android/support/v4/util/ArrayMap * https://github.com/austinv11/Long-Map-Benchmarks/blob/master/src/jmh/java/com/austinv11/bench/MapTests.java<file_sep>package com.github.stokito.jsmallmap; import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.RunnerException; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import java.util.concurrent.TimeUnit; @State(Scope.Thread) public class MapPutBenchmarkSmallMap { private SmallMap<Long, Long> map = new SmallMap<Long, Long>(); private long key; @Benchmark @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.MILLISECONDS) public Long testPutNonExistingKeyKey() { if (key >= 5) { key = 0; map.clear(); } Long oldVal = map.put(key, key); key++; return oldVal; } public static void main(String[] args) throws RunnerException { Options opt = new OptionsBuilder() .include(".*" + MapPutBenchmarkSmallMap.class.getSimpleName() + ".*") .warmupIterations(1) .measurementIterations(1) .forks(1) .build(); new Runner(opt).run(); } } <file_sep>package com.github.stokito.jsmallmap; import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.RunnerException; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import java.util.HashMap; import java.util.TreeMap; import java.util.concurrent.TimeUnit; @State(Scope.Thread) public class MapPutAllBenchmarkHashMap { private HashMap<Long, Long> map = new HashMap<Long, Long>(); private HashMap<Long, Long> otherMap = new HashMap<Long, Long>(); private TreeMap<Long, Long> otherMapClass = new TreeMap<Long, Long>(); @Setup(Level.Iteration) public void setup() { for (long i = 0; i < 5; i++) { otherMap.put(i, i); otherMapClass.put(i, i); } } @Benchmark @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.MILLISECONDS) public HashMap testPutAll() { map.putAll(otherMap); return map; } @Benchmark @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.MILLISECONDS) public HashMap testPutAllFromOtherMapClass() { map.putAll(otherMapClass); return map; } public static void main(String[] args) throws RunnerException { Options opt = new OptionsBuilder() .include(".*" + MapPutAllBenchmarkHashMap.class.getSimpleName() + ".*") .warmupIterations(1) .measurementIterations(1) .forks(1) .build(); new Runner(opt).run(); } }
be15adb148423d736f79bd8aa5564432e8e464ad
[ "Markdown", "Java" ]
4
Java
stokito/jsmallmap
b13ab2638c3dd4339efb35889e8227b61d36b70a
61860e646d8b7a25779a3e944ee2a67c6afa28c6
refs/heads/master
<file_sep>alias g='gedit' alias mtargz='tar -xzf' alias mtarbz='tar -xjf' alias tips='vim /media/hdd/home/default/Docs/tips /media/hdd/home/default/Docs/key_combinations /media/hdd/home/default/Docs/todo /media/hdd/home/default/Docs/configs' alias :q='exit' alias llg='ls -lt | head -6 | tail -5' alias unz='tar -x -I zstd -f' #Git alias gst='git status' alias gstt='git status --untracked-files=no' alias gdf='git diff' alias gdfc='git diff --cached' alias gh='git log --perl-regexp --author="<NAME>|Stuthedian"\ --pretty=format:"%h %ad | %s%d [%an]" --graph --date=format:"%d.%m.%Y"' alias gha='git log --pretty=format:"%h %ad | %s%d [%an]" --graph --date=format:"%d.%m.%Y"' alias gco='git checkout' alias gci='git commit -m' alias gbr='git branch' alias gad='git add' alias grbi='git rebase -i' alias grbc='git rebase --continue' #Git dotfiles alias dotfiles='/usr/bin/git --git-dir=$HOME/.dotfiles/ --work-tree=$HOME' alias dst='dotfiles status' alias ddf='dotfiles diff' alias ddfc='dotfiles diff --cached' alias dh='dotfiles log --perl-regexp --author="<NAME>|Stuthedian" \ --pretty=format:"%h %ad | %s%d [%an]" --graph --date=short' alias dco='dotfiles checkout' alias dci='dotfiles commit -m' alias dbr='dotfiles branch' alias dad='dotfiles add' bake() { make "$@" 1>build.log local result=$? notify-send "done" return $result } <file_sep>#!/bin/bash function get_keyboard_layout() { if [ "$(xset -q|grep LED| awk '{ print $10 }')" -lt "00001004" ] then echo "En"; else echo "Ru"; fi } get_keyboard_layout
cf800650dcf25402358d590286603693072e708d
[ "Shell" ]
2
Shell
Stuthedian/.dotfiles
3807f47759a5f2bc1a9809675d3fe33c28a31c91
9de61ad05456200def3b11b67d5aa6ca7ac4dbab
refs/heads/master
<file_sep>import numpy as np import cv2 path = input("Input image path ... (ex: ./image.jpg) : ") bgr_img = cv2.imread(path, 1) bgra_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2BGRA) b, g, r, a = cv2.split(bgra_img) h, w, c = bgra_img.shape for i in range(w): for j in range(h): a[j, i] = 200 for i in range(w): for j in range(h): if (b[j, i] == 0 and g[j, i] == 0 and r[j, i] == 0): a[j, i] = 0 b[j, i] = 255 g[j, i] = 255 r[j, i] = 255 output = cv2.merge([b, g, r, a]) cv2.imwrite("./output.png", output) cv2.waitKey(0)
a406fc57ee3c2c29f3ee334c37dfea7a706f7448
[ "Python" ]
1
Python
m5823779/transparency
6b93b055a2a2cc37e3e56b5b5f6d07801bfc0ec2
b89336b70be721a97d12da72bb629b4105c22252
refs/heads/master
<file_sep>// // Stack.swift // SwiftUtils // // Created by <NAME> on 10/17/15. // Copyright © 2015 <NAME>. All rights reserved. // // Simple Stack with a couple tiny twists. Stack and Item impl both in this file. import Foundation //MARK: - Stack class public class Stack<T> { //MARK: - Private members private var head: StackItem<T>! private var _count = 0 // MARK: - Initializers public init() { } // "convenience" init when we know what the first item in the stack is at time of creation. public convenience init(withFirstItem: T?) { self.init() self.push(withFirstItem) } // MARK: - Public methods // Classic stack push. public func push(item: T?) { // Don't accept nil's on my stack. if item == nil { return } let newItem = StackItem(withItem: item!) newItem.prior = head head = newItem _count++ } // Classic stack pop. Note that the work is done by helper function popStackItem() which is also used by first() public func pop() -> T? { if let stackItem = popStackItem() { return stackItem.value } else { return nil } } // Inspect the item at the top of the stack, without popping it. public func peek() -> T? { return head?.value } // Empty the stack and return the first value that was ever pushed. This was created to support // an "undo all" operation. public func first() -> T? { if head == nil { return nil } var result = head while result.prior != nil { result = popStackItem() } return result.value } // Number of items in the stack. public var count: Int { get { return _count } } //MARK: - Private methods // Stack pop operation returns the StackItem object rather than the value. At creation time, // this is in order to support the first() operation. private func popStackItem() -> StackItem<T>? { if head == nil { return nil } _count-- let result = head if result != nil { head = result.prior } else { head = nil } return result } } //MARK: - StackItem class public class StackItem<T> { internal var value: T internal var prior: StackItem! init(withItem: T) { self.value = withItem } } <file_sep>// // SuperString.swift // SwiftUtils // // Created by <NAME> on 10/19/15. // Copyright © 2015 <NAME>. All rights reserved. // /* SuperString gives extensions to the String class for greater fluency. */ import Foundation public extension String { // simple length property. // Note that this is EXPENSIVE and shouldn't be used injudiciously. public var length: Int { get { return self.characters.count } } // Wrapper of String.substringToIndex that takes a nice simple Int // and handles invalid indices sensibly. public func substringToIndex(index: Int) -> String { if index < 1 { return "" } if index >= self.length { return self } else { return self.substringToIndex(self.startIndex.advancedBy(index)) } } // Wrapper of String.substringFromIndex that takes a nice simple Int // and handles invalid indices sensibly. public func substringFromIndex(index: Int) -> String { if index < 1 { return self } if index >= self.length { return "" } return self.substringFromIndex(self.startIndex.advancedBy(index)) } // Trim leading and trailing spaces. public mutating func trim() { let space: Character = " " // the character to trim self.trim(space) } // Trim leading and trailing characters public mutating func trim(trimChar: Character) { var start: String.Index! // Will hold index of first non-space character, if any var end: String.Index! // Will hold index of last non-space character, if any for index in self.characters.indices { if self[index] != trimChar { // Assign start to the first non-space index we find. if start == nil { start = index } // Assign end to the last non-space index we find. end = index } } // if either start or end is unassigned, then that means there were no non-space characters. if start == nil || end == nil { self = "" } else { // There were non-space characters. Return the substring of that range. self = self.substringWithRange(Range<Index>(start: start, end: end.successor())) } } //MARK: - objC bridging sugar public func stringByAppendingPathComponent(path: String) -> String? { return (self as NSString).stringByAppendingPathComponent(path) } } <file_sep># SwiftLib Handy little library of Swift classes and extensions <file_sep>// // SuperDate.swift // SwiftUtils // // Created by <NAME> on 10/17/15. // Copyright © 2015 <NAME>. All rights reserved. // /* These extensions make NSDate work more fluently. Importantly, they are all pretty naive: All work happens in currentCalendar(), etc. This is good enough for simple apps but care should be exercised for high-precision work. I'm throwing a few little EventKit extensions in too... */ import Foundation import EventKit //MARK: - NSDate extensions public extension NSDate { // initialize from Y/M/D convenience init(year: Int, month: Int, day: Int) { let calendar = NSCalendar.currentCalendar() let components = NSDateComponents() components.year = year components.month = month components.day = day self.init(timeInterval:0, sinceDate: calendar.dateFromComponents(components)!) } // Short string func toShortString() -> String { return self.toString(dateStyle: .ShortStyle, timeStyle: .NoStyle) } // Describe self in specified style func toString(dateStyle dateStyle: NSDateFormatterStyle, timeStyle: NSDateFormatterStyle) -> String { return NSDateFormatter.localizedStringFromDate(self, dateStyle: dateStyle, timeStyle: timeStyle) } // Return only year/month/day components of current date. func toYearMonthDay() -> NSDateComponents { return NSCalendar.currentCalendar().components([.Year, .Month, .Day], fromDate: self) } } // MARK: - NSDate: ISO8601 conformance public extension NSDate { private static var iso8601formatter: NSDateFormatter { let formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" formatter.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierISO8601) formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0) formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") return formatter } // Convert self to an ISO8601 string func toISO8601() -> String { let formatter = NSDate.iso8601formatter return formatter.stringFromDate(self) } // Initialize from an ISO8601 string convenience init?(fromISO8601 iso: String) { let formatter = NSDate.iso8601formatter if let initDate = formatter.dateFromString(iso) { self.init(timeInterval:0, sinceDate:initDate) } else { return nil } } } //MARK: - NSCalendar extensions public extension NSCalendar { // return LOCAL start of first day of month func startOfMonth(year year: Int, month: Int) -> NSDate { return NSDate(year: year, month: month, day: 1) } // return LOCAL start of first day of month func startOfMonth(date: NSDate) -> NSDate { let ymd = date.toYearMonthDay() return startOfMonth(year: ymd.year, month: ymd.month) } // return LOCAL START of last day of month func endOfMonth(year year: Int, month: Int) -> NSDate { let comps = NSDateComponents() comps.month = 1 comps.day = -1 return dateByAddingComponents(comps, toDate: startOfMonth(year: year, month: month), options: [])! } // return LOCAL START of last day of month func endOfMonth(date: NSDate) -> NSDate { let ymd = date.toYearMonthDay() return endOfMonth(year: ymd.year, month: ymd.month) } // Return LOCAL end of day for date. // IMPORTANT: This returns the beginning of the last second of the day (23:59:59.000). // Close enough for some things and not for others; make good choices. func endOfDayForDate(date: NSDate) -> NSDate { let comps = NSDateComponents() comps.day = 1 comps.second = -1 return dateByAddingComponents(comps, toDate: startOfDayForDate(date), options: [])! } } //MARK: - EKCalendarItem extensions public extension EKCalendarItem { // displayDate gets the best possible date from either an EKEvent or an EKReminder. // PLEASE NOTE that this value can actually be nil for an EKReminder. var displayDate: NSDate! { if let event = self as? EKEvent { return event.startDate } else if let reminder = self as? EKReminder { if let comps = reminder.startDateComponents { return NSCalendar.currentCalendar().dateFromComponents(comps) } } return nil } }
5e5587924b30f7716844eed6dba59b206e92ed4a
[ "Swift", "Markdown" ]
4
Swift
mchaffee1/SwiftLib
4d24b8e07e6bff1f36e1490c570ca58e60c3c3f5
782e4b9ed880db4ac005f0bbd7179f494821235d
refs/heads/master
<file_sep>//var OBDReader = require('OBDReader'); var btOBDReader = new OBDReader(); var dataReceivedMarker = {}; module.exports = btOBDReader;
724da6b49c49afb807795182c49c830a78e35b7b
[ "JavaScript" ]
1
JavaScript
peter-kutak/node-bluetooth-obd
325fd0c1dbf5442baa80fe1264fe72f81d95047e
a056a52aea8db6c434509cf70843e5351f658ecb
refs/heads/master
<file_sep>// PLEASE DON'T change function name module.exports = function makeExchange(currency) { if (currency < 0) { ERROR = {}; return(ERROR); } else if (currency >= 10000) { ERROR = {error: "You are rich, my friend! We don't have so much coins for exchange"}; return (ERROR); } else { money = {}; // create new object H = currency / 50; H = Math.floor(H); if (H != 0) { money.H = H; currency = currency - 50 * H; } if (currency >= 25) { money.Q = 1; currency = currency - 25; } D = currency / 10; D = Math.floor(D); if (D !=0 ) { money.D = D; currency = currency - 10 * D; } if (currency >= 5) { money.N = 1; currency = currency - 5; } if (currency > 0) { money.P = currency; } return(money); } }
2209f4deada7afb48bd25bd51435fef0d45415ed
[ "JavaScript" ]
1
JavaScript
DashaShandrak/money-exchange
2520c52477d2ff2545a9a91b05e5490c803412aa
c56b9b6f2a22a92536018c28bc8942c5376b0da2
refs/heads/master
<file_sep>// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. import { app, ipcMain, BrowserWindow, BrowserWindowConstructorOptions } from "electron"; import { IpcMainProxy } from "./common/ipcMainProxy"; import LocalFileSystem from "./providers/storage/localFileSystem"; // Keep a global reference of the window object, if you don't, the window will // be closed automatically when the JavaScript object is garbage collected. let mainWindow: BrowserWindow | null; let ipcMainProxy: IpcMainProxy; async function createWindow() { const windowOptions: BrowserWindowConstructorOptions = { width: 1024, height: 768, frame: process.platform === "linux", titleBarStyle: "hidden", backgroundColor: "#272B30", show: false, }; const staticUrl = process.env.ELECTRON_START_URL || `file:///${__dirname}/index.html`; if (process.env.ELECTRON_START_URL) { windowOptions.webPreferences = { nodeIntegration: true, webSecurity: false, }; } mainWindow = new BrowserWindow(windowOptions); mainWindow.loadURL(staticUrl); mainWindow.maximize(); mainWindow.on("closed", () => { mainWindow = null; ipcMainProxy.unregisterAll(); }); mainWindow.on("ready-to-show", () => { mainWindow!.show(); }); if (!ipcMainProxy) { ipcMainProxy = new IpcMainProxy(ipcMain, mainWindow); } const localFileSystem = new LocalFileSystem(mainWindow); ipcMainProxy.registerProxy("LocalFileSystem", localFileSystem); } // This method will be called when Electron has finished // initialization and is ready to create browser windows. // Some APIs can only be used after this event occurs. app.on("ready", createWindow); // Quit when all windows are closed. app.on("window-all-closed", () => { // On OS X it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== "darwin") { app.quit(); } }); app.on("activate", () => { // On OS X it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (mainWindow === null) { createWindow(); } }); <file_sep># Test Runbook ## **Fix: enable to reorder tags quickly** > ### Feature description ### Enable reordering tags quickly > ### Use Case ### **`As`** a user\ **`I want`** to be able to move though tags list quickly\ **`So`** I can reorder long list of tags faster > ### Acceptance criteria ### #### Scenario One #### **`Given`** I've opened a project containing documents with long tags list.\ **`When`** I clicking fast on tags buttons `'Move tag up'` or `'Move tag down'`\ **`Then`** it moves without visible jittering. ___ ___ ## **Enable rerun OCR for current or all documents** > ### Feature description ### Adding the following buttons to the canvas command bar: - "Run OCR on current document" - "Run OCR on all documents" > ### Use Case ### **`As`** a user **`I want`** to rerun OCR on documents **`So`** I can update OCR results > ### Acceptance criteria ### #### Scenario One #### **`Given`** I've opened a project containing documents and I'm on the Tag Editor page.\ **`When`** I click "Run OCR on current document" in the canvas command bar\ **`Then`** I should see "Running OCR..." for the current docucment. When running OCR finishes, I should be able to view the document's updated OCR JSON file. #### **Scenario Two** #### **`Given`** I've opened a project containing documents and I'm on the Tag Editor page.\ **`When`** I click "Run OCR on all documents" in the canvas command bar\ **`Then`** I should see "Running OCR..." for all documents. When running OCR finishes for each document, I should be ale to view each document's updated OCR JSON file. ___ ___ ## **Feat: enable compose model and add model name when training a new model** > ### Feature description ### - Add model name imput field on train page to add model name when training a new model - Add model compose page in order to compose a new model with existing models > ### Use Case ### **`As`** a user **`I want`** to give the new train model a customerized name **`So`** I can type the name in input field in train page before click train button. **`As`** a user **`I want`** to generate a new mode through existing model **`So`** I can use model compose > ### Acceptance criteria ### #### Scenario One #### **`Given`** I've opened a project containing documents and I'm on the Train page.\ **`When`** I type customerized name in input field and click train button\ **`Then`** I should see typed name shows in Train Record after record shows up.\ #### **Scenario Two** #### **`Given`** I've opened a project containing documents and I'm on the Model Compose page. There are enough existing models in modelList.\ **`When`** I select more than one models then click compose button\ **`Then`** I should see a pop up modal with a list contains selected models and a input field.\ **`When`** I type customerized model name in input field and click compose button on modal\ **`Then`** I should see "Model is composing, please wait...". After that the list shows up again, new composed model with given name will be on the top of the list. The new composed model also has a "combine" icon. #### ***Scenario Three*** #### **`Given`** I've opened a project containing documents and I'm on the Model Compose page.\ **`When`** I click the header of a column\ **`Then`** I should see the column becomes sorted in either ascending or discending order.\ **`When`** I type some text inside the fliter field on top right\ **`Then`** I should see items whose id or name contains the text be filtered out.
25784862f79fbbedd9d776917fd1c2d1b4b813db
[ "Markdown", "TypeScript" ]
2
TypeScript
existimatio/OCR-Form-Tools-1
8297b18a084be86bc4c986a1a332cb40bd807d1b
efe6ec0aa610b0d5348c9039853d190400edcd1e
refs/heads/master
<repo_name>ryanp538853/Sandbox<file_sep>/password_entry.py """Ryan""" MINIMUM_LENGTH = 6 password = input("Please enter your password that has at least {} character: ".format(MINIMUM_LENGTH)) while len(password) < MINIMUM_LENGTH: input("Invalid password!\nPlease enter password that contains at least {} characters: ".format(MINIMUM_LENGTH)) print("*" * len(password)) <file_sep>/README.md # Sandbox Project for various tests import files
91b74d65957a732c12d0cce93e29bbdea82c11e2
[ "Markdown", "Python" ]
2
Python
ryanp538853/Sandbox
224dc068645666e2baccebb787d7170c735e2755
4d1aac6cf494ce7e65d8f9827d1f894b5cb87e40
refs/heads/springboot_01
<file_sep>package com.mrk.sys.dao.pre; public interface BaseDaoPre<T,PK> { int deleteByPrimaryKey(PK key); int insert(T record); int insertSelective(T record); T selectByPrimaryKey(PK key); int updateByPrimaryKeySelective(T record); int updateByPrimaryKey(T record); } <file_sep>package com.mrk.sys.dao; import org.springframework.stereotype.Repository; import com.mrk.sys.dao.pre.BaseDaoPre; import com.mrk.sys.entity.Account; @Repository("accountMapper") public interface AccountMapper extends BaseDaoPre<Account, Integer> { }<file_sep>package com.mrk.sys.dao; import java.util.List; import org.springframework.stereotype.Repository; import com.mrk.sys.entity.DfMoneyFile; @Repository("dfMoneyFileMapper") public interface DfMoneyFileMapper { List<DfMoneyFile> selectByExample(); }<file_sep>package com.mrk.assist.util.generator; import java.util.List; import org.mybatis.generator.api.IntrospectedColumn; import org.mybatis.generator.api.IntrospectedTable; import org.mybatis.generator.api.JavaTypeResolver; import org.mybatis.generator.api.PluginAdapter; import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType; import org.mybatis.generator.api.dom.java.Interface; import org.mybatis.generator.api.dom.java.TopLevelClass; import org.mybatis.generator.config.TableConfiguration; import org.mybatis.generator.internal.types.JavaTypeResolverDefaultImpl; import org.mybatis.generator.logging.Log; import org.mybatis.generator.logging.LogFactory; public class BaseDaoGeneratorPlugin extends PluginAdapter { public static final String BASE_DAO="BaseDao"; public static final String BASE_DAOP="BaseDaoPre"; public static final String BASE_DAO_IMP="com.mrk.sys.dao.pre"; private Log logger; @Override public boolean validate(List<String> warnings) { return true; } @Override public boolean clientGenerated(Interface interfaze, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) { interfaze.getImportedTypes().clear(); List<IntrospectedColumn> Columns = introspectedTable.getPrimaryKeyColumns(); int knum = Columns.size(); if (knum == 0) { try { throw new Exception(); } catch (Exception e) { e.printStackTrace(); } } String a, impBaseDao; if (gethasEx(introspectedTable)) { a = BASE_DAOP + "<" + introspectedTable.getBaseRecordType() + ","; impBaseDao = BASE_DAO_IMP + "." + BASE_DAOP; } else { a = BASE_DAO + "<" + introspectedTable.getBaseRecordType() + "," + introspectedTable.getExampleType() + ","; FullyQualifiedJavaType imp3 = new FullyQualifiedJavaType(introspectedTable.getExampleType()); interfaze.addImportedType(imp3); impBaseDao = BASE_DAO_IMP + "." + BASE_DAO; } FullyQualifiedJavaType imp = new FullyQualifiedJavaType(impBaseDao); FullyQualifiedJavaType imp2 = new FullyQualifiedJavaType(introspectedTable.getBaseRecordType()); interfaze.addImportedType(imp); interfaze.addImportedType(imp2); // 如果主键只有一个 没有单独生成主键类 处理泛型接口类别 if (Columns.size() == 1) { JavaTypeResolver javaTypeResolver = new JavaTypeResolverDefaultImpl(); FullyQualifiedJavaType fullyQualifiedJavaType = javaTypeResolver.calculateJavaType(Columns.get(0)); a = a + fullyQualifiedJavaType + ">"; interfaze.addImportedType(fullyQualifiedJavaType); } else { a = a + introspectedTable.getPrimaryKeyType() + ">"; FullyQualifiedJavaType imp4 = new FullyQualifiedJavaType(introspectedTable.getPrimaryKeyType()); interfaze.addImportedType(imp4); } FullyQualifiedJavaType fqjt = new FullyQualifiedJavaType(a); interfaze.addSuperInterface(fqjt); interfaze.getMethods().clear(); interfaze.getAnnotations().clear(); logger = LogFactory.getLog(getClass()); logger.debug(a); return true; } // 判断是否生成ex类 public boolean gethasEx(IntrospectedTable introspectedTable) { TableConfiguration tableConfiguration = introspectedTable.getTableConfiguration(); Boolean b1 = tableConfiguration.isCountByExampleStatementEnabled(); Boolean b2 = tableConfiguration.isUpdateByExampleStatementEnabled(); Boolean b3 = tableConfiguration.isSelectByExampleStatementEnabled(); Boolean b4 = tableConfiguration.isDeleteByExampleStatementEnabled(); if (b1 && b2 && b3 && b4) { return false; } return true; } } <file_sep>package com.mrk.sys.dao.pre; import java.util.List; import org.apache.ibatis.annotations.Param; public interface BaseDao<T, M, PK> extends BaseDaoPre<T, PK>{ long countByExample(M example); int deleteByExample(M example); List<T> selectByExample(M example); int updateByExampleSelective(@Param("record") T record, @Param("example") M example); int updateByExample(@Param("record") T record, @Param("example") M example); } <file_sep>package com.mrk.sys.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Repository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.mrk.sys.dao.DfMoneyFileMapper; import com.mrk.sys.entity.DfMoneyFile; import com.mrk.sys.service.DfMoneyFileService; @Service @Repository("dfMoneyFileService") public class DfMoneyFileServiceImpl implements DfMoneyFileService{ @Autowired @Qualifier("dfMoneyFileMapper") private DfMoneyFileMapper dfMoneyFileMapper; @Override @Transactional public List<DfMoneyFile> selectByExample() { return dfMoneyFileMapper.selectByExample(); } } <file_sep>package com.mrk.webassist; import com.mrk.sys.entity.Account; public class HostHolder { //本地线程变量,在每个线程中都有一份该变量的拷贝,因此有多个线程同时访问的时候也不会发生冲突 private static ThreadLocal<Account> accounts = new ThreadLocal<>(); public static Account getAccount() { return accounts.get(); } public static void setAccount(Account account) { accounts.set(account); } public static void clear() { accounts.remove(); } } <file_sep>package com.mrk.assist.util.logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; public class LoggerHandlerUtil { private static final String mobile_regex = "(1[3-9])\\d{9}$"; private static final String sus_regex = "\n|\t|\r"; private LoggerHandlerUtil() { throw new IllegalStateException("java IllegalStateException "); } /** * 手机号码保留前三位和后四位,其他隐藏<如:188******1234> * * @param mobile * 手机号 * @return String */ public static String mobileHandler(String mobile, String type) { switch (type) { case mobile_regex: if (StringUtils.isNoneBlank(mobile)) { mobile = mobile.substring(0, 3) + "****" + mobile.substring(7, mobile.length()); } break; default: break; } return mobile; } public static String reHandler(String msg) { String result = msg; result = result.replaceAll(sus_regex, "_"); result = reHandlerUtilM(result, mobile_regex); return result; } public static String reHandlerUtilM(String msg, String type) { Pattern pattern = Pattern.compile(type); Matcher matcher = pattern.matcher(msg); StringBuffer sb = new StringBuffer(); while (matcher.find()) { String tmp = matcher.group(); String v = mobileHandler(tmp, type); matcher.appendReplacement(sb, v); matcher.appendTail(sb); msg = sb.toString(); } return msg; } } <file_sep>package com.mrk.webassist; import javax.servlet.Filter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.ServletListenerRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import com.mrk.webassist.filter.WebFilter; import com.mrk.webassist.interceptor.LoginInterceptor; import com.mrk.webassist.interceptor.TicketInterceptor; import com.mrk.webassist.listener.WebHttpSessionListener; @Configuration public class WebConfigurer implements WebMvcConfigurer{ @Autowired private LoginInterceptor loginInterceptor; @Autowired private TicketInterceptor ticketInterceptor; @Autowired private WebFilter webFilter; @Autowired private WebHttpSessionListener httpSessionListener; //过滤器注册 @Bean public FilterRegistrationBean<Filter> filterRegist() { FilterRegistrationBean<Filter> frBean =new FilterRegistrationBean<>(); frBean.setFilter(webFilter); frBean.addUrlPatterns("/*"); frBean.setOrder(1); return frBean; } //拦截器注册 @Override public void addInterceptors(InterceptorRegistry interceptorregistry) { interceptorregistry.addInterceptor(loginInterceptor).addPathPatterns("/**"); interceptorregistry.addInterceptor(ticketInterceptor).addPathPatterns("/**").excludePathPatterns("/login/**").excludePathPatterns("/error"); WebMvcConfigurer.super.addInterceptors(interceptorregistry); } //监听器 @Bean public ServletListenerRegistrationBean<WebHttpSessionListener> listenerRegist() { ServletListenerRegistrationBean<WebHttpSessionListener> srb = new ServletListenerRegistrationBean<WebHttpSessionListener>(); srb.setListener(httpSessionListener); return srb; } }
5f274bf3f34a2774d7552ad89858739e416df05c
[ "Java" ]
9
Java
fishkkw/SpringBoot
9539dc255508f99438127978462b7fdfa68d7953
3d8fdf84f7ee7a5a221e28b5319d301d2eaa18b4
refs/heads/master
<file_sep>package callAPI import ( "api_test/db" "google.golang.org/api/youtube/v3" ) //チャンネル情報を取得 func GetChannelContent(service *youtube.Service, channelID string, gID uint) (chContent2 db.Channel) { call := service.Channels.List("snippet,contentDetails").Id(channelID) resp, err := call.Do() if err != nil { panic(err) } chContent2 = db.Channel{ ID: channelID, GroupID: gID, Name: resp.Items[0].Snippet.Title, Thumbnail: resp.Items[0].Snippet.Thumbnails.Default.Url, } return } <file_sep>package callAPI import ( "strconv" "strings" ) //歌ってみた「動画」かどうかの判別 func CheckVideoTime(videoTime string) bool { //PT?M?S という形なので、まずPTを消す trimTime := strings.TrimLeft(videoTime, "PT") //1時間以上のものを除外 if strings.Contains(trimTime, "H") { return false } //10分以上のものを除外 if strings.Contains(trimTime, "M") { indexM := strings.Index(trimTime, "M") minute, _ := strconv.Atoi(trimTime[:indexM]) if minute >= 10 { return false } } return true } <file_sep>package back import ( "api_test/db" ) //DB上のグループを全て取得 func GroupList(gName string, page string) (groups []db.Group) { database := db.ConnectDB() defer database.Close() database.LogMode(true) offset := Page2Offset(page) database. Where("name LIKE ?", "%"+gName+"%"). Order("id"). Offset(offset).Limit(10). Find(&groups) return } func GroupRandomList() (groups []db.Group) { database := db.ConnectDB() defer database.Close() database.LogMode(true) database.Order("RANDOM()").Limit(10).Preload("Group").Find(&groups) return } <file_sep>package main import ( "encoding/json" "fmt" "io/ioutil" "net/http" "net/url" "os" "time" ) type Data struct { Url string `json:"url"` Title string `json:"title"` LikesCount int `json:"likes_count"` ReactionsCount int `json:"reactions_count"` PageViewsCount int `json:"page_views_count"` } func fetchQiitaData(accessToken string, targetDate time.Time) []Data { baseUrl := "https://qiita.com/api/v2/" action := "items" baseParam := "?page=1&per_page=30" year, month, day := targetDate.Date() targetDay := dateNum2String(year, int(month), day) year, month, day = targetDate.AddDate(0, 0, 1).Date() nextDay := dateNum2String(year, int(month), day) varParam := "&query=stocks:>30+created:>=" + targetDay + "+created:<" + nextDay endpointURL, err := url.Parse(baseUrl + action + baseParam + varParam) if err != nil { panic(err) } b, err := json.Marshal(Data{}) if err != nil { panic(err) } var resp = &http.Response{} if len(accessToken) > 0 { resp, err = http.DefaultClient.Do(&http.Request{ URL: endpointURL, Method: "GET", Header: http.Header{ "Content-Type": {"application/json"}, "Authorization": {"Bearer " + accessToken}, }, }) } else { resp, err = http.DefaultClient.Do(&http.Request{ URL: endpointURL, Method: "GET", Header: http.Header{ "Content-Type": {"application/json"}, }, }) } defer resp.Body.Close() if err != nil { panic(err) } b, err = ioutil.ReadAll(resp.Body) if err != nil { panic(err) } var datas []Data if err := json.Unmarshal(b, &datas); err != nil { fmt.Println("JSON Unmarshal error:", err) return nil } return datas } func outputQiitaData(datas []Data) { for _, val := range datas { fmt.Println(val.LikesCount, val.Title, val.Url) } fmt.Println() } func dateNum2String(year int, month int, day int) string { return fmt.Sprintf("%d-%d-%d", year, month, day) } func main() { //qiitaToken := os.Getenv("QIIT_TOKEN") var baseDate time.Time fmt.Println("いいね数 タイトル URL") var err error if len(os.Args) >= 2 { arg := os.Args[1] layout := "2006-01-02" baseDate, err = time.Parse(layout, arg) if err != nil { panic(err) } } else { baseDate = time.Now() } startDate := baseDate.AddDate(-1, 0, -6) num0fDates := 7 for i := 0; i < num0fDates; i++ { targetDate := startDate.AddDate(0, 0, i) fmt.Printf("%d-%d-%d\n", targetDate.Year(), int(targetDate.Month()), targetDate.Day()) datas := fetchQiitaData(qiitaToken, targetDate) outputQiitaData(datas) } } <file_sep>package callAPI /* チャンネルIDからチャンネルデータを取り、DBに保存するプログラムの試行 */ import ( "api_test/db" ) func GetChannel(inputURL string, gID uint) (bool, string) { chID := Url2chID(inputURL) if chID == "1" { return false, "youtubeのURLではありません" } else if chID == "2" { return false, "チャンネルのURLではありません" } if !db.CheckExistChannel(chID) { return false, "既にチャンネルが存在します" } if !db.CheckExistGroup(gID) { return false, "与えられたグループが存在しません" } service := GetClient() chContent := GetChannelContent(service, chID, gID) db.AddChannel(chContent.ID, chContent.GroupID, chContent.Name, chContent.Thumbnail) return true, "チャンネルを追加しました" } <file_sep>package callAPI import "net/url" func Url2viID(inputURL string) (videoID string) { u, err := url.Parse(inputURL) if (err != nil) || u.Host != "www.youtube.com" { return "URLが正しくありません" } for k, v := range u.Query() { if k == "v" { videoID = v[0] } } return } <file_sep>package main import ( "fmt" "google.golang.org/api/googleapi/transport" "google.golang.org/api/youtube/v3" "log" "net/http" "os" ) //var ( // query = flag.String("query", "夏色まつり", "Search term") // maxResults = flag.Int64("max-results", 1, "Max YouTube results") //) func main() { developerKey := os.Getenv("youtube_key") client := &http.Client{ Transport: &transport.APIKey{Key: developerKey}, } service, err := youtube.New(client) if err != nil { log.Fatalf("Errr creating new Youtube client: %v", err) } //call := service.Channels.List("id,snippet,contentDetails").Id("UCQ0UDLQCjY0rmuxCDE38FGg").MaxResults(1) call := service.Channels.List("id,snippet,contentDetails").Id("UCQ0UDLQCjY0rmuxCDE38FGg").MaxResults(1) resp, err := call.Do() if err != nil { panic(err) } else { //fmt.Print(resp) //fmt.Print(resp.Items[0]) //fmt.Print(resp.Items[0].Snippet.PublishedAt) fmt.Print(resp.Items[0].ContentDetails.RelatedPlaylists.Uploads) } } <file_sep>package back import ( "api_test/db" ) //ビデオ情報取得 func VideoInfo(vID string) (video db.Video) { database := db.ConnectDB() defer database.Close() database.LogMode(true) database. Where("id = ?", vID). Preload("Channel"). Preload("Group"). First(&video) return } <file_sep>{{define "body"}} <h2>検索</h2> <form method="get" action="/channels"> <p><input type="text" name="chName" placeholder="チャンネル名を入力"></p> <p><input type="submit" value="Send"></p> </form> <div> <ul> {{range .channels}} <ul> <li><img src="{{.Thumbnail}}" alt=""></li> <li>Title: {{.Name}}</li> <li>グループ: {{.Group.Name}} <a href="/group/{{.GroupID}}">グループページへ飛ぶ</a></li> <li><a href="/channel/{{.ID}}">個別ページへ飛ぶ</a></li> <li><a href="https://www.youtube.com/channel/{{.ID}}">リンク</a></li> <strong>----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------</strong> </ul> {{end}} </ul> </div> {{end}} <file_sep>package main /* 与えられたチャンネルにある再生リストから歌ってみたのリストを抽出し、保存 また、そのチャンネルがDBに存在しない場合、追加 */ import ( "api_test/db" "fmt" "github.com/jinzhu/gorm" "google.golang.org/api/googleapi/transport" "google.golang.org/api/youtube/v3" "log" "net/http" "os" "strconv" "strings" "time" ) var reS []map[string]string func main() { database, err := gorm.Open("sqlite3", "./db/test.sqlite3") if err != nil { panic("failed to connect database") } defer database.Close() service := getClient4() var channels []db.Channel //database.Select("id").Where("group_id = ?", 3).Find(&channels) database.Select("id").Find(&channels) for _, channel := range channels { chID := channel.ID plID := getSingPlaylist4(service, chID) if len(plID) != 0 { //ret := getPlaylistContn4(service, plID) for _, pl := range plID { getPlaylistContn4(service, pl) time.Sleep(3) } ret := reS fmt.Println(ret) groupID := db.SearchGroup(chID) if !db.CheckExistGroup(groupID) { panic("与えられたグループが存在しません") } for _, video := range ret { fmt.Println("------------------------------------------") switch db.CheckExistVideo(video["channelID"], video["videoID"]) { case 1: fmt.Println("チャンネルを確認・動画非重複") db.InsertVideo(video["videoID"], video["channelID"], groupID, video["title"]) case 2: fmt.Println("チャンネルを非確認") chCon3 := getChannelContent4(service, video["channelID"], groupID) db.AddChannel(chCon3.ID, chCon3.GroupID, chCon3.Name, chCon3.Thumbnail) db.InsertVideo(video["videoID"], video["channelID"], groupID, video["title"]) default: fmt.Println("動画追加済み") } fmt.Println("------------------------------------------") } } } } //APIクライアント生成 func getClient4() *youtube.Service { developerKey := os.Getenv("youtube_key") client := &http.Client{ Transport: &transport.APIKey{Key: developerKey}, } service, err := youtube.New(client) if err != nil { log.Fatalf("Errr creating new Youtube client: %v", err) } return service } //歌ってみた動画の再生リストを抽出 func getSingPlaylist4(service *youtube.Service, channelID string) []string { var ( nextPageToken string plIndex int64 asari func(ind int64, token string) playlistID []string itemsConts int64 ) asari = func(ind int64, token string) { call := service.Playlists.List("snippet,contentDetails").ChannelId(channelID).MaxResults(50).PageToken(token) resp, err := call.Do() if err != nil { panic(err) } if ind == 0 { plIndex = resp.PageInfo.TotalResults itemsConts = 0 } nextPageToken = resp.NextPageToken //再生リストの名前で「歌ってみた」動画を判別 for _, playlist := range resp.Items { if (strings.Contains(playlist.Snippet.Title, "歌")) || (strings.Contains(playlist.Snippet.Title, "うた")) || (strings.Contains(playlist.Snippet.Title, "sing")) || (strings.Contains(playlist.Snippet.Title, "Music")) { //if (!strings.Contains(playlist.Snippet.Title, "配信")) && // (!strings.Contains(playlist.Snippet.Title, "枠")) && // (!strings.Contains(playlist.Snippet.Title, "わく")) && // (!strings.Contains(playlist.Snippet.Title, "雑談")) && // (!strings.Contains(playlist.Snippet.Title, "放送")) //{ //if playlist.ContentDetails.ItemCount > itemsConts { // playlistID = playlist.Id //} playlistID = append(playlistID, playlist.Id) //} } } if plIndex > 50 { plIndex -= 50 asari(plIndex, nextPageToken) } } asari(0, nextPageToken) return playlistID } //プレイリストの中身を漁る func getPlaylistContn4(service *youtube.Service, playlistID string) { var ( //reS []map[string]string content map[string]string nextPageToken string plIndex int64 asari func(ind int64, token string) ) asari = func(ind int64, token string) { call := service.PlaylistItems.List("snippet,contentDetails").PlaylistId(playlistID).MaxResults(50).PageToken(token) resp, err := call.Do() if err != nil { panic(err) } if ind == 0 { plIndex = resp.PageInfo.TotalResults } nextPageToken = resp.NextPageToken for _, item := range resp.Items { //非公開動画は除外・時間で動画のみ抽出 //if (item.Snippet.Title != "Private video") && (checkVideoTime4(filteringSingVideo4(service, item.ContentDetails.VideoId))) { if item.Snippet.Title != "Private video" { videoDuration, videoChId := filteringSingVideo4(service, item.ContentDetails.VideoId) if checkVideoTime4(videoDuration) { content = map[string]string{ "title": item.Snippet.Title, "videoID": item.ContentDetails.VideoId, "channelID": videoChId, } reS = append(reS, content) } } } if plIndex > 50 { plIndex -= 50 asari(plIndex, nextPageToken) } } asari(0, nextPageToken) fmt.Println("---------------------\n" + "合計取得数: " + strconv.Itoa(len(reS)) + "\n---------------------") //return } //各動画の中身を漁る func filteringSingVideo4(service *youtube.Service, videoID string) (string, string) { call := service.Videos.List("snippet,contentDetails").Id(videoID) resp, err := call.Do() if err != nil { panic(err) } //fmt.Println(resp.Items[0].ContentDetails.Duration) //fmt.Println(resp.Items[0].Snippet.ChannelId) //fmt.Println(resp.Items[0].Snippet.Title) return resp.Items[0].ContentDetails.Duration, resp.Items[0].Snippet.ChannelId } //「歌ってみた動画」かどうかの判別 func checkVideoTime4(videoTime string) bool { //PT?M?S という形なので、まずPTを消す trimTime := strings.TrimLeft(videoTime, "PT") //1時間以上のものを除外 if strings.Contains(trimTime, "H") { return false } //10分以上のものを除外 if strings.Contains(trimTime, "M") { indexM := strings.Index(trimTime, "M") minute, _ := strconv.Atoi(trimTime[:indexM]) if minute >= 10 { return false } } return true } //チャンネル情報を取得 func getChannelContent4(service *youtube.Service, channelID string, gID uint) db.Channel { call := service.Channels.List("snippet,contentDetails").Id(channelID) resp, err := call.Do() if err != nil { panic(err) } chContent4 := db.Channel{ ID: channelID, GroupID: gID, Name: resp.Items[0].Snippet.Title, Thumbnail: resp.Items[0].Snippet.Thumbnails.Default.Url, } return chContent4 } <file_sep>package main /* Vtuberの名前から、その人の再生リストを見にいき、「歌ってみた」動画の再生リストの中身を取ってくる */ import ( "flag" "fmt" "google.golang.org/api/googleapi/transport" "google.golang.org/api/youtube/v3" "log" "net/http" "os" "strconv" "strings" ) func main() { flag.Parse() args := flag.Args() var searchWord string if len(args) == 0 { searchWord = "夏色まつり" } else { searchWord = SummarySearchWord(args) } fmt.Println("検索ワード: " + searchWord) fmt.Println("----------------------------------") fmt.Println() service := GetClient() chID := SearchChannelID(service, searchWord) plID := GetSingPlaylist(service, chID) GetPlaylistContnt(service, plID) //contents := GetPlaylistContnt(service, plID) //fmt.Println(contents) } func GetClient() *youtube.Service { developerKey := os.Getenv("youtube_key") client := &http.Client{ Transport: &transport.APIKey{Key: developerKey}, } service, err := youtube.New(client) if err != nil { log.Fatalf("Errr creating new Youtube client: %v", err) } return service } //コマンドラインで受け取った引数を検索用の文字列に変換 func SummarySearchWord(words []string) string { var re string for _, s := range words { re += s + " " } return re } //検索用ワードからチャンネルを検索 func SearchChannelID(service *youtube.Service, name string) string { call := service.Search.List("snippet").Q(name).MaxResults(1).Type("channel") resp, err := call.Do() if err != nil { panic(err) } return resp.Items[0].Snippet.ChannelId } //歌ってみた動画の再生リストを抽出 func GetSingPlaylist(service *youtube.Service, channelID string) string { var ( nextPageToken string plIndex int64 asari func(ind int64, token string) playlistID string itemsConts int64 ) asari = func(ind int64, token string) { call := service.Playlists.List("snippet,contentDetails").ChannelId(channelID).MaxResults(50).PageToken(token) resp, err := call.Do() if err != nil { panic(err) } if ind == 0 { plIndex = resp.PageInfo.TotalResults itemsConts = 0 } nextPageToken = resp.NextPageToken //再生リストの名前で「歌ってみた」動画を判別 for _, playlist := range resp.Items { if (strings.Contains(playlist.Snippet.Title, "歌")) || (strings.Contains(playlist.Snippet.Title, "うた")) { if (!strings.Contains(playlist.Snippet.Title, "配信")) && (!strings.Contains(playlist.Snippet.Title, "枠")) && (!strings.Contains(playlist.Snippet.Title, "わく")) && (!strings.Contains(playlist.Snippet.Title, "雑談")) && (!strings.Contains(playlist.Snippet.Title, "放送")) { if playlist.ContentDetails.ItemCount > itemsConts { playlistID = playlist.Id } } } } if plIndex > 50 { plIndex -= 50 asari(plIndex, nextPageToken) } } asari(0, nextPageToken) if playlistID == "" { panic("Missed get PlaylistID") } return playlistID } //プレイリストの中身を漁る func GetPlaylistContnt(service *youtube.Service, playlistID string) []map[string]string { var ( reS []map[string]string content map[string]string nextPageToken string plIndex int64 asari func(ind int64, token string) ) asari = func(ind int64, token string) { call := service.PlaylistItems.List("snippet,contentDetails").PlaylistId(playlistID).MaxResults(50).PageToken(token) resp, err := call.Do() if err != nil { panic(err) } if ind == 0 { plIndex = resp.PageInfo.TotalResults } nextPageToken = resp.NextPageToken for _, item := range resp.Items { //非公開動画は除外・時間で動画のみ抽出 if (item.Snippet.Title != "Private video") && (CheckVideoTime(FilteringSingVideo(service, item.ContentDetails.VideoId))) { //if item.Snippet.Title != "Private video" { fmt.Println(item.Snippet.Title) fmt.Println("https://www.youtube.com/watch?v=" + item.ContentDetails.VideoId) fmt.Println("再生時間: " + FilteringSingVideo(service, item.ContentDetails.VideoId)) //fmt.Println("videoID: " + item.ContentDetails.VideoId) //fmt.Println("channelID: "+ item.Snippet.ChannelId) //fmt.Println("サムネURL: " + item.Snippet.Thumbnails.Default.Url) //fmt.Println("インデックス: " + strconv.Itoa(item.Snippet.Position)) fmt.Println() content = map[string]string{ "Title": item.Snippet.Title, "videoID": item.ContentDetails.VideoId, "channelID": item.Snippet.ChannelId, } reS = append(reS, content) } } if plIndex > 50 { plIndex -= 50 asari(plIndex, nextPageToken) } } asari(0, nextPageToken) fmt.Println("---------------------\n" + "合計取得数: " + strconv.Itoa(len(reS)) + "\n---------------------") return reS } //各動画の中身を漁る func FilteringSingVideo(service *youtube.Service, videoID string) string { call := service.Videos.List("contentDetails").Id(videoID) resp, err := call.Do() if err != nil { panic(err) } return resp.Items[0].ContentDetails.Duration } //歌ってみた「動画」かどうかの判別 func CheckVideoTime(videoTime string) bool { //PT?M?S という形なので、まずPTを消す trimTime := strings.TrimLeft(videoTime, "PT") //1時間以上のものを除外 if strings.Contains(trimTime, "H") { return false } //10分以上のものを除外 if strings.Contains(trimTime, "M") { indexM := strings.Index(trimTime, "M") minute, _ := strconv.Atoi(trimTime[:indexM]) if minute >= 10 { return false } } return true } <file_sep>package main /* 与えられたチャンネルにある再生リストから歌ってみたのリストを抽出し、保存 また、そのチャンネルがDBに存在しない場合、追加 */ import ( "api_test/db" "flag" "fmt" "google.golang.org/api/googleapi/transport" "google.golang.org/api/youtube/v3" "log" "net/http" "os" "strconv" "strings" ) func main() { flag.Parse() args := flag.Args() //var searchWord string // //if len(args) == 0 { // searchWord = "夏色まつり" //} else { // searchWord = summarySearchWord3(args) //} // //fmt.Println("検索ワード: " + searchWord) //fmt.Println("----------------------------------") //fmt.Println() service := getClient3() //chID := searchChannelID3(service, searchWord) chID := args[0] plID := getSingPlaylist3(service, chID) ret := getPlaylistContnt3(service, plID) fmt.Println(ret) groupID := db.SearchGroup(chID) if !db.CheckExistGroup(groupID) { panic("与えられたグループが存在しません") } for _, video := range ret { fmt.Println("------------------------------------------") switch db.CheckExistVideo(video["channelID"], video["videoID"]) { case 1: fmt.Println("チャンネルを確認・動画非重複") db.InsertVideo(video["videoID"], video["channelID"], groupID, video["title"]) case 2: fmt.Println("チャンネルを非確認") chCon3 := getChannelContent3(service, video["channelID"], groupID) db.AddChannel(chCon3.ID, chCon3.GroupID, chCon3.Name, chCon3.Thumbnail) db.InsertVideo(video["videoID"], video["channelID"], groupID, video["title"]) default: fmt.Println("動画追加済み") } fmt.Println("------------------------------------------") } } //APIクライアント生成 func getClient3() *youtube.Service { developerKey := os.Getenv("youtube_key") client := &http.Client{ Transport: &transport.APIKey{Key: developerKey}, } service, err := youtube.New(client) if err != nil { log.Fatalf("Errr creating new Youtube client: %v", err) } return service } //コマンドラインで受け取った引数を検索用の文字列に変換 func summarySearchWord3(words []string) string { var re string for _, s := range words { re += s + " " } return re } //検索用ワードからチャンネルを検索 func searchChannelID3(service *youtube.Service, name string) string { call := service.Search.List("snippet").Q(name).MaxResults(1).Type("channel") resp, err := call.Do() if err != nil { panic(err) } return resp.Items[0].Snippet.ChannelId } //歌ってみた動画の再生リストを抽出 func getSingPlaylist3(service *youtube.Service, channelID string) string { var ( nextPageToken string plIndex int64 asari func(ind int64, token string) playlistID string itemsConts int64 ) asari = func(ind int64, token string) { call := service.Playlists.List("snippet,contentDetails").ChannelId(channelID).MaxResults(50).PageToken(token) resp, err := call.Do() if err != nil { panic(err) } if ind == 0 { plIndex = resp.PageInfo.TotalResults itemsConts = 0 } nextPageToken = resp.NextPageToken //再生リストの名前で「歌ってみた」動画を判別 for _, playlist := range resp.Items { if (strings.Contains(playlist.Snippet.Title, "歌")) || (strings.Contains(playlist.Snippet.Title, "うた")) { if (!strings.Contains(playlist.Snippet.Title, "配信")) && (!strings.Contains(playlist.Snippet.Title, "枠")) && (!strings.Contains(playlist.Snippet.Title, "わく")) && (!strings.Contains(playlist.Snippet.Title, "雑談")) && (!strings.Contains(playlist.Snippet.Title, "放送")) { if playlist.ContentDetails.ItemCount > itemsConts { playlistID = playlist.Id } } } } if plIndex > 50 { plIndex -= 50 asari(plIndex, nextPageToken) } } asari(0, nextPageToken) if playlistID == "" { panic("Missed get PlaylistID") } return playlistID } //プレイリストの中身を漁る func getPlaylistContnt3(service *youtube.Service, playlistID string) []map[string]string { var ( reS []map[string]string content map[string]string nextPageToken string plIndex int64 asari func(ind int64, token string) ) asari = func(ind int64, token string) { call := service.PlaylistItems.List("snippet,contentDetails").PlaylistId(playlistID).MaxResults(50).PageToken(token) resp, err := call.Do() if err != nil { panic(err) } if ind == 0 { plIndex = resp.PageInfo.TotalResults } nextPageToken = resp.NextPageToken for _, item := range resp.Items { //非公開動画は除外・時間で動画のみ抽出 if item.Snippet.Title != "Private video" { videoDuration, videoChId := filteringSingVideo3(service, item.ContentDetails.VideoId) if checkVideoTime3(videoDuration) { content = map[string]string{ "title": item.Snippet.Title, "videoID": item.ContentDetails.VideoId, "channelID": videoChId, } reS = append(reS, content) } } } if plIndex > 50 { plIndex -= 50 asari(plIndex, nextPageToken) } } asari(0, nextPageToken) fmt.Println("---------------------\n" + "合計取得数: " + strconv.Itoa(len(reS)) + "\n---------------------") return reS } //各動画の中身を漁る func filteringSingVideo3(service *youtube.Service, videoID string) (string, string) { call := service.Videos.List("contentDetails").Id(videoID) resp, err := call.Do() if err != nil { panic(err) } return resp.Items[0].ContentDetails.Duration, resp.Items[0].Snippet.ChannelId } //「歌ってみた動画」かどうかの判別 func checkVideoTime3(videoTime string) bool { //PT?M?S という形なので、まずPTを消す trimTime := strings.TrimLeft(videoTime, "PT") //1時間以上のものを除外 if strings.Contains(trimTime, "H") { return false } //10分以上のものを除外 if strings.Contains(trimTime, "M") { indexM := strings.Index(trimTime, "M") minute, _ := strconv.Atoi(trimTime[:indexM]) if minute >= 10 { return false } } return true } //チャンネル情報を取得 func getChannelContent3(service *youtube.Service, channelID string, gID uint) db.Channel { call := service.Channels.List("snippet,contentDetails").Id(channelID) resp, err := call.Do() if err != nil { panic(err) } chContent3 := db.Channel{ ID: channelID, GroupID: gID, Name: resp.Items[0].Snippet.Title, Thumbnail: resp.Items[0].Snippet.Thumbnails.Default.Url, } return chContent3 } <file_sep>package back import "strconv" func Page2Offset(page string) (offset int) { intPage, err := strconv.Atoi(page) if err != nil { intPage = 1 } offset = (intPage - 1) * 10 return } <file_sep>package main /* 県枠ワードから動画を検索して、該当チャンネルから出されている「歌ってみた」動画を抽出 ・・・したかったが、「歌」・「歌ってみた」で検索すると、関係ない動画も大量に出てしまい、このやり方で動画を集めるのは厳しいか? */ import ( "flag" "fmt" "google.golang.org/api/googleapi/transport" "google.golang.org/api/youtube/v3" "log" "net/http" "os" "strconv" "strings" ) func main() { flag.Parse() args := flag.Args() var searchWord string if len(args) == 0 { searchWord = "夏色まつり" } else { searchWord = ssummarySearchWord(args) } fmt.Println("検索ワード: " + searchWord) fmt.Println("----------------------------------") fmt.Println() chID := ssearchChannelID(searchWord) ggetOnluSearchVideo(chID) } //コマンドラインで受け取った引数を検索用の文字列に変換 func ssummarySearchWord(words []string) string { var re string for _, s := range words { re += s + " " } return re } //検索用ワードからチャンネルを検索 func ssearchChannelID(name string) string { developerKey := os.Getenv("youtube_key") client := &http.Client{ Transport: &transport.APIKey{Key: developerKey}, } service, err := youtube.New(client) if err != nil { log.Fatalf("Errr creating new Youtube client: %v", err) } call := service.Search.List("snippet").Q(name).MaxResults(1).Type("channel") resp, err := call.Do() if err != nil { panic(err) } return resp.Items[0].Snippet.ChannelId } func ggetOnluSearchVideo(channelID string) string { developerKey := os.Getenv("youtube_key") client := &http.Client{ Transport: &transport.APIKey{Key: developerKey}, } service, err := youtube.New(client) if err != nil { log.Fatalf("Errr creating new Youtube client: %v", err) } call := service.Search.List("id,snippet").Q("歌ってみた").MaxResults(50).ChannelId(channelID).Type("video") resp, err := call.Do() if err != nil { panic(err) } for _, item := range resp.Items { //非公開動画は除外・時間で動画のみ抽出 if (item.Snippet.Title != "Private video") && (ccheckVideoTime(ffilteringSingVideo(item.Id.VideoId))) { fmt.Println(item.Snippet.Title) fmt.Println("https://www.youtube.com/watch?v=" + item.Id.VideoId) fmt.Println("再生時間: " + ffilteringSingVideo(item.Id.VideoId)) fmt.Println() } } return "0" } //各動画の中身を漁る func ffilteringSingVideo(videoID string) string { developerKey := os.Getenv("youtube_key") client := &http.Client{ Transport: &transport.APIKey{Key: developerKey}, } service, err := youtube.New(client) if err != nil { log.Fatalf("Errr creating new Youtube client: %v", err) } call := service.Videos.List("contentDetails").Id(videoID) resp, err := call.Do() if err != nil { panic(err) } return resp.Items[0].ContentDetails.Duration } //歌ってみた「動画」かどうかの判別 func ccheckVideoTime(videoTime string) bool { //PT?M?S という形なので、まずPTを消す trimTime := strings.TrimLeft(videoTime, "PT") //1時間以上のものを除外 if strings.Contains(trimTime, "H") { return false } //10分以上のものを除外 if strings.Contains(trimTime, "M") { indexM := strings.Index(trimTime, "M") minute, _ := strconv.Atoi(trimTime[:indexM]) if minute >= 10 { return false } } return true } <file_sep>package main import ( "flag" "fmt" "google.golang.org/api/googleapi/transport" "google.golang.org/api/youtube/v3" "log" "net/http" "os" ) var ( query = flag.String("query", "にじさんじ", "Search term") maxResults = flag.Int64("max-results", 5, "Max YouTube results") ) func main() { developerKey := os.Getenv("youtube_key") client := &http.Client{ Transport: &transport.APIKey{Key: developerKey}, } service, err := youtube.New(client) if err != nil { log.Fatalf("Errr creating new Youtube client: %v", err) } call := service.Search.List("id,snippet").Q(*query).MaxResults(*maxResults) resp, err := call.Do() if err != nil { panic(err) } videos := make(map[string]string) channels := make(map[string]string) playlists := make(map[string]string) for _, item := range resp.Items { switch item.Id.Kind { case "youtube#video": videos[item.Id.VideoId] = item.Snippet.Title case "youtube#channel": channels[item.Id.ChannelId] = item.Snippet.Title case "youtube#playlist": playlists[item.Id.PlaylistId] = item.Snippet.Title } } printIDs("Videos", videos) printIDs("Channels", channels) printIDs("Playlists", playlists) } func printIDs(sectionName string, matches map[string]string) { fmt.Printf("%v:\n", sectionName) for id, title := range matches { fmt.Printf("[%v] %v\n", id, title) } fmt.Printf("\n\n") } <file_sep>package callAPI import ( "net/url" "strings" ) func Url2chID(inputURL string) string { u, err := url.Parse(inputURL) if (err != nil) || u.Host != "www.youtube.com" { return "1" } slPa := strings.Split(u.Path, "/") if slPa[1] != "channel" { return "2" } var chID string chID = slPa[2] return chID } <file_sep>package back import ( "api_test/db" ) //DB上の全てのチャンネル取得 //func ChannelList() (channels []db.Channel) { // database := db.ConnectDB() // defer database.Close() // database.LogMode(true) // // database.Order("name").Preload("Group").Find(&channels) // // return //} func ChannelSearchList(chName string, page string) (channels []db.Channel) { database := db.ConnectDB() defer database.Close() database.LogMode(true) offset := Page2Offset(page) database. Where("name LIKE ?", "%"+chName+"%"). Order("name"). Offset(offset).Limit(10). Preload("Group").Find(&channels) return } func ChannelRandomList() (channels []db.Channel) { database := db.ConnectDB() defer database.Close() database.LogMode(true) database.Order("RANDOM()").Limit(10).Preload("Group").Find(&channels) return } <file_sep>package main import ( "fmt" "google.golang.org/api/googleapi/transport" "google.golang.org/api/youtube/v3" "log" "net/http" "os" ) //var ( // query = flag.String("query", "夏色まつり", "Search term") // maxResults = flag.Int64("max-results", 1, "Max YouTube results") //) func main() { developerKey := os.Getenv("youtube_key") client := &http.Client{ Transport: &transport.APIKey{Key: developerKey}, } service, err := youtube.New(client) if err != nil { log.Fatalf("Errr creating new Youtube client: %v", err) } call := service.PlaylistItems.List("id,snippet,contentDetails,status").PlaylistId("PL6sZ3uYmeG1vGZVLNlWdJkm3W0R86y_Qa").MaxResults(50) resp, err := call.Do() if err != nil { panic(err) } //fmt.Print(resp.Items[0].Snippet.Title) //fmt.Println(reflect.TypeOf(resp.Items)) for _, item := range resp.Items { fmt.Println(item.Snippet.Title) fmt.Println("https://www.youtube.com/watch?v=" + item.ContentDetails.VideoId) fmt.Println() } } <file_sep>package main /* 投げられたURLの動画を保存する。 また、そのチャンネルがDBに存在しない場合、追加 また、すでにある動画は追加されない */ import ( "api_test/db" "flag" "fmt" "google.golang.org/api/googleapi/transport" "google.golang.org/api/youtube/v3" "log" "net/http" "net/url" "os" "strconv" "strings" ) func main() { flag.Parse() args := flag.Args() u, err := url.Parse(args[0]) if err != nil { panic("ERRORRRORROR") } var videoID string for k, v := range u.Query() { if k == "v" { videoID = v[0] } } service := getClient2() viContent := getVideoContent2(service, videoID) if !db.CheckExistGroup(viContent.GroupID) { panic("与えられたグループが存在しません") } switch db.CheckExistVideo(viContent.ChannelID, viContent.ID) { case 1: fmt.Println("チャンネルを確認・動画非重複") db.InsertVideo(viContent.ID, viContent.ChannelID, viContent.GroupID, viContent.Title) case 2: fmt.Println("チャンネルを非確認") chCon2 := getChannelContent2(service, viContent.ChannelID, viContent.GroupID) db.AddChannel(chCon2.ID, chCon2.GroupID, chCon2.Name, chCon2.Thumbnail) db.InsertVideo(viContent.ID, chCon2.ID, chCon2.GroupID, viContent.Title) default: fmt.Println("False!") } } //APIクライアント生成 func getClient2() *youtube.Service { developerKey := os.Getenv("youtube_key") client := &http.Client{ Transport: &transport.APIKey{Key: developerKey}, } service, err := youtube.New(client) if err != nil { log.Fatalf("Errr creating new Youtube client: %v", err) } return service } //各動画の中身を漁る func getVideoContent2(service *youtube.Service, videoID string) db.Video { call := service.Videos.List("snippet,contentDetails").Id(videoID) resp, err := call.Do() if err != nil { panic(err) } var viContent db.Video //非公開動画は除外・時間で動画のみ抽出 if (resp.Items[0].Snippet.Title != "Private video") && (checkVideoTime2(resp.Items[0].ContentDetails.Duration)) { groupID := db.SearchGroup(resp.Items[0].Snippet.ChannelId) viContent = db.Video{ ID: videoID, ChannelID: resp.Items[0].Snippet.ChannelId, GroupID: groupID, Title: resp.Items[0].Snippet.Title, } } return viContent } //チャンネル情報を取得 func getChannelContent2(service *youtube.Service, channelID string, gID uint) db.Channel { call := service.Channels.List("snippet,contentDetails").Id(channelID) resp, err := call.Do() if err != nil { panic(err) } chContent2 := db.Channel{ ID: channelID, GroupID: gID, Name: resp.Items[0].Snippet.Title, Thumbnail: resp.Items[0].Snippet.Thumbnails.Default.Url, } return chContent2 } //歌ってみた「動画」かどうかの判別 func checkVideoTime2(videoTime string) bool { //PT?M?S という形なので、まずPTを消す trimTime := strings.TrimLeft(videoTime, "PT") //1時間以上のものを除外 if strings.Contains(trimTime, "H") { return false } //10分以上のものを除外 if strings.Contains(trimTime, "M") { indexM := strings.Index(trimTime, "M") minute, _ := strconv.Atoi(trimTime[:indexM]) if minute >= 10 { return false } } return true } <file_sep>package callAPI /* 投げられたURLの動画を保存する。 また、そのチャンネルがDBに存在しない場合、追加 また、すでにある動画は追加されない */ import ( "api_test/db" "fmt" "google.golang.org/api/youtube/v3" ) func GetVideo(inputURL string) (bool, string) { videoID := Url2viID(inputURL) if videoID == "" { return false, "URLが正しくありません" } service := GetClient() viContent, err := getVideoContent(service, videoID) if err != nil { return false, "失敗しました" } if !db.CheckExistGroup(viContent.GroupID) { return false, "与えられたグループが存在しません" } switch db.CheckExistVideo(viContent.ChannelID, viContent.ID) { case 1: fmt.Println("チャンネルを確認・動画非重複") db.InsertVideo(viContent.ID, viContent.ChannelID, viContent.GroupID, viContent.Title) return true, "動画を追加しました" //TODO ここどうする? > アイフル case 2: //fmt.Println("チャンネルを非確認") //chCon2 := GetChannelContent(service, viContent.ChannelID, viContent.GroupID) //db.AddChannel(chCon2.ID, chCon2.GroupID, chCon2.Name, chCon2.Thumbnail) //db.InsertVideo(viContent.ID, chCon2.ID, chCon2.GroupID, viContent.Title) //return true, "チャンネル・動画を追加しました" return false, "チャンネルが存在しません" default: return false, "既に追加されています" } } //各動画の中身を漁る func getVideoContent(service *youtube.Service, videoID string) (db.Video, error) { call := service.Videos.List("snippet,contentDetails").Id(videoID) resp, err := call.Do() if err != nil { return db.Video{}, err } var viContent db.Video //非公開動画は除外・時間で動画のみ抽出 if (resp.Items[0].Snippet.Title != "Private video") && (CheckVideoTime(resp.Items[0].ContentDetails.Duration)) { groupID := db.SearchGroup(resp.Items[0].Snippet.ChannelId) viContent = db.Video{ ID: videoID, ChannelID: resp.Items[0].Snippet.ChannelId, GroupID: groupID, Title: resp.Items[0].Snippet.Title, } } return viContent, nil } <file_sep>package callAPI import ( "google.golang.org/api/googleapi/transport" "google.golang.org/api/youtube/v3" "log" "net/http" "os" ) //APIクライアント生成 func GetClient() (service *youtube.Service) { developerKey := os.Getenv("youtube_key") client := &http.Client{ Transport: &transport.APIKey{Key: developerKey}, } service, err := youtube.New(client) if err != nil { log.Fatalf("Errr creating new Youtube client: %v", err) } return } <file_sep>package back import ( "api_test/db" ) //DB上の全動画の中から、ランダムで一定数を取得 //func RandomVideos() (videos []db.Video) { // database := db.ConnectDB() // defer database.Close() // database.LogMode(true) // // database.Order("RANDOM()").Limit(5).Preload("Channel").Find(&videos) // // return //} func RandomVideos(viName string) (videos []db.Video) { database := db.ConnectDB() defer database.Close() database.LogMode(true) database. Where("title LIKE ?", "%"+viName+"%"). Order("RANDOM()"). Limit(10). Preload("Channel"). Find(&videos) return } <file_sep>package main import ( "api_test/back" "api_test/db" "fmt" ) func main() { //fmt.Println(back.Page2Offset("2")) database := db.ConnectDB() var channels []db.Channel offset := back.Page2Offset("2") database.Select("name").Offset(offset).Limit(10).Find(&channels) for _, ch := range channels { fmt.Println(ch.Name) } } <file_sep>package back import ( "api_test/db" ) //グループ情報取得 func GroupInfo(gID uint) (group db.Group) { database := db.ConnectDB() defer database.Close() database.LogMode(true) database.Where("id = ?", gID).First(&group) return } func GroupHasCh(gID uint, chName string, page string) (channels []db.Channel) { database := db.ConnectDB() defer database.Close() database.LogMode(true) offset := Page2Offset(page) database.Where("group_id = ? AND name LIKE ?", gID, "%"+chName+"%"). Order("name"). Offset(offset).Limit(10). Preload("Group").Find(&channels) return } <file_sep>package main import ( "api_test/back" "api_test/callAPI" "api_test/db" "github.com/gin-gonic/gin" _ "github.com/mattn/go-sqlite3" "html/template" "strconv" ) func main() { router := gin.Default() router.LoadHTMLGlob("templates/*.html") router.Static("/assets", "./assets") //TOP router.GET("/", func(ctx *gin.Context) { ctx.Request.URL.Path = "/index" router.HandleContext(ctx) }) //INDEX //全動画からランダムで表示 router.GET("/index", func(ctx *gin.Context) { html := template.Must(template.ParseFiles("templates/base.html", "templates/index.html")) router.SetHTMLTemplate(html) ctx.HTML(200, "base.html", gin.H{"videos": back.RandomVideos(ctx.Query("viName"))}) }) //新しく情報を追加 router.GET("/add", func(ctx *gin.Context) { html := template.Must(template.ParseFiles("templates/base.html", "templates/add.html")) router.SetHTMLTemplate(html) ctx.HTML(200, "base.html", gin.H{"groups": back.GroupList("", "")}) }) //ビデオ追加 router.POST("/add-vi", func(ctx *gin.Context) { html := template.Must(template.ParseFiles("templates/base.html", "templates/add.html")) router.SetHTMLTemplate(html) status, message := callAPI.GetVideo(ctx.PostForm("video-url")) if status { viID := callAPI.Url2viID(ctx.PostForm("video-url")) video := back.VideoInfo(viID) ctx.HTML(200, "base.html", gin.H{"message": message, "video": video}) } else { //TODO リダイレクトとしては不適切? /addにmessageだけ送りたいがどうしようか? html := template.Must(template.ParseFiles("templates/base.html", "templates/add.html")) router.SetHTMLTemplate(html) ctx.HTML(200, "base.html", gin.H{"groups": back.GroupList("", ""), "message": message}) } }) //チャンネル追加 router.POST("/add-ch", func(ctx *gin.Context) { html := template.Must(template.ParseFiles("templates/base.html", "templates/added.html")) router.SetHTMLTemplate(html) inputURL := ctx.PostForm("channel-url") gID, err := strconv.Atoi(ctx.PostForm("select-group")) if err != nil { ctx.HTML(200, "base.html", gin.H{"message": "グループ選択にエラーが発生しました"}) } status, message := callAPI.GetChannel(inputURL, uint(gID)) if status { chID := callAPI.Url2chID(inputURL) channel := back.ChannelInfo(chID) callAPI.ReadList(chID) videos := back.ChannelContents(chID, "", "1") ctx.HTML(200, "base.html", gin.H{"message": message, "channel": channel, "videos": videos}) } else { //TODO リダイレクトとしては不適切? /addにmessageだけ送りたいがどうしようか? html := template.Must(template.ParseFiles("templates/base.html", "templates/add.html")) router.SetHTMLTemplate(html) ctx.HTML(200, "base.html", gin.H{"groups": back.GroupList("", ""), "message": message}) } }) //ビデオ詳細 router.GET("/video/:vID", func(ctx *gin.Context) { html := template.Must(template.ParseFiles("templates/base.html", "templates/video.html")) router.SetHTMLTemplate(html) video := back.VideoInfo(ctx.Param("vID")) ctx.HTML(200, "base.html", gin.H{"video": video}) }) //チャンネル情報と、そのチャンネルの動画を全て表示 //TODO ページ上限取得 router.GET("/channel/:chID", func(ctx *gin.Context) { html := template.Must(template.ParseFiles("templates/base.html", "templates/channel.html")) router.SetHTMLTemplate(html) videos := back.ChannelContents(ctx.Param("chID"), ctx.Query("viName"), ctx.Query("page")) channel := back.ChannelInfo(ctx.Param("chID")) ctx.HTML(200, "base.html", gin.H{"videos": videos, "channel": channel}) }) //グループ情報と、そのグループに所属するチャンネル一覧。また、そのチャンネルらの持つ動画一覧 //TODO ページ上限取得 router.GET("/group/:gID", func(ctx *gin.Context) { html := template.Must(template.ParseFiles("templates/base.html", "templates/group.html")) router.SetHTMLTemplate(html) n := ctx.Param("gID") gID, err := strconv.Atoi(n) if err != nil { gID = 1 } display := ctx.Query("display") var group db.Group if display == "channel" { group = back.GroupInfo(uint(gID)) channels := back.GroupHasCh(uint(gID), ctx.Query("chName"), ctx.Query("page")) ctx.HTML(200, "base.html", gin.H{"group": group, "channels": channels}) } else { group = back.GroupInfo(uint(gID)) videos := back.GroupContents(uint(gID), ctx.Query("viName"), ctx.Query("page")) ctx.HTML(200, "base.html", gin.H{"videos": videos, "group": group}) } }) //チャンネルのリスト //TODO ページ上限取得 router.GET("/channels", func(ctx *gin.Context) { html := template.Must(template.ParseFiles("templates/base.html", "templates/listCh.html")) router.SetHTMLTemplate(html) chName := ctx.Query("chName") if chName == "random" { ctx.HTML(200, "base.html", gin.H{"channels": back.ChannelRandomList()}) } else { ctx.HTML(200, "base.html", gin.H{"channels": back.ChannelSearchList(chName, ctx.Query("page"))}) } }) //グループのリスト //TODO ページ上限取得 router.GET("/groups", func(ctx *gin.Context) { html := template.Must(template.ParseFiles("templates/base.html", "templates/listGr.html")) router.SetHTMLTemplate(html) gName := ctx.Query("gName") if gName == "random" { ctx.HTML(200, "base.html", gin.H{"groups": back.GroupRandomList()}) } else { ctx.HTML(200, "base.html", gin.H{"groups": back.GroupList(gName, ctx.Query("page"))}) } }) router.Run() } <file_sep>package main /* 投げられたURLから取得する 動画からチャンネルを特定し、そのチャンネルがDBにあるか確認する感じを仮予定 */ import ( "flag" "fmt" "google.golang.org/api/googleapi/transport" "google.golang.org/api/youtube/v3" "log" "net/http" "net/url" "os" "strconv" "strings" ) var reM = make(map[string]string) func main() { flag.Parse() args := flag.Args() u, err := url.Parse(args[0]) //u, err := url.Parse("https://www.youtube.com/watch?v=5DfRzFrmHzQ") if err != nil { panic("ERRORRRORROR") } var videoID string for k, v := range u.Query() { if k == "v" { videoID = v[0] } } service := getClient() chID := getVideoContent(service, videoID) getChannelContent(service, chID) fmt.Println(reM) } func getClient() *youtube.Service { developerKey := os.Getenv("youtube_key") client := &http.Client{ Transport: &transport.APIKey{Key: developerKey}, } service, err := youtube.New(client) if err != nil { log.Fatalf("Errr creating new Youtube client: %v", err) } return service } //各動画の中身を漁る func getVideoContent(service *youtube.Service, videoID string) string { call := service.Videos.List("snippet,contentDetails").Id(videoID) resp, err := call.Do() if err != nil { panic(err) } //非公開動画は除外・時間で動画のみ抽出 if (resp.Items[0].Snippet.Title != "Private video") && (checkVideoTime(resp.Items[0].ContentDetails.Duration)) { fmt.Println("Title: " + resp.Items[0].Snippet.Title) fmt.Println("再生時間: " + resp.Items[0].ContentDetails.Duration) fmt.Println("ビデオID: " + videoID) reM["Title"] = resp.Items[0].Snippet.Title reM["videoID"] = videoID reM["channelID"] = resp.Items[0].Snippet.ChannelId } return resp.Items[0].Snippet.ChannelId } func getChannelContent(service *youtube.Service, channelID string) { call := service.Channels.List("snippet,contentDetails").Id(channelID) resp, err := call.Do() if err != nil { panic(err) } fmt.Println("(チャンネル名: " + resp.Items[0].Snippet.Title + ")") fmt.Println("チャンネルID: " + channelID) fmt.Println("サムネ: " + resp.Items[0].Snippet.Thumbnails.Default.Url) fmt.Println() //fmt.Println(resp.Items[0].Snippet.Description) } //歌ってみた「動画」かどうかの判別 func checkVideoTime(videoTime string) bool { //PT?M?S という形なので、まずPTを消す trimTime := strings.TrimLeft(videoTime, "PT") //1時間以上のものを除外 if strings.Contains(trimTime, "H") { return false } //10分以上のものを除外 if strings.Contains(trimTime, "M") { indexM := strings.Index(trimTime, "M") minute, _ := strconv.Atoi(trimTime[:indexM]) if minute >= 10 { return false } } return true } <file_sep>package back import ( "api_test/db" ) //チャンネル情報取得 func ChannelInfo(chID string) (channel db.Channel) { database := db.ConnectDB() defer database.Close() database.LogMode(true) database.Where("id = ?", chID).Preload("Group").First(&channel) return } <file_sep>package callAPI /* DB上のチャンネルのチャンネル情報と、プレイリストを更新する 日〜土の曜日によって1~7の数値が与えられ、その値でDB全体を割ったときの割合部分にあたるチャンネルを更新する。 例:月曜日(=2)、総チャンネル数100 100/7 = 14, 14*2 = 28 よって、先頭から15~28のチャンネルらを更新する */ import ( "api_test/db" "github.com/jinzhu/gorm" "google.golang.org/api/youtube/v3" "time" ) func UpdateChannel() { updateChs, database := weekChannels() service := GetClient() for i, _ := range updateChs { chUpdate(service, updateChs[i], database) ReadList(updateChs[i].ID) } } func weekChannels() ([]db.Channel, *gorm.DB) { wdays := [...]int{1, 2, 3, 4, 5, 6, 7} t := time.Now() weekNum := wdays[t.Weekday()] database := db.ConnectDB() defer database.Close() var channels []db.Channel var count int database.Select("id").Model(&channels).Count(&count) sli := count / 7 offset := sli * (weekNum - 1) if weekNum != 7 { database.Offset(offset).Limit(sli).Find(&channels) } else { database.Offset(offset).Limit(count - offset).Find(&channels) } return channels, database } func chUpdate(service *youtube.Service, channel db.Channel, database *gorm.DB) { call := service.Channels.List("snippet,contentDetails").Id(channel.ID) resp, err := call.Do() if err != nil { panic(err) } channel.Name = resp.Items[0].Snippet.Title channel.Thumbnail = resp.Items[0].Snippet.Thumbnails.Default.Url database.Save(&channel) } <file_sep>package main import ( "api_test/db" "fmt" "github.com/jinzhu/gorm" _ "github.com/mattn/go-sqlite3" ) func main() { database, err := gorm.Open("sqlite3", "./db/test.sqlite3") if err != nil { panic("failed to connect database") } defer database.Close() database.LogMode(true) var videos []db.Video //sqliteだと"RANDOM()"、mysqlだと"RAND()" 切り替える database.Order("RANDOM()").Limit(5).Preload("Channel").Find(&videos) //database.Order("RANDOM()").Limit(5).Preload("Channel").Find(&videos) //database.Raw("SELECT * FROM videos AS vi, " + // "(SELECT id FROM videos ORDER BY RANDOM() LIMIT 0, 5) AS random" + // " WHERE vi.id = random.id LIMIT 0, 5").Scan(&videos) //fmt.Println(videos) for _, v := range videos { fmt.Println(v) break } } //func reIndex() []db.Video { // database, err := gorm.Open("sqlite3", "./db/test.sqlite3") // if err != nil { // panic("failed to connect database") // } // defer database.Close() // database.LogMode(true) // // var videos []db.Video // database.Order("RANDOM()").Limit(5).Find(&videos) // // return videos //} func reContents(chID string) []db.Video { database, err := gorm.Open("sqlite3", "./db/test.sqlite3") if err != nil { panic("failed to connect database") } defer database.Close() database.LogMode(true) var videos []db.Video database.Where("channel_id = ?", chID).Preload("Channel").Find(&videos) } <file_sep>package main import ( "flag" "fmt" "google.golang.org/api/googleapi/transport" "google.golang.org/api/youtube/v3" "log" "net/http" "os" ) var ( query = flag.String("query", "夏色まつり", "Search term") maxResults = flag.Int64("max-results", 1, "Max YouTube results") ) func main() { developerKey := os.Getenv("youtube_key") client := &http.Client{ Transport: &transport.APIKey{Key: developerKey}, } service, err := youtube.New(client) if err != nil { log.Fatalf("Errr creating new Youtube client: %v", err) } call := service.Search.List("snippet").Q(*query).MaxResults(*maxResults) resp, err := call.Do() if err != nil { panic(err) } else { //fmt.Print(resp) //fmt.Print(resp.Items) //fmt.Print(resp.Items[0].Snippet) fmt.Print(resp.Items[0].Id.ChannelId) //fmt.Print(resp.Items[0].Snippet.Thumbnails.Default.Url) //fmt.Print(resp.Items[0].) //re := resp.Items[0] //fmt.Print(*re) //fmt.Print(reflect.TypeOf(resp.Items[0].Snippet)) } } <file_sep>package db import ( "fmt" "github.com/jinzhu/gorm" _ "github.com/mattn/go-sqlite3" ) //チャンネル情報 type Channel struct { ID string `gorm:"primary_key"` GroupID uint Group Group Name string `gorm:"unique;not null"` Thumbnail string `gorm:"unique;not null"` Descripition string `gorm:"type:text"` Video []Video `gorm:"foreignkey:ChannelID"` } //該当Vtuberのグループ情報 type Group struct { ID uint `gorm:"primary_key;AUTO_INCREMENT"` Name string `gorm:"unique;not null"` Channel []Channel `gorm:"foreignkey:GroupID"` Video []Video `gorm:"foreignkey:GroupID"` } //動画情報 type Video struct { ID string `gorm:"primary_key"` ChannelID string Channel Channel GroupID uint Group Group Title string `gorm:"unique;not null"` Descripition string `gorm:"type:text"` } func main() { db := ConnectDB() defer db.Close() db.LogMode(true) db.AutoMigrate(&Channel{}, &Group{}, &Video{}) //fmt.Println(checkExistVideo("UCQ0UDLQCjY0rmuxCDE38FGgあ", "hoge")) //fmt.Println(checkExistVideo("UCQ0UDLQCjY0rmuxCDE38FGg", "jcCGvpvxqVQ")) //SearchGroup("UCQ0UDLQCjY0rmuxCDE38FGg") //ChangeChGroup("UCXTpFs_3PqI41qX2d9tL2Rw", 2) //var videos Video //db.First(&videos).Related(&videos.Channel, "Channel") //fmt.Println(videos) } func ConnectDB() *gorm.DB { db, err := gorm.Open("sqlite3", "./db/test.sqlite3") if err != nil { panic("failed to connect database") } return db } //新しくチャンネルをDBに追加 func AddChannel(chID string, gID uint, name string, thumbnail string) { db := ConnectDB() defer db.Close() //db.LogMode(true) var channel Channel db.Where("id = ?", chID).Find(&channel) //重複チェック if channel.ID != "" { panic("既に存在します(channel)") } else { channel = Channel{ ID: chID, GroupID: gID, Name: name, Thumbnail: thumbnail, } db.NewRecord(&channel) db.Create(&channel) fmt.Println("チャンネルを追加しました") } } //渡された動画が既にDBにないか確認 func CheckExistVideo(chID string, viID string) int { db := ConnectDB() defer db.Close() //db.LogMode(true) var videos Video var channels Channel db.Where("id = ?", chID).Find(&channels) //チャンネルすら無いのか・チャンネルはあるが動画はないのか・どっちも既にあるのか if channels.ID == "" { fmt.Println("存在しません(channel)") return 2 } db.Where("id = ?", viID).Find(&videos) if videos.ID != "" { fmt.Println("すでに存在します(video)") return 0 } fmt.Println("動画を追加できます") return 1 } //渡された動画が既にDBにないか確認 func CheckExistChannel(chID string) bool { db := ConnectDB() defer db.Close() //db.LogMode(true) var channel Channel db.Where("id = ?", chID).Find(&channel) //チャンネルすら無いのか・チャンネルはあるが動画はないのか・どっちも既にあるのか if channel.ID == "" { //存在しなければtrue return true } else { return false } } //動画をDBに保存 func InsertVideo(viID string, chID string, gID uint, title string) { db := ConnectDB() defer db.Close() db.LogMode(true) var videos Video videos = Video{ ID: viID, ChannelID: chID, GroupID: gID, Title: title, } db.NewRecord(&videos) db.Create(&videos) fmt.Println("動画を追加しました") } //該当チャンネルの所属グループを確認 func SearchGroup(chID string) uint { db := ConnectDB() defer db.Close() //db.LogMode(true) var channel Channel db.Where("id = ?", chID).Find(&channel) //fmt.Println(channel.GroupID) //所属グループが割り振られてい無い場合、1(その他)を入れる if channel.GroupID == 0 { return 1 } else { return channel.GroupID } } //該当チャンネル、および投稿動画のグループを変更 func ChangeChGroup(chID string, newGroupID uint) { db := ConnectDB() defer db.Close() //db.LogMode(true) var group Group db.Where("id = ?", newGroupID).Find(&group) if group.ID != 0 { var channel Channel var videos []Video //チャンネルのGroupIDを変更 db.Where("id = ?", chID).Take(&channel) channel.GroupID = newGroupID db.Save(&channel) //該当チャンネルの持つ投稿動画を全て変更 db.Find(&videos).Where("channel_id = ?", chID) for i, _ := range videos { videos[i].GroupID = newGroupID db.Save(&videos[i]) } fmt.Println("グループを変更しました") } else { fmt.Println("存在しないグループです") } } //グループの存在を確認 func CheckExistGroup(gID uint) bool { db := ConnectDB() defer db.Close() //db.LogMode(true) var group Group db.Where("id = ?", gID).Find(&group) if group.ID == 0 { return false } else { return true } } <file_sep>package main /* チャンネルIDからチャンネルデータを取り、DBに保存するプログラムの試行 */ import ( "api_test/db" "flag" "google.golang.org/api/googleapi/transport" "google.golang.org/api/youtube/v3" "log" "net/http" "os" "strconv" ) func main() { flag.Parse() args := flag.Args() chID := args[0] var gID uint inputGID, err := strconv.ParseUint(args[1], 10, 32) if err != nil { panic("第2引数はuintで入力してください") } gID = uint(inputGID) if !db.CheckExistGroup(gID) { panic("与えられたグループが存在しません") } service := getClient1() chContent := getChannelContent1(service, chID, gID) db.AddChannel(chContent.ID, chContent.GroupID, chContent.Name, chContent.Thumbnail) } //APIクライアント生成 func getClient1() (service *youtube.Service) { developerKey := os.Getenv("youtube_key") client := &http.Client{ Transport: &transport.APIKey{Key: developerKey}, } service, err := youtube.New(client) if err != nil { log.Fatalf("Errr creating new Youtube client: %v", err) } return } //チャンネル情報を取得 func getChannelContent1(service *youtube.Service, channelID string, gID uint) (chContent db.Channel) { call := service.Channels.List("snippet,contentDetails").Id(channelID) resp, err := call.Do() if err != nil { panic(err) } chContent = db.Channel{ ID: channelID, GroupID: gID, Name: resp.Items[0].Snippet.Title, Thumbnail: resp.Items[0].Snippet.Thumbnails.Default.Url, } return } <file_sep>package callAPI /* 与えられたチャンネルにある再生リストから歌ってみたのリストを抽出し、保存 また、そのチャンネルがDBに存在しない場合、追加 */ import ( "api_test/db" "google.golang.org/api/youtube/v3" "strings" ) func ReadList(chID string) (bool, string) { service := GetClient() plID := getSingPlaylist(service, chID) if plID == "" { return false, "歌ってみたプレイリストが見つかりませんでした" } ret := getPlaylistContnt(service, plID, chID) groupID := db.SearchGroup(chID) if !db.CheckExistGroup(groupID) { return false, "与えられたグループが存在しません" } for _, video := range ret { switch db.CheckExistVideo(video["channelID"], video["videoID"]) { case 1: db.InsertVideo(video["videoID"], video["channelID"], groupID, video["title"]) case 2: chCon3 := GetChannelContent(service, video["channelID"], groupID) db.AddChannel(chCon3.ID, chCon3.GroupID, chCon3.Name, chCon3.Thumbnail) db.InsertVideo(video["videoID"], video["channelID"], groupID, video["title"]) default: } } return true, "収集が終わりました" } //歌ってみた動画の再生リストを抽出 func getSingPlaylist(service *youtube.Service, channelID string) (playlistID string) { var ( nextPageToken string plIndex int64 asari func(ind int64, token string) itemsConts int64 ) asari = func(ind int64, token string) { call := service.Playlists.List("snippet,contentDetails").ChannelId(channelID).MaxResults(50).PageToken(token) resp, err := call.Do() if err != nil { panic(err) } if ind == 0 { plIndex = resp.PageInfo.TotalResults itemsConts = 0 } nextPageToken = resp.NextPageToken //再生リストの名前で「歌ってみた」動画を判別 for _, playlist := range resp.Items { if (strings.Contains(playlist.Snippet.Title, "歌")) || (strings.Contains(playlist.Snippet.Title, "うた")) { if (!strings.Contains(playlist.Snippet.Title, "配信")) && (!strings.Contains(playlist.Snippet.Title, "枠")) && (!strings.Contains(playlist.Snippet.Title, "わく")) && (!strings.Contains(playlist.Snippet.Title, "雑談")) && (!strings.Contains(playlist.Snippet.Title, "放送")) { if playlist.ContentDetails.ItemCount > itemsConts { playlistID = playlist.Id } } } } if plIndex > 50 { plIndex -= 50 asari(plIndex, nextPageToken) } } asari(0, nextPageToken) return } //プレイリストの中身を漁る func getPlaylistContnt(service *youtube.Service, playlistID string, channelID string) (reS []map[string]string) { var ( content map[string]string nextPageToken string plIndex int64 asari func(ind int64, token string) ) asari = func(ind int64, token string) { call := service.PlaylistItems.List("snippet,contentDetails").PlaylistId(playlistID).MaxResults(50).PageToken(token) resp, err := call.Do() if err != nil { panic(err) } if ind == 0 { plIndex = resp.PageInfo.TotalResults } nextPageToken = resp.NextPageToken for _, item := range resp.Items { //非公開動画は除外・時間で動画のみ抽出 if item.Snippet.Title != "Private video" { videoDuration, videoChId := filteringSingVideo(service, item.ContentDetails.VideoId) if CheckVideoTime(videoDuration) { content = map[string]string{ "title": item.Snippet.Title, "videoID": item.ContentDetails.VideoId, "channelID": videoChId, } reS = append(reS, content) } } } if plIndex > 50 { plIndex -= 50 asari(plIndex, nextPageToken) } } asari(0, nextPageToken) return } //各動画の中身を漁る func filteringSingVideo(service *youtube.Service, videoID string) (string, string) { call := service.Videos.List("contentDetails").Id(videoID) resp, err := call.Do() if err != nil { panic(err) } return resp.Items[0].ContentDetails.Duration, resp.Items[0].Snippet.ChannelId } <file_sep>package back import ( "api_test/db" ) //該当チャンネルの持つ動画を全て取得 func ChannelContents(chID string, viName string, page string) (videos []db.Video) { database := db.ConnectDB() defer database.Close() database.LogMode(true) offset := Page2Offset(page) database.Order("title"). Where("channel_id = ? AND title LIKE ?", chID, "%"+viName+"%"). Offset(offset).Limit(10). Preload("Channel").Find(&videos) return }
9591f522ee1e7e96b228a8b4227023ef2babf0b6
[ "Go", "HTML" ]
34
Go
hyo07/go-youtube-api
d0bd0514db62df036bbb34a36514cfe498005c72
a8cfdd9be13c5d0ef2baedc0477ae9671c9aa763
refs/heads/master
<file_sep>package clustering; import static compression_algorithms.sequitur.Sequitur.compress; import static compression_algorithms.sequitur.Sequitur.init; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import net.jpountz.lz4.LZ4; import compression_algorithms.sequitur.Sequitur; public class ClusterAll { static BufferedReader f = null; static PrintWriter o = null; static ArrayList<String> sequences; static ArrayList<String> origSequences; static ArrayList<LZ4> sequencesLz4; static ArrayList<LZ4> origSequencesLz4; static ArrayList<String> sequencesSequitur; static ArrayList<String> origSequencesSequitur; static int size; static final int MATCHFACTOR = 2; static final int MISMATCHFACTOR = -1; static final int GAPPENALTY = -1; static final int GAPEXTENSION = -1; static final int[][] DNASUBSITUTIONMATRIX = {{0,2,1,2},{2,0,2,1},{1,2,0,2},{2,1,2,0}}; static String fileName; static HashMap<String, Double> LSA; static int max, maxI,maxJ, h; static int[][] score = new int[61][61]; static int[][] pointers = new int[61][61]; static StringBuilder a = new StringBuilder(); static StringBuilder b = new StringBuilder(); public static void main(String[] args) { LSA = new HashMap<String, Double>(); String[] asdf = new String[2]; asdf[1] = "LSHDIV_DataFiles"; fileName = args[0]; try { System.out.println("Loading Sequences"); BufferedReader a = new BufferedReader(new FileReader("PreComputed/" + fileName)); String s; double d; while((s = a.readLine()) != null) { d = Double.parseDouble(a.readLine()); LSA.put(s, d); } a.close(); } catch (IOException e) { e.printStackTrace(); } File s = new File(fileName); if(!s.exists()) s.mkdir(); asdf[0] = fileName; ClusterCDMLz4.main(asdf); ClusterCDMSequitur.main(asdf); ClusterLz4.main(asdf); try { System.out.println("Reprinting LSA"); PrintWriter o = new PrintWriter(new File("PreComputed/" + fileName)); for(String b : LSA.keySet()) { o.println(b); o.println(LSA.get(b)); } o.close(); } catch (IOException e) { e.printStackTrace(); } } /** * Populates the sequences ArrayLis t with the first n sequences from the dataset * * @param n - Number of sequences */ public static void populateSequences(int n, boolean wsim) { sequences = new ArrayList<String>(); String sequence; String curLine = " "; try { f.readLine(); // Skips past first header if(n != -1) { for(int i = 0; i < n ; i++) { sequence = ""; while((curLine = f.readLine()).charAt(0) != '>') { curLine = curLine.replaceAll("n", ""); // Filter out the n's in the DNA sequence sequence += curLine; } sequences.add(sequence); } } else { while(true) { sequence = ""; curLine = f.readLine(); if(curLine == null) break; while((curLine).charAt(0) != '>') { curLine = curLine.replaceAll("n", ""); // Filter out the n's in the DNA sequence sequence += curLine; curLine = f.readLine(); if(curLine == null) break; } sequences.add(sequence); } } } catch (IOException e) { e.printStackTrace(); } size = sequences.size(); origSequences = new ArrayList<String>(sequences); init(); for(int i = 0; i < sequences.size(); i++) { compress(sequences.get(i)); } sequencesSequitur = new ArrayList<String>(); Sequitur.firstRule.getRules(sequencesSequitur, false); origSequencesSequitur = new ArrayList<String>(sequencesSequitur); sequencesLz4 = new ArrayList<LZ4>(); for(int i = 0; i < sequences.size(); i++) { try { sequencesLz4.add(LZ4.compress(sequences.get(i))); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } origSequencesLz4 = new ArrayList<LZ4>(sequencesLz4); } /** * Generates the statistics from the clustering in clusters * @param clusters * @return [Singletons,Doubletons, <NAME>, Chao1, Shannon, Sace] */ public static double[] generateStatistics(ArrayList<ArrayList<String>> clusters, boolean wsim) { double[] stat = new double[6]; int[] freq = new int[size+1]; double total = 0; for(ArrayList<String> c : clusters) { if(c.size() == 1) stat[0]++; if(c.size() == 2) stat[1]++; freq[c.size()]++; total += (c.size()*(c.size()-1))/2; } if(wsim) { stat[2] = 0; double sim,den; System.out.print(" "); for(ArrayList<String> c : clusters) { sim = 0; den = 0; for(int i = 0; i < c.size(); i++) { for(int j = i+1; j < c.size(); j++) { if(LSA.containsKey(c.get(i) + "_" + c.get(j))) sim += LSA.get(c.get(i) + "_" + c.get(j)); else if(LSA.containsKey(c.get(j) + "_" + c.get(i))) sim += LSA.get(c.get(j) + "_" + c.get(i)); else { LSA.put(c.get(i) + "_" + c.get(j), localSeqAlignmentSimilarity(c.get(i),c.get(j))); sim += LSA.get(c.get(i) + "_" + c.get(j)); } den++; System.out.printf("\r %.2f", den/total); } } if(c.size() != 1) sim = sim/den; else sim = 1.0; stat[2] += (c.size()/((double) size)) * sim; } stat[2] = stat[2]*100; System.out.println(); } int obs = clusters.size(); stat[3] = obs + ((stat[0]*(stat[0]-1.0))/(2.0*(stat[1]+1.0))); for(int i = 0 ; i < clusters.size(); i++) { stat[4] += ( clusters.get(i).size()/ (double) size) * Math.log(clusters.get(i).size()/ (double) size); } stat[4] = -stat[4]; int threshold = 10; int sRare = 0, sAbund = 0; for(ArrayList<String> s : clusters) { if(s.size() > threshold) sAbund++; else sRare++; freq[s.size()]++; } double nRare = 0; double a = 0; for(int i = 1 ; i <= threshold; i++) { nRare += i * freq[i]; a += i*(i-1)*freq[i]; } double cACE = 1 - freq[1]/nRare; double lamdaACE2 = Math.max((sRare/cACE) * (a/(nRare*(nRare -1)))-1, 0); double lamdaACE = Math.max(lamdaACE2*(1 + (nRare*(1 - cACE)*a)/(nRare*(nRare-cACE))),0); if(Math.sqrt(lamdaACE2) < .8) { stat[5] = sAbund + (sRare/cACE) + (freq[1]/cACE)*lamdaACE2; } else { stat[5] = sAbund + (sRare/cACE) + (freq[1]/cACE)*lamdaACE; } sequences = new ArrayList<String>(origSequences); sequencesLz4 = new ArrayList<LZ4>(origSequencesLz4); sequencesSequitur = new ArrayList<String>(origSequencesSequitur); System.out.println(); System.out.println(); return stat; } public static double localSeqAlignmentSimilarity(String s1, String s2) { //System.out.println(s1); //System.out.println(s2); //System.out.println(); s1 = " " + s1; s2 = " " + s2; max = 0; h = 0; maxI = 0; maxJ = 0; //int[][] score = new int[s1.length()][s2.length()]; //int[][] pointers = new int[s1.length()][s2.length()]; // Pointer convention. 1 = left, 2 = up, 3 = diagonal left up for(int i = 1; i < s1.length(); i++) { pointers[i][0] = 2; } for(int i = 1; i < s2.length(); i++) { pointers[0][i] = 1; } boolean inGap = false; for(int i = 1; i < s1.length(); i++) { for(int j = 1; j < s2.length(); j++) { h = -99; if(score[i-1][j-1] + match(s1.charAt(i),s2.charAt(j)) > h) { h = score[i-1][j-1] + match(s1.charAt(i),s2.charAt(j)); pointers[i][j] = 3; inGap = false; } if(!inGap) { if(score[i-1][j] + GAPPENALTY > h) { h = score[i-1][j] + GAPPENALTY; pointers[i][j] = 2; inGap = true; } if(score[i][j-1] + GAPPENALTY > h) { h = score[i][j-1] + GAPPENALTY; pointers[i][j] = 1; inGap = true; } } else { if(score[i-1][j] + GAPEXTENSION > h) { h = score[i-1][j] + GAPEXTENSION; pointers[i][j] = 2; inGap = true; } if(score[i][j-1] + GAPEXTENSION > h) { h = score[i][j-1] + GAPEXTENSION; pointers[i][j] = 1; inGap = true; } } if(0 > h) h = 0; score[i][j] = h; if(h >= max) { max = h; maxI = i; maxJ = j; } } } /* for(int i = 0 ; i < s1.length(); i++) { for(int j = 0 ; j < s2.length(); j++) { System.out.print(score[i][j] + " "); } System.out.print(" "); for(int j = 0 ; j < s2.length(); j++) { System.out.print(pointers[i][j] + " "); } System.out.println(); } */ double matches = 0; String o1 = "", o2 = ""; while(!(maxI == 0 && maxJ == 0)) { if(pointers[maxI][maxJ] == 3) { o1 += s1.charAt(maxI); o2 += s2.charAt(maxJ); maxI--; maxJ--; } else if(pointers[maxI][maxJ] == 2) { o1 += s1.charAt(maxI); o2 += "_"; maxI--; } else if(pointers[maxI][maxJ] == 1) { o1 += "_"; o2 += s2.charAt(maxJ); maxJ--; } } a.append(o1); b.append(o2); o1 = a.reverse().toString(); o2 = b.reverse().toString(); a.setLength(0); b.setLength(0); //System.out.println(o1); //System.out.println(o2); for(int i = 0; i < Math.min(o1.length(), o2.length()); i++) { if(o1.charAt(i) == o2.charAt(i)) matches++; } return matches/Math.min(o1.length(), o2.length()); } public static int match(char c1, char c2) { if(c1 == c2) return MATCHFACTOR; else return MISMATCHFACTOR; //return 2 - DNASUBSITUTIONMATRIX["ACGT".indexOf(c1)]["ACGT".indexOf(c1)]; } } <file_sep>package compression_algorithms; public class EditDistance implements Comparable<EditDistance> { int distance; int sequenceNumber; public EditDistance(int distance, int sequenceNumber) { this.distance = distance; this.sequenceNumber = sequenceNumber; } public EditDistance(EditDistance copy) { this.distance = copy.distance; this.sequenceNumber = copy.sequenceNumber; } @Override public int compareTo(EditDistance arg0) { return distance - arg0.distance; } } <file_sep>package clustering; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; public class Precompute { /** * @param args */ public static void main(String[] args) { String file = "60_Equal_112R.fasta"; ArrayList<String> sequences = new ArrayList<String>(); String sequence; String curLine = " "; try { BufferedReader f = new BufferedReader(new FileReader("LSHDIV_DataFiles/" + file)); f.readLine(); // Skips past first header while(true) { sequence = ""; curLine = f.readLine(); if(curLine == null) break; while((curLine).charAt(0) != '>') { curLine = curLine.replaceAll("n", ""); // Filter out the n's in the DNA sequence sequence += curLine; curLine = f.readLine(); if(curLine == null) break; } sequences.add(sequence); } PrintWriter o = new PrintWriter(new File("PreComputed/" + file)); long total = sequences.size(); total = total * (total-1); total = total/ 2; long counter = 0; System.out.print(" "); for(int i = 0; i < sequences.size(); i++) { for(int j = i +1; j < sequences.size(); j++) { o.println(sequences.get(i) + "_" + sequences.get(j)); o.println(ClusterAll.localSeqAlignmentSimilarity(sequences.get(i),sequences.get(j))); counter++; System.out.print("\r" + counter + "/" + total + " " + (double)counter/total + "% "); } } System.out.println(); f.close(); o.close(); } catch (IOException e) { e.printStackTrace(); } } } <file_sep>package compression_algorithms.sequitur; public class guard extends symbol{ rule r; boolean isMiddle; guard(rule theRule){ r = theRule; value = -1; p = this; n = this; isMiddle = false; } public guard(rule theRule, boolean t){ r = theRule; value = -1; p = this; n = this; isMiddle = t; } public void cleanUp(){ join(p,n); } public boolean isGuard(){ return !isMiddle; } public void deleteDigram(){ // Do nothing } public boolean check(){ return false; } }<file_sep>package compression_algorithms.sequitur; import java.util.ArrayList; import java.util.Vector; public class rule{ // Guard symbol to mark beginning // and end of rule. public guard theGuard; // Counter keeps track of how many // times the rule is used in the // grammar. public int count; // The total number of rules. public static int numRules = 0; // The rule's number. // Used for identification of // non-terminals. public int number; // Index used for printing. public int index; // Number of total characters. public int length; rule(){ number = numRules; numRules++; theGuard = new guard(this); count = 0; index = 0; length = 0; } public symbol first(){ return theGuard.n; } public symbol last(){ return theGuard.p; } public void getRules(ArrayList<String> s, boolean compute){ Vector<rule> rules = new Vector<rule>(numRules); rule currentRule; rule referedTo; symbol sym; int index; int processedRules = 0; StringBuffer text = new StringBuffer(); rules.addElement(this); currentRule = (rule)rules.elementAt(processedRules); text.append(' '); for (sym=currentRule.first();(!sym.isGuard());sym=sym.n){ if (sym.isNonTerminal()){ referedTo = ((nonTerminal)sym).r; if ((rules.size() > referedTo.index) && ((rule)rules.elementAt(referedTo.index) == referedTo)){ index = referedTo.index; }else{ index = rules.size(); referedTo.index = index; rules.addElement(referedTo); } text.append(index); }else{ if (sym.value == ' '){ text.append('_'); }else{ if (sym.value == '\n'){ text.append("\\n"); }else if(sym.value == -1) { text.deleteCharAt(0); s.add(new String(text)); text.setLength(0); } else { text.append((char)sym.value); } } } text.append(' '); } text.setLength(0); if(!compute) return; Sequitur.firstRule.getRulesVerbose(); Sequitur.similarity = new double[Sequitur.rules.size()][Sequitur.rules.size()]; for(double[] d : Sequitur.similarity) { for(int i = 0; i < d.length; i++) { d[i] = -1; } } Sequitur.firstRule.calculateLength(); } public String getRule0(){ Vector<rule> rules = new Vector<rule>(numRules); rule currentRule; rule referedTo; symbol sym; int index; int processedRules = 0; StringBuffer text = new StringBuffer(); rules.addElement(this); currentRule = (rule)rules.elementAt(processedRules); text.append(' '); for (sym=currentRule.first();(!sym.isGuard());sym=sym.n){ if (sym.isNonTerminal()){ referedTo = ((nonTerminal)sym).r; if ((rules.size() > referedTo.index) && ((rule)rules.elementAt(referedTo.index) == referedTo)){ index = referedTo.index; }else{ index = rules.size(); referedTo.index = index; rules.addElement(referedTo); } text.append(index); }else{ if (sym.value == ' '){ text.append('_'); }else{ if (sym.value == '\n'){ text.append("\\n"); }else if(sym.value == -1) { text.deleteCharAt(0); return text.toString(); } else { text.append((char)sym.value); } } } text.append(' '); } return text.toString(); } public String getRulesVerbose(){ Vector<rule> rules = new Vector<rule>(numRules); rule currentRule; rule referedTo; symbol sym; int index; int processedRules = 0; StringBuffer text = new StringBuffer(); rules.addElement(this); Sequitur.rules.add(this); while (processedRules < rules.size()){ currentRule = (rule)rules.elementAt(processedRules); if(processedRules > 0) { text.append("R"); text.append(processedRules + " " + currentRule.length); text.append(" -> "); } for (sym=currentRule.first();(!sym.isGuard());sym=sym.n){ if (sym.isNonTerminal()){ referedTo = ((nonTerminal)sym).r; if ((rules.size() > referedTo.index) && ((rule)rules.elementAt(referedTo.index) == referedTo)){ index = referedTo.index; }else{ index = rules.size(); referedTo.index = index; rules.addElement(referedTo); Sequitur.rules.add(referedTo); } if(processedRules > 0) { text.append('R'); text.append(index); } }else if(processedRules > 0) { if (sym.value == ' '){ text.append('_'); }else{ if (sym.value == '\n'){ text.append("\\n"); }else text.append((char)sym.value); } } if(processedRules > 0) { text.append(' '); } } if(processedRules > 0) { text.append('\n'); } processedRules++; } return new String(text); } /** * * @param rule1 * @param rule2 * @return Percentage of rule1 in rule2 */ public double similarity(String rule1, String rule2) { int r1, r2; rule currentRule; symbol sym; int sum = 0, counter = 0; r1 = Integer.parseInt(rule1); r2 = Integer.parseInt(rule2); if(Sequitur.similarity[r1][r2] != -1) { return Sequitur.similarity[r1][r2]; } else if(r1 == r2) { Sequitur.similarity[r1][r2] = 1; return 1; } else { currentRule = Sequitur.rules.get(r2); for (sym=currentRule.first();(!sym.isGuard());sym=sym.n){ if(sym.isNonTerminal()) { sum += similarity(rule1, ((nonTerminal)sym).r.index + "") * ((nonTerminal)sym).r.length; counter += ((nonTerminal)sym).r.length; } else { counter++; } } Sequitur.similarity[r1][r2] = sum/(double)counter; return sum/(double)counter; } } public void calculateLength() { symbol sym; for(sym = first(); (!sym.isGuard());sym=sym.n) { if(sym.isNonTerminal()) { if(((nonTerminal)sym).r.length == 0) ((nonTerminal)sym).r.calculateLength(); length += ((nonTerminal)sym).r.length; } else { length++; } } } @Override public String toString() { return "R" + index; } } <file_sep>package compression_algorithms; public class LocalSequenceAlignment implements Comparable<LocalSequenceAlignment>{ int distance; int sequenceNumber; public LocalSequenceAlignment(Double double1, int sequenceNumber) { this.distance = double1.intValue(); this.sequenceNumber = sequenceNumber; } public LocalSequenceAlignment(LocalSequenceAlignment copy) { this.distance = copy.distance; this.sequenceNumber = copy.sequenceNumber; } @Override public int compareTo(LocalSequenceAlignment arg0) { return (distance > arg0.distance)?-1:1; } } <file_sep>George-Mason-University-Internship ================================== Metagenomics Research src/ contains all of the code. The remaining directories are raw data and results. School Stuff/ contains the formal results. <file_sep>package net.jpountz.lz4; import java.io.UnsupportedEncodingException; public class LZ4 { static LZ4Factory factory = LZ4Factory.fastestInstance(); static LZ4Compressor compressor = factory.fastCompressor(); public int length; public byte[] data; public LZ4(int length, byte[] data) { super(); this.length = length; this.data = data; } @Override public String toString() { String ans = ""; for(int i = 0 ; i < length; i++) { ans += data[i] + " "; } return ans; } public static LZ4 compress(String s) throws UnsupportedEncodingException { int maxCompressedLength; int length; byte[] data; maxCompressedLength = compressor.maxCompressedLength(s.length()); data = new byte[maxCompressedLength]; length = compressor.compress(s.getBytes("UTF-8"), 0, s.length(), data, 0); return new LZ4(length,data); } public static void main(String[] args) throws UnsupportedEncodingException { System.out.println(compress("CAGACTTGACATTGAAGGAACCTGCTAGAAATAGCGGGGTGCTCTTCGGAGCCCATGAAA")); } } <file_sep>package compression_algorithms; public class JaccardCoefficient implements Comparable<JaccardCoefficient>{ double jaccard; int sequenceNumber; public JaccardCoefficient(double jaccard, int sequenceNumber) { this.jaccard = jaccard; this.sequenceNumber = sequenceNumber; } public JaccardCoefficient(JaccardCoefficient copy) { this.jaccard = copy.jaccard; this.sequenceNumber = copy.sequenceNumber; } @Override public int compareTo(JaccardCoefficient arg0) { if(jaccard - arg0.jaccard == 0) return 0; return (jaccard - arg0.jaccard > 0)?-1:1; } }
dde82420a0e60f774da8da9db8c3bd050536f699
[ "Markdown", "Java" ]
9
Java
AshwinSekar/George-Mason-University-Internship
f928bc995a7045609056e25e66c3a65e5414f0a4
3f71fc0773dea8f727b6e9e84aab6ed011418722
refs/heads/master
<file_sep>'use strict'; (function () { const Timer = global.Timer; const PlayGround = global.PlayGround; const SettingsStorage = global.SettingsStorage; const TIME_OVER_MS = 300500; function Game () { this.prevCardElement = null; this.isRotateInProcess = false; this.backRotateTimerId = undefined; this.timeOverTimerId = undefined; this.clickHandlerBind = this.clickHandler.bind(this); this.foundCardsCounter = 0; this.settings = { category: SettingsStorage.getCategory(), cardsNumber: SettingsStorage.getCardsNumber() }; this.messageElement = null; this.timer = null; this.timeOverHandlerBind = this.timeOverHandler.bind(this); this.showGameWinMessageBind = this.showGameWinMessage.bind(this); this.destroyBind = this.destroy.bind(this); } Game.prototype.start = function start () { var playGroundElement = document.body.querySelector(".playground"); var elementTimer = document.body.querySelector(".timer__label"); this.playground = new PlayGround(playGroundElement, this.settings); this.timer = new Timer(elementTimer); this.playground.start(); this.timer.start(); this.scheduleTimeOver(); playGroundElement.addEventListener("click", this.clickHandlerBind); window.addEventListener('hashchange', this.destroyBind); } Game.prototype.restart = function restart () { this.prevCardElement = null; this.foundCardsCounter = 0; this.playground.start(); this.timer.start(); this.scheduleTimeOver(); } Game.prototype.scheduleTimeOver = function scheduleTimeOver () { this.timeOverTimerId = setTimeout(this.timeOverHandlerBind, TIME_OVER_MS); } Game.prototype.clickHandler = function clickHandler () { if (this.isRotateInProcess) { return; } var currentElement = event.target; if (currentElement.classList.contains("card__front")) { var cardElement = currentElement.closest('.card'); if (cardElement.classList.contains('card--hidden')) { return; } cardElement.classList.toggle("card--rotate"); if (this.prevCardElement) { this.handelTwoOpenedCards(cardElement); } else { this.prevCardElement = cardElement; } } } Game.prototype.handelTwoOpenedCards = function handelTwoOpenedCards (cardElement) { var _this = this; if (this.prevCardElement.dataset.type === cardElement.dataset.type) { this.prevCardElement.classList.add('card--hidden'); cardElement.classList.add('card--hidden'); this.prevCardElement = null; this.foundCardsCounter += 2; this.checkIsGameOver(); } else { this.isRotateInProcess = true; this.backRotateTimerId = setTimeout(function () { _this.rotateBack(_this.prevCardElement, cardElement); _this.prevCardElement = null; _this.isRotateInProcess = false; }, 500); } } Game.prototype.rotateBack = function rotateBack (prevCardElement, cardElement) { prevCardElement.classList.toggle('card--rotate'); cardElement.classList.toggle('card--rotate'); } Game.prototype.checkIsGameOver = function checkIsGameOver () { if (this.foundCardsCounter === this.settings.cardsNumber) { this.stop(); setTimeout(this.showGameWinMessageBind, 1000); } } Game.prototype.timeOverHandler = function timeOverHandler () { this.stop(); this.showGameOverMessage(); } Game.prototype.showGameWinMessage = function () { this.playground.clearScene(); this.showMessage('You are a winner!!!'); } Game.prototype.showGameOverMessage = function () { this.playground.clearScene(); this.showMessage('Time is over.'); } Game.prototype.removeMessage = function removeMessage () { if (this.messageElement) { this.messageElement.parentNode.removeChild(this.messageElement); } } Game.prototype.showMessage = function showMessage (message) { var _this = this; var messageTextElement = document.createElement('p'); messageTextElement.innerText = message; var messageTextWrapperElement = document.createElement('div'); messageTextWrapperElement.classList.add('game-message__text'); messageTextWrapperElement.appendChild(messageTextElement); var messageMenuButtonElement = document.createElement('a'); messageMenuButtonElement.classList.add('game-message__button'); messageMenuButtonElement.innerText = 'Main menu'; messageMenuButtonElement.href = '#main-menu'; var messageAgainButtonElement = messageMenuButtonElement.cloneNode(true); messageAgainButtonElement.innerText = 'Play again'; messageAgainButtonElement.href = '#game'; messageAgainButtonElement.addEventListener('click', function () { _this.removeMessage(); _this.restart(); }) var messageButtonWrapperElement = document.createElement('div'); messageButtonWrapperElement.classList.add('game-message__button-wrapper'); messageButtonWrapperElement.appendChild(messageMenuButtonElement); messageButtonWrapperElement.appendChild(messageAgainButtonElement); var messageElement = document.createElement('div'); messageElement.classList.add('game-message'); messageElement.appendChild(messageTextWrapperElement); messageElement.appendChild(messageButtonWrapperElement); document.body.appendChild(messageElement); this.messageElement = messageElement; } Game.prototype.stop = function () { this.timer.stop(); clearTimeout(this.backRotateTimerId); clearTimeout(this.timeOverTimerId); } Game.prototype.destroy = function () { this.stop(); this.removeMessage(); window.removeEventListener('hashchange', this.destroyBind); } global.Game = Game; })();<file_sep>'use strict'; (function () { const SettingsStorage = global.SettingsStorage; function GameSettings () { } GameSettings.prototype.start = function () { this.difficultyClickHandlerBind = this.difficultyClickHandler.bind(this); this.difficultyElement = document.body.querySelector('.difficulty__options'); this.difficultyElement.addEventListener('click', this.difficultyClickHandlerBind); this.setCheckedDifficulty(); this.categoryClickHandlerBind = this.categoryClickHandler.bind(this); this.categoryElement = document.body.querySelector('.card-categories__options'); this.categoryElement.addEventListener('click', this.categoryClickHandlerBind); this.setCheckedCategory(); } GameSettings.prototype.setCheckedDifficulty = function () { var currentDifficulty = SettingsStorage.getCardsNumber(); var difficultyOptionElement = this.difficultyElement.querySelector(`[data-difficulty="${currentDifficulty}"]`); difficultyOptionElement.classList.add('difficulty__options-item--checked'); } GameSettings.prototype.difficultyClickHandler = function (event) { var currentElement = event.target; var optionElement = currentElement.closest('.difficulty__options-item'); if (optionElement) { for (var i = 0; i < this.difficultyElement.children.length; i++) { this.difficultyElement.children[i].classList.remove('difficulty__options-item--checked'); } optionElement.classList.add('difficulty__options-item--checked'); } SettingsStorage.setCardsNumber(parseInt(optionElement.dataset.difficulty, 10)); } GameSettings.prototype.setCheckedCategory = function () { var currentCategory = SettingsStorage.getCategory(); var categoryOptionElement = this.categoryElement.querySelector(`[data-category="${currentCategory}"]`); categoryOptionElement.classList.add('card-categories__options-item--checked'); } GameSettings.prototype.categoryClickHandler = function (event) { var currentElement = event.target; var optionElement = currentElement.closest('.card-categories__options-item'); if (optionElement) { for (var i = 0; i < this.categoryElement.children.length; i++) { this.categoryElement.children[i].classList.remove('card-categories__options-item--checked'); } optionElement.classList.add('card-categories__options-item--checked'); } SettingsStorage.setCategory(parseInt(optionElement.dataset.category, 10)); } global.GameSettings = GameSettings; })();<file_sep>'use strict'; (function () { let routes = [ { state: 'main-menu', url: 'app/main-menu/main-menu.html', html: '' }, { state: 'game', url: 'app/game/game.html', html: '', handler: function () { var game = new global.Game(); game.start(); } }, { state: 'settings', url: 'app/settings/settings.html', html: '', handler: function () { var setting = new global.GameSettings(); setting.start(); } }, { state: 'about', url: 'app/about/about.html', html: '' } ] function Router () { this.hashChangeHandlerBind = this.hashChangeHandler.bind(this); window.location.hash = '#main-menu'; this.updateRoute('main-menu'); window.addEventListener('hashchange', this.hashChangeHandlerBind); } Router.prototype.hashChangeHandler = function hashChangeHandler (event) { var splitUrl = event.newURL.split('#'); var newState = splitUrl[1]; this.updateRoute(newState); } Router.prototype.updateRoute = function updateRoute (state) { var route = routes.find(function (route) { if (route.state === state) { return true; } }); this.loadTemplateHtml(route.url, function (templateHtml) { var mainElement = document.body.querySelector('.main'); mainElement.innerHTML = templateHtml; if (route.handler) { route.handler(); } }); } Router.prototype.loadTemplateHtml = function loadTemplateHtml (url, callback) { var xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.send(); xhr.addEventListener('readystatechange', function () { if (xhr.readyState === 4 && xhr.status === 200) { callback(xhr.responseText); } }) } var router = new Router(); })(); <file_sep>'use strict'; (function () { window.global = window.global || {}; function SettingsStorage () { this.currentCategory = 0; this.cardsNumber = 8; } SettingsStorage.prototype.getCategory = function () { return this.currentCategory; } SettingsStorage.prototype.setCategory = function (value) { this.currentCategory = value; } SettingsStorage.prototype.getCardsNumber = function () { return this.cardsNumber; } SettingsStorage.prototype.setCardsNumber = function (value) { this.cardsNumber = value; } global.SettingsStorage = new SettingsStorage(); })()<file_sep>'use strict'; (function () { function Timer (element) { this.element = element; this.secondCounter = 0; this.timerId = undefined; this.displayTimeBind = this.displayTime.bind(this); } Timer.prototype.start = function start () { this.secondCounter = 0; this.element.innerHTML = '00:00:00'; this.timerId = setInterval(this.displayTimeBind, 1000); } Timer.prototype.displayTime = function displayTime () { this.secondCounter++; var timeLabel = this.getTimeLabelBySecond(this.secondCounter); this.element.textContent = timeLabel; } Timer.prototype.getTimeLabelBySecond = function getTimeLabelBySecond (seconds) { var hours = Math.floor(seconds / 3600); seconds -= hours * 3600; var min = Math.floor(seconds / 60); seconds -= min * 60; var secondView = this.formatView(seconds); var minView = this.formatView(min); var hoursView = this.formatView(hours); var timeLabel = hoursView + ':' + minView + ':' + secondView; return timeLabel; } Timer.prototype.formatView = function formatView (time) { var result = time; if (Math.floor(time / 10) < 1) { result = '0' + time; } return result; } Timer.prototype.stop = function stop () { clearInterval(this.timerId); } global.Timer = Timer; })(); <file_sep>'use strict'; (function () { const IMAGES_URL = './images/categories/'; function Card (category, type) { this.category = category; this.type = type; } Card.prototype.createElement = function createElement () { var srcFront = `${IMAGES_URL}${this.category}/cover.png`; var srcBack = `${IMAGES_URL}${this.category}/types/${this.type}.png`; var card = document.createElement('div'); card.classList.add("card"); var frontCard = document.createElement('img'); frontCard.classList.add("card__front"); frontCard.src = srcFront; frontCard.alt = "card"; var backCard = document.createElement('img'); backCard.classList.add("card__back"); backCard.src = srcBack; backCard.alt = "card"; card.appendChild(frontCard); card.appendChild(backCard); card.dataset.type = this.type; return card; } function PlayGround (element, options) { this.element = element; this.category = options.category; this.cardsNumber = options.cardsNumber; this.pair = 2 this.cardsTypes = this.cardsNumber / this.pair; } PlayGround.prototype.start = function start () { this.createCards(); } PlayGround.prototype.createCards = function createCards () { const positions = this.getPositions(this.cardsNumber); const cards = this.getCards(this.cardsTypes, this.category, this.pair) while (positions.length) { const randIndex = this.getRandomNumber(0, positions.length - 1); const randomPosition = positions[randIndex]; const randomCard = cards[randomPosition]; const cardElement = randomCard.createElement(); this.element.appendChild(cardElement); positions.splice(randIndex, 1); } } PlayGround.prototype.getRandomNumber = function getRandomNumber (min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } PlayGround.prototype.getPositions = function getPositions (cardsNumber) { const positions = []; for (var i = 0; i < cardsNumber; i++) { positions[i] = i; } return positions; } PlayGround.prototype.getCards = function getCards (cardsTypes, category, pair) { const cards = []; for (var i = 0; i < cardsTypes; i++) { for (var j = 0; j < pair; j++) { cards.push(new Card(category, i)); } } return cards; } PlayGround.prototype.clearScene = function clearScene () { this.element.innerHTML = ''; } global.PlayGround = PlayGround; })();
b86a7c6eead471500514fd203cd54fda60f12532
[ "JavaScript" ]
6
JavaScript
Mar1nka/match-match-game
ff492c81dcf34a4a7e3f695ab625530a12c2b7b2
9fc65e0f608bfc552addad26a85739b77d83d263
refs/heads/master
<file_sep>package com.allmsi.flow.service; import java.util.List; import com.allmsi.flow.model.FlowField; import com.allmsi.flow.model.ovo.FlowFieldOVO; public interface FlowFieldService { FlowFieldOVO getFlowFieldOVo(String id); boolean deleteByPrimaryKey(String id); List<FlowField> listFlowField(String nodeId,List<String> userList); } <file_sep>package com.allmsi.flow.model; import java.util.Date; import com.allmsi.flow.model.ivo.TransferInterimIVO; import com.allmsi.sys.util.DateUtil; import com.allmsi.sys.util.StrUtil; public class TransferInterim { private String id; private String principal; private String agent; private String flowCode; private String nodeId; private Date startTime; private Date endTime; private Integer isRetain; private String cUserId; private Date cTime; private String uUserId; private Date uTime; private Boolean del; public TransferInterim() { } public TransferInterim(TransferInterimIVO transferInterimIVo) { if(transferInterimIVo != null) { this.id = transferInterimIVo.getId(); this.principal = transferInterimIVo.getPrincipal(); this.agent = transferInterimIVo.getAgent(); this.flowCode = transferInterimIVo.getFlowCode(); this.nodeId = transferInterimIVo.getNodeId(); String startTimeStr = transferInterimIVo.getStartTime(); if(StrUtil.notEmpty(startTimeStr)) { this.startTime = DateUtil.stringConvertDateTime(startTimeStr); } String endTimeStr = transferInterimIVo.getEndTime(); if(StrUtil.notEmpty(endTimeStr)) { this.endTime = DateUtil.stringConvertDateTime(endTimeStr); } this.isRetain = transferInterimIVo.getIsRetain(); this.cUserId = transferInterimIVo.getcUserId(); this.uUserId = transferInterimIVo.getuUserId(); } } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPrincipal() { return principal; } public void setPrincipal(String principal) { this.principal = principal; } public String getAgent() { return agent; } public void setAgent(String agent) { this.agent = agent; } public String getFlowCode() { return flowCode; } public void setFlowCode(String flowCode) { this.flowCode = flowCode; } public String getNodeId() { return nodeId; } public void setNodeId(String nodeId) { this.nodeId = nodeId; } public Date getStartTime() { return startTime; } public void setStartTime(Date startTime) { this.startTime = startTime; } public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } public Integer getIsRetain() { return isRetain; } public void setIsRetain(Integer isRetain) { this.isRetain = isRetain; } public String getcUserId() { return cUserId; } public void setcUserId(String cUserId) { this.cUserId = cUserId; } public Date getcTime() { return cTime; } public void setcTime(Date cTime) { this.cTime = cTime; } public String getuUserId() { return uUserId; } public void setuUserId(String uUserId) { this.uUserId = uUserId; } public Date getuTime() { return uTime; } public void setuTime(Date uTime) { this.uTime = uTime; } public Boolean getDel() { return del; } public void setDel(Boolean del) { this.del = del; } } <file_sep>package com.allmsi.flow.service; import java.util.List; import java.util.Map; import com.allmsi.flow.model.TransferForever; import com.allmsi.flow.model.ivo.TransferForeverIVO; public interface TransferForeverService { public boolean insertSelective(TransferForeverIVO record); public List<TransferForever> listAgentsForPrincipal(Map<String, Object> map); public List<String> listtPrincipalByAgent(Map<String, Object> map); } <file_sep>package com.allmsi.flow.dao; import com.allmsi.flow.model.FlowFieldProperty; public interface FlowFieldPropertyMapper { int deleteByPrimaryKey(String id); FlowFieldProperty getFlowFieldProperty(String id); }<file_sep>package com.allmsi.flow.model; public class OperationMenu { public static final String SUCCESS = "success"; public static final String ERROR = "error"; public static final String WARN = "warn"; public static final String QUERY = "query"; public static final String ROUTE = "route"; public static final String DRAFT = "draft"; public static final String USER = "user"; public static final String MULTI_PERSON_HANDLING = "doing"; public static final String CONTINUE = "continue"; public static final String VOTE = "vote"; public static final String PARAMETER_MSG = "参数不合法"; public static final String CONTINUE_MSG = "节点类型判定结束,可提交下一流程"; public static final String DISAGREE_OPERATION_WARN_MSG = "当前无拒绝权限,请联系管理员"; public static final String FLOW_CODE_BIZ = "fbiz01"; public static final String FLOW_CODE_FIN = "ffin01"; public static final String FLOW_CODE_CONT = "fcont01"; public static final String FLOW_CODE_PAY = "fpay01"; public static final String TODO = "01"; public static final String TOREAD = "02"; public static final String TAB_NODE = "node"; public static final String TAB_FLOW = "flow"; } <file_sep>package com.allmsi.flow.service; import java.util.List; import com.allmsi.flow.model.ovo.FlowReadDealOVO; public interface FlowReadDealService { List<FlowReadDealOVO> listFlowReadDealOVo(String tab, String tabId); } <file_sep>package com.allmsi.flow.model; import java.util.Date; public class FlowDoneView { private String id; private String flowCode; private String instanceId; private String objId; private String objName; private Date dealTime;// 发送时间 private String handlerName;// 创建人 private String handlerDept;// 创建人部门 private String nodeId; private String nodeName; private String auditorId; private String auditorName; private String objValue1; private String objValue2; private String objValue3; private String objValue4; private String objValue5; private String code; private String version; public String getFlowCode() { return flowCode; } public void setFlowCode(String flowCode) { this.flowCode = flowCode; } public String getInstanceId() { return instanceId; } public void setInstanceId(String instanceId) { this.instanceId = instanceId; } public String getObjId() { return objId; } public void setObjId(String objId) { this.objId = objId; } public String getObjName() { return objName; } public void setObjName(String objName) { this.objName = objName; } public Date getDealTime() { return dealTime; } public void setDealTime(Date dealTime) { this.dealTime = dealTime; } public String getHandlerName() { return handlerName; } public void setHandlerName(String handlerName) { this.handlerName = handlerName; } public String getHandlerDept() { return handlerDept; } public void setHandlerDept(String handlerDept) { this.handlerDept = handlerDept; } public String getNodeId() { return nodeId; } public void setNodeId(String nodeId) { this.nodeId = nodeId; } public String getNodeName() { return nodeName; } public void setNodeName(String nodeName) { this.nodeName = nodeName; } public String getAuditorId() { return auditorId; } public void setAuditorId(String auditorId) { this.auditorId = auditorId; } public String getAuditorName() { return auditorName; } public void setAuditorName(String auditorName) { this.auditorName = auditorName; } public String getObjValue1() { return objValue1; } public void setObjValue1(String objValue1) { this.objValue1 = objValue1; } public String getObjValue2() { return objValue2; } public void setObjValue2(String objValue2) { this.objValue2 = objValue2; } public String getObjValue3() { return objValue3; } public void setObjValue3(String objValue3) { this.objValue3 = objValue3; } public String getObjValue4() { return objValue4; } public void setObjValue4(String objValue4) { this.objValue4 = objValue4; } public String getObjValue5() { return objValue5; } public void setObjValue5(String objValue5) { this.objValue5 = objValue5; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getId() { return id; } public void setId(String id) { this.id = id; } @Override public String toString() { return "FlowDoneView [id=" + id + ", flowCode=" + flowCode + ", instanceId=" + instanceId + ", objId=" + objId + ", objName=" + objName + ", dealTime=" + dealTime + ", handlerName=" + handlerName + ", handlerDept=" + handlerDept + ", nodeId=" + nodeId + ", nodeName=" + nodeName + ", auditorId=" + auditorId + ", auditorName=" + auditorName + ", objValue1=" + objValue1 + ", objValue2=" + objValue2 + ", objValue3=" + objValue3 + ", objValue4=" + objValue4 + ", objValue5=" + objValue5 + ", code=" + code + ", version=" + version + "]"; } } <file_sep>package com.allmsi.flow.service; import java.util.List; import com.allmsi.flow.model.external.FlowUserModel; public interface ReadDealRuleEngine { List<FlowUserModel> getReadDealUser(String nodeId, String instanceId); } <file_sep>package com.allmsi.flow.service.impl; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.allmsi.flow.dao.FlowFieldPropertyMapper; import com.allmsi.flow.model.FlowFieldProperty; import com.allmsi.flow.service.FlowFieldPropertyService; @Service public class FlowFieldPropertyServiceImpl implements FlowFieldPropertyService { @Resource private FlowFieldPropertyMapper FlowFieldPropertyDao; @Override public FlowFieldProperty getFlowFieldProperty(String id) { FlowFieldProperty flowFieldProperty = FlowFieldPropertyDao.getFlowFieldProperty(id); if (flowFieldProperty == null) { return null; } return flowFieldProperty; } @Override public boolean deleteByPrimaryKey(String id) { int flag = FlowFieldPropertyDao.deleteByPrimaryKey(id); return (flag == 0) ? false : true; } } <file_sep>package com.allmsi.flow.dao; import java.util.List; import com.allmsi.flow.model.FlowRoute; public interface FlowRouteMapper { FlowRoute selectByPrimaryKey(String id); List<FlowRoute> listRouteByPreNode(FlowRoute flowRoute); FlowRoute getStartNodeRoute(String flowId); int isfinish(String nodeId); }<file_sep>package com.allmsi.flow.dao; import java.util.List; import java.util.Map; import com.allmsi.flow.model.FlowDraftView; public interface FlowDraftViewMapper { List<FlowDraftView> selectFlowDraft(Map<String, String> map); } <file_sep>package com.allmsi.flow.service.impl; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.allmsi.flow.dao.FlowInstanceMapper; import com.allmsi.flow.model.FlowInstance; import com.allmsi.flow.model.ivo.FlowInstanceIVO; import com.allmsi.flow.service.FlowInstanceService; import com.allmsi.sys.util.UUIDUtil; @Service public class FlowInstanceServiceImpl implements FlowInstanceService { @Resource private FlowInstanceMapper flowInstanceDao; @Override public List<String> listInstanceByObjId(String objId) { List<String> list = new ArrayList<String>(); List<FlowInstance> fiList = flowInstanceDao.listInstanceByObjId(objId); for (FlowInstance flowInstance : fiList) { list.add(flowInstance.getId()); } return list; } @Override public String insertFlowInstance(FlowInstanceIVO flowInstanceIVo) { FlowInstance fi = new FlowInstance(flowInstanceIVo); String id = UUIDUtil.getUUID(); fi.setId(id); int msg = flowInstanceDao.insertSelective(fi);// 添加流程实例 return (msg == 0) ? "" : id; } @Override public String updateFlowInstanceDratf(String instanceId) { FlowInstance flowInstance = flowInstanceDao.selectByPrimaryKey(instanceId); Integer draft = flowInstance.getDraft(); if (0 == draft) {// 修改 int msg = flowInstanceDao.updateDraft(instanceId); return (msg == 0) ? "" : instanceId; } return instanceId; } } <file_sep>package com.allmsi.flow.dao; import java.util.List; import com.allmsi.flow.model.FlowNodeDeal; public interface FlowNodeDealMapper { List<FlowNodeDeal> listNodeDeals(String nodeId); }<file_sep>package com.allmsi.flow.service.impl; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.allmsi.flow.model.OperationMenu; import com.allmsi.flow.model.external.FlowBeforNodeMapKey; import com.allmsi.flow.model.external.FlowUserModel; import com.allmsi.flow.model.ovo.FlowInstanceOVO; import com.allmsi.flow.model.ovo.FlowReadDealOVO; import com.allmsi.flow.reflection.FlowBeforeNodeReflection; import com.allmsi.flow.reflection.FlowNodeReadUserRegisterQueryReflection; import com.allmsi.flow.reflection.FlowUserServiceReflection; import com.allmsi.flow.service.FlowInstenceEngine; import com.allmsi.flow.service.FlowReadDealService; import com.allmsi.flow.service.ReadDealRuleEngine; import com.allmsi.sys.util.StrUtil; @Service public class ReadDealRuleEngineImpl implements ReadDealRuleEngine { @Resource private FlowReadDealService flowReadDealService; @Resource private FlowUserServiceReflection flowUserServiceReflection; @Resource private FlowInstenceEngine flowInstenceEngine; @Resource private FlowBeforeNodeReflection flowBeforeNodeReflection; @Resource private FlowNodeReadUserRegisterQueryReflection flowNodeReadUserRegisterQueryReflection; @SuppressWarnings("unchecked") public List<FlowUserModel> getReadDealUser(String nodeId, String instanceId) { List<FlowUserModel> readlist = new ArrayList<FlowUserModel>();// 节点待阅人员 if (StrUtil.notEmpty(nodeId)) { List<FlowReadDealOVO> rfdList = flowReadDealService.listFlowReadDealOVo(OperationMenu.TAB_NODE, nodeId); List<FlowReadDealOVO> selectedRouteList = new ArrayList<FlowReadDealOVO>(); String strQuery = getQueryRule(rfdList);// 需匹配的字段 if (StrUtil.notEmpty(strQuery)) { FlowInstanceOVO fi = flowInstenceEngine.getFlowInstanceOVO(instanceId); if (fi == null) { return null; } System.out.println("流程节点阅读条件:"+strQuery); String moduleQuery = flowNodeReadUserRegisterQueryReflection.getFlowNodeReadUserService() .getReadQurey(strQuery, fi.getObjectId(), fi.getFlowCode()); selectedRouteList = queryRuleJudgment(rfdList, moduleQuery); } else { selectedRouteList = rfdList; } Set<String> userids = new HashSet<String>(); for (FlowReadDealOVO flowReadDealOVo : selectedRouteList) { String readId = flowReadDealOVo.getReadId(); String readType = flowReadDealOVo.getReadType(); if (StrUtil.notEmpty(readType)) { switch (readType) { case "01":// 查询用户 FlowUserModel u = flowUserServiceReflection.getFlowExternalService().selectUserInfo(readId); if (u != null) { userids.add(u.getUserId()); readlist.add(u); } break; case "02":// 查询部门 List<FlowUserModel> dl = flowUserServiceReflection.getFlowExternalService() .selectUserByDeptId(readId); if (dl != null && dl.size() > 0) { for (FlowUserModel flowUserModel : dl) { if (!userids.contains(flowUserModel.getUserId())) { userids.add(flowUserModel.getUserId()); readlist.add(flowUserModel); } } } break; case "03":// 查询角色 List<FlowUserModel> rl = flowUserServiceReflection.getFlowExternalService() .selectUserByRoleId(readId); if (rl != null && rl.size() > 0) { for (FlowUserModel flowUserModel : rl) { if (!userids.contains(flowUserModel.getUserId())) { userids.add(flowUserModel.getUserId()); readlist.add(flowUserModel); } } } break; case "11":// 发起人 // 查询发起人信息 FlowInstanceOVO flowInstanceOVo = flowInstenceEngine.getFlowInstanceOVO(instanceId); if (flowInstanceOVo != null) { FlowUserModel user = flowInstanceOVo.getUser(); if (user != null) { if (!userids.contains(user.getUserId())) { userids.add(user.getUserId()); readlist.add(user); } } } break; case "99":// 额外人员 // 查询发起人信息 FlowInstanceOVO flowInstanceOVo1 = flowInstenceEngine.getFlowInstanceOVO(instanceId); if (flowInstanceOVo1 != null) { Map<String, Object> map = flowBeforeNodeReflection.getFlowBeforeNodeReflection().flowBeforeNode(FlowBeforNodeMapKey.TYPE_NODE, nodeId, flowInstanceOVo1.getFlowCode(),flowInstanceOVo1.getObjectId()); String key=FlowBeforNodeMapKey.TYPE_NODE_KEY+nodeId; if(map != null && map.get(key) != null) { List<FlowUserModel> list = (List<FlowUserModel>) map.get(key); if (list != null && list.size() > 0) { for (FlowUserModel flowUserModel : list) { if (!userids.contains(flowUserModel.getUserId())) { userids.add(flowUserModel.getUserId()); readlist.add(flowUserModel); } } } } } break; } } } } return readlist; } private List<FlowReadDealOVO> queryRuleJudgment(List<FlowReadDealOVO> rfdList, String query) { List<FlowReadDealOVO> queryReadList = new ArrayList<FlowReadDealOVO>(); Map<String, String> queryMap = new HashMap<>(); if (StrUtil.notEmpty(query)) { queryMap = parseQuery2Map(query); } for (FlowReadDealOVO fr : rfdList) { List<String> queryList = fr.getQueryList(); if (queryList != null && queryList.size() > 0) { for (String queryParm : queryList) {// 进行单个条件完全匹配的校验 int count = 0; List<String> keys = getQueryParmKey(queryParm);// 要匹配的字段(完全匹配的字段) for (int i = 0; i < keys.size(); i++) { String key = keys.get(i); String value = getQueryParmValue(queryParm, key);// 流程中的字段值(‘A,S’或者‘B’或者‘!B’) String queryValue = queryMap.get(key);// 业务所对应的值 String[] values = value.split(","); if (queryMap.containsKey(key) && StrUtil.notEmpty(queryValue)) { for (int j = 0; j < values.length; j++) { String s = values[j]; if (s.equals(queryValue) || queryValue.contains(s)) {// 匹配上 count++; } } } else {// 没有key,匹配下一个queryParm break; } } if (count == keys.size()) {// 完全匹配 queryReadList.add(fr); } } } else { queryReadList.add(fr); } continue; } return queryReadList; } private String getQueryParmValue(String queryParm, String key) { JSONObject jsonx = JSON.parseObject(queryParm); return jsonx.get(key).toString(); } private Map<String, String> parseQuery2Map(String query) { Map<String, String> map = new HashMap<>(); Set<String> keySet = new HashSet<>(); if (StrUtil.notEmpty(query)) { String[] strs = query.split(";"); for (String s : strs) { String[] kv = s.split(":"); if (kv.length == 2) { if (!keySet.contains(kv[0])) { keySet.add(kv[0]); } else { String kv1 = map.get(kv[0]).toString(); kv[1] = kv1 + "," + kv[1]; } map.put(kv[0], kv[1]); } } } return map; } private String getQueryRule(List<FlowReadDealOVO> rfdList) { Set<String> keySet = new HashSet<>(); for (FlowReadDealOVO fr : rfdList) { List<String> queryList = fr.getQueryList(); if (queryList != null && queryList.size() > 0) { for (String queryStr : queryList) { List<String> keysList = getQueryParmKey(queryStr); for (String string : keysList) { if (!keySet.contains(string)) { keySet.add(string); } } } } } String param = ""; for (String string : keySet) { param += string + ";"; } if (param.endsWith(";")) { param = param.substring(0, param.length() - 1); } return param; } private List<String> getQueryParmKey(String queryParm) { JSONObject jsonx = JSON.parseObject(queryParm); List<String> keys = new ArrayList<>(); for (String key : jsonx.keySet()) { String[] keyArray = key.split(","); for (String keyStr : keyArray) { keys.add(keyStr); } } return keys; } } <file_sep>package com.allmsi.flow.dao; import java.util.List; import java.util.Map; import com.allmsi.flow.model.FlowInstanceLog; public interface FlowInstanceLogMapper { int insertSelective(FlowInstanceLog record); int insertBantch(List<FlowInstanceLog> list); List<FlowInstanceLog> listInstenceStateLog(String instanceId); int isFinsh(String objId); List<FlowInstanceLog> doneFlow(List<String> objIds);// 1 int deleteByInstenceId(String instenceId); FlowInstanceLog getDoneInfo(Map<String, String> map); List<String> listDealState(Map<String, String> map); List<String> listVoteDealState(Map<String, String> map); int updateDeatState(Map<String, String> map); List<FlowInstanceLog> listVote(String id); }<file_sep>package com.allmsi.flow.service; import java.util.List; import com.allmsi.flow.model.FlowInstanceLog; import com.allmsi.flow.model.FlowInstanceState; import com.allmsi.flow.model.ovo.FlowStateLogOVO; public interface FlowInstenceLogEngine { public String insertFlowInstenceLog(FlowInstanceState fs,String remark,String dealState); public String insertFlowInstenceLog(FlowInstanceLog record); FlowInstanceLog getDoneInfo (String instanceId,String nodeId,String sufDealId); public boolean insertBantch(List<FlowInstanceLog> list); // List<FlowInstanceLog> listInstenceStateLog(String instanceId); List<FlowStateLogOVO> listFlowLog(String instanceId); List<String> listVote(String instanceId, String nodeId); boolean updateDealState(String instanceId,String nodeId,String sufDealId,String dealState); List<FlowStateLogOVO> listVote(String id); } <file_sep>package com.allmsi.flow.service.impl; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.allmsi.flow.dao.FlowRouteDealQueryMapper; import com.allmsi.flow.service.FlowRouteDealQueryService; @Service public class FlowRouteDealQueryServiceImpl implements FlowRouteDealQueryService { @Resource private FlowRouteDealQueryMapper flowRouteDealQueryDao; @Override public List<String> queryList(String id) { List<String> queryList = flowRouteDealQueryDao.queryList(id); List<String> list = new ArrayList<>(); if (queryList != null && queryList.size() > 0) { for (String queryStr : queryList) { list.add(queryStr.replace("\"", "")); } } return list; } } <file_sep>package com.allmsi.flow.service.impl; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.allmsi.flow.dao.FlowInstanceLogMapper; import com.allmsi.flow.model.FlowInstanceLog; import com.allmsi.flow.model.ivo.FlowInstanceLogIVO; import com.allmsi.flow.service.FlowInstanceLogService; import com.allmsi.sys.util.StrUtil; import com.allmsi.sys.util.UUIDUtil; @Service public class FlowInstanceLogServiceImpl implements FlowInstanceLogService { @Resource private FlowInstanceLogMapper flowInstanceLogDao; @Override public String insertFlowInstanceLog(FlowInstanceLogIVO flowInstanceLogIVo) { if (flowInstanceLogIVo == null || StrUtil.isEmpty(flowInstanceLogIVo.getInstanceId())) { return null; } FlowInstanceLog flowInstanceLog = new FlowInstanceLog(flowInstanceLogIVo); String id = UUIDUtil.getUUID(); flowInstanceLog.setId(id); return (flowInstanceLogDao.insertSelective(flowInstanceLog) == 0) ? null : id; } @Override public String isFinsh(String objId) { if (StrUtil.isEmpty(objId)) { return ""; } int count = flowInstanceLogDao.isFinsh(objId); return (count == 0) ? "" : objId; } @Override public List<String> doneFlow(List<String> objIds) { List<String> list = new ArrayList<String>(); if (objIds != null && objIds.size() > 0) { List<FlowInstanceLog> filList = flowInstanceLogDao.doneFlow(objIds);// 未完结的项目 for (FlowInstanceLog flowInstanceLog : filList) { String objId = flowInstanceLog.getObjId(); list.add(objId); } return list; } return null; } } <file_sep>package com.allmsi.flow.third.service; import java.util.List; import java.util.Map; import com.allmsi.flow.model.external.FlowUserModel; public interface FlowExternalNodeDealUserService { Map<String,List<FlowUserModel>> listNodeDealUsers(String objId,String nodeId); } <file_sep>package com.allmsi.flow.service.impl; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.allmsi.flow.dao.FlowNodeDealMapper; import com.allmsi.flow.model.FlowNodeDeal; import com.allmsi.flow.model.external.FlowUserModel; import com.allmsi.flow.model.ovo.FlowNodeDealOVO; import com.allmsi.flow.reflection.FlowUserServiceReflection; import com.allmsi.flow.service.FlowNodeDealService; import com.allmsi.sys.util.StrUtil; @Service public class FlowNodeDealServiceImpl implements FlowNodeDealService { @Resource private FlowNodeDealMapper flowNodeDealDao; @Resource private FlowUserServiceReflection flowUserServiceReflection; @Override public List<FlowNodeDealOVO> listFlowNodeDeal(String nodeId) { List<FlowNodeDealOVO> list = new ArrayList<FlowNodeDealOVO>(); List<FlowNodeDeal> fndList = flowNodeDealDao.listNodeDeals(nodeId); for (FlowNodeDeal flowNodeDeal : fndList) { list.add(new FlowNodeDealOVO(flowNodeDeal)); } return list; } @Override public List<FlowUserModel> listNodeUsers(String userId,String nodeId) { List<FlowUserModel> list = new ArrayList<FlowUserModel>(); if (StrUtil.isEmpty(nodeId)) { return null; } List<FlowNodeDeal> fndList = flowNodeDealDao.listNodeDeals(nodeId); for (FlowNodeDeal flowNodeDeal : fndList) { String nodeType = flowNodeDeal.getNodeDealType(); String dealId = flowNodeDeal.getNodeDealId(); if (StrUtil.notEmpty(nodeType)) { switch (nodeType) { case "01": list.add(flowUserServiceReflection.getFlowExternalService().selectUserInfo(dealId)); break; case "02": list.addAll(flowUserServiceReflection.getFlowExternalService().selectUserByDeptId(dealId)); break; case "03": list.addAll(flowUserServiceReflection.getFlowExternalService().selectUserByRoleId(dealId)); break; default: break; } } } return list; } } <file_sep>package com.allmsi.flow.service; import java.util.List; import java.util.Map; import com.allmsi.flow.model.FlowInstanceDeal; import com.allmsi.flow.model.ovo.FlowInstanceDealOVO; public interface FlowInstanceDealService { FlowInstanceDealOVO getPreDealUserForNodeId(Map<String, String> map); List<FlowInstanceDealOVO> listPreDealUsersForNodeId(Map<String, String> map); FlowInstanceDeal getFlowInstanceDealByState(String stateId); boolean insertBatch(List<FlowInstanceDeal> list); int insertSelective(FlowInstanceDeal flowInstanceDeal); } <file_sep>package com.allmsi.flow.dao; import java.util.List; import java.util.Map; import com.allmsi.flow.model.FlowMySelfView; public interface FlowMySelfViewMapper { List<FlowMySelfView> selectMySelfList(Map<String, String> map); } <file_sep>package com.allmsi.flow.dao; import java.util.List; import com.allmsi.flow.model.FlowNodeButton; public interface FlowNodeButtonMapper { List<FlowNodeButton> listFlowNodeButton(String nodeId); }<file_sep>package com.allmsi.flow.service.impl; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import com.allmsi.flow.dao.FlowInstanceStateMapper; import com.allmsi.flow.model.FlowInstanceDeal; import com.allmsi.flow.model.FlowInstanceLog; import com.allmsi.flow.model.FlowInstanceState; import com.allmsi.flow.model.OperationMenu; import com.allmsi.flow.model.external.FlowUserModel; import com.allmsi.flow.model.ivo.FlowInstanceDealIVO; import com.allmsi.flow.model.ivo.FlowInstanceStateIVO; import com.allmsi.flow.model.ivo.NodeDealIVO; import com.allmsi.flow.model.ovo.FlowInstenceCurrencyOVO; import com.allmsi.flow.model.ovo.FlowInstenceStateDoneInfoOVO; import com.allmsi.flow.model.ovo.FlowNodeButtonSimpleOVO; import com.allmsi.flow.model.ovo.FlowNodeFieldOVO; import com.allmsi.flow.model.ovo.FlowNodeOVO; import com.allmsi.flow.reflection.FlowUserServiceReflection; import com.allmsi.flow.service.FlowInstanceDealService; import com.allmsi.flow.service.FlowInstanceStateService; import com.allmsi.flow.service.FlowInstenceLogEngine; import com.allmsi.flow.service.FlowInstenceStateEngine; import com.allmsi.flow.service.FlowNodeButtonService; import com.allmsi.flow.service.FlowNodeFieldService; import com.allmsi.flow.service.NodeDealRuleEngine; import com.allmsi.flow.util.LogStatusUtil; import com.allmsi.sys.util.DateUtil; import com.allmsi.sys.util.StrUtil; import com.allmsi.sys.util.UUIDUtil; @Service public class FlowInstenceStateEngineImpl implements FlowInstenceStateEngine { @Resource private FlowInstanceStateService flowInstanceStateService; @Resource private FlowInstenceLogEngine flowInstenceLogEngine; @Resource private FlowUserServiceReflection flowUserServiceReflection; @Resource private FlowInstanceStateMapper flowInstanceStateDao; @Resource private FlowInstanceDealService flowInstanceDealService; @Resource private FlowNodeFieldService flowNodeFieldService; @Resource private FlowNodeButtonService flowNodeButtonService; @Resource private NodeDealRuleEngine nodeDealRuleEngine; @Value("${im.flow.recall.hour:2}") private String RECALL_HOUR; public String insertFlowInstanceState(FlowInstanceStateIVO flowInstanceStateIVo) { FlowInstanceState flowInstanceState = new FlowInstanceState(flowInstanceStateIVo); List<FlowInstanceState> fiList = new ArrayList<FlowInstanceState>(); if (flowInstanceState != null) { fiList.add(flowInstanceState); } if (fiList != null && fiList.size() > 0) { int msg = flowInstanceStateDao.insertBantch(fiList); return (msg == 0) ? "" : flowInstanceStateIVo.getId(); } return null; } @Override public List<String> insertFlowInstanceStateForNodeDealList(String instanceId, String nodeId, String routeId, String preDealId, List<NodeDealIVO> nodeDealList) { if (StrUtil.isEmpty(instanceId) || StrUtil.isEmpty(nodeId) || StrUtil.isEmpty(preDealId) || nodeDealList == null || nodeDealList.size() < 1) { return null; } FlowUserModel flowUserModel = flowUserServiceReflection.getFlowExternalService().selectUserInfo(preDealId); List<FlowInstanceState> list = new ArrayList<FlowInstanceState>();// 待办表 List<FlowInstanceDeal> dealList = new ArrayList<FlowInstanceDeal>();// 实例状态办理表 List<String> strList = new ArrayList<String>();// 实例状态ID if (flowUserModel != null) { String preId = flowUserModel.getUserId(); String preName = flowUserModel.getName(); String preDeptId = flowUserModel.getDeptId(); String preDeptName = flowUserModel.getDeptName(); for (NodeDealIVO nodeDealVo : nodeDealList) { String sufDealId = nodeDealVo.getDealId(); String sufDealType = nodeDealVo.getDealType(); String sufAuthType = nodeDealVo.getAuthType(); String stateId = UUIDUtil.getUUID(); Integer isProxy = nodeDealVo.getIsProxy(); String proxyId = nodeDealVo.getProxyId(); list.add(new FlowInstanceState(stateId, instanceId, nodeId, routeId, preDealId, sufDealId, sufDealType, sufAuthType, preDealId, isProxy, proxyId)); strList.add(stateId); dealList.add(new FlowInstanceDeal(UUIDUtil.getUUID(), stateId, preId, preName, preDeptId, preDeptName, sufDealId, nodeDealVo.getDealName(), nodeDealVo.getDeptId(), nodeDealVo.getDeptName())); } } int msg = 0; if (list != null && list.size() > 0) { msg = flowInstanceStateDao.insertBantch(list); } if (dealList != null && dealList.size() > 0) { flowInstanceDealService.insertBatch(dealList); } return (msg == 0) ? null : strList; } @Override public String insertFlowInstenceDeal(FlowInstanceDealIVO flowInstanceDealIVo) { FlowInstanceDeal FlowInstanceDeal = new FlowInstanceDeal(flowInstanceDealIVo); int msg = flowInstanceDealService.insertSelective(FlowInstanceDeal); return (msg == 0) ? "" : FlowInstanceDeal.getId(); } @Override public boolean deleteBantchForInstanceAndNodeId(String instanceId, String nodeId, String sufAuthType) { if (StrUtil.isEmpty(instanceId) || StrUtil.isEmpty(nodeId)) { return false; } FlowInstanceState fis = new FlowInstanceState(); fis.setInstanceId(instanceId); fis.setNodeId(nodeId); fis.setSufAuthType(sufAuthType); fis.setSufDealType("01"); int msg = flowInstanceStateDao.deleteBantchByFis(fis);// 删除实例状态信息 return (msg == 0) ? false : true; } @Override public FlowInstanceState getInstenceStateNow(String instanceId, String nodeId, String sufDealId, String sufAuthType) { FlowInstanceState flowInstanceState = new FlowInstanceState(); flowInstanceState.setInstanceId(instanceId); flowInstanceState.setSufDealId(sufDealId); flowInstanceState.setNodeId(nodeId); flowInstanceState.setSufAuthType(sufAuthType); // FlowInstanceState fs = flowInstanceStateDao.getInstenceNow(flowInstanceState); return getInstenceStateNow(flowInstanceState); } @Override public FlowInstanceState getInstenceStateNow(FlowInstanceState flowInstanceState) { return flowInstanceStateDao.getInstenceNow(flowInstanceState); } @Override public boolean deleteInstenceNow(String id) { if (StrUtil.isEmpty(id)) { return false; } int msg = flowInstanceStateDao.deleteById(id);// 删除本人的办理实例 return (msg == 0) ? false : true; } @Override public boolean deleteBantchByInstenceId(String instanceId) { int msg = flowInstanceStateDao.deleteBantch(instanceId); return (msg == 0) ? false : true; } @Override public List<FlowInstanceState> listByFis(String instanceId, String nodeId, String sufAuthType) { FlowInstanceState fis = new FlowInstanceState(); fis.setInstanceId(instanceId); fis.setNodeId(nodeId); fis.setSufAuthType(sufAuthType); return flowInstanceStateDao.getByFis(fis); } @Override public boolean isRecall(String instanceId, String preDealId) { boolean isRecall = false; List<FlowInstanceState> list = flowInstanceStateService.listInstanceStateByInstance(instanceId, preDealId); if (list != null && list.size() > 0) {// 存在待办信息 // 判断是否可以撤回 for (FlowInstanceState flowInstanceState : list) { if (flowInstanceState.getIsRecall() != null && 1 == flowInstanceState.getIsRecall()) {// 存在可撤回的信息&& // flowInstanceState.getuTime() SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String uTime = format.format(flowInstanceState.getuTime()); String date = format.format(new Date()); BigDecimal number = new BigDecimal( Double.toString((DateUtil.strConvertSecond(date) - DateUtil.strConvertSecond(uTime))));// 秒数 BigDecimal recallHr = new BigDecimal(Double.toString(Double.valueOf(RECALL_HOUR) * 3600)); if (recallHr.subtract(number).doubleValue() > 0) { isRecall = true; return isRecall; } else { break; } } } } return isRecall; } @Override public boolean recall(String preDealId, String instanceId) { List<FlowInstanceState> list = flowInstanceStateService.listInstanceStateByInstance(instanceId, preDealId); if (list != null && list.size() > 0) { FlowInstanceState flowInstanceState = list.get(0); if (flowInstanceState != null) { // log表用户前一步办理信息得到nodeId,routeId FlowInstanceLog flowInstanceLog = flowInstenceLogEngine.getDoneInfo(instanceId, null, preDealId); if (flowInstanceLog != null) { String nodeId = flowInstanceLog.getNodeId(); String routeId = flowInstanceLog.getRouteId(); // 添加待办,instance_deal List<NodeDealIVO> nodeDealList = new ArrayList<NodeDealIVO>(); FlowUserModel flowUserModel = flowUserServiceReflection.getFlowExternalService() .selectUserInfo(preDealId); nodeDealList.add(new NodeDealIVO(preDealId, "01", "01", flowUserModel.getDeptId(), flowUserModel.getDeptName(), flowUserModel.getName())); List<String> states = insertFlowInstanceStateForNodeDealList(instanceId, nodeId, routeId, preDealId, nodeDealList); if (states != null && states.size() > 0) { // log String logId = UUIDUtil.getUUID(); FlowInstanceState flog = new FlowInstanceState(logId, instanceId, flowInstanceState.getNodeId(), flowInstanceState.getRouteId(), preDealId, preDealId, "01", "01", preDealId, null, null); flowInstenceLogEngine.insertFlowInstenceLog(flog, LogStatusUtil.RECAL_MSG, "08"); insertFlowInstenceDeal(new FlowInstanceDealIVO(UUIDUtil.getUUID(), logId, preDealId, flowUserModel.getName(), flowUserModel.getDeptId(), flowUserModel.getDeptName(), preDealId, flowUserModel.getName(), flowUserModel.getDeptId(), flowUserModel.getDeptName())); // 删除其它待办 for (FlowInstanceState fisInfo : list) { String id = fisInfo.getId(); deleteInstenceNow(id); } return true; } } } } return false; } @Override public boolean updateAuthType(String instanceId, String nodeId, String sufAuthType) { Map<String, Object> map = new HashMap<String, Object>(); map.put("instanceId", instanceId); map.put("nodeId", nodeId); map.put("sufAuthType", "02"); flowInstanceStateDao.updateAuthType(map); return true; } @Override public boolean updateRead(String instanceId, String userId) { FlowInstanceState fis = new FlowInstanceState(); fis.setInstanceId(instanceId); fis.setSufAuthType(OperationMenu.TOREAD); fis.setSufDealId(userId); fis.setSufDealType("01"); List<FlowInstanceState> list1 = flowInstanceStateDao.getByFis(fis); List<FlowInstanceLog> list = new ArrayList<FlowInstanceLog>(); for (FlowInstanceState flowInstanceState : list1) { Integer isProxy = flowInstanceState.getIsProxy(); if (isProxy != null && 1 == isProxy) {// 代理办理 String proxyId = flowInstanceState.getProxyId();// 被代理的人 // 删除待办表中的被代理人信息 FlowInstanceState fs1 = new FlowInstanceState(); fs1.setInstanceId(flowInstanceState.getInstanceId()); fs1.setNodeId(flowInstanceState.getNodeId()); fs1.setRouteId(flowInstanceState.getRouteId()); fs1.setPreDealId(flowInstanceState.getPreDealId()); fs1.setSufDealId(proxyId); fs1.setSufDealType("01"); flowInstanceStateDao.deleteBantchByFis(fs1); } else { FlowInstanceState fs1 = new FlowInstanceState(); fs1.setInstanceId(flowInstanceState.getInstanceId()); fs1.setNodeId(flowInstanceState.getNodeId()); fs1.setRouteId(flowInstanceState.getRouteId()); fs1.setPreDealId(flowInstanceState.getPreDealId()); fs1.setProxyId(flowInstanceState.getSufDealId()); fs1.setSufAuthType(flowInstanceState.getSufAuthType()); flowInstanceStateDao.deleteBantchByFis(fs1); } FlowInstanceLog record = new FlowInstanceLog(flowInstanceState); record.setDealTime(new Date()); list.add(record); } if (list != null && list.size() > 0) { flowInstenceLogEngine.insertBantch(list); } int count = flowInstanceStateDao.deleteBantchByFis(fis); return (count == 0) ? false : true; } @Override public int sCount(String userId) { return flowInstanceStateDao.sCount(userId); } @Override public FlowInstenceCurrencyOVO getTodoInfo(String objId, String authType, String userId, String flowCode) { Map<String, String> map = new HashMap<String, String>(); map.put("objId", objId); map.put("sufDealId", userId); map.put("sufDealType", "01"); map.put("sufAuthType", authType); FlowInstanceState flowInstanceState = flowInstanceStateDao.getInstenceStateInfo(map); if (flowInstanceState == null && StrUtil.isEmpty(flowCode)) {// 不存在,草稿 return null; } FlowInstenceCurrencyOVO flowInstenceCurrencyOVO = new FlowInstenceCurrencyOVO(flowInstanceState); String nodeId = ""; if (flowInstanceState != null) { nodeId = flowInstanceState.getNodeId(); } else { FlowNodeOVO flowNodeOVo = nodeDealRuleEngine.getTheNextNodeToStart(flowCode); if (flowNodeOVo != null) { nodeId = flowNodeOVo.getId(); } } if (StrUtil.notEmpty(nodeId)) { List<FlowNodeButtonSimpleOVO> list = flowNodeButtonService.listNodeButtons(nodeId); List<FlowNodeFieldOVO> fieldList = flowNodeFieldService.listNodeField(userId, nodeId); flowInstenceCurrencyOVO.setNodeButtonList(list); flowInstenceCurrencyOVO.setNodeFieldList(fieldList); } return flowInstenceCurrencyOVO; } @Override public FlowInstenceStateDoneInfoOVO getDoneInfo(String objId, String preDealId) { Map<String, String> map = new HashMap<String, String>(); map.put("objId", objId); FlowInstanceState flowInstanceState = flowInstanceStateDao.getInstenceStateDoneInfo(map); if (flowInstanceState != null) { boolean flag = isRecall(flowInstanceState.getInstanceId(), preDealId); if (flag) { flowInstanceState.setIsRecall(1); } } FlowInstenceStateDoneInfoOVO flowInstenceInfoForObjOvo = new FlowInstenceStateDoneInfoOVO(flowInstanceState); return flowInstenceInfoForObjOvo; } } <file_sep>package com.allmsi.flow.dao; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.Mapper; import com.allmsi.flow.model.FlowInstanceDeal; @Mapper public interface FlowInstanceDealMapper { int insertSelective(FlowInstanceDeal record); int insertBatch(List<FlowInstanceDeal> list); FlowInstanceDeal getPreDealUserForNodeId(Map<String, String> map); List<FlowInstanceDeal> listPreDealUsersForNodeId(Map<String, String> map); int deleteByInstenceId(String instenceId); FlowInstanceDeal getFlowInstanceDealByState(String stateId); }<file_sep>package com.allmsi.flow.model; import java.util.Date; import com.allmsi.flow.model.ivo.FlowInstanceDealIVO; public class FlowInstanceDeal { private String id; private String stateId; private String preId; private String preName; private String preDeptId; private String preDeptName; private String sufId; private String sufName; private String sufDeptId; private String sufDeptName; // 回退时的返回参数 private String flowId; // 路由处理 private String preRouteId; private String preRouteName; private String routeDealType; private String query; private Integer preRouteIsBack; private String preNodeId; private String preNodeName; private String preNodeType; private String sufNodeId; private String sufNodeName; private String sufNodeType; private Date uTime; public FlowInstanceDeal() { } public FlowInstanceDeal(FlowInstanceDealIVO flowInstanceDealIVo) { if (flowInstanceDealIVo != null) { this.id = flowInstanceDealIVo.getId(); this.stateId = flowInstanceDealIVo.getStateId(); this.preId = flowInstanceDealIVo.getPreId(); this.preName = flowInstanceDealIVo.getPreName(); this.preDeptId = flowInstanceDealIVo.getPreDeptId(); this.preDeptName = flowInstanceDealIVo.getPreDeptName(); this.sufId = flowInstanceDealIVo.getSufId(); this.sufName = flowInstanceDealIVo.getSufName(); this.sufDeptId = flowInstanceDealIVo.getSufDeptId(); this.sufDeptName = flowInstanceDealIVo.getSufDeptName(); } } public FlowInstanceDeal(String id, String stateId, String preId, String preName, String preDeptId, String preDeptName, String sufId, String sufName, String sufDeptId, String sufDeptName) { this.id = id; this.stateId = stateId; this.preId = preId; this.preName = preName; this.preDeptId = preDeptId; this.preDeptName = preDeptName; this.sufId = sufId; this.sufName = sufName; this.sufDeptId = sufDeptId; this.sufDeptName = sufDeptName; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getStateId() { return stateId; } public void setStateId(String stateId) { this.stateId = stateId; } public String getPreId() { return preId; } public void setPreId(String preId) { this.preId = preId; } public String getPreName() { return preName; } public void setPreName(String preName) { this.preName = preName; } public String getPreDeptId() { return preDeptId; } public void setPreDeptId(String preDeptId) { this.preDeptId = preDeptId; } public String getPreDeptName() { return preDeptName; } public void setPreDeptName(String preDeptName) { this.preDeptName = preDeptName; } public String getSufId() { return sufId; } public void setSufId(String sufId) { this.sufId = sufId; } public String getSufName() { return sufName; } public void setSufName(String sufName) { this.sufName = sufName; } public String getSufDeptId() { return sufDeptId; } public void setSufDeptId(String sufDeptId) { this.sufDeptId = sufDeptId; } public String getSufDeptName() { return sufDeptName; } public void setSufDeptName(String sufDeptName) { this.sufDeptName = sufDeptName; } public String getFlowId() { return flowId; } public void setFlowId(String flowId) { this.flowId = flowId; } public String getPreRouteId() { return preRouteId; } public void setPreRouteId(String preRouteId) { this.preRouteId = preRouteId; } public String getPreRouteName() { return preRouteName; } public void setPreRouteName(String preRouteName) { this.preRouteName = preRouteName; } public String getPreNodeId() { return preNodeId; } public void setPreNodeId(String preNodeId) { this.preNodeId = preNodeId; } public String getPreNodeName() { return preNodeName; } public void setPreNodeName(String preNodeName) { this.preNodeName = preNodeName; } public String getPreNodeType() { return preNodeType; } public void setPreNodeType(String preNodeType) { this.preNodeType = preNodeType; } public Integer getPreRouteIsBack() { return preRouteIsBack; } public void setPreRouteIsBack(Integer preRouteIsBack) { this.preRouteIsBack = preRouteIsBack; } public String getRouteDealType() { return routeDealType; } public void setRouteDealType(String routeDealType) { this.routeDealType = routeDealType; } public String getQuery() { return query; } public void setQuery(String query) { this.query = query; } public String getSufNodeId() { return sufNodeId; } public void setSufNodeId(String sufNodeId) { this.sufNodeId = sufNodeId; } public String getSufNodeName() { return sufNodeName; } public void setSufNodeName(String sufNodeName) { this.sufNodeName = sufNodeName; } public String getSufNodeType() { return sufNodeType; } public void setSufNodeType(String sufNodeType) { this.sufNodeType = sufNodeType; } public Date getuTime() { return uTime; } public void setuTime(Date uTime) { this.uTime = uTime; } }<file_sep>package com.allmsi.flow.exception; public class FlowException extends RuntimeException { private static final long serialVersionUID = 1L; private String exceptionCode; private String exceptionMessage; public FlowException() { } public FlowException(FlowExceptionEnums flowException) { this.exceptionCode = flowException.getExceptionCode(); this.exceptionMessage = flowException.getExceptionMessage(); } public String getExceptionCode() { return exceptionCode; } public void setExceptionCode(String exceptionCode) { this.exceptionCode = exceptionCode; } public String getExceptionMessage() { return exceptionMessage; } public void setExceptionMessage(String exceptionMessage) { this.exceptionMessage = exceptionMessage; } public String toString() { return "FlowException [exceptionCode=" + exceptionCode + ", exceptionMessage=" + exceptionMessage + "]"; } } <file_sep>package com.allmsi.flow.dao; public interface FlowMapper { String getFlowIdByCode(String flowCode); String getFlowCodeById(String flowId); }<file_sep>package com.allmsi.flow.service.impl; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.allmsi.flow.dao.FlowNodeReadDealQueryMapper; import com.allmsi.flow.service.FlowNodeReadDealQueryService; @Service public class FlowNodeReadDealQueryServiceImpl implements FlowNodeReadDealQueryService { @Resource private FlowNodeReadDealQueryMapper flowNodeReadDealQueryDao; @Override public List<String> listQuery(String id) { List<String> queryList = flowNodeReadDealQueryDao.queryList(id); List<String> list=new ArrayList<>(); if (queryList != null && queryList.size() > 0) { for(String queryStr:queryList) { list.add(queryStr.replace("\"","")); } } return list; } } <file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.allmsi.flow</groupId> <artifactId>im-flow-spring-boot</artifactId> <version>0.1.37</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.12.RELEASE</version> <relativePath /> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <mybatis.version>1.3.0</mybatis.version> <im-core-spring-boot.version>0.0.5</im-core-spring-boot.version> <im-auth-spring-boot.version>0.1.3</im-auth-spring-boot.version> </properties> <distributionManagement> <!-- <snapshotRepository> <id>user-snapshot</id> <name>User Porject Snapshot</name> <url>http://192.168.127.12:8081/nexus/content/repositories/snapshots/</url> <uniqueVersion>true</uniqueVersion> </snapshotRepository> --> <repository> <id>user-release</id> <name>User Porject Release</name> <url>http://192.168.127.12:8081/nexus/content/repositories/im/</url> </repository> </distributionManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <!-- 自动重启 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> <scope>compile</scope> </dependency> <!-- 分页插件pagehelper --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.0.0</version> </dependency> <dependency> <groupId>com.allmsi.sys</groupId> <artifactId>im-core-spring-boot</artifactId> <version>${im-core-spring-boot.version}</version> </dependency> <dependency> <groupId>com.allmsi.auth</groupId> <artifactId>im-auth-spring-boot</artifactId> <version>${im-auth-spring-boot.version}</version> </dependency> <!-- Json --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> </dependency> <!-- <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.15</version> </dependency> --> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <artifactId>maven-source-plugin</artifactId> <executions> <execution> <goals> <goal>jar</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project><file_sep>package com.allmsi.flow.service; public interface FlowOpinionEngine { public String insertOpinion(String userId, String opinion, String stateId); } <file_sep>package com.allmsi.flow.model.ovo; import java.util.ArrayList; import java.util.List; public class SubGuide { private String type; private String msg; private Object data; private boolean flag; private List<String> userIds = new ArrayList<String>(); private List<String> todoUserIds = new ArrayList<String>(); private List<String> toreadUserIds = new ArrayList<String>(); public SubGuide() { } public SubGuide(String type, String msg) { this(type, msg, false, null); } public SubGuide(String type, String msg, Object data) { this(type, msg, false, data); } public SubGuide(String type, String msg, boolean flag) { this(type, msg, flag, null); } public SubGuide(String type, String msg, boolean flag, Object data) { this.type = type; this.msg = msg; this.flag = flag; this.data = data; } public SubGuide(String type, String msg, boolean flag, Object data, List<String> userIds) { this.type = type; this.msg = msg; this.data = data; this.flag = flag; this.userIds = userIds; } public SubGuide(String type, String msg, boolean flag, Object data, List<String> userIds, List<String> todoUserIds, List<String> toreadUserIds) { this.type = type; this.msg = msg; this.data = data; this.flag = flag; this.userIds = userIds; this.todoUserIds = todoUserIds; this.toreadUserIds = toreadUserIds; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } public boolean isFlag() { return flag; } public void setFlag(boolean flag) { this.flag = flag; } public List<String> getUserIds() { return userIds; } public void setUserIds(List<String> userIds) { this.userIds = userIds; } public List<String> getTodoUserIds() { return todoUserIds; } public void setTodoUserIds(List<String> todoUserIds) { this.todoUserIds = todoUserIds; } public List<String> getToreadUserIds() { return toreadUserIds; } public void setToreadUserIds(List<String> toreadUserIds) { this.toreadUserIds = toreadUserIds; } @Override public String toString() { return "SubGuide [type=" + type + ", msg=" + msg + ", data=" + data + ", flag=" + flag + ", userIds=" + userIds + ", todoUserIds=" + todoUserIds + ", toreadUserIds=" + toreadUserIds + "]"; } } <file_sep>package com.allmsi.flow.model; import java.util.ArrayList; import java.util.List; public class AuthGuide { private List<String> stateIdList = new ArrayList<String>(); private List<String> userIds = new ArrayList<String>(); private List<String> todoUserIds = new ArrayList<String>(); private List<String> toreadUserIds = new ArrayList<String>(); public List<String> getStateIdList() { return stateIdList; } public void setStateIdList(List<String> stateIdList) { this.stateIdList = stateIdList; } public List<String> getUserIds() { return userIds; } public void setUserIds(List<String> userIds) { this.userIds = userIds; } public List<String> getTodoUserIds() { return todoUserIds; } public void setTodoUserIds(List<String> todoUserIds) { this.todoUserIds = todoUserIds; } public List<String> getToreadUserIds() { return toreadUserIds; } public void setToreadUserIds(List<String> toreadUserIds) { this.toreadUserIds = toreadUserIds; } @Override public String toString() { return "AuthGuide [stateIdList=" + stateIdList + ", userIds=" + userIds + ", todoUserIds=" + todoUserIds + ", toreadUserIds=" + toreadUserIds + "]"; } } <file_sep>package com.allmsi.flow.service.impl; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.allmsi.flow.dao.FlowNodeFieldMapper; import com.allmsi.flow.model.FlowField; import com.allmsi.flow.model.ovo.FlowNodeFieldOVO; import com.allmsi.flow.reflection.FlowUserServiceReflection; import com.allmsi.flow.service.FlowFieldService; import com.allmsi.flow.service.FlowNodeFieldAuthService; import com.allmsi.flow.service.FlowNodeFieldService; @Service public class FlowNodeFieldServiceImpl implements FlowNodeFieldService { @Resource private FlowNodeFieldMapper flowNodeFieldDao; @Resource private FlowFieldService flowFieldService; @Resource private FlowNodeFieldAuthService flowNodeFieldAuthService; @Resource private FlowUserServiceReflection flowUserServiceReflection; @Override public List<FlowNodeFieldOVO> listNodeField(String userId, String nodeId) { List<String> userList = flowUserServiceReflection.getFlowExternalService().getUserMap(userId); List<FlowNodeFieldOVO> list = new ArrayList<FlowNodeFieldOVO>(); List<FlowField> fieldList = flowFieldService.listFlowField(nodeId, userList); if (fieldList != null && fieldList.size() > 0) { for (FlowField flowField : fieldList) { list.add(new FlowNodeFieldOVO(flowField)); } } return list; } @Override public boolean deleteByPrimaryKey(String id) { int msg = flowNodeFieldDao.deleteByPrimaryKey(id); return (msg == 0) ? false : true; } } <file_sep>package com.allmsi.flow.model.ovo; import java.util.Date; import com.allmsi.flow.model.FlowInstanceState; public class FlowInstenceStateDoneInfoOVO { private String id; private String flowCode; private String instanceId; private String nodeId; private String routeId; // node private String nodeName; private String nodeType; // route private String routeName; private Integer isRecall; // flow private String objectId; private String sufId; private String sufName; private String sufDeptId; private String sufDeptName; private Date uTime; private String code; public FlowInstenceStateDoneInfoOVO() { } public FlowInstenceStateDoneInfoOVO(FlowInstanceState flowInstanceState) { if (flowInstanceState != null) { this.id=flowInstanceState.getId(); this.flowCode = flowInstanceState.getFlowCode(); this.instanceId = flowInstanceState.getInstanceId(); this.objectId = flowInstanceState.getObjectId(); this.nodeId = flowInstanceState.getNodeId(); this.nodeName = flowInstanceState.getNodeName(); this.nodeType = flowInstanceState.getNodeType(); this.routeId = flowInstanceState.getRouteId(); this.routeName = flowInstanceState.getRouteName(); this.sufId = flowInstanceState.getSufId(); this.sufName = flowInstanceState.getSufName(); this.sufDeptId = flowInstanceState.getSufDeptId(); this.sufDeptName = flowInstanceState.getSufDeptName(); this.uTime = flowInstanceState.getuTime(); this.isRecall = flowInstanceState.getIsRecall(); this.code = flowInstanceState.getCode(); } } public String getFlowCode() { return flowCode; } public void setFlowCode(String flowCode) { this.flowCode = flowCode; } public String getInstanceId() { return instanceId; } public void setInstanceId(String instanceId) { this.instanceId = instanceId; } public String getNodeId() { return nodeId; } public void setNodeId(String nodeId) { this.nodeId = nodeId; } public String getRouteId() { return routeId; } public void setRouteId(String routeId) { this.routeId = routeId; } public String getNodeName() { return nodeName; } public void setNodeName(String nodeName) { this.nodeName = nodeName; } public String getNodeType() { return nodeType; } public void setNodeType(String nodeType) { this.nodeType = nodeType; } public String getRouteName() { return routeName; } public void setRouteName(String routeName) { this.routeName = routeName; } public String getObjectId() { return objectId; } public void setObjectId(String objectId) { this.objectId = objectId; } public String getSufId() { return sufId; } public void setSufId(String sufId) { this.sufId = sufId; } public String getSufName() { return sufName; } public void setSufName(String sufName) { this.sufName = sufName; } public String getSufDeptId() { return sufDeptId; } public void setSufDeptId(String sufDeptId) { this.sufDeptId = sufDeptId; } public String getSufDeptName() { return sufDeptName; } public void setSufDeptName(String sufDeptName) { this.sufDeptName = sufDeptName; } public Date getuTime() { return uTime; } public void setuTime(Date uTime) { this.uTime = uTime; } public Integer getIsRecall() { return isRecall; } public void setIsRecall(Integer isRecall) { this.isRecall = isRecall; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } } <file_sep>package com.allmsi.flow.service; import java.util.List; import com.allmsi.flow.model.external.FlowUserModel; import com.allmsi.flow.model.ivo.NodeDealIVO; import com.allmsi.flow.model.ovo.BusGuide; import com.allmsi.flow.model.ovo.FlowInstenceCurrencyOVO; import com.allmsi.flow.model.ovo.SubGuide; public interface OperationBusService { BusGuide guide(String flowCode, String instanceId, String nodeId, String isback, String routeId, String query, String userId); SubGuide submit(String preDealId, FlowInstenceCurrencyOVO flowInfoVo, List<NodeDealIVO> nodeDealList); SubGuide isRecall(String preDealId, String instanceId); BusGuide vote(String instanceId, String nodeId, String userId, String voteState, String opinion, String query); List<FlowUserModel> transfer(String userId, String nodeId); } <file_sep>package com.allmsi.flow.service.impl; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.allmsi.flow.dao.FlowNodeButtonMapper; import com.allmsi.flow.model.FlowNodeButton; import com.allmsi.flow.model.ovo.FlowNodeButtonSimpleOVO; import com.allmsi.flow.service.FlowNodeButtonService; @Service public class FlowNodeButtonServiceImpl implements FlowNodeButtonService { @Resource private FlowNodeButtonMapper flowNodeButtonDao; @Override public List<FlowNodeButtonSimpleOVO> listNodeButtons(String nodeId) { List<FlowNodeButtonSimpleOVO> flowNodeButtonVList = new ArrayList<FlowNodeButtonSimpleOVO>(); List<FlowNodeButton> flowNodeButtonPList = flowNodeButtonDao.listFlowNodeButton(nodeId); for (FlowNodeButton flowNodeButton : flowNodeButtonPList) { flowNodeButtonVList.add(new FlowNodeButtonSimpleOVO(flowNodeButton.getButtonName(), flowNodeButton.getButtonType(), flowNodeButton.getSort())); } return flowNodeButtonVList; } } <file_sep>package com.allmsi.flow.third.service; import java.util.Map; public interface FlowExternalBeforeNodeService { // List<FlowUserModel> getEndOfCCDealUser(String flowCode,String objId); Map<String, Object> flowBeforeNode(String type, String typeId,String flowCode, String moduleId); } <file_sep>package com.allmsi.flow.exception; public enum FlowExceptionEnums implements IExceptionCode { /** 对象为空 */ NULL_OBJ("A11002", "对象为空"), /** 参数错误 */ ERROR_PARAME("A11002", "参数错误"); //参数不合法 A10001开始 private String exceptionCode; private String exceptionMessage; private FlowExceptionEnums(String exceptionCode, String exceptionMessage) { this.exceptionCode = exceptionCode; this.exceptionMessage = exceptionMessage; } public String getExceptionCode() { return exceptionCode; } public String getExceptionMessage() { return exceptionMessage; } public void setExceptionCode(String exceptionCode) { this.exceptionCode = exceptionCode; } public void setExceptionMessage(String exceptionMessage) { this.exceptionMessage = exceptionMessage; } } <file_sep>package com.allmsi.flow.service.impl; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.allmsi.flow.dao.FlowInstanceLogMapper; import com.allmsi.flow.dao.FlowInstanceStateMapper; import com.allmsi.flow.model.FlowInstanceLog; import com.allmsi.flow.model.FlowInstanceState; import com.allmsi.flow.model.external.FlowUserModel; import com.allmsi.flow.model.ovo.FlowStateLogOVO; import com.allmsi.flow.reflection.FlowUserServiceReflection; import com.allmsi.flow.service.FlowInstenceLogEngine; import com.allmsi.flow.util.LogStatusUtil; import com.allmsi.flow.util.NodeTypeUtil; import com.allmsi.sys.util.StrUtil; import com.github.pagehelper.PageInfo; @Service public class FlowInstenceLogEngineImpl implements FlowInstenceLogEngine { @Resource private FlowInstanceLogMapper flowInstanceLogDao; @Resource private FlowInstanceStateMapper flowInstanceStateDao; @Resource private FlowUserServiceReflection flowUserServiceReflection; @Override public String insertFlowInstenceLog(FlowInstanceState fs, String remark, String dealState) { FlowInstanceLog fil = new FlowInstanceLog(fs); fil.setRemark(remark); fil.setDealState(dealState); int msg = flowInstanceLogDao.insertSelective(fil);// 添加已办 Integer isProxy = fs.getIsProxy(); if (isProxy != null && 1 == isProxy) {// 代理办理 String proxyId = fs.getProxyId();// 被代理的人 // 删除待办表中的被代理人信息 FlowInstanceState fs1 = new FlowInstanceState(); fs1.setInstanceId(fs.getInstanceId()); fs1.setNodeId(fs.getNodeId()); fs1.setRouteId(fs.getRouteId()); fs1.setPreDealId(fs.getPreDealId()); fs1.setSufDealId(proxyId); fs1.setSufDealType("01"); flowInstanceStateDao.deleteBantchByFis(fs1); } else {// 授权人 FlowInstanceState fs1 = new FlowInstanceState(); fs1.setInstanceId(fs.getInstanceId()); fs1.setNodeId(fs.getNodeId()); fs1.setRouteId(fs.getRouteId()); fs1.setPreDealId(fs.getPreDealId()); fs1.setProxyId(fs.getSufDealId()); fs1.setSufAuthType(fs.getSufAuthType()); flowInstanceStateDao.deleteBantchByFis(fs1); } return (msg == 0) ? "" : fil.getId(); } @Override public String insertFlowInstenceLog(FlowInstanceLog record) { int msg = flowInstanceLogDao.insertSelective(record); return (msg == 0) ? "" : record.getId(); } @Override public FlowInstanceLog getDoneInfo(String instanceId, String nodeId, String sufDealId) { Map<String, String> map = new HashMap<String, String>(); map.put("instanceId", instanceId); map.put("nodeId", nodeId); map.put("sufDealId", sufDealId); FlowInstanceLog flowInstanceLog = flowInstanceLogDao.getDoneInfo(map); return flowInstanceLog; } @Override public boolean insertBantch(List<FlowInstanceLog> list) { int msg = 0; if (list != null && list.size() > 0) {// 添加principal_log msg = flowInstanceLogDao.insertBantch(list); } return (msg == 0) ? false : true; } @Override public List<FlowStateLogOVO> listFlowLog(String instanceId) { List<FlowStateLogOVO> logList = new ArrayList<FlowStateLogOVO>(); List<FlowInstanceLog> list = flowInstanceLogDao.listInstenceStateLog(instanceId); PageInfo<FlowInstanceLog> pageInfo = new PageInfo<FlowInstanceLog>(list); int total = (int) pageInfo.getTotal(); int agreeCount = 0; int disAgreeCount = 0; int editCount = 1; if (list != null && list.size() > 0) { FlowStateLogOVO indexVote = null; // 开始节点 FlowInstanceLog flowInstanceLog = list.get(0); FlowStateLogOVO vo = new FlowStateLogOVO(flowInstanceLog); String startNodeId = vo.getNodeId(); vo.setDealState(LogStatusUtil.START); vo.setDealStateName(LogStatusUtil.START_MSG); logList.add(vo); for (int i = 1; i < total; i++) { FlowInstanceLog fil = list.get(i); String nodeId = fil.getNodeId(); String nodeType = fil.getNodeType(); String dealState = fil.getDealState(); if (NodeTypeUtil.MULTI_PERSON_VOTE_WHOLE.equals(nodeType)) {// 多人完全投票 indexVote = new FlowStateLogOVO(fil); indexVote.setSufDealName(""); if (LogStatusUtil.AGREE.equals(dealState)) { agreeCount += 1; } else if (LogStatusUtil.DISAGREE.equals(dealState)) { disAgreeCount += 1; } if (i == total - 1) {// 投票中 indexVote.setDealState(LogStatusUtil.VOTE_DOING); indexVote.setDealStateName(LogStatusUtil.VOTE_DOING_MSG); logList.add(indexVote); agreeCount = 0; disAgreeCount = 0; } } else { FlowStateLogOVO index = new FlowStateLogOVO(fil); if (startNodeId.equals(nodeId)) {// 修改 index.setDealState(LogStatusUtil.CHANGE); index.setDealStateName(LogStatusUtil.CHANGE_MSG.replace("n", String.valueOf(editCount))); editCount = editCount + 1; } else { if (StrUtil.notEmpty(dealState)) { switch (dealState) { case LogStatusUtil.AGREE:// 同意 index.setDealStateName(LogStatusUtil.AGREE_MSG); break; case LogStatusUtil.DISAGREE:// 拒绝 index.setDealStateName(LogStatusUtil.DISAGREE_MSG); break; case LogStatusUtil.TRANSFER:// 转交 index.setDealStateName(LogStatusUtil.TRANSFER_MSG); break; case LogStatusUtil.RECAL:// 撤回 index.setDealStateName(LogStatusUtil.RECAL_MSG); break; case LogStatusUtil.DOING:// 审核中 index.setDealStateName(LogStatusUtil.DOING_MSG); break; case LogStatusUtil.END:// 结束 index.setDealStateName(LogStatusUtil.END_MSG); break; default: index.setDealStateName(LogStatusUtil.OTHER_MSG); break; } } } if (indexVote != null) { indexVote.setSufDealName(""); indexVote.setOpinion(""); if (agreeCount > disAgreeCount) {// 投票通过 indexVote.setDealState(LogStatusUtil.VOTE_PASS); indexVote.setDealStateName(LogStatusUtil.VOTE_PASS_MSG); logList.add(indexVote); } else {// 投票不通过 indexVote.setDealState(LogStatusUtil.VOTE_REFUSE); indexVote.setDealStateName(LogStatusUtil.VOTE_REFUSE_MSG); logList.add(indexVote); } agreeCount = 0; disAgreeCount = 0; indexVote = null; } logList.add(index); } } } return logList; } @Override public List<String> listVote(String instanceId, String nodeId) { if (StrUtil.isEmpty(instanceId) || StrUtil.isEmpty(nodeId)) { return null; } Map<String, String> map = new HashMap<>(); map.put("instanceId", instanceId); map.put("nodeId", nodeId); List<String> list = flowInstanceLogDao.listVoteDealState(map); if (list != null && list.size() > 0) { return list; } return null; } @Override public boolean updateDealState(String instanceId, String nodeId, String sufDealId, String dealState) { if (StrUtil.isEmpty(instanceId) || StrUtil.isEmpty(nodeId) || StrUtil.isEmpty(dealState)) { return false; } Map<String, String> map = new HashMap<>(); map.put("instanceId", instanceId); map.put("nodeId", nodeId); map.put("sufDealId", sufDealId); map.put("dealState", dealState); int msg = flowInstanceLogDao.updateDeatState(map); return (msg == 0) ? false : true; } @Override public List<FlowStateLogOVO> listVote(String id) { if (StrUtil.isEmpty(id)) { return null; } List<FlowStateLogOVO> list = new ArrayList<FlowStateLogOVO>(); List<FlowInstanceLog> flowInstanceLogList = flowInstanceLogDao.listVote(id); if (flowInstanceLogList != null && flowInstanceLogList.size() > 0) { List<String> userIds = new ArrayList<String>(); Map<String, FlowInstanceLog> mapLog = new HashMap<String, FlowInstanceLog>(); for (FlowInstanceLog flowInstanceLog : flowInstanceLogList) { userIds.add(flowInstanceLog.getSufDealId()); mapLog.put(flowInstanceLog.getSufDealId(), flowInstanceLog); } if (userIds != null && userIds.size() > 0) { List<FlowUserModel> fums = flowUserServiceReflection.getFlowExternalService().FlowUserInfoList(userIds); if (fums != null && fums.size() > 0) { for (FlowUserModel flowUserModel : fums) { String sufDealName = flowUserModel.getName(); String key = flowUserModel.getUserId(); FlowInstanceLog flowInstanceLog = mapLog.get(key); String dealState = flowInstanceLog.getDealState(); String dealStateName = ""; if (StrUtil.notEmpty(dealState)) { switch (dealState) { case LogStatusUtil.AGREE:// 同意 dealStateName = LogStatusUtil.AGREE_MSG; break; case LogStatusUtil.DISAGREE:// 拒绝 dealStateName = "不同意"; break; default: break; } } list.add(new FlowStateLogOVO(flowInstanceLog.getInstanceId(), flowInstanceLog.getId(), sufDealName, dealState, dealStateName, flowInstanceLog.getDealTime(), flowInstanceLog.getOpinion(), flowInstanceLog.getNodeId())); } } } } return list; } } <file_sep>package com.allmsi.flow.dao; import java.util.List; import java.util.Map; import com.allmsi.flow.model.TransferInterim; public interface TransferInterimMapper { public int insertSelective(TransferInterim record); public int deleteByParemerKey(Map<String,Object> map); public List<TransferInterim> listByPrincipal(Map<String,Object> map); } <file_sep>package com.allmsi.flow.service.impl; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.allmsi.flow.dao.ModuleAuthMapper; import com.allmsi.flow.model.FlowModuleAuth; import com.allmsi.flow.model.external.FlowUserModel; import com.allmsi.flow.reflection.FlowUserServiceReflection; import com.allmsi.flow.service.ModuleAuthService; import com.allmsi.sys.util.StrUtil; @Service public class ModuleAuthServiceImpl implements ModuleAuthService { @Resource private ModuleAuthMapper moduleAuthDao; @Resource private FlowUserServiceReflection flowUserServiceReflection; @Override public List<FlowUserModel> listModuleAuth(String flowId) { if (StrUtil.isEmpty(flowId)) { return null; } List<FlowUserModel> moduleAuthList = new ArrayList<>(); List<FlowModuleAuth> authList = moduleAuthDao.listModuleAuth(flowId); if (authList != null && authList.size() > 0) { for (FlowModuleAuth flowModuleAuth : authList) { String authId = flowModuleAuth.getAuthId(); String authType = flowModuleAuth.getAuthType(); Set<String> userids = new HashSet<String>(); if (StrUtil.notEmpty(authType)) { switch (authType) { case "01":// 查询用户 FlowUserModel u = flowUserServiceReflection.getFlowExternalService().selectUserInfo(authId); if (u != null) { userids.add(u.getUserId()); moduleAuthList.add(u); } break; case "02":// 查询部门 List<FlowUserModel> dl = flowUserServiceReflection.getFlowExternalService() .selectUserByDeptId(authId); if (dl != null && dl.size() > 0) { for (FlowUserModel flowUserModel : dl) { if (!userids.contains(flowUserModel.getUserId())) { userids.add(flowUserModel.getUserId()); moduleAuthList.add(flowUserModel); } } } break; case "03":// 查询角色 List<FlowUserModel> rl = flowUserServiceReflection.getFlowExternalService() .selectUserByRoleId(authId); if (rl != null && rl.size() > 0) { for (FlowUserModel flowUserModel : rl) { if (!userids.contains(flowUserModel.getUserId())) { userids.add(flowUserModel.getUserId()); moduleAuthList.add(flowUserModel); } } } break; } } } } return moduleAuthList; } @Override public boolean isAdmin(String flowId, String userId) { if (StrUtil.isEmpty(userId)) { return false; } List<FlowUserModel> moduleAuthList = listModuleAuth(flowId); if (moduleAuthList != null && moduleAuthList.size() > 0) { for (FlowUserModel flowUserModel : moduleAuthList) { if (userId.equals(flowUserModel.getUserId())) { return true; } } } return false; } } <file_sep>package com.allmsi.flow.service; import java.util.List; import com.allmsi.flow.model.FlowInstanceState; import com.allmsi.flow.model.ivo.FlowInstanceDealIVO; import com.allmsi.flow.model.ivo.FlowInstanceStateIVO; import com.allmsi.flow.model.ivo.NodeDealIVO; import com.allmsi.flow.model.ovo.FlowInstenceCurrencyOVO; import com.allmsi.flow.model.ovo.FlowInstenceStateDoneInfoOVO; public interface FlowInstenceStateEngine { public String insertFlowInstanceState(FlowInstanceStateIVO flowInstanceStateIVo); public List<String> insertFlowInstanceStateForNodeDealList(String instanceId, String nodeId, String routeId, String preDealId, List<NodeDealIVO> nodeDealList); public String insertFlowInstenceDeal(FlowInstanceDealIVO flowInstanceDealIVo); public boolean deleteBantchForInstanceAndNodeId(String instanceId, String nodeId, String sufAuthType); public boolean deleteBantchByInstenceId(String instanceId); public FlowInstanceState getInstenceStateNow(String instanceId, String nodeId, String sufDealId, String sufAuthType); public FlowInstanceState getInstenceStateNow(FlowInstanceState flowInstanceState); public boolean deleteInstenceNow(String id); public List<FlowInstanceState> listByFis(String instanceId, String nodeId, String sufAuthType); public boolean isRecall(String instanceId, String preDealId); public boolean recall(String preDealId, String instanceId); public boolean updateAuthType(String instanceId, String nodeId, String sufAuthType); public boolean updateRead(String instanceId, String userId); public int sCount(String userId); FlowInstenceCurrencyOVO getTodoInfo(String objId, String authType, String userId,String flowCode); FlowInstenceStateDoneInfoOVO getDoneInfo(String objId,String preDealId); } <file_sep>package com.allmsi.flow.service; import com.allmsi.flow.model.FlowFieldType; public interface FlowFieldTypeService { FlowFieldType getFlowFieldType(String id); boolean deleteByPrimaryKey(String id); } <file_sep>package com.allmsi.flow.model; public class FlowRouteDealQuery { private String id; private String routeDealId; private String queryName; private String queryValue; private String queryGroup; private Byte del; public String getId() { return id; } public void setId(String id) { this.id = id == null ? null : id.trim(); } public String getRouteDealId() { return routeDealId; } public void setRouteDealId(String routeDealId) { this.routeDealId = routeDealId == null ? null : routeDealId.trim(); } public String getQueryName() { return queryName; } public void setQueryName(String queryName) { this.queryName = queryName == null ? null : queryName.trim(); } public String getQueryValue() { return queryValue; } public void setQueryValue(String queryValue) { this.queryValue = queryValue == null ? null : queryValue.trim(); } public String getQueryGroup() { return queryGroup; } public void setQueryGroup(String queryGroup) { this.queryGroup = queryGroup == null ? null : queryGroup.trim(); } public Byte getDel() { return del; } public void setDel(Byte del) { this.del = del; } }<file_sep>package com.allmsi.flow.service.impl; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.allmsi.flow.dao.TransferForeverMapper; import com.allmsi.flow.model.TransferForever; import com.allmsi.flow.model.ivo.TransferForeverIVO; import com.allmsi.flow.service.TransferForeverService; @Service public class TransferForeverServiceImpl implements TransferForeverService { @Resource private TransferForeverMapper transferForeverDao; @Override public boolean insertSelective(TransferForeverIVO record) { int count = 0; if (record != null) { count = transferForeverDao.insertSelective(new TransferForever(record)); } return (count == 0) ? false : true; } @Override public List<TransferForever> listAgentsForPrincipal(Map<String, Object> map) { return transferForeverDao.listPrincipal(map); } @Override public List<String> listtPrincipalByAgent(Map<String, Object> map) { // TODO Auto-generated method stub return null; } } <file_sep>package com.allmsi.flow.model; public class FlowFieldProperty { private String id; private String propertyName; private Byte del; public String getId() { return id; } public void setId(String id) { this.id = id == null ? null : id.trim(); } public String getPropertyName() { return propertyName; } public void setPropertyName(String propertyName) { this.propertyName = propertyName == null ? null : propertyName.trim(); } public Byte getDel() { return del; } public void setDel(Byte del) { this.del = del; } @Override public String toString() { return "FlowFieldProperty [id=" + id + ", propertyName=" + propertyName + ", del=" + del + "]"; } }<file_sep># im-flow-spring-boot <file_sep>package com.allmsi.flow.dao; import java.util.List; import com.allmsi.flow.model.FlowNodeFieldAuth; public interface FlowNodeFieldAuthMapper { int deleteByPrimaryKey(String id); FlowNodeFieldAuth selectByPrimaryKey(String id); List<FlowNodeFieldAuth> listNodeFieldAuth(String id); }<file_sep>package com.allmsi.flow.model.ovo; import java.util.Date; import java.util.List; import com.allmsi.flow.model.FlowInstanceState; public class FlowInstenceCurrencyOVO { private String id; private String stateId; private String instanceId; private String preNodeId; private String sufNodeId; private String routeId; private String preDealId; private String sufDealId; private String sufDealType; private String sufAuthType; private String sufName; private String sufDeptId; private String sufDeptName; private Date uTime; private String uUserId; // node private String preNodeName; private String preNodeType; // route private String routeName; private Integer isBack; private Integer isRecall; // flow private String flowId; private String flowCode; private String objectId; private String sufDealName; private String remark; private String opinion; private String dealState; // private String code; // button private List<FlowNodeButtonSimpleOVO> nodeButtonList; // field private List<FlowNodeFieldOVO> nodeFieldList; public FlowInstenceCurrencyOVO() { } public FlowInstenceCurrencyOVO(FlowInstanceState flowInstanceState) { if (flowInstanceState != null) { this.id = flowInstanceState.getId(); this.stateId = flowInstanceState.getStateId(); this.instanceId = flowInstanceState.getInstanceId(); this.preNodeId = flowInstanceState.getNodeId(); this.routeId = flowInstanceState.getRouteId(); this.preDealId = flowInstanceState.getPreDealId(); this.sufDealId = flowInstanceState.getSufDealId(); this.sufDealType = flowInstanceState.getSufDealType(); this.sufAuthType = flowInstanceState.getSufAuthType(); this.sufDealName = flowInstanceState.getSufName(); this.sufDeptId = flowInstanceState.getSufDeptId(); this.sufDeptName = flowInstanceState.getSufDeptName(); this.uTime = flowInstanceState.getuTime(); this.uUserId = flowInstanceState.getuUserId(); this.opinion = flowInstanceState.getOpinion(); this.preNodeName = flowInstanceState.getNodeName(); this.preNodeType = flowInstanceState.getNodeType(); this.routeName = flowInstanceState.getRouteName(); this.isBack = flowInstanceState.getIsBack(); this.isRecall = flowInstanceState.getIsRecall(); this.flowId = flowInstanceState.getFlowId(); this.flowCode = flowInstanceState.getFlowCode(); this.objectId = flowInstanceState.getObjectId(); this.code = flowInstanceState.getCode(); } } public FlowInstenceCurrencyOVO(FlowInstenceStateDoneInfoOVO flowInfo) { if (flowInfo != null) { this.id = flowInfo.getId(); this.instanceId = flowInfo.getInstanceId(); this.sufNodeId = flowInfo.getNodeId(); this.sufDealId = flowInfo.getSufId(); this.routeId = flowInfo.getRouteId(); this.preNodeName = flowInfo.getNodeName(); this.preNodeType = flowInfo.getNodeType(); this.routeName = flowInfo.getRouteName(); this.flowCode = flowInfo.getFlowCode(); this.objectId = flowInfo.getObjectId(); this.sufDealName = flowInfo.getSufName(); this.uTime = flowInfo.getuTime(); this.isRecall = flowInfo.getIsRecall(); } } public FlowInstenceCurrencyOVO(String id, String flowId, String instanceId, String preNodeId, String sufNodeId, String routeId, String opinion, String dealState, String objectId) { this.id = id; this.instanceId = instanceId; this.preNodeId = preNodeId; this.sufNodeId = sufNodeId; this.routeId = routeId; this.flowId = flowId; this.objectId = objectId; this.opinion = opinion; this.dealState = dealState; } public String getStateId() { return stateId; } public void setStateId(String stateId) { this.stateId = stateId; } public String getInstanceId() { return instanceId; } public void setInstanceId(String instanceId) { this.instanceId = instanceId; } public String getPreNodeId() { return preNodeId; } public void setPreNodeId(String preNodeId) { this.preNodeId = preNodeId; } public String getSufNodeId() { return sufNodeId; } public void setSufNodeId(String sufNodeId) { this.sufNodeId = sufNodeId; } public String getRouteId() { return routeId; } public void setRouteId(String routeId) { this.routeId = routeId; } public String getPreDealId() { return preDealId; } public void setPreDealId(String preDealId) { this.preDealId = preDealId; } public String getSufDealId() { return sufDealId; } public void setSufDealId(String sufDealId) { this.sufDealId = sufDealId; } public String getSufDealType() { return sufDealType; } public void setSufDealType(String sufDealType) { this.sufDealType = sufDealType; } public String getSufAuthType() { return sufAuthType; } public void setSufAuthType(String sufAuthType) { this.sufAuthType = sufAuthType; } public Date getuTime() { return uTime; } public void setuTime(Date uTime) { this.uTime = uTime; } public String getuUserId() { return uUserId; } public void setuUserId(String uUserId) { this.uUserId = uUserId; } public String getPreNodeName() { return preNodeName; } public void setPreNodeName(String preNodeName) { this.preNodeName = preNodeName; } public String getPreNodeType() { return preNodeType; } public void setPreNodeType(String preNodeType) { this.preNodeType = preNodeType; } public String getRouteName() { return routeName; } public void setRouteName(String routeName) { this.routeName = routeName; } public String getFlowId() { return flowId; } public void setFlowId(String flowId) { this.flowId = flowId; } public String getFlowCode() { return flowCode; } public void setFlowCode(String flowCode) { this.flowCode = flowCode; } public String getObjectId() { return objectId; } public void setObjectId(String objectId) { this.objectId = objectId; } public List<FlowNodeButtonSimpleOVO> getNodeButtonList() { return nodeButtonList; } public void setNodeButtonList(List<FlowNodeButtonSimpleOVO> nodeButtonList) { this.nodeButtonList = nodeButtonList; } public Integer getIsBack() { return isBack; } public void setIsBack(Integer isBack) { this.isBack = isBack; } public String getSufDealName() { return sufDealName; } public void setSufDealName(String sufDealName) { this.sufDealName = sufDealName; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getOpinion() { return opinion; } public void setOpinion(String opinion) { this.opinion = opinion; } public String getDealState() { return dealState; } public void setDealState(String dealState) { this.dealState = dealState; } public String getSufName() { return sufName; } public void setSufName(String sufName) { this.sufName = sufName; } public String getSufDeptId() { return sufDeptId; } public void setSufDeptId(String sufDeptId) { this.sufDeptId = sufDeptId; } public String getSufDeptName() { return sufDeptName; } public void setSufDeptName(String sufDeptName) { this.sufDeptName = sufDeptName; } public Integer getIsRecall() { return isRecall; } public void setIsRecall(Integer isRecall) { this.isRecall = isRecall; } public List<FlowNodeFieldOVO> getNodeFieldList() { return nodeFieldList; } public void setNodeFieldList(List<FlowNodeFieldOVO> nodeFieldList) { this.nodeFieldList = nodeFieldList; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } @Override public String toString() { return "FlowInstenceCurrencyOVo [id=" + id + ", stateId=" + stateId + ", instanceId=" + instanceId + ", preNodeId=" + preNodeId + ", sufNodeId=" + sufNodeId + ", routeId=" + routeId + ", preDealId=" + preDealId + ", sufDealId=" + sufDealId + ", sufDealType=" + sufDealType + ", sufAuthType=" + sufAuthType + ", sufName=" + sufName + ", sufDeptId=" + sufDeptId + ", sufDeptName=" + sufDeptName + ", uTime=" + uTime + ", uUserId=" + uUserId + ", preNodeName=" + preNodeName + ", preNodeType=" + preNodeType + ", routeName=" + routeName + ", isBack=" + isBack + ", isRecall=" + isRecall + ", flowId=" + flowId + ", flowCode=" + flowCode + ", objectId=" + objectId + ", sufDealName=" + sufDealName + ", remark=" + remark + ", opinion=" + opinion + ", dealState=" + dealState + ", nodeButtonList=" + nodeButtonList + ", nodeFieldList=" + nodeFieldList + "]"; } } <file_sep>package com.allmsi.flow.dao; import com.allmsi.flow.model.FlowInstanceOpinion; public interface FlowInstanceOpinionMapper { FlowInstanceOpinion getByInstanceLogId(String instanceLogId); int insertSelective(FlowInstanceOpinion record); int deleteByPrimaryKey(String id); int deleteByInstenceLogId(String instanceLogId); }<file_sep>package com.allmsi.flow.third.service.impl; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.allmsi.auth.model.vo.DeptVo; import com.allmsi.auth.model.vo.RoleVo; import com.allmsi.auth.model.vo.UserDeptVo; import com.allmsi.auth.model.vo.UserInfoVo; import com.allmsi.auth.model.vo.UserRoleVo; import com.allmsi.auth.service.DeptService; import com.allmsi.auth.service.RoleService; import com.allmsi.auth.service.UserService; import com.allmsi.flow.model.external.FlowDealIdATypeModel; import com.allmsi.flow.model.external.FlowUserDeptVo; import com.allmsi.flow.model.external.FlowUserModel; import com.allmsi.flow.model.external.FlowUserRoleVo; import com.allmsi.flow.third.service.FlowExternalUserService; import com.allmsi.sys.model.ListBean; import com.allmsi.sys.util.StrUtil; @Service("defaultFlowExternalUserService") public class FlowExternalUserServiceImpl implements FlowExternalUserService { @Resource private UserService userService; @Resource private DeptService deptService; @Resource private RoleService roleService; @Override public FlowUserModel selectUserInfo(String nodeDealId) { return getUserInfo(nodeDealId).get(nodeDealId); } @Override public Map<String, FlowUserModel> getUserInfo(String id) { Map<String, FlowUserModel> map = new HashMap<String, FlowUserModel>(); if (StrUtil.isEmpty(id)) { return map; } UserInfoVo userInfoVo = userService.selectByPrimaryKey(id); map.put(id, new FlowUserModel(userInfoVo.getId(), userInfoVo.getUserName(), "01", userInfoVo.getSort(), userInfoVo.getDeptId(), userInfoVo.getDeptName())); return map; } public Map<String, FlowUserModel> getFlowUserInfoList(List<String> ids) { Map<String, FlowUserModel> map = new HashMap<String, FlowUserModel>(); if (ids != null && ids.size() > 0) { List<UserInfoVo> uList = userService.listUserInfo(ids); for (UserInfoVo userInfoVo : uList) { map.put(userInfoVo.getId(), new FlowUserModel(userInfoVo.getId(), userInfoVo.getUserName(), "01", userInfoVo.getSort(), userInfoVo.getDeptId(), userInfoVo.getDeptName())); } } return map; } @Override public List<FlowUserModel> FlowUserInfoList(List<String> userIds) { List<FlowUserModel> list = new ArrayList<FlowUserModel>(); if (userIds != null && userIds.size() > 0) { List<UserInfoVo> uList = userService.listUserInfo(userIds); for (UserInfoVo userInfoVo : uList) { list.add(new FlowUserModel(userInfoVo.getId(), userInfoVo.getUserName(), "01", userInfoVo.getSort(), userInfoVo.getDeptId(), userInfoVo.getDeptName())); } } return list; } public Map<String, String> getDealNameByDealIdAndType(List<FlowDealIdATypeModel> dealIdAndDealType) { Map<String, String> map = new HashMap<String, String>(); List<String> userList = new ArrayList<String>(); List<String> deptList = new ArrayList<String>(); List<String> roleList = new ArrayList<String>(); for (FlowDealIdATypeModel model : dealIdAndDealType) { if ("01".equals(model.getDealType())) { userList.add(model.getDealId()); } if ("02".equals(model.getDealType())) { deptList.add(model.getDealId()); } if ("03".equals(model.getDealType())) { roleList.add(model.getDealId()); } } // 批量查询用户 if (userList != null && userList.size() > 0) { Map<String, FlowUserModel> map1 = getFlowUserInfoList(userList); for (String key : map1.keySet()) { FlowUserModel value = map1.get(key); map.put(key, value.getName()); } } // 批量查询部门 if (deptList != null && deptList.size() > 0) { List<DeptVo> dList = deptService.listDeptList(deptList); for (DeptVo deptVo : dList) { map.put(deptVo.getId(), deptVo.getDeptName()); } } if (roleList != null && roleList.size() > 0) { // 批量查询角色 List<RoleVo> rList = roleService.listRoles(roleList); for (RoleVo roleVo : rList) { map.put(roleVo.getId(), roleVo.getRoleName()); } } return map; } public String getDealNameByDealIdAndType(String dealId, String dealType) { String dealName = null; if ("01".equals(dealType)) {// 查询用户信息 UserInfoVo userInfoVo = userService.selectByPrimaryKey(dealId); if (userInfoVo != null) { dealName = userInfoVo.getUserName(); } } if ("02".equals(dealType)) { DeptVo deptVo = deptService.selectByPrimaryKey(dealId); dealName = deptVo.getDeptName(); } if ("03".equals(dealType)) { RoleVo roleVo = roleService.selectByPrimaryKey(dealId); dealName = roleVo.getRoleName(); } return dealName; } public Map<String, List<String>> getUserAuthIdSort(String userId) { Map<String, List<String>> authMap = new HashMap<String, List<String>>(); // 查询用户的基本信息 UserInfoVo userInfoVo = userService.selectByPrimaryKey(userId); List<String> userList = new ArrayList<String>(); userList.add(userInfoVo.getId()); if (userList != null && userList.size() > 0) { authMap.put("01", userList); } // 查询用户部门信息 List<UserDeptVo> udVoList = deptService.listUserDeptVo(userId); List<String> udList = new ArrayList<String>(); if (udVoList != null && udVoList.size() > 0) { for (UserDeptVo userDeptVo : udVoList) { udList.add(userDeptVo.getDeptId()); } authMap.put("02", udList); } // 查询用户角色信息 List<UserRoleVo> uRInfoList = roleService.listUserRole(userId); List<String> urList = new ArrayList<String>(); if (uRInfoList != null && uRInfoList.size() > 0) { for (UserRoleVo userRoleVo : uRInfoList) { urList.add(userRoleVo.getRoleId()); } authMap.put("03", urList); } return authMap; } @Override public List<FlowUserDeptVo> selectUserDept(String userId) { if (StrUtil.isEmpty(userId)) { return null; } List<UserDeptVo> udList = deptService.listUserDeptVo(userId); List<FlowUserDeptVo> udInfoList = new ArrayList<FlowUserDeptVo>(); for (UserDeptVo userDeptVo : udList) { udInfoList.add(new FlowUserDeptVo(userDeptVo.getDeptId(), userDeptVo.getUdType(), userDeptVo.getDeptName(), userDeptVo.getDeptType())); } return udInfoList; } @Override public List<FlowUserRoleVo> selectUserRoleList(String userId) { if (StrUtil.isEmpty(userId)) { return null; } List<UserRoleVo> urJson = roleService.listUserRole(userId); List<FlowUserRoleVo> uRInfoList = new ArrayList<FlowUserRoleVo>(); for (UserRoleVo userRoleVo : urJson) { uRInfoList.add(new FlowUserRoleVo(userRoleVo.getRoleId(), userRoleVo.getRoleName())); } return uRInfoList; } @SuppressWarnings("unchecked") @Override public List<FlowUserModel> selectUserByDeptId(String deptId) { if (StrUtil.isEmpty(deptId)) { return null; } ListBean listBean = userService.listUserInfoByDeptId(deptId, 1, Integer.MAX_VALUE); List<UserInfoVo> userVoList = (List<UserInfoVo>) listBean.getList(); List<FlowUserModel> list = new ArrayList<FlowUserModel>(); for (UserInfoVo UserInfoVo : userVoList) { FlowUserModel flowUserModel = new FlowUserModel(); flowUserModel.setUserId(UserInfoVo.getId()); flowUserModel.setName(UserInfoVo.getUserName()); flowUserModel.setDeptId(deptId); flowUserModel.setDeptName(UserInfoVo.getDeptName()); list.add(flowUserModel); } return list; } @SuppressWarnings("unchecked") @Override public List<FlowUserModel> selectUserByRoleId(String roleId) { if (StrUtil.isEmpty(roleId)) { return null; } ListBean listBean = userService.listUserInfoByRoleId(roleId, 1, Integer.MAX_VALUE); List<UserInfoVo> userVoList = (List<UserInfoVo>) listBean.getList(); List<FlowUserModel> list = new ArrayList<FlowUserModel>(); for (UserInfoVo userInfoVo : userVoList) { list.add(new FlowUserModel(userInfoVo.getId(), userInfoVo.getUserName(), "01", userInfoVo.getDeptId(), userInfoVo.getDeptName())); } return list; } @Override public List<FlowUserModel> deptUserByUser(String userId) { if (StrUtil.isEmpty(userId)) { return null; } List<UserInfoVo> uList = userService.listDeptUsersByUserId(userId); List<FlowUserModel> list = new ArrayList<FlowUserModel>(); for (UserInfoVo userInfoVo : uList) { list.add(new FlowUserModel(userInfoVo.getId(), userInfoVo.getUserName(), "01", userInfoVo.getDeptId(), userInfoVo.getDeptName())); } return list; } // @Override public List<FlowUserModel> allDeptUserByUser(String userId) { if (StrUtil.isEmpty(userId)) { return null; } List<UserInfoVo> uList = userService.listParentsDeptUsersByUserId(userId); List<FlowUserModel> list = new ArrayList<FlowUserModel>(); for (UserInfoVo userInfoVo : uList) { list.add(new FlowUserModel(userInfoVo.getId(), userInfoVo.getUserName(), "01", userInfoVo.getDeptId(), userInfoVo.getDeptName())); } return list; } @SuppressWarnings("unchecked") @Override public List<FlowUserModel> selectUserList() { ListBean listBean = userService.getAllUser(1, Integer.MAX_VALUE); List<UserInfoVo> uList = (List<UserInfoVo>) listBean.getList(); List<FlowUserModel> list = new ArrayList<FlowUserModel>(); for (UserInfoVo userInfoVo : uList) { list.add(new FlowUserModel(userInfoVo.getId(), userInfoVo.getUserName(), "01", userInfoVo.getDeptId(), userInfoVo.getDeptName())); } return list; } @Override public List<String> getUserMap(String id) { List<String> userList = new ArrayList<>(); if (StrUtil.isEmpty(id)) { return userList; } userList.add(id); UserInfoVo userInfoVo = userService.selectByPrimaryKey(id); if (userInfoVo != null) { List<UserRoleVo> roleList = userInfoVo.getuRoleVoList(); if (roleList != null && roleList.size() > 0) { for (UserRoleVo userRoleVo : roleList) { String roleId = userRoleVo.getRoleId(); userList.add(roleId); } } List<UserDeptVo> deptList = userInfoVo.getuDeptVoList(); if (deptList != null && deptList.size() > 0) { for (UserDeptVo userDeptVo : deptList) { String deptId = userDeptVo.getDeptId(); userList.add(deptId); } } } return userList; } } <file_sep>package com.allmsi.flow.service.impl; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.TypeReference; import com.allmsi.flow.model.OperationMenu; import com.allmsi.flow.model.external.FlowUserModel; import com.allmsi.flow.model.ovo.BusGuide; import com.allmsi.flow.model.ovo.BusGuideRoute; import com.allmsi.flow.model.ovo.FlowInstanceOVO; import com.allmsi.flow.model.ovo.FlowRouteOVO; import com.allmsi.flow.reflection.FlowUserServiceReflection; import com.allmsi.flow.service.FlowInstenceEngine; import com.allmsi.flow.service.FlowInstenceStateEngine; import com.allmsi.flow.service.FlowRouteDealQueryService; import com.allmsi.flow.service.FlowRouteService; import com.allmsi.flow.service.NodeDealRuleEngine; import com.allmsi.flow.service.RouteDealRuleEngine; import com.allmsi.sys.util.StrUtil; @Service public class RouteDealRuleEngineImpl implements RouteDealRuleEngine { @Resource private FlowUserServiceReflection flowUserServiceReflection; @Resource private FlowRouteService flowRouteService; @Resource private FlowInstenceEngine flowInstenceEngine; @Resource private FlowInstenceStateEngine flowInstenceStateEngine; @Resource private FlowRouteDealQueryService flowRouteDealQueryService; @Resource private NodeDealRuleEngine nodeDealRuleEngine; @Override public List<FlowRouteOVO> guideRoute(String flowCode, String nodeId, String query, String userId) { List<FlowRouteOVO> list = new ArrayList<FlowRouteOVO>(); List<FlowRouteOVO> flowRouteOVoList = flowRouteService.listRouteListByPreNode(flowCode, nodeId);// 获取到路由列表信息 if (flowRouteOVoList != null && flowRouteOVoList.size() > 0) { for (FlowRouteOVO flowRouteOVo : flowRouteOVoList) { String id = flowRouteOVo.getDealId(); List<String> queryList = flowRouteDealQueryService.queryList(id); flowRouteOVo.setQueryList(queryList); list.add(flowRouteOVo); } } return list; } @Override public BusGuideRoute ruleJudgment(List<FlowRouteOVO> frList, String instanceId, String userId, String nodeId, String query) { BusGuideRoute busGuideRoute = new BusGuideRoute(); List<FlowRouteOVO> selectedRouteList = frList; if (StrUtil.isEmpty(query)) { String strQuery = getQueryRule(frList);// 判断是否有查询条件 if (StrUtil.isEmpty(strQuery)) {// 不需要查询条件 busGuideRoute.setType(OperationMenu.ROUTE); busGuideRoute.setFlowRouteList(selectedRouteList); return busGuideRoute;// 多条路由 } else {// 需要查询条件 if (StrUtil.isEmpty(query)) {// 如果没有传入query busGuideRoute.setType(OperationMenu.QUERY); busGuideRoute.setMsg(strQuery); return busGuideRoute;// 返回给mis } } } selectedRouteList = queryRuleJudgment(frList, query); if (selectedRouteList == null || selectedRouteList.size() == 0) {// 没有查询到路由返回错误 busGuideRoute.setType(OperationMenu.ROUTE); busGuideRoute.setFlowRouteList(frList); } if (selectedRouteList.size() > 0) { busGuideRoute.setType(OperationMenu.ROUTE); busGuideRoute.setFlowRouteList(selectedRouteList); } return busGuideRoute; } private String getQueryRule(List<FlowRouteOVO> frList) { Set<String> keysList = new HashSet<String>(); for (FlowRouteOVO fr : frList) { List<String> queryList = fr.getQueryList(); if (queryList != null && queryList.size() > 0) { for (String queryStr : queryList) { keysList.addAll(getQueryParmKey(queryStr)); } } } String param = ""; for (String string : keysList) { param += string + ";"; } if (param.endsWith(";")) { param = param.substring(0, param.length() - 1); } System.out.println("路由条件---" + param); return param; } private List<FlowRouteOVO> queryRuleJudgment(List<FlowRouteOVO> frList, String query) { List<FlowRouteOVO> queryRouteList = new ArrayList<FlowRouteOVO>(); Map<String, String> queryMap = new HashMap<>(); if (StrUtil.notEmpty(query)) { queryMap = parseQuery2Map(query); } Set<String> routeIdSet = new HashSet<String>(); for (FlowRouteOVO fr : frList) { List<String> queryList = fr.getQueryList(); if (queryList != null && queryList.size() > 0) { System.out.println("路由fr: "+fr.getId()+"--"+queryList.toString()); for (String queryParm : queryList) {// 进行单个条件完全匹配的校验 int count = 0; List<String> keys = getQueryParmKey(queryParm);// 要匹配的字段(完全匹配的字段) for (int i = 0; i < keys.size(); i++) { String key = keys.get(i); String value = getQueryParmValue(queryParm, key);// 流程中的字段值(‘A,S’或者‘B’或者‘!B’) String queryValue = queryMap.get(key);// 业务所对应的值 String[] values = value.split(","); if (queryMap.containsKey(key) && StrUtil.notEmpty(queryValue)) { for (int j = 0; j < values.length; j++) { String s = values[j]; if (s.equals(queryValue)) {// 匹配上 count++; break; } } } else {// 没有key,匹配下一个queryParm break; } } if (count == keys.size()) {// 完全匹配 if(!routeIdSet.contains(fr.getId())) { routeIdSet.add(fr.getId()); queryRouteList.add(fr); } } } } continue; } return queryRouteList; } private Map<String, String> parseQuery2Map(String query) { Map<String, String> map = new HashMap<>(); Set<String> keySet = new HashSet<>(); if (StrUtil.notEmpty(query)) { // String[] Strquery = query.split(","); // for (int i = 0; i < Strquery.length; i++) { String[] strs = query.split(";"); for (String s : strs) { String[] kv = s.split(":"); if (kv.length == 2) { if (!keySet.contains(kv[0])) { keySet.add(kv[0]); } else { String kv1 = map.get(kv[0]).toString(); kv[1] = kv1 + "," + kv[1]; } map.put(kv[0], kv[1]); } } // } } return map; } @Override public FlowRouteOVO getFlowRoute(String routeId) { return flowRouteService.getRouteInfo(routeId); } @Override public BusGuideRoute getFlowDealModelList(FlowRouteOVO flowRouteOVo, String instanceId, String userId,String flowCode) { BusGuideRoute busGuideRoute = new BusGuideRoute(); String routeDealType = flowRouteOVo.getRouteDealType(); String routeDealId = flowRouteOVo.getRouteDealId(); List<FlowUserModel> list = new ArrayList<FlowUserModel>();// 路由处理人 if (StrUtil.notEmpty(routeDealType)) { switch (routeDealType) { case "21":// 本部门 // boolean flag = false; List<FlowUserModel> ulist = flowUserServiceReflection.getFlowExternalService().deptUserByUser(userId); if (ulist != null && ulist.size() > 0) { list.addAll(ulist); } // for (FlowUserModel flowUserModel : ulist) { // String deptId = flowUserModel.getDeptId(); // if ("30169926".equals(deptId)) { // flag = true; // break; // } // } // if (flag) { // list.add(flowUserService.selectUserInfo("2831544335238090")); // busGuideRoute.setFlag(true); // } else { // if (ulist != null && ulist.size() > 0) { // list.addAll(ulist); // } // } break; case "22":// 大部门 // if ("2831544335238090".equals(userId)) {// 谭宏斌 // list.add(flowUserService.selectUserInfo("01295238232274"));// 李珂 // busGuideRoute.setFlag(true); // } else { // List<FlowUserModel> auList = flowUserService.allDeptUserByUser(userId); // if (auList != null && auList.size() > 0) { // list.addAll(auList); // } // } List<FlowUserModel> auList = flowUserServiceReflection.getFlowExternalService() .allDeptUserByUser(userId); if (auList != null && auList.size() > 0) { list.addAll(auList); } break; case "11":// 发起人 // 查询发起人信息 FlowInstanceOVO flowInstanceOVo = flowInstenceEngine.getFlowInstanceOVO(instanceId); if (flowInstanceOVo != null) { FlowUserModel user = flowInstanceOVo.getUser(); if (user != null) { list.add(user); } } busGuideRoute.setFlag(true); break; case "01":// 用户 FlowUserModel user = flowUserServiceReflection.getFlowExternalService().selectUserInfo(routeDealId); list.add(user); break; case "02":// 部门 List<FlowUserModel> dlist = flowUserServiceReflection.getFlowExternalService() .selectUserByDeptId(routeDealId); if (dlist != null && dlist.size() > 0) { list.addAll(dlist); } break; case "03":// 角色 List<FlowUserModel> rlist = flowUserServiceReflection.getFlowExternalService() .selectUserByRoleId(routeDealId); if (rlist != null && rlist.size() > 0) { list.addAll(rlist); } break; case "12":// 上一节点办理人 // FlowInstanceState flowInstanceState = new FlowInstanceState(); // flowInstanceState.setNodeId(flowRouteOVo.getPreNode()); // flowInstanceState.setSufDealId(userId); // flowInstanceState.setInstanceId(instanceId); // flowInstanceState.setSufAuthType("01"); // FlowInstanceState fs = flowInstenceStateEngine.getInstenceStateNow(flowInstanceState); // if (fs != null) { // FlowUserModel r1list = flowUserServiceReflection.getFlowExternalService() // .selectUserInfo(fs.getPreDealId()); // // } BusGuide busGuide = nodeDealRuleEngine.isBack("1", flowRouteOVo.getPreNode(), instanceId, userId, flowCode); list.addAll(busGuide.getFlowUserList()); busGuideRoute.setFlag(true); break; } } busGuideRoute.setType(OperationMenu.USER); busGuideRoute.setRouteUserList(list); List<FlowRouteOVO> flowRouteList = new ArrayList<FlowRouteOVO>(); flowRouteList.add(flowRouteOVo); busGuideRoute.setFlowRouteList(flowRouteList); return busGuideRoute; } private List<String> getQueryParmKey(String queryParm) { JSONObject jsonx = JSON.parseObject(queryParm); List<String> keys = new ArrayList<String>(); for (String key : jsonx.keySet()) { String[] keyArray = key.split(","); for (String keyStr : keyArray) { keys.add(keyStr); } } return keys; } private String getQueryParmValue(String queryParm, String key) { HashMap<String,String> map = JSON.parseObject(queryParm, new TypeReference<HashMap<String,String>>() {}); return map.get(key).toString(); } } <file_sep>package com.allmsi.flow.dao; import java.util.List; import java.util.Map; import com.allmsi.flow.model.FlowTodoView; public interface FlowTodoViewMapper { List<FlowTodoView> selectTodoList(Map<String, String> map); List<FlowTodoView> flowInstenceDept(Map<String, Object> map); } <file_sep>package com.allmsi.flow.model; public class FlowModuleAuth { private String id; private String flowId; private String authId; private String authType; private Integer del; public String getId() { return id; } public void setId(String id) { this.id = id == null ? null : id.trim(); } public String getFlowId() { return flowId; } public void setFlowId(String flowId) { this.flowId = flowId == null ? null : flowId.trim(); } public String getAuthId() { return authId; } public void setAuthId(String authId) { this.authId = authId == null ? null : authId.trim(); } public String getAuthType() { return authType; } public void setAuthType(String authType) { this.authType = authType == null ? null : authType.trim(); } public Integer getDel() { return del; } public void setDel(Integer del) { this.del = del; } }<file_sep>package com.allmsi.flow.service; import java.util.List; public interface FlowNodeReadDealQueryService { List<String> listQuery(String id); } <file_sep>package com.allmsi.flow.service; import com.allmsi.flow.model.ivo.FlowInstanceIVO; import com.allmsi.flow.model.ovo.FlowInstanceOVO; import com.allmsi.flow.model.ovo.SubGuide; public interface FlowInstenceEngine { String addFlowInstance(FlowInstanceIVO flowInstanceIVo); SubGuide flowInstanceEngine(String objId, String instanceId); String updateFlowInstanceDratf(String instanceId); String deleteInstence(String userId, String objId); FlowInstanceOVO getFlowInstanceOVO(String instanceId); } <file_sep>package com.allmsi.flow.model.ovo; import java.util.Date; import com.allmsi.flow.model.FlowInstanceLog; public class FlowStateLogOVO { private String instanceId; private String stateId; private String sufDealName; private String dealState; private String dealStateName; private Date dealTime; private String opinion; private String nodeId; public FlowStateLogOVO() { } public FlowStateLogOVO(String instanceId, String stateId, String sufDealName, String dealState, String dealStateName, Date dealTime, String opinion, String nodeId) { this.instanceId = instanceId; this.stateId = stateId; this.sufDealName = sufDealName; this.dealState = dealState; this.dealStateName = dealStateName; this.dealTime = dealTime; this.opinion = opinion; this.nodeId = nodeId; } public FlowStateLogOVO(FlowInstanceLog flowInstanceLog) { if (flowInstanceLog != null) { this.instanceId = flowInstanceLog.getInstanceId(); this.stateId = flowInstanceLog.getId(); this.sufDealName = flowInstanceLog.getSufDealName(); this.dealState = flowInstanceLog.getDealState(); this.dealTime = flowInstanceLog.getDealTime(); this.opinion = flowInstanceLog.getOpinion(); this.nodeId = flowInstanceLog.getNodeId(); } } public String getInstanceId() { return instanceId; } public void setInstanceId(String instanceId) { this.instanceId = instanceId; } public String getStateId() { return stateId; } public void setStateId(String stateId) { this.stateId = stateId; } public String getSufDealName() { return sufDealName; } public void setSufDealName(String sufDealName) { this.sufDealName = sufDealName; } public String getDealState() { return dealState; } public void setDealState(String dealState) { this.dealState = dealState; } public String getDealStateName() { return dealStateName; } public void setDealStateName(String dealStateName) { this.dealStateName = dealStateName; } public Date getDealTime() { return dealTime; } public void setDealTime(Date dealTime) { this.dealTime = dealTime; } public String getOpinion() { return opinion; } public void setOpinion(String opinion) { this.opinion = opinion; } public String getNodeId() { return nodeId; } public void setNodeId(String nodeId) { this.nodeId = nodeId; } @Override public String toString() { return "FlowStateLogOVo [instanceId=" + instanceId + ", stateId=" + stateId + ", sufDealName=" + sufDealName + ", dealState=" + dealState + ", dealStateName=" + dealStateName + ", dealTime=" + dealTime + ", opinion=" + opinion + ", nodeId=" + nodeId + "]"; } } <file_sep>package com.allmsi.flow.service; import com.allmsi.flow.model.ovo.FlowNodeOVO; public interface FlowNodeService { FlowNodeOVO getTheNextNodeToStart(String flowCode); boolean isfinish(String nodeId); FlowNodeOVO getFlowNodeOVO(String nodeId); } <file_sep>package com.allmsi.flow.model.ovo; import com.allmsi.flow.model.FlowNode; import com.allmsi.flow.model.external.FlowUserModel; public class FlowNodeOVO { private String id; private String flowId; private String nodeName; private String nodeType; private String continuation; private FlowUserModel user; public FlowNodeOVO() { } public FlowNodeOVO(FlowNode flowNode) { if (flowNode != null) { this.id = flowNode.getId(); this.flowId = flowNode.getFlowId(); this.nodeName = flowNode.getNodeName(); this.nodeType = flowNode.getNodeType(); this.continuation = flowNode.getContinuation(); } } public String getId() { return id; } public void setId(String id) { this.id = id == null ? null : id.trim(); } public String getFlowId() { return flowId; } public void setFlowId(String flowId) { this.flowId = flowId == null ? null : flowId.trim(); } public String getNodeName() { return nodeName; } public void setNodeName(String nodeName) { this.nodeName = nodeName == null ? null : nodeName.trim(); } public String getNodeType() { return nodeType; } public void setNodeType(String nodeType) { this.nodeType = nodeType == null ? null : nodeType.trim(); } public FlowUserModel getUser() { return user; } public void setUser(FlowUserModel user) { this.user = user; } public String getContinuation() { return continuation; } public void setContinuation(String continuation) { this.continuation = continuation; } }<file_sep>package com.allmsi.flow.model; public class FlowNode { private String id; private String flowId; private String nodeName; private String nodeType; private Boolean del; private String continuation; public FlowNode() { } public String getId() { return id; } public void setId(String id) { this.id = id == null ? null : id.trim(); } public String getFlowId() { return flowId; } public void setFlowId(String flowId) { this.flowId = flowId == null ? null : flowId.trim(); } public String getNodeName() { return nodeName; } public void setNodeName(String nodeName) { this.nodeName = nodeName == null ? null : nodeName.trim(); } public String getNodeType() { return nodeType; } public void setNodeType(String nodeType) { this.nodeType = nodeType == null ? null : nodeType.trim(); } public Boolean getDel() { return del; } public void setDel(Boolean del) { this.del = del; } public String getContinuation() { return continuation; } public void setContinuation(String continuation) { this.continuation = continuation; } }<file_sep>package com.allmsi.flow.service; import java.util.List; import com.allmsi.flow.model.external.FlowUserModel; public interface ModuleAuthService { List<FlowUserModel> listModuleAuth(String flowId); boolean isAdmin(String flowId,String userId); } <file_sep>package com.allmsi.flow.model.ovo; import com.allmsi.flow.model.FlowField; import com.allmsi.flow.model.FlowNodeField; public class FlowNodeFieldOVO { private String fieldName; private String cnName; private String typeName; private String propertyName; private Integer fieldLength; private Integer sort; private Integer status; public FlowNodeFieldOVO() { } public FlowNodeFieldOVO(FlowNodeField flowNodeField) { if (flowNodeField != null) { this.status = flowNodeField.getStatus(); this.sort = flowNodeField.getSort(); } } public FlowNodeFieldOVO(FlowFieldOVO flowFieldOVO) { if (flowFieldOVO != null) { this.fieldName = flowFieldOVO.getFieldName(); this.cnName = flowFieldOVO.getCnName(); this.typeName = flowFieldOVO.getTypeName(); this.propertyName = flowFieldOVO.getPropertyName(); this.fieldLength = flowFieldOVO.getFieldLength(); } } public FlowNodeFieldOVO(FlowField flowField) { if (flowField != null) { this.fieldName = flowField.getFieldName(); this.cnName = flowField.getCnName(); this.typeName = flowField.getTypeName(); this.propertyName = flowField.getPropertyName(); this.fieldLength = flowField.getFieldLength(); } } public String getFieldName() { return fieldName; } public void setFieldName(String fieldName) { this.fieldName = fieldName; } public Integer getFieldLength() { return fieldLength; } public void setFieldLength(Integer fieldLength) { this.fieldLength = fieldLength; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public Integer getSort() { return sort; } public void setSort(Integer sort) { this.sort = sort; } public String getTypeName() { return typeName; } public void setTypeName(String typeName) { this.typeName = typeName; } public String getPropertyName() { return propertyName; } public void setPropertyName(String propertyName) { this.propertyName = propertyName; } public String getCnName() { return cnName; } public void setCnName(String cnName) { this.cnName = cnName; } @Override public String toString() { return "FlowNodeFieldOVO [fieldName=" + fieldName + ", cnName=" + cnName + ", typeName=" + typeName + ", propertyName=" + propertyName + ", fieldLength=" + fieldLength + ", sort=" + sort + ", status=" + status + "]"; } } <file_sep>package com.allmsi.flow.dao; import java.util.List; public interface FlowRouteDealQueryMapper { List<String> queryList(String id); }
d00ade2c3b51771c4bc722039283dc8ee88b8c76
[ "Markdown", "Java", "Maven POM" ]
64
Java
nannan07/im-flow-spring-boot
7c1295920d638c2851b78970986fc509c14f080d
e21eaeab6b5ba17a8e4e089b7681078790a1e2b1
refs/heads/main
<repo_name>mishraapoorva/QuestSolution<file_sep>/Part3/lambda_function.py import urllib3 import json import boto3 import pandas as pd from io import StringIO s3 = boto3.client('s3') # Config for JSON file json_bucket = 'rearc-population-data' json_file_name = 'data.json' # Config for CSV files csv_bucket = 'rearc-pr-time-series-data' csv_file_name = 'pr.data.0.Current' def print_analytics_result(): csv_data = StringIO(s3.get_object(Bucket=csv_bucket, Key=csv_file_name)['Body'].read().decode('utf-8')) time_series_csv_df = pd.read_csv(csv_data, sep='\t') time_series_csv_df.columns = time_series_csv_df.columns.str.strip() time_series_csv_df_grouped = time_series_csv_df.groupby(['series_id', 'year']).agg({'value': 'sum'}).reset_index() # print(time_series_csv_df_grouped.head(30)) result = time_series_csv_df_grouped.groupby(['series_id'], as_index=False)['value'].max().rename( columns={'value': 'value'}) time_series_report = time_series_csv_df_grouped.merge(result, on=['series_id', 'value']) print(time_series_report.head()) http = urllib3.PoolManager() r = http.request('GET', 'https://datausa.io/api/data?drilldowns=Nation&measures=Population') population_json = json.loads(r.data.decode('UTF-8')) temp_data = population_json["data"] population_df = pd.DataFrame(temp_data) population_df = population_df.rename(columns={'Year': 'year'}) population_df['year'] = population_df['year'].astype(int) clubbed_df = time_series_csv_df.merge(population_df, on=['year']) clubbed_df.drop(['footnote_codes', 'ID Nation', 'Nation', 'ID Year', 'Slug Nation'], axis=1, inplace=True) print(clubbed_df.head()) def lambda_handler(event, context): print_analytics_result() return { 'statusCode': 200 } <file_sep>/Part1&2/lambda_function.py import urllib3 import boto3 import re s3 = boto3.client('s3') s3_resource = boto3.resource('s3') http_pool = urllib3.PoolManager() # Config for JSON file json_file_name = 'data.json' json_url = 'https://datausa.io/api/data?drilldowns=Nation&measures=Population' # Config for CSV files csv_root_url = 'https://download.bls.gov/pub/time.series/pr' csv_bucket = 'rearc-pr-time-series-data' csv_file_name = 'pr.data.0.Current' csv_base_url = 'https://download.bls.gov' csv_uri = '/pub/time.series/pr/' pattern = re.compile(r'HREF=\"(.*?)\"[^>]*') def save_url_to_s3(url, bucket, key): response = http_pool.request('GET', url) if response.status == 200: s3.put_object(Body=response.data.decode('UTF-8'), Bucket=bucket, Key=key) def source_csv(): # print(csv_root_url) response = http_pool.urlopen('GET', csv_base_url + csv_uri) csv_html_page = (response.data.decode('utf-8')) csv_files = [] s3_files = list(s3_resource.Bucket(csv_bucket).objects.all()) for (csv_link) in re.findall(pattern, csv_html_page): if (csv_link.startswith(csv_uri)): csv_files.append(csv_link.split(csv_uri)[1]) # print("Adding/deleting new/old files") for mutation_file in list(set(csv_files) - set(s3_files)): if mutation_file in csv_files: # print("Add new file") print(mutation_file) save_url_to_s3(csv_base_url + csv_uri + mutation_file, csv_bucket, mutation_file) else: # print("Deleting old file") print(mutation_file) s3_resource.Object(csv_bucket, mutation_file).delete() # print("Updating commons files") for common_file in list(set(s3_files) & set(csv_files)): # print("Update common file") print(common_file) save_url_to_s3(csv_base_url + csv_uri + common_file, csv_bucket, common_file) def source_json(json_bucket): # print("saving json to s3") save_url_to_s3(json_url, json_bucket, json_file_name) def lambda_handler(event, context): source_csv() source_json(event['bucket']) return { 'statusCode': 200 } <file_sep>/README.md ## AWSDataPipeline So, lets create a data pipeline using the Amazing Amazon Web Services!!! <br /> All we have to do, is to create an AWS account and work with a few different services! <br /> Step 1: Write a cool function to load data to S3 (but remember to implement code reusability) <br /> Step 2: Trigger a message to SQS queue as soon as the data is loaded to S3 <br /> Step 3: Recieve the message from SQS queue, fetch csv & json data from S3 and show off your data analytics skills using Pandas. So, it looks something like this: <br /> <br /> ![Or not](https://github.com/mishraapoorva/AWSDataPipeline/blob/master/img/rearc-dataflow.jpg) ### Services Used (- {& for what???}): - Lambda - To write Functions (code) to perform the tasks like reading to and from S3, data analysis - S3 - For Storing data from multiple sources (CSV & API) - SQS - Gets populated each time data is loaded into S3 - CloudFormation - For creating and orchestrating the data pipeline ## Also note, This project consists of three folders solving three challenges of a data quest ### Part 1 & 2: AWS S3 & Sourcing Datasets (sources: CSV and API) > - This folder contains the source code for Part 1 & Part 2 combined > - The .py file (lambda function) loads data from two sources (viz, CSV and API) into S3 buckets > - Link to data in S3 and source code: >> - https://rearc-population-data-1633606565.s3.amazonaws.com/data.json >> - https://rearc-pr-time-series-data.s3.amazonaws.com/pr.data.0.Current ### Part 3: Data Analytics > - This folder contains the source code for Part 3 > - There is a AnalyticsNotebook.ipynb which contains the results within the notebook > - Used Lambda Layer for importing pandas, boto3 packages ### Part 4: Infrastructure as Code & Data Pipeline with AWS CloudFormation > - Create a neat, little stack using yaml template to define the resources using CloudFormation <br /> > - This folder consists of the cloudFormation.yaml file >
8e53c8544598d77064d68242c23160df3c361aa9
[ "Markdown", "Python" ]
3
Python
mishraapoorva/QuestSolution
6d0ab0c8297f5d85a2389cd82355c35c0be27d7f
abf80e387f94283291982056bc4484590af27170
refs/heads/master
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; using UnityEngine.SceneManagement; using UnityEngine.UI; public class SpaceFlightController : MonoBehaviour { [SerializeField] SharedBool _inSpace; [SerializeField] RocketFlight _rocket; [SerializeField] string _resultsScene; [SerializeField] float _flightTimeAfterLastPlanet; [SerializeField] AudioController _audioController; [SerializeField] SharedString _reachedPlanetName; [SerializeField] SharedStringGameEvent _ReachedPlanetStringGameEvent; [SerializeField] SharedStringGameEvent _ReachedPlanetStringHeaderGameEvent; [SerializeField] SharedInt _finalPlanetIndex; [Header("Background")] [SerializeField] Renderer _spaceBackdrop; [SerializeField] float _backdropSpeed; [Header("Planets")] [SerializeField] Planet[] _planets; float _travelTimer = 0f; int _nextPlanetIndex = 0; Vector2 _backdropOffset; Material _backdropMaterial; int _backdropNameID; bool _leavingSolarSystem = false; bool _cheatScreenSaverMode; private void Start() { _inSpace.Value = true; _backdropNameID = Shader.PropertyToID("_MainTex"); _backdropOffset = _spaceBackdrop.material.GetTextureOffset(_backdropNameID); _backdropMaterial = _spaceBackdrop.material; _rocket.OnMalfunction += OnRocketMalfunction; } private void Update() { if (DebugKey.GetKeyDown(KeyCode.S)) { _cheatScreenSaverMode = !_cheatScreenSaverMode; Debug.Log("Screensaver Mode = " + _cheatScreenSaverMode.ToString()); } // do calculations for the score counting up // planet flyby _travelTimer += Time.deltaTime; PlanetFlyBy(); // space background texture scrollby _backdropOffset.y -= Time.deltaTime * _backdropSpeed; _backdropMaterial.SetTextureOffset(_backdropNameID, _backdropOffset); } /// <summary> /// Do this when rocket explodes /// </summary> void OnRocketMalfunction() { _backdropSpeed *= 0.5f; // disable unvisited planets foreach (Planet planet in _planets) { if (!planet.flyingBy) { planet.flyBySpeed = 0; } else { planet.isBraking = true; } } } /// <summary> /// Send a planet across the background /// </summary> void PlanetFlyBy() { // debug: skip to next planet if (Input.GetKeyDown(KeyCode.Z)) { _travelTimer = _planets[_nextPlanetIndex].distanceFromEarth; _rocket.Age = _travelTimer; } // do not do stuff if we've moved past the last planet already, or the rocket has died if (_leavingSolarSystem || _rocket.hasMalfunctioned) { return; } else if (_travelTimer > _planets[_nextPlanetIndex].distanceFromEarth) { // if this planet is null switch to results screen if (_planets[_nextPlanetIndex] == null) { StartCoroutine(SwitchToResultsScreen()); } // else move the next planet past the rocket else { Planet currentPlanet = _planets[_nextPlanetIndex]; _nextPlanetIndex++; _reachedPlanetName.Value = currentPlanet.appellation; currentPlanet.flyingBy = true; // Let the UI know that we reached a new planet and display a fact about it if (_nextPlanetIndex <= _finalPlanetIndex.Value) { int planetFactIndex = Random.Range(0, currentPlanet.reachedText.Length); _ReachedPlanetStringHeaderGameEvent.Value = currentPlanet.appellation; _ReachedPlanetStringGameEvent.Value = currentPlanet.reachedText[planetFactIndex]; } // if there is no next planet in the array initiate scene transition if (_planets.Length == _nextPlanetIndex) { StartCoroutine(SwitchToResultsScreen()); } } } } IEnumerator SwitchToResultsScreen() { _leavingSolarSystem = true; yield return new WaitForSeconds(_flightTimeAfterLastPlanet); if (_cheatScreenSaverMode) { PlanetaryReset(); } else { GamePlayer.localGamePlayer.InterruptNetworkTimer(); SceneManager.LoadScene(_resultsScene); } } /// <summary> /// Debug feature. Resets all the planets so they will flyby again, cool for looping. /// </summary> void PlanetaryReset() { _leavingSolarSystem = false; foreach (Planet planet in _planets) { if (planet != null) { planet.ResetPosition(); } } _planets[0].transform.position += Vector3.up * 100 + Vector3.forward * 10; // Move earth out of the way by some arbitrary amount, specifics not important, is debug feature. _nextPlanetIndex = 0; _travelTimer = 0; } }<file_sep># RakwetWetenschappen This is not the full project, as I don't own the rights to publish the source code. However, I am able to show these few scripts I worked on. <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; using RocketVariables; using System; public class ScoreController : MonoBehaviour // todo @Oane make this server side if there's time left, execute from networklist.cs or something. Also put this not on the rocket? { [Header("Timer")] [SerializeField] SharedFloat _timeRemainder; [SerializeField] SharedInt _gameDuration; [Header("Missions")] [SerializeField] SharedInt _playerCount; [SerializeField] SegmentSelection[] _segmentSelections; [SerializeField] MissionContainer[] _missionContainers; [SerializeField] SharedInt _minimumPlayerCount; [SerializeField] SharedBool _rocketFinished; [Header("Score")] [SerializeField] float _missionScoreWeightSuccess; [SerializeField] float _timerScoreWeightSuccess; [SerializeField] float _missionScoreWeightFailure; [SerializeField] float _timerScoreWeightFailure; [SerializeField] AnimationCurve _timerScoreCurve; [SerializeField] float _fixedMultiplier; [SerializeField] SharedFloat _score; [Header("Result Effects")] [SerializeField] RocketEvents _rocket; [Header("References"), SerializeField] MissionController _missionController; [SerializeField] bool _calculateSuccess = true; private void Start() { // Calculate Score float maxScore = (_timerScoreWeightSuccess + _missionScoreWeightSuccess) * _fixedMultiplier; _score.Value = Mathf.Round(Score()); float failureThreshold = _missionController.FailureThreshold; // pick effect based on both timer & missions completed float scoreRate = _score.Value / maxScore; // formula to convert the range (_successThreshold to 1) to a range of (0 to 1) float failureEventIndex = (scoreRate - failureThreshold) * (1 / (1 - failureThreshold)); _rocket.PickRocketFailureEvent(failureEventIndex); } /// <summary> /// Score /// </summary> /// <returns></returns> public float Score() { GamePlayer gamePlayer = GamePlayer.localGamePlayer; int roundIndex = gamePlayer ? gamePlayer.RoundIndex : 0; // initialized the missioncontroller _missionController.Initialize(roundIndex, _calculateSuccess, 0); // todo: if we want to make the teamcaptain dynamic at some point, change this. float score = _missionController.SuccessRate; float playerMissionScore = _missionController.PlayerSuccessRate; // Todo @Johan these return the amount of missions completed etc. Might be worth looking into these if stuff is bugged. I dont know how these work exactly, I didnt write them. float captainMissionScore = _missionController.CaptainSuccessRate; float timerScore = _timeRemainder.Value / _gameDuration.Value; timerScore = _timerScoreCurve.Evaluate(timerScore); float failureThreshold = _missionController.FailureThreshold; if (_rocketFinished.Value == false || playerMissionScore < failureThreshold || captainMissionScore < failureThreshold) { // total failure. // Todo @Johan: If score is 0, this happens. Work from here? score *= _missionScoreWeightFailure; timerScore *= _timerScoreWeightFailure; score += timerScore; } else { // succeeded. score *= _missionScoreWeightSuccess; timerScore *= _timerScoreWeightSuccess; score += timerScore; score = Mathf.Round(score); // round here so our score will be multiples of _fixedMultiplier } score *= _fixedMultiplier; score = Mathf.Round(score); Debug.Log(string.Format("Calculated Score \nTotal Score: {0}, timerScore: {1}", score, timerScore)); return score; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using System; using UnityEngine.SceneManagement; public class Rocket : MonoBehaviour { [Header("Rocket Segments")] [SerializeField] protected RocketSegment _top; [SerializeField] protected RocketSegment _middle; [SerializeField] protected RocketSegment _bottom; [SerializeField] protected RocketSegment _leftBooster; [SerializeField] protected RocketSegment _rightBooster; /// <summary> /// To have a visual cue in the scene for the rocket spawn point /// </summary> private void OnDrawGizmos() { Gizmos.color = Color.yellow; Gizmos.DrawLine(transform.position, transform.position + transform.up * (30 * transform.localScale.y)); Gizmos.DrawLine(transform.position + transform.right * 2, transform.position + transform.up * (15 * transform.localScale.y) + transform.right * (2 * transform.localScale.x)); Gizmos.DrawLine(transform.position + transform.right * -2, transform.position + transform.up * (15 * transform.localScale.y) + transform.right * (-2 * transform.localScale.x)); } void Start() { Assemble(); } /// <summary> /// Assembles the five segments of the rocket into one /// </summary> protected void Assemble() { _bottom.transform.localPosition = Vector3.zero; _middle.transform.localPosition = new Vector3(0, _bottom.height, 0); _top.transform.localPosition = new Vector3(0, _bottom.height + _middle.height, 0); _leftBooster.transform.localPosition = new Vector3(-_bottom.width - _leftBooster.width, 0, 0); _rightBooster.transform.localPosition = new Vector3(_bottom.width + _rightBooster.width, 0, 0); _bottom.transform.localScale = Vector3.one; _middle.transform.localScale = Vector3.one; _top.transform.localScale = Vector3.one; _leftBooster.transform.localScale = Vector3.one; _rightBooster.transform.localScale = Vector3.one; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public class RocketSegment : MonoBehaviour { [SerializeField] SegmentSelection _segmentSelection; [SerializeField] SharedBool _rocketFinished; int _elementCount; [SerializeField] bool _assembleOnStart = true; // The amount and model of connectors that are to be attached if this is a booster [Header("Booster Only Properties")] [SerializeField] int _boosterConnectorCount; [SerializeField] GameObject _boosterConnectorModel; enum Sides { Left, Right } [SerializeField] Sides attachTo; [NonSerialized] public float height; [NonSerialized] public float width; GameObject _topElement; GameObject _centerElement; GameObject _lowerElement; RocketElement[] _rocketElements; void Awake() { // If the rocket is unfinished, don't put any connectors so the rocket can fall apart more properly. if (_rocketFinished.Value == false ) { _boosterConnectorCount = 0; } _elementCount = _segmentSelection.Count - 1; // -1 because color shouldn't be counted todo @oane put a proper check here // Array of rocket elements _rocketElements = new RocketElement[_elementCount + _boosterConnectorCount]; } private void Start() { if (_assembleOnStart) Assemble(); } /// <summary> /// Assemble this rocket part out of all the elements /// </summary> void Assemble() { // Spawn the 3 elements _topElement = Instantiate(_segmentSelection.ElementAt(0).Model); _centerElement = Instantiate(_segmentSelection.ElementAt(1).Model); _lowerElement = Instantiate(_segmentSelection.ElementAt(2).Model); // Get the RocketElements _rocketElements[0] = _topElement.GetComponent<RocketElement>(); _rocketElements[1] = _centerElement.GetComponent<RocketElement>(); _rocketElements[2] = _lowerElement.GetComponent<RocketElement>(); // Get the boundaries Bounds topBounds = _topElement.GetComponent<Renderer>().bounds; Bounds centerBounds = _centerElement.GetComponent<Renderer>().bounds; Bounds lowerBounds = _lowerElement.GetComponent<Renderer>().bounds; // Calculate bottom element position Vector3 lowerPosition = Vector3.zero; lowerPosition.y -= _rocketElements[2].attachmentDepth; // Calculate middle element position Vector3 centerPosition = lowerPosition; centerPosition.y += lowerBounds.size.y; centerPosition.y -= _rocketElements[1].attachmentDepth; // Calculate top element position Vector3 topPosition = centerPosition; topPosition.y += centerBounds.size.y; topPosition.y -= _rocketElements[0].attachmentDepth; // Setting parent here and not when instantiating because rotations are hard _topElement.transform.parent = transform; _centerElement.transform.parent = transform; _lowerElement.transform.parent = transform; // Set Scale _topElement.transform.localScale = Vector3.one; _centerElement.transform.localScale = Vector3.one; _lowerElement.transform.localScale = Vector3.one; // Set position _topElement.transform.localPosition = topPosition; _centerElement.transform.localPosition = centerPosition; _lowerElement.transform.localPosition = lowerPosition; // Setting rotation _topElement.transform.localRotation = _topElement.transform.rotation; _centerElement.transform.localRotation = _centerElement.transform.rotation; _lowerElement.transform.localRotation = _lowerElement.transform.rotation; // Calculate height and width for use in full rocket assembly height = lowerBounds.size.y + centerBounds.size.y + topBounds.size.y; height -= _rocketElements[0].attachmentDepth; height -= _rocketElements[1].attachmentDepth; height -= _rocketElements[2].attachmentDepth; width = Mathf.Max(lowerBounds.extents.x, topBounds.extents.x, centerBounds.extents.x); // Attach the connectors if it has them if (_boosterConnectorCount > 0) { // Get boundaries Bounds connectorBounds = _boosterConnectorModel.GetComponent<Renderer>().bounds; float protrusionDistance = connectorBounds.extents.x; width -= protrusionDistance; // Calculate the difference in height between each connector (attached evenly across the bottom half of the booster) float distanceBetweenConnectors = height / (_boosterConnectorCount * 2); float connectionHeight = 0.0f; // Spawn and attach connectors for (int i = 0; i < _boosterConnectorCount; i++) { // Calculate where the next connector is to be attached connectionHeight = distanceBetweenConnectors * (i + 1); // +1 because we dont want to attach at 0 height Vector3 connectionLocation = Vector3.zero; connectionLocation.x = width - protrusionDistance; connectionLocation.y = connectionHeight; // Flip the attachment location to the other side of the booster if needed if (attachTo == Sides.Right) { connectionLocation.x *= -1; } // Spawn and position the connector GameObject connectionPiece = Instantiate(_boosterConnectorModel, transform); connectionPiece.transform.localPosition = connectionLocation; // Flip piece around if needed if (attachTo == Sides.Right) { Vector3 mirrorScale = connectionPiece.transform.localScale; mirrorScale.x *= -1; connectionPiece.transform.localScale = mirrorScale; } // Add connector to array of elements _rocketElements[i + _elementCount] = connectionPiece.GetComponent<RocketElement>(); } } // Get materials of all objects Material _topColor = _topElement.GetComponent<Renderer>().material; Material _centerColor = _centerElement.GetComponent<Renderer>().material; Material _lowerColor = _lowerElement.GetComponent<Renderer>().material; // Set their overlay color int overlayColorID = Shader.PropertyToID("_OverlayColor"); Color color = _segmentSelection.ElementAt(3).Color; _topColor.SetColor(overlayColorID, color); _centerColor.SetColor(overlayColorID, color); _lowerColor.SetColor(overlayColorID, color); } /// <summary> /// Disassemble rocket and assemble it again (in case of new parts selected). /// </summary> public void Rebuild() { Destroy(_topElement); Destroy(_centerElement); Destroy(_lowerElement); Assemble(); } /// <summary> /// Detach all the elements from this part /// </summary> /// <param name="debrisGroup"></param> /// <param name="velocity"></param> public void DetachObjects(Transform debrisGroup, Vector3 velocity, float explosionPower) { foreach (RocketElement rocketElement in _rocketElements) { rocketElement.Detach(debrisGroup, velocity, explosionPower); } } }<file_sep>using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class RocketElement : MonoBehaviour { [NonSerialized] public new Rigidbody rigidbody; [NonSerialized] public new Collider collider; [SerializeField] SharedBool _inSpace; [SerializeField] bool _despawnOnMalfunction; public float attachmentDepth; public void Start() { rigidbody = GetComponent<Rigidbody>(); collider = GetComponent<Collider>(); } public void Update() { if (DebugKey.GetKeyDown(KeyCode.D)) { rigidbody.useGravity = !_inSpace.Value; rigidbody.isKinematic = false; collider.enabled = true; rigidbody.velocity = Vector3.one; Vector3 randomDirection = UnityEngine.Random.insideUnitSphere; rigidbody.velocity += randomDirection; } } /// <summary> /// Detach this object from the rocket /// </summary> /// <param name="debrisGroup"></param> /// <param name="velocity"></param> public void Detach(Transform debrisGroup, Vector3 velocity, float explosionPower) { if (_despawnOnMalfunction) { gameObject.SetActive(false); } else { rigidbody.useGravity = !_inSpace.Value; rigidbody.isKinematic = false; rigidbody.velocity = velocity; Vector3 randomDirection = UnityEngine.Random.insideUnitSphere; rigidbody.velocity += randomDirection * explosionPower; collider.enabled = true; transform.parent = debrisGroup; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using System; using UnityEngine.SceneManagement; public class RocketFlight : Rocket { [Header("Other Rocket Parts")] [SerializeField] GameObject _flames; [SerializeField] GameObject _explosions; [SerializeField] GameObject _smoke; [SerializeField] CameraShake _cameraShake; [Header("Flight Data")] [SerializeField] float _launchSpeed = 15f; [SerializeField] float _explosionPower; [NonSerialized] public bool hasMalfunctioned; [NonSerialized] public bool isLaunching; [SerializeField] float driftSpeed; [SerializeField] SharedFloat _lifespan; float _age; public float Age { get { return _age; } set { _age = value; } } bool _explodeBeforeReachingSpace; bool _explodeInSpace; bool _fallApartImmediately; [Header("Misc")] [SerializeField] string _resultsScene; [SerializeField] Transform _debrisGroup; [SerializeField] SharedInt _playerCount; [SerializeField] SharedBool _inSpace; [SerializeField] AudioController _audioController; [SerializeField] float _assemblyDuration; [SerializeField] int _assemblyToolCount; [SerializeField] float _sceneTransitionAfterMalfunctionTimer; public float SceneTransitionAfterMalfunctionTimer { get { return _sceneTransitionAfterMalfunctionTimer; } set { _sceneTransitionAfterMalfunctionTimer = value; } } const float explosionChargeUpTimer = 3.146f; const float waitForFireballTimer = 0f; const float engineStartupTimer = 2.78f; [NonSerialized] public new Rigidbody rigidbody; public delegate void OnExplodeDelegate(); public event OnExplodeDelegate OnMalfunction; // Debug stuff TODO @Oane Remove bool cheatGodMode = false; /// <summary> /// To have a visual cue in the scene for the rocket spawn point /// </summary> private void OnDrawGizmos() { Gizmos.color = Color.green; Gizmos.DrawLine(transform.position, transform.position + transform.up * (30 * transform.localScale.y)); Gizmos.DrawLine(transform.position + transform.right * (2 * transform.localScale.x), transform.position + transform.up * (15 * transform.localScale.y) + transform.right * (2 * transform.localScale.x)); Gizmos.DrawLine(transform.position + transform.right * (-2 * transform.localScale.x), transform.position + transform.up * (15 * transform.localScale.y) + transform.right * (-2 * transform.localScale.x)); } void Start() { rigidbody = gameObject.GetComponent<Rigidbody>(); rigidbody.useGravity = !_inSpace.Value; //_scoreCalculator = GetComponent<ScoreCalculator>(); Assemble(); StartCoroutine(_audioController.MultipleToolSounds(_assemblyDuration, _assemblyToolCount)); //_scoreCalculator.PickRocketFailureEvent(); if (_inSpace.Value == true) { // if we're in space, make flying sounds _audioController.RocketFlySound(); } } void Update() { if (DebugKey.GetKeyDown(KeyCode.G)) { cheatGodMode = !cheatGodMode; Debug.Log("God mode: " + cheatGodMode); } if (DebugKey.GetKeyDown(KeyCode.B)) { //GamePlayer.localGamePlayer.StopNetworkTimer(); //_explosionPower = 1; Explode(); StartCoroutine(Explode()); _lifespan.Value = 0f; _explodeBeforeReachingSpace = true; _explodeInSpace = true; } if (DebugKey.GetKeyDown(KeyCode.D)) { Vector3 velocity = GetComponent<Rigidbody>().velocity; rigidbody.isKinematic = true; gameObject.GetComponent<Collider>().enabled = false; } if (DebugKey.GetKeyDown(KeyCode.I)) { StopAllCoroutines(); GamePlayer.localGamePlayer.InterruptNetworkTimer(); StartCoroutine(TransitionToResults(0)); } if (Input.GetKeyDown(KeyCode.K)) { //_launchSpeed = 90; StartCoroutine(DebugForcedLaunch()); } if (_inSpace.Value == true) { // if we're in space, fly FlyThroughSpace(); } } /// <summary> /// Rocket falls apart right away, before the countdown has even completed, applying a force of nudge power to ensure the rocket topples over /// </summary> public void SetToFallApartImmediately(float nudge) { _explodeBeforeReachingSpace = false; _launchSpeed = 0; _explosionPower *= nudge; _fallApartImmediately = true; _lifespan.Value = 0; } /// <summary> /// Rocket will explode after delay seconds /// </summary> /// <param name="delay"></param> public void SetToExplodeDuringLaunch(float delay) { _lifespan.Value = delay; _explodeBeforeReachingSpace = true; _fallApartImmediately = false; } /// <summary> /// Rocket will not launch at all, and explode after delay seconds /// </summary> /// <param name="delay"></param> public void SetToNotLaunchAndExplode(float delay) { _lifespan.Value = delay; _launchSpeed = 0; _fallApartImmediately = false; _explodeBeforeReachingSpace = true; } /// <summary> /// Rocket will leave the atmosphere and travel in space for delay seconds, then explode /// </summary> /// <param name="delay"></param> public void SetToExplodeInSpace(float delay) { _lifespan.Value = delay; _explodeBeforeReachingSpace = false; _fallApartImmediately = false; _explodeInSpace = true; } /// <summary> /// Rocket will leave the atmosphere and travel in space for delay seconds, then stop flying and float in one spot /// </summary> /// <param name="delay"></param> public void SetToFlyToPointInSpace(float delay) { _lifespan.Value = delay; _explodeBeforeReachingSpace = false; _fallApartImmediately = false; _explodeInSpace = false; } /// <summary> /// Rocket will leave the atmosphere and travel indefinitely without exploding /// </summary> public void SetToFlyIndefinitely() { _lifespan.Value = Mathf.Infinity; _fallApartImmediately = false; _explodeBeforeReachingSpace = false; } /// <summary> /// Rocket flies through space /// </summary> void FlyThroughSpace() { if (_age < _lifespan.Value) { _age += Time.deltaTime; _flames.SetActive(_inSpace.Value); } else if (hasMalfunctioned == false) { if (_explodeInSpace) { StartCoroutine(Explode()); } else { StopFlying(); } } } /// <summary> /// Rocket stops flying, but wont explode /// </summary> void StopFlying() { // debug cheat if (cheatGodMode) { return; } hasMalfunctioned = true; // stop the flying sound _audioController.StopAllSounds(); // todo @Oane overkill: Make this only the relevant sounds // Call event so controller knows to stop planets from moving past if (OnMalfunction != null) { OnMalfunction(); } _flames.SetActive(false); // give the rocket a slight spin to make it look like control has been lost Vector3 driftDirection = UnityEngine.Random.onUnitSphere * driftSpeed; rigidbody.angularVelocity += driftDirection; StartCoroutine(TransitionToResults(_sceneTransitionAfterMalfunctionTimer)); } /// <summary> /// Rocket explodes /// </summary> IEnumerator Explode() { if (!cheatGodMode) { int explosionSoundIndex = _audioController.ExplosionSound(); hasMalfunctioned = true; yield return new WaitForSeconds(explosionChargeUpTimer); if (OnMalfunction != null) { OnMalfunction(); } _flames.SetActive(false); _explosions.SetActive(true); yield return new WaitForSeconds(waitForFireballTimer); _audioController.StopAllSoundsExcept(explosionSoundIndex); FallApart(); } else { yield return null; } } /// <summary> /// Debug code to force the rocket to launch even when it shouldn't without any bells attached /// </summary> /// <returns></returns> public IEnumerator DebugForcedLaunch() { Debug.Log("Forced Launch with speed " + _launchSpeed); _audioController.RocketEngineStartupSound(); yield return new WaitForSeconds(engineStartupTimer); _audioController.RocketLaunchSound(); bool debugLaunching = true; while (debugLaunching) { rigidbody.AddRelativeForce(Vector3.up * _launchSpeed * Time.deltaTime, ForceMode.Force); if (_launchSpeed > 0) { _flames.SetActive(true); if (_smoke != null) { _smoke.SetActive(true); } } if (Input.GetKeyDown(KeyCode.K)) { debugLaunching = false; } yield return null; } } /// <summary> /// Launch the rocket, explode it when it's expired. /// </summary> public IEnumerator Launch() { if (_fallApartImmediately) { FallApart(); _audioController.RumblingSound(); hasMalfunctioned = true; } else { _audioController.RocketEngineStartupSound(); yield return new WaitForSeconds(engineStartupTimer); _audioController.RocketLaunchSound(); } while (_explodeBeforeReachingSpace == false || _age < _lifespan.Value) { _age += Time.deltaTime; rigidbody.AddRelativeForce(Vector3.up * _launchSpeed * Time.deltaTime, ForceMode.Force); if (_launchSpeed > 0) { _flames.SetActive(true); if (_smoke != null) { _smoke.SetActive(true); } } yield return null; // debug cheat if (cheatGodMode && _age >= _lifespan.Value) { _age = _lifespan.Value - 1.0f; } } if (hasMalfunctioned == false) { StartCoroutine(Explode()); } } /// <summary> /// Detaches the rocket into individual pieces which fall down /// </summary> /// <returns></returns> void FallApart() { // Disable rocket's physics Vector3 velocity = GetComponent<Rigidbody>().velocity; rigidbody.isKinematic = true; gameObject.GetComponent<Collider>().enabled = false; // Enable individual segment's physics _top.DetachObjects(_debrisGroup, velocity, _explosionPower); _middle.DetachObjects(_debrisGroup, velocity, _explosionPower); _bottom.DetachObjects(_debrisGroup, velocity, _explosionPower); _leftBooster.DetachObjects(_debrisGroup, velocity, _explosionPower); _rightBooster.DetachObjects(_debrisGroup, velocity, _explosionPower); StartCoroutine(TransitionToResults(_sceneTransitionAfterMalfunctionTimer)); _cameraShake.StopShake(); } IEnumerator TransitionToResults(float delay) { yield return new WaitForSeconds(delay); SceneManager.LoadScene(_resultsScene); } }
3a2840a436efd1ec814d84ca7a61a9efe3bb1bcc
[ "Markdown", "C#" ]
7
C#
lotsofs/RakwetWetenschappen
9e559e78b96c37c61b2bc4e41223e1374088aaaf
f7d89cb604b339d8600269364a279d3276dc119c
refs/heads/master
<file_sep>-- MySQL dump 10.13 Distrib 5.7.17, for Win64 (x86_64) -- -- Host: 127.0.0.1 Database: test -- ------------------------------------------------------ -- Server version 8.0.11 /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `t_employee` -- DROP TABLE IF EXISTS `t_employee`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `t_employee` ( `P_EMPLOYEE_ID` int(11) NOT NULL AUTO_INCREMENT, `NAME` varchar(100) NOT NULL, `SEX` tinyint(4) NOT NULL, `BIRTHDAY` date DEFAULT NULL, `IDCARD` varchar(32) NOT NULL, `PHONE` varchar(32) NOT NULL, `ADDRESS` varchar(255) DEFAULT NULL, `PHOTO` varchar(255) DEFAULT NULL, `ACTIVE` tinyint(4) NOT NULL, PRIMARY KEY (`P_EMPLOYEE_ID`) ) ENGINE=InnoDB AUTO_INCREMENT=1041 DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `t_employee` -- LOCK TABLES `t_employee` WRITE; /*!40000 ALTER TABLE `t_employee` DISABLE KEYS */; INSERT INTO `t_employee` VALUES (1001,'Lily',0,'1998-05-03','352525752752566','13558687876','Tokyo','upload/img3.png',0),(1002,'Tom',1,'1995-03-09','368575275288875','15888596142','Pair',NULL,0),(1020,'张三',1,'1990-06-26','355552555515555','15525485866','北京',NULL,1),(1030,'老王',1,'1972-05-09','355145197205092548','13055847758','深圳市福田区深南中路新城大厦',NULL,1),(1031,'小李',0,'1989-06-05','352145198906062584','15195847856','湖南省长沙市天心区',NULL,1),(1032,'李四',1,'1988-02-17','351514198802172541','13966582555','广东省广州市越秀区广卫路二号','upload/img2.png',1),(1033,'王五',1,'1971-01-12','355598197101125255','13999685999','南京市鼓楼区中山路55','upload/img.jpg',1),(1037,'赵六',0,'1992-12-09','352215199212092544','13052415285','四川省成都市锦江区','upload/img3.png',1),(1039,'Lily',0,'1991-05-14','362251199105145223','13666258488','Aiduw iwd kdmk-512',NULL,0); /*!40000 ALTER TABLE `t_employee` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `t_user` -- DROP TABLE IF EXISTS `t_user`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `t_user` ( `uid` int(11) NOT NULL, `username` varchar(20) DEFAULT NULL, `password` varchar(20) DEFAULT NULL, PRIMARY KEY (`uid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `t_user` -- LOCK TABLES `t_user` WRITE; /*!40000 ALTER TABLE `t_user` DISABLE KEYS */; INSERT INTO `t_user` VALUES (1,'123','123'),(2,'admin','123'),(3,'lucy','uu1222'),(4,'Tom','8979'),(5,'5454','4545'),(6,'umum','667675'),(7,'vv','12345'),(8,'Cat','2222'),(9,'77','1452'),(10,'Emm','emm'),(11,'admin','123456'); /*!40000 ALTER TABLE `t_user` ENABLE KEYS */; UNLOCK TABLES; -- -- Dumping events for database 'test' -- -- -- Dumping routines for database 'test' -- /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2018-08-30 15:52:40 <file_sep>$(function() { // 获取当前已登陆用户并显示用户名 $('#userName').append(getUserName() + ","); /* * 正则表达式验证输入信息 */ $.extend($.fn.validatebox.defaults.rules,{ idcard : {// 验证身份证 validator : function(value) { return /^\d{15}(\d{2}[A-Za-z0-9])?$/i.test(value) || /^\d{18}(\d{2}[A-Za-z0-9])?$/i.test(value); }, message : '身份证号码格式不正确' }, phoneAndMobile : {// 验证电话号码或手机号码 validator : function(value) { return /^((\d2,3)|(\d{3}\-))?(0\d2,3|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/i.test(value) || /^(13|15|18)\d{9}$/i.test(value); }, message : '电话号码或手机号码格式不正确' }, capitalAndChinese:{// 验证姓名,只能是中文或英文 validator:function(value,param){ return /^[a-zA-Z\u4e00-\u9fa5]+$/i.test(value); }, message:'只能输入中文或英文' } }); }); var type; // 增删改查操作类型:add、edit、delete、search var pid; // 选中行的Employee主键id function addEmployee(){ type = 'add'; $('#dlg').dialog({ title:"New Employee", buttons : [{ text : 'Save&nbsp&nbsp', iconCls : 'icon-ok', handler : function (){ saveEmployee(); } },{ text : 'Cancel&nbsp', iconCls : 'icon-cancel', handler : function (){ $('#dlg').dialog('close'); } }], }) $("#idcard").textbox('enable'); $('#dlg').dialog('open') $('#fm').form('clear'); document.getElementById('sex1').checked=true; } function editEmployee(){ type = 'edit'; var row = $('#dg').datagrid('getSelected'); if (row){ // $('#dlg').dialog('open').dialog('center').dialog('setTitle','Edit Employee'); // $('#fm').form('load',row); pid = row.id; $('#dlg').dialog({ title:"Edit Employee", buttons : [{ text : 'Save&nbsp&nbsp', iconCls : 'icon-ok', handler : function (){ saveEmployee(); } },{ text : 'Cancel&nbsp', iconCls : 'icon-cancel', handler : function (){ $('#dlg').dialog('close'); } }], }); $('#dlg').dialog('open'); $('#fm').form('clear'); // 加载选中行的Employee信息 $('#fm').form('load',{ name:row.name, birthday:formatDate(row.birthday), idcard:row.idcard, phone:row.phone, address:row.address }); document.getElementById('sex'+row.sex).checked=true; $("#idcard").textbox('disable'); }else{ $.messager.alert('系统提示', '请选择行!','info'); return; } } function saveEmployee(){ //获取表单信息 // var name = $("#name").val(); // var sex = $("input[name='sex']:checked").val(); // var birthday = $("#birthday").val(); // var idcard = $("#idcard").val(); // var phone = $("#phone").val(); // var address = $("#address").val(); if(type == 'add'){ $("#fm").form("submit",{ type: "POST", url: "EmployeeServlet?type=add", onSubmit: function(){ return $(this).form("validate");//表单验证 }, dataType: "text", success: function(data){ $.messager.alert('提示信息',data,'info'); $('#dlg').dialog('close'); $("#dg").datagrid("reload"); }, error: function(){ $.messager.alert('提示信息','Error!','error'); } }); }else if(type == 'edit'){ $("#fm").form("submit",{ type: "POST", url: "EmployeeServlet?type=" +type+ "&pid="+pid, onSubmit: function(){ return $(this).form("validate");//表单验证 }, dataType: "text", success: function(data){ $.messager.alert('提示信息',data,'info'); $('#dlg').dialog('close'); $("#dg").datagrid("reload"); }, error: function(){ $.messager.alert('提示信息','Error!','error'); } }) } } function SearchEmployee(){ // type = 'search'; // $('#dg').datagrid({ // url: "EmployeeServlet?type=search", // }); // 在datagrid已经设置了获取Employee信息的url,这里直接刷新表格即可 $("#dg").datagrid("reload"); } function delEmployee(){ type="delete"; var rows = $('#dg').datagrid('getChecked'); var length = rows.length; if(length > 0){ $.messager.confirm('提示信息','确认删除已勾选的员工信息?',function(r){ if (r){ for(var i=0; i<length; i++){ $.ajax({ type: "POST", url: "EmployeeServlet", data:"pid=" +rows[i].id+ "&type=" +type, dataType: "text", success: function(){ $("#dg").datagrid("reload"); }, error: function(){ $.messager.alert('提示信息','Error!','error'); } }); } $.messager.alert('提示信息','删除成功','info'); } }) }else{ $.messager.alert('提示信息','请勾选行!','info'); return; } } function getUserName(){ var strcookie = document.cookie;//获取cookie字符串 var arrcookie = strcookie.split("; ");//分割 //遍历匹配 for ( var i = 0; i < arrcookie.length; i++) { var arr = arrcookie[i].split("="); if (arr[0] == "loginName"){ return arr[1]; } } return ""; } /* * 数据显示格式化(日期、性别、证件照) */ function myformatter(date){ var y = date.getFullYear(); var m = date.getMonth()+1; var d = date.getDate(); return y+'-'+(m<10?('0'+m):m)+'-'+(d<10?('0'+d):d); } function myparser(s){ if (!s) return new Date(); var ss = (s.split('-')); var y = parseInt(ss[0],10); var m = parseInt(ss[1],10); var d = parseInt(ss[2],10); if (!isNaN(y) && !isNaN(m) && !isNaN(d)){ return new Date(y,m-1,d); } else { return new Date(); } } function formatSex(value){ if(value == 0){ return '女' ; } else if(value == 1){ return '男' ; } else { return value; } } function formatDate(value){ var date = new Date(value); var y = date.getFullYear(); var m = date.getMonth() + 1; var d = date.getDate(); return y + '-' +m + '-' + d; } function showImg(value, row, index){ if(row.photo){ return "<img style='width:50px;height:50px;' src='./" +row.photo+ "'/>"; }else{ // 若用户没有上传图片则根据性别显示默认照片 if(row.sex){ return "<img style='width:50px;height:50px;' src='default-img/img1.png'/>"; }else{ return "<img style='width:50px;height:50px;' src='default-img/img0.png'/>"; } } }<file_sep>package com.startdima.service; import java.sql.SQLException; import com.startdima.dao.LoginDaoImpl; import com.startdima.pojo.User; public class LoginService { LoginDaoImpl loginDaoImpl = new LoginDaoImpl(); /** * 用户登陆 * @param user * @return boolean * @throws SQLException */ public boolean login(User user) throws SQLException { return loginDaoImpl.login(user); } } <file_sep># EmployeeManagement The Employee Management System contain the basic web project CRUD function The system use mvc model architecture:servlet for controller,html pages for view Use MySQL for database <file_sep>package com.startdima.controller; import java.io.IOException; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.startdima.pojo.User; import com.startdima.service.LoginService; /** * @Description 用户登陆Servlet * @author zhaozsh * @date 2018年8月22日 上午8:28:24 */ @WebServlet("/LoginServlet") public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { LoginService loginService = new LoginService(); //创建session对象 HttpSession session = request.getSession(); String logType = request.getParameter("logType"); if(logType != null && logType.equals("logOut")) { session.removeAttribute("loginName"); response.sendRedirect("index.html"); //重定向到登陆页 }else { User user = new User(); user.setUsername(request.getParameter("loginName")); user.setPassword(request.getParameter("passWord")); try { if("admin".equals(user.getUsername()) || loginService.login(user)) { //把用户数据保存在session域对象中 session.setAttribute("loginName", user.getUsername()); Cookie c1 = new Cookie("loginName", user.getUsername()); response.addCookie(c1); request.getRequestDispatcher("main.html").forward(request, response);//转发到成功页面 }else { response.sendRedirect("index.html"); //重定向到登陆页 } } catch (SQLException e) { e.printStackTrace(); } } } } <file_sep>package com.startdima.controller; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import org.apache.catalina.core.ApplicationPart; import com.alibaba.fastjson.JSONArray; import com.startdima.pojo.Employee; import com.startdima.service.EmployeeService; @WebServlet("/EmployeeServlet") @MultipartConfig(location = "D://") public class EmployeeServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); Employee emp = new Employee(); EmployeeService employeeService = new EmployeeService(); // 获取操作类型值type:add、delete、edit、srarch String type = request.getParameter("type"); try { PrintWriter out = response.getWriter(); // 新增或修改Employee信息 if(type.equals("add") || type.equals("edit") ) { // 获取员工属性值并注入 emp.setName(request.getParameter("name")); emp.setSex(Integer.parseInt(request.getParameter("sex"))); emp.setBirthday(request.getParameter("birthday")); emp.setPhone(request.getParameter("phone")); emp.setAddress(request.getParameter("address")); // 设置存放员工证件照的路径 String path=this.getServletContext().getRealPath("/"); File f = new File(path+"upload\\"); if (!f.exists()) {// 若图片保存路径不存在则创建 f.mkdir(); } Part p=request.getPart("file"); if(p.getContentType().contains("image")){ ApplicationPart ap= (ApplicationPart) p; String fname=ap.getSubmittedFileName(); p.write(path+"upload\\"+fname); emp.setPhoto("upload/"+fname); } if(type.equals("add")){ emp.setIdcard(request.getParameter("idcard")); if(employeeService.addEmployee(emp)) { out.println("添加成功!"); }else { out.println("添加失败!"); } }else{ emp.setPid(request.getParameter("pid")); if(employeeService.editEmployee(emp)) { out.println("修改成功!"); }else { out.println("修改失败!"); } } } // 显示Employee信息 else if(type.equals("search")) { JSONArray jsonArray = employeeService.getEmployees(); out = response.getWriter(); out.println(jsonArray); } // 删除Employee信息 else if(type.equals("delete")) { String pid = request.getParameter("pid"); if(employeeService.deleteEmployee(pid)) { out.println("删除成功!"); }else { out.println("删除失败!"); } } else { out.println("无效的type值!"); System.out.println("无效的type值!"); } } catch (SQLException e) { e.printStackTrace(); } } }
24d058e0e3bad311503299b3684055db3d3d1e99
[ "JavaScript", "SQL", "Java", "Markdown" ]
6
SQL
zhaozsh/EmployeeManagement
cf46694f0b21b7fc85aa89bf457e5765cacce79a
ee896440cf6fce4cc32ba626567ac81c959902fb
refs/heads/master
<file_sep>package com.phicomm.decodeutil; /** * Created by xin08.zhang on 2017/10/25. */ public class DecodeFrameUtil { static { System.loadLibrary("decodeframe"); } public static native int decode(String inputurl, String outputurl); } <file_sep> #include <jni.h> #include <string> extern "C" { #include <libavutil/log.h> #include <libavcodec/avcodec.h> #include <libavformat/avformat.h> #include <libswscale/swscale.h> #include <libavutil/imgutils.h> #include <android/log.h> #define LOGE(format, ...) __android_log_print(ANDROID_LOG_ERROR, "(>_<)", format, ##__VA_ARGS__) #define LOGI(format, ...) __android_log_print(ANDROID_LOG_INFO, "(^_^)", format, ##__VA_ARGS__) #define BI_RGB 0x0 typedef struct tagBITMAPFILEHEADER { unsigned short bfType; //2 位图文件的类型,必须为“BM” unsigned long bfSize; //4 位图文件的大小,以字节为单位 unsigned short bfReserved1; //2 位图文件保留字,必须为0 unsigned short bfReserved2; //2 位图文件保留字,必须为0 unsigned long bfOffBits; //4 位图数据的起始位置,以相对于位图文件头的偏移量表示,以字节为单位 } BITMAPFILEHEADER; //该结构占据14个字节。 typedef struct tagBITMAPINFOHEADER { unsigned long biSize; //4 本结构所占用字节数 long biWidth; //4 位图的宽度,以像素为单位 long biHeight; //4 位图的高度,以像素为单位 unsigned short biPlanes; //2 目标设备的平面数不清,必须为1 unsigned short biBitCount; //2 每个像素所需的位数,必须是1(双色), 4(16色),8(256色)或24(真彩色)之一 unsigned long biCompression; //4 位图压缩类型,必须是 0(不压缩),1(BI_RLE8压缩类型)或2(BI_RLE4压缩类型)之一 unsigned long biSizeImage; //4 位图的大小,以字节为单位 long biXPelsPerMeter; //4 位图水平分辨率,每米像素数 long biYPelsPerMeter; //4 位图垂直分辨率,每米像素数 unsigned long biClrUsed; //4 位图实际使用的颜色表中的颜色数 unsigned long biClrImportant;//4 位图显示过程中重要的颜色数 } BITMAPINFOHEADER; //Output FFmpeg's av_log() void custom_log(void *ptr, int level, const char* fmt, va_list vl){ FILE *fp=fopen("/storage/emulated/0/av_log.txt","a+"); if(fp){ vfprintf(fp,fmt,vl); fflush(fp); fclose(fp); } } int SaveFrameToBMP(char *pPicFile, uint8_t *pRGBBuffer, int nWidth, int nHeight, int nBitCount) { BITMAPFILEHEADER bmpheader; BITMAPINFOHEADER bmpinfo; memset(&bmpheader, 0, sizeof(BITMAPFILEHEADER)); memset(&bmpinfo, 0, sizeof(BITMAPINFOHEADER)); FILE *fp = NULL; fp = fopen(pPicFile, "wb"); if (NULL == fp) { LOGE("file open error"); return -1; } // set BITMAPFILEHEADER value bmpheader.bfType = ('M' << 8) | 'B'; bmpheader.bfReserved1 = 0; bmpheader.bfReserved2 = 0; bmpheader.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER)-2; bmpheader.bfSize = bmpheader.bfOffBits + nWidth * nHeight * nBitCount / 8; // set BITMAPINFOHEADER value bmpinfo.biSize = sizeof(BITMAPINFOHEADER); bmpinfo.biWidth = nWidth; bmpinfo.biHeight = 0 - nHeight; bmpinfo.biPlanes = 1; bmpinfo.biBitCount = nBitCount; bmpinfo.biCompression = BI_RGB; bmpinfo.biSizeImage = 0; bmpinfo.biXPelsPerMeter = 100; bmpinfo.biYPelsPerMeter = 100; bmpinfo.biClrUsed = 0; bmpinfo.biClrImportant = 0; // write pic file fwrite(&bmpheader.bfType, sizeof(bmpheader.bfType), 1, fp); fwrite(&bmpheader.bfSize, sizeof(bmpheader.bfSize), 1, fp); fwrite(&bmpheader.bfReserved1, sizeof(bmpheader.bfReserved1), 1, fp); fwrite(&bmpheader.bfReserved2, sizeof(bmpheader.bfReserved2), 1, fp); fwrite(&bmpheader.bfOffBits, sizeof(bmpheader.bfOffBits), 1, fp); fwrite(&bmpinfo.biSize, sizeof(bmpinfo.biSize), 1, fp); fwrite(&bmpinfo.biWidth, sizeof(bmpinfo.biWidth), 1, fp); fwrite(&bmpinfo.biHeight, sizeof(bmpinfo.biHeight), 1, fp); fwrite(&bmpinfo.biPlanes, sizeof(bmpinfo.biPlanes), 1, fp); fwrite(&bmpinfo.biBitCount, sizeof(bmpinfo.biBitCount), 1, fp); fwrite(&bmpinfo.biCompression, sizeof(bmpinfo.biCompression), 1, fp); fwrite(&bmpinfo.biSizeImage, sizeof(bmpinfo.biSizeImage), 1, fp); fwrite(&bmpinfo.biXPelsPerMeter, sizeof(bmpinfo.biXPelsPerMeter), 1, fp); fwrite(&bmpinfo.biYPelsPerMeter, sizeof(bmpinfo.biYPelsPerMeter), 1, fp); fwrite(&bmpinfo.biClrUsed, sizeof(bmpinfo.biClrUsed), 1, fp); fwrite(&bmpinfo.biClrImportant, sizeof(bmpinfo.biClrImportant), 1, fp); fwrite(pRGBBuffer, nWidth * nHeight * nBitCount / 8, 1, fp); fclose(fp); LOGI("write over"); return 0; } JNIEXPORT jint JNICALL Java_com_phicomm_decodeutil_DecodeFrameUtil_decode( JNIEnv *env, jobject , jstring input_jstr, jstring output_jstr) { AVFormatContext *pFormatCtx; int i, videoindex; AVCodecContext *pCodecCtx; AVCodec *pCodec; AVFrame *pFrame,*pFrameYUV; uint8_t *out_buffer; AVPacket *packet; //int y_size; int ret, got_picture; int picoutid=0; struct SwsContext *img_convert_ctx; //FILE *fp_yuv; int frame_cnt; clock_t time_start, time_finish; double time_duration = 0.0; char input_str[500]={0}; char output_str[500]={0}; char info[1000]={0}; sprintf(input_str,"%s",env->GetStringUTFChars(input_jstr, NULL)); sprintf(output_str,"%s",env->GetStringUTFChars(output_jstr, NULL)); //FFmpeg av_log() callback av_log_set_callback(custom_log); av_register_all(); avformat_network_init(); pFormatCtx = avformat_alloc_context(); if(avformat_open_input(&pFormatCtx,input_str,NULL,NULL)!=0){ LOGE("Couldn't open input stream.\n"); return -1; } if(avformat_find_stream_info(pFormatCtx,NULL)<0){ LOGE("Couldn't find stream information.\n"); return -1; } videoindex=-1; for(i=0; i<pFormatCtx->nb_streams; i++) if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO){ videoindex=i; break; } if(videoindex==-1){ LOGE("Couldn't find a video stream.\n"); return -1; } pCodecCtx=pFormatCtx->streams[videoindex]->codec; pCodec=avcodec_find_decoder(pCodecCtx->codec_id); if(pCodec==NULL){ LOGE("Couldn't find Codec.\n"); return -1; } if(avcodec_open2(pCodecCtx, pCodec,NULL)<0){ LOGE("Couldn't open codec.\n"); return -1; } pFrame=av_frame_alloc(); pFrameYUV=av_frame_alloc(); out_buffer=(unsigned char *)av_malloc(av_image_get_buffer_size(AV_PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height,1)); av_image_fill_arrays(pFrameYUV->data, pFrameYUV->linesize,out_buffer, AV_PIX_FMT_YUV420P,pCodecCtx->width, pCodecCtx->height,1); packet=(AVPacket *)av_malloc(sizeof(AVPacket)); img_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height, AV_PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL); sprintf(info, "[Input ]%s\n", input_str); sprintf(info, "%s[Output ]%s\n",info,output_str); sprintf(info, "%s[Format ]%s\n",info, pFormatCtx->iformat->name); sprintf(info, "%s[Codec ]%s\n",info, pCodecCtx->codec->name); sprintf(info, "%s[Resolution]%dx%d\n",info, pCodecCtx->width,pCodecCtx->height); /*fp_yuv=fopen(output_str,"wb+"); if(fp_yuv==NULL){ printf("Cannot open output file.\n"); return -1; }*/ frame_cnt=0; time_start = clock(); while (av_read_frame(pFormatCtx, packet) >= 0 && picoutid < 8) { if(packet->stream_index==videoindex){ ret = avcodec_decode_video2(pCodecCtx, pFrame, &got_picture, packet); if(ret < 0){ LOGE("Decode Error.\n"); return -1; } if(got_picture){ /*sws_scale(img_convert_ctx, (const uint8_t* const*)pFrame->data, pFrame->linesize, 0, pCodecCtx->height, pFrameYUV->data, pFrameYUV->linesize); y_size=pCodecCtx->width*pCodecCtx->height; fwrite(pFrameYUV->data[0],1,y_size,fp_yuv); //Y fwrite(pFrameYUV->data[1],1,y_size/4,fp_yuv); //U fwrite(pFrameYUV->data[2],1,y_size/4,fp_yuv); //V*/ //Output info char pictype_str[10]={0}; switch(pFrame->pict_type){ case AV_PICTURE_TYPE_I: { sprintf(pictype_str, "I"); char szPicFile[256]; picoutid++; memset(szPicFile, 0, sizeof(szPicFile)); strncpy(szPicFile, output_str, sizeof(szPicFile)); char sframecnt[3]; sprintf(sframecnt, "%d", picoutid); strncat(szPicFile, sframecnt, sizeof(szPicFile)); strncat(szPicFile, ".bmp", sizeof(szPicFile)); // Convert the image from its native format to RGB AVFrame *pFrameRGB = NULL; // Allocate an AVFrame structure pFrameRGB = av_frame_alloc(); if (pFrameRGB == NULL) { LOGI("Allocate an AVFrame structure error."); return -1; } uint8_t *pBuffer; int numBytes; int destw = pCodecCtx->width; int desth = pCodecCtx->height; if (destw > 252 || desth > 252) { int sca = destw / 252 > desth / 252 ? destw / 252 : desth / 252; destw = destw / sca; desth = desth / sca; } numBytes = av_image_get_buffer_size(AV_PIX_FMT_BGR24, destw, desth, 1); pBuffer = (uint8_t *) av_malloc(numBytes * sizeof(uint8_t)); av_image_fill_arrays(pFrameRGB->data, pFrameRGB->linesize, pBuffer, AV_PIX_FMT_BGR24, destw, desth, 1); struct SwsContext *convert_ctx; convert_ctx = sws_getContext( pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt, destw, desth, AV_PIX_FMT_BGR24, SWS_BICUBIC, NULL, NULL, NULL); sws_scale(convert_ctx, (uint8_t const *const *) pFrame->data, pFrame->linesize, 0, pCodecCtx->height, pFrameRGB->data, pFrameRGB->linesize); SaveFrameToBMP(szPicFile, pFrameRGB->data[0], destw, desth, 24); sws_freeContext(convert_ctx); LOGI("Frame Index: %5d. Type:%s saved", frame_cnt, pictype_str); } break; case AV_PICTURE_TYPE_P:sprintf(pictype_str,"P");break; case AV_PICTURE_TYPE_B:sprintf(pictype_str,"B");break; default:sprintf(pictype_str,"Other");break; } LOGI("Frame Index: %5d. Type:%s",frame_cnt,pictype_str); frame_cnt++; } } av_free_packet(packet); } time_finish = clock(); time_duration=(double)(time_finish - time_start); sprintf(info, "%s[Time ]%fms\n",info,time_duration); sprintf(info, "%s[Count ]%d\n",info,frame_cnt); sws_freeContext(img_convert_ctx); //fclose(fp_yuv); av_frame_free(&pFrameYUV); av_frame_free(&pFrame); avcodec_close(pCodecCtx); avformat_close_input(&pFormatCtx); return picoutid; } }
a26f25e7476d010909a0ac1844e475c2d16ed19b
[ "Java", "C++" ]
2
Java
zx06063068/MovieToPic
823aaff6921c77a643f0d093eae2a8ece544dcb3
cfdc118b532a6d481c7818a3f7de1cbf0bfcaa0f
refs/heads/master
<repo_name>lee-pham/js-functions-lab-bootcamp-prep-000<file_sep>/index.js // write your code below! function learn() => { }
0aa8077e970c060c10602aa61206d76e2cecda24
[ "JavaScript" ]
1
JavaScript
lee-pham/js-functions-lab-bootcamp-prep-000
ad7b0e5ac5df9f61e84e931f44ce4869bcb8adc6
6a8ef4ffb8b2262156cd1b8edc1a7d4e16d5f04b
refs/heads/main
<file_sep>import { Component, OnInit } from '@angular/core'; import * as MediumEditor from 'medium-editor'; import { AngularFireAuth } from '@angular/fire/auth'; import { AuthService } from '../services/auth.service'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'], }) export class HomeComponent implements OnInit { latestContent: string; name: string; content: string; editor: MediumEditor.MediumEditor; constructor( private afAuth: AngularFireAuth, private authService: AuthService ) {} ngOnChanges(): void { // this.editor.setContent(this.latestContent); } ngOnInit(): void { this.editor = new MediumEditor('.editable'); const handleContentChange = () => { this.content = this.editor.getContent(); this.authService.addContent(this.content); }; this.getLatestContent(); console.log('undefined???', this.latestContent); this.afAuth.authState.subscribe((user) => { if (user) { this.name = user.displayName.split(' ')[0]; } }); this.editor.subscribe('editableInput', handleContentChange.bind(this)); } handleLogout() { this.authService.logoutUser(); } getLatestContent() { this.authService.getLatestContent().subscribe((value) => { this.latestContent = JSON.stringify(value[0]['content']); console.log('this.latestContent', this.latestContent); }); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { AuthService } from '../services/auth.service'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'], }) export class LoginComponent implements OnInit { isLoggedIn: boolean = false; constructor(private authService: AuthService, private router: Router) {} ngOnInit(): void { if (this.authService.userLoggedIn) { this.isLoggedIn = true; this.router.navigate(['/dashboard']); } } loginUser() { this.authService.loginWithGoogle().then((result) => { if (result == null) { this.router.navigate(['/home']); } else if (result.isValid == false) { console.log('login error', result); } }); } } <file_sep>import { Injectable } from '@angular/core'; import firebase from 'firebase/app'; import { AngularFireAuth } from '@angular/fire/auth'; import { AngularFirestore } from '@angular/fire/firestore'; import { Router } from '@angular/router'; @Injectable({ providedIn: 'root', }) export class AuthService { userLoggedIn: boolean; userId: string; constructor( private router: Router, private afAuth: AngularFireAuth, private afs: AngularFirestore ) { this.userLoggedIn = false; this.afAuth.onAuthStateChanged((user) => { if (user) { this.userLoggedIn = true; this.userId = user.uid; } else { this.userLoggedIn = false; } }); } loginWithGoogle(): Promise<any> { return this.afAuth .signInWithPopup(new firebase.auth.GoogleAuthProvider()) .then(() => { this.userLoggedIn = true; console.log('Successfully logged with with Google'); }) .catch((error) => { console.log('error:', error); if (error.code) return error; }); } logoutUser(): Promise<void> { return this.afAuth .signOut() .then(() => { this.router.navigate(['/login']); }) .catch((error) => { console.log('error', error); if (error.code) return error; }); } addContent(content: string) { this.afs .collection('editor-content') .add({ userId: this.userId, content: content, created: firebase.firestore.FieldValue.serverTimestamp(), }) .then(function (res) { // console.log(res); }); } getLatestContent() { return this.afs .collection('editor-content', (ref) => ref .where('userId', '==', this.userId) .orderBy('created', 'desc') .limit(1) ) .valueChanges(); // .subscribe((value) => { // this.latestContent = JSON.stringify(value[0]['content']); // console.log('this.latestContent', this.latestContent); // }); // return this.latestContent; } }
ecf7abe025bfe435abab0a117951bd82c49758fc
[ "TypeScript" ]
3
TypeScript
jiayu-joyce-he/angular-firebase-medium-editor
3574c48d1c78c1f16813f19fc1c64cbd4ca7789d
49b09d6539ad50256995f0a75df13d76dba258d9
refs/heads/master
<repo_name>SkamDart/iface-watcher<file_sep>/Cargo.toml [package] name = "iface-reporter" version = "0.1.0" authors = ["<NAME> <<EMAIL>>"] edition = "2018" [dependencies] clap = "2.33.1" dogstatsd = "0.6.1" serde_json = "1.0.56" <file_sep>/src/main.rs use std::{fs, io, path, thread, time::Duration}; use clap::{App, AppSettings, Arg}; use dogstatsd::{Client, Options}; use serde_json::{Map, Value}; trait Report { fn report(&mut self, tag: String, value: String) -> io::Result<()>; } struct Interface { name: String, alias: String, entries: Vec<Entry>, } struct Entry { path: path::PathBuf, tag: String, } struct DatadogReporter { client: Client, } struct LogReporter {} impl LogReporter { pub fn new() -> Self { Self {} } } impl Interface { pub fn from_path(prefix: String, name: String, alias: String) -> io::Result<Self> { // What does this mean <NAME>? let mut s = name.to_owned(); s.pop().unwrap().to_string(); s.remove(0).to_string(); let root_dir = "/sys/class/net/".to_owned() + s.as_str() + "/statistics/"; let entries = fs::read_dir(root_dir)? .into_iter() .filter_map(Result::ok) .map(|e| Entry { path: e.path(), tag: prefix.to_owned() + alias.as_str() + "." + e.file_name().to_str().unwrap(), }) .collect::<Vec<_>>(); Ok(Self { name, alias, entries, }) } pub fn report<R: Report>(&mut self, reporter: &mut R) -> Vec<io::Result<()>> { self.entries .iter() .map(|entry| { fs::read_to_string(entry.path.as_path()) .and_then(|mut contents| { if contents.ends_with('\n') { contents.pop(); } Ok(contents) }) .and_then(|contents| { contents .parse::<u64>() .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)) }) .and_then(|value| { reporter .report(entry.tag.to_string(), value.to_string()) .map_err(|e| io::Error::new(io::ErrorKind::Other, e)) }) }) .collect::<Vec<_>>() } } impl DatadogReporter { pub fn new() -> io::Result<Self> { match Client::new(Options::default()) { Ok(client) => Ok(Self { client }), Err(e) => Err(io::Error::new(io::ErrorKind::Other, e)), } } } impl Report for DatadogReporter { fn report(&mut self, tag: String, value: String) -> io::Result<()> { self.client .gauge(tag.to_string(), value.to_string(), &["tag:required"]) .map_err(|e| io::Error::new(io::ErrorKind::Other, e)) } } impl Report for LogReporter { fn report(&mut self, tag: String, value: String) -> io::Result<()> { println!("{} {}", tag, value); Ok(()) } } fn create_report(filename: String, prefix: String) -> io::Result<Vec<Interface>> { let content = fs::read_to_string(filename)?; let json: Map<String, Value> = serde_json::from_str(&content)?; let ifaces = json .iter() .map(move |(alias, iface)| { match Interface::from_path(prefix.to_string(), iface.to_string(), alias.to_string()) { Ok(i) => { println!("Watching {}", i.alias); Ok(i) } Err(e) => { println!("Slain by {:?} {:?}. Reason: {:?}", alias, iface, e); Err(e) } } }) .filter_map(Result::ok) .collect::<Vec<_>>(); Ok(ifaces) } fn main() -> io::Result<()> { let matches = App::new("iface-reporter") .setting(AppSettings::ArgRequiredElseHelp) .version("0.0.1") .author("<NAME> <<EMAIL>") .about("Publishes /sys/class/net/<iface> metrics to datadog") .arg(Arg::with_name("filename").index(1).required(true).help( "json file containing a set of key-value pairs of clean name to interface to watch", )) .arg( Arg::with_name("prefix") .index(2) .required(true) .help("prefix to report metrics with."), ) .arg(Arg::with_name("config")) .get_matches(); let filename = matches.value_of("filename").expect("No file passed"); let prefix = matches.value_of("prefix").expect("No prefix passed"); let mut report = create_report(filename.to_string(), prefix.to_string())?; if report.len() == 0 { return Err(io::Error::new(io::ErrorKind::Other, "Empty report")); } let mut dd = DatadogReporter::new()?; // let mut dd = LogReporter::new(); loop { for iface in report.iter_mut() { let _ = iface.report(&mut dd); } thread::sleep(Duration::from_millis(500)); } } <file_sep>/README.md # IFace Reporter Network debugging tool that prints publishes [sys/class/net](https://www.kernel.org/doc/Documentation/ABI/testing/sysfs-class-net) data to Datadog
61f6c5b1523e66d0f9248287022c58718030ad9c
[ "TOML", "Rust", "Markdown" ]
3
TOML
SkamDart/iface-watcher
96e7574f508cd93816b5b2d0b06f7b3aae701e2c
4d0ce433598bc5dd53287ee35f374a91991efec6
refs/heads/dev
<repo_name>alhparsa/PySyft<file_sep>/syft/version.py __version__ = "0.2.0a2"
2fbd23448476aeaf1c7b2233f36efefd6ce282f3
[ "Python" ]
1
Python
alhparsa/PySyft
c4f33aab94e6bfbc704d8856b4e570c7d3069059
ed5fa49db45670a7af985b8fe4d4f21ffd116e2d
refs/heads/main
<repo_name>ekhacahya/rijksmuseum<file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/view/home/ArtViewState.kt package dev.ecbn.rijksmuseum.view.home import dev.ecbn.rijksmuseum.data.model.Art /** * Created by <NAME> on 03/11/21. * <EMAIL> */ sealed class ArtViewState { data class Success(val artCollections: List<Art>): ArtViewState() data class Loading(val isLoading: Boolean): ArtViewState() data class Error(val message: String): ArtViewState() } <file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/view/main/MainActivity.kt package dev.ecbn.rijksmuseum.view.main import android.os.Bundle import android.view.MenuItem import android.view.View import androidx.core.view.GravityCompat import androidx.navigation.Navigation import androidx.navigation.ui.* import coil.load import coil.transform.CircleCropTransformation import dev.ecbn.rijksmuseum.R import dev.ecbn.rijksmuseum.base.BaseActivity import dev.ecbn.rijksmuseum.databinding.ActivityMainBinding import dev.ecbn.rijksmuseum.databinding.NavHeaderBinding import dev.ecbn.rijksmuseum.utils.observe import dev.ecbn.rijksmuseum.view.profile.ProfileViewModel import dev.ecbn.rijksmuseum.view.profile.ProfileViewState class MainActivity : BaseActivity<ProfileViewModel, ActivityMainBinding>( ProfileViewModel::class, ActivityMainBinding::inflate ) { private lateinit var appBarConfiguration: AppBarConfiguration private val navController by lazy { return@lazy Navigation.findNavController(this, R.id.nav_host_fragment) } override fun onInitUI(savedInstanceState: Bundle?) { setupDrawerLayout() } private fun setupDrawerLayout() { with(binding) { setSupportActionBar(toolbar) appBarConfiguration = AppBarConfiguration( setOf(R.id.homeFragment, R.id.profileFragment), drawerLayout ) navView.setupWithNavController(navController) NavigationUI.setupActionBarWithNavController( this@MainActivity, navController, appBarConfiguration ) } } override fun onInitData() { with(viewModel) { observe(profileViewState, ::onProfileReceived) getAccount() } } private fun onProfileReceived(data: ProfileViewState) { when (data) { is ProfileViewState.Success -> { with(binding) { if (navView.headerCount > 0) { val headerView: View = navView.getHeaderView(0) val headerBinding: NavHeaderBinding = NavHeaderBinding.bind(headerView) with(headerBinding) { ivProfile.load(data.account.profileUrl) { crossfade(true) transformations(CircleCropTransformation()) } tvWelcome.text = String.format(getString(R.string.message_welcome), data.account.username) } } } } is ProfileViewState.Loading -> { } } } override fun onSupportNavigateUp() = navController.navigateUp(appBarConfiguration) override fun onOptionsItemSelected(item: MenuItem) = item.onNavDestinationSelected(navController) || super.onOptionsItemSelected(item) override fun onBackPressed() { if (binding.drawerLayout.isDrawerOpen(GravityCompat.START)) { binding.drawerLayout.closeDrawer(GravityCompat.START) } else { super.onBackPressed() } } }<file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/view/login/LoginViewState.kt package dev.ecbn.rijksmuseum.view.login import dev.ecbn.rijksmuseum.data.model.Account /** * Created by <NAME> on 04/11/21. * <EMAIL> */ sealed class LoginViewState { data class Success(val account: Account) : LoginViewState() data class Loading(val isLoading: Boolean) : LoginViewState() data class Error(val message: String) : LoginViewState() data class ValidationError(val type: String, val message: String) : LoginViewState() }<file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/view/login/LoginActivity.kt package dev.ecbn.rijksmuseum.view.login import android.content.Intent import android.os.Bundle import dev.ecbn.rijksmuseum.BuildConfig import dev.ecbn.rijksmuseum.base.BaseActivity import dev.ecbn.rijksmuseum.databinding.ActivityLoginBinding import dev.ecbn.rijksmuseum.utils.logInfo import dev.ecbn.rijksmuseum.utils.observe import dev.ecbn.rijksmuseum.utils.snackBarDismissAction import dev.ecbn.rijksmuseum.view.main.MainActivity import dev.ecbn.rijksmuseum.view.register.RegisterActivity class LoginActivity : BaseActivity<LoginViewModel, ActivityLoginBinding>( LoginViewModel::class, ActivityLoginBinding::inflate ) { override fun onInitUI(savedInstanceState: Bundle?) { with(binding) { setSupportActionBar(toolbar) btnLogin.setOnClickListener { viewModel.validate( tilUsername.editText?.text.toString(), tilPassword.editText?.text.toString() ) } tvRegister.setOnClickListener { gotoRegister() } } } override fun onInitData() { with(viewModel) { observe(loginViewState, ::onLoginViewStateReceived) } } private fun onLoginViewStateReceived(state: LoginViewState) { logInfo("onLoginViewStateReceived $state") when (state) { is LoginViewState.ValidationError -> { removeError() with(binding) { if (state.type == "username") tilUsername.error = state.message else tilPassword.error = state.message } } is LoginViewState.Loading -> { removeError() } is LoginViewState.Error -> { mRootView?.snackBarDismissAction("OK", state.message) } is LoginViewState.Success -> { gotoMain() } } } private fun removeError() { with(binding) { tilUsername.error = "" tilPassword.error = "" } } private fun gotoRegister() { val intent = Intent(this, RegisterActivity::class.java) startActivity(intent) } private fun gotoMain() { val intent = Intent(this, MainActivity::class.java) startActivity(intent) finish() } }<file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/utils/TimberExt.kt package dev.ecbn.rijksmuseum.utils import com.orhanobut.logger.AndroidLogAdapter import com.orhanobut.logger.Logger import dev.ecbn.rijksmuseum.BuildConfig import timber.log.Timber /** * Created by <NAME> on 27/10/21. * <EMAIL> */ fun timberInitialization() { if (BuildConfig.DEBUG) { Timber.plant(object : Timber.DebugTree() { override fun log(priority: Int, tag: String?, message: String, t: Throwable?) { Logger.log(priority, tag, message, t) } }) } Logger.addLogAdapter(AndroidLogAdapter()) } fun logInfo(s: String, vararg objects: Any) { Timber.i(s, *objects) } fun logInfo(throwable: Throwable, s: String, vararg objects: Any) { Timber.i(throwable, s, *objects) } fun logDebug(s: String, vararg objects: Any) { Timber.d(s, *objects) } fun logDebug(throwable: Throwable, s: String, vararg objects: Any) { Timber.d(throwable, s, *objects) } fun logWarning(s: String, vararg objects: Any) { Timber.d(s, *objects) } fun logWarning(throwable: Throwable, s: String, vararg objects: Any) { Timber.w(throwable, s, *objects) } fun logVerbose(s: String, vararg objects: Any) { Timber.v(s, *objects) } fun logVerbose(throwable: Throwable, s: String, vararg objects: Any) { Timber.v(throwable, s, *objects) } fun logError(s: String, vararg objects: Any) { Timber.e(s, *objects) } fun logError(throwable: Throwable, s: String, vararg objects: Any) { Timber.e(throwable, s, *objects) }<file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/view/splash/SplashViewModel.kt package dev.ecbn.rijksmuseum.view.splash import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import dev.ecbn.rijksmuseum.base.BaseViewModel import kotlinx.coroutines.delay import kotlinx.coroutines.launch /** * Created by <NAME> on 04/11/21. * <EMAIL> */ class SplashViewModel : BaseViewModel() { private val _isLoggedIn: MutableLiveData<Boolean> = MutableLiveData() val isLoggedIn: LiveData<Boolean> = _isLoggedIn fun checkSession(){ viewModelScope.launch { delay(1000) _isLoggedIn.postValue(sessionHelper.isLogin()) } } }<file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/data/repo/profile/AccountRepository.kt package dev.ecbn.rijksmuseum.data.repo.profile import dev.ecbn.rijksmuseum.data.local.AccountDao import dev.ecbn.rijksmuseum.data.model.Account import dev.ecbn.rijksmuseum.data.remote.Response import dev.ecbn.rijksmuseum.utils.logInfo /** * Created by <NAME> on 04/11/21. * <EMAIL> */ class AccountRepository constructor( private val local: AccountDao ) : IAccountRepository { override fun registerAccount( username: String, password: String, response: Response<Account> ) { val user = local.getAccount(username) if (user == null) { local.insertAccount(Account(username, password)) val checkUser = local.getAccount(username) if (checkUser != null) response.onSuccess(checkUser) else response.onError("Registration failed") } else { response.onError("User already exist") } } override fun loginAccount( username: String, password: String, response: Response<Account> ) { val user = local.getAccount(username) logInfo("USER -> $user") if (user == null) { response.onError("User not found") return } if (user.password == password) { logInfo("USER ->onSuccess $user") response.onSuccess(user) } else { response.onError("Wrong password") } } override fun getAccount() { } }<file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/data/model/ArtCollectionResponse.kt package dev.ecbn.rijksmuseum.data.model import com.google.gson.annotations.SerializedName /** * Created by <NAME> on 02/11/21. * <EMAIL> */ data class ArtCollectionResponse( @SerializedName("artObjects") var artObjects: List<Art> ) open class BaseResponse( @SerializedName("count") var count: Int = 1, @SerializedName("elapsedMilliseconds") var elapsedMilliseconds: Int = 0, ) data class DataResponse<T>( @SerializedName("artObjects") var results: T? ): BaseResponse() <file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/data/local/LocalDB.kt package dev.ecbn.rijksmuseum.data.local import androidx.room.Database import androidx.room.RoomDatabase import androidx.room.TypeConverters import dev.ecbn.rijksmuseum.data.model.Account import dev.ecbn.rijksmuseum.data.model.Art /** * Created by <NAME> on 02/11/21. * <EMAIL> */ @Database(entities = [Art::class, Account::class], version = 1, exportSchema = true) @TypeConverters(HeaderImageConverter::class, WebImageConverter::class) abstract class LocalDB: RoomDatabase() { abstract fun artDao(): ArtDao abstract fun accountDao(): AccountDao }<file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/data/local/SessionHelper.kt package dev.ecbn.rijksmuseum.data.local import com.orhanobut.hawk.Hawk import dev.ecbn.rijksmuseum.data.model.Account /** * Created by <NAME> on 02/11/21. * <EMAIL> */ const val IS_LOGIN = "is_login" const val ACCOUNT = "logged_in_account" class SessionHelper { fun setLogin(isLogin: Boolean) = Hawk.put(IS_LOGIN, isLogin) fun isLogin(): Boolean = Hawk.get(IS_LOGIN, false) fun setAccount(account: Account) = Hawk.put(ACCOUNT, account) fun getAccount(): Account = Hawk.get(ACCOUNT) fun deleteSession(key: String) = Hawk.delete(key) fun clearSession() = Hawk.deleteAll() }<file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/data/model/Account.kt package dev.ecbn.rijksmuseum.data.model import android.os.Parcelable import androidx.room.Entity import androidx.room.PrimaryKey import kotlinx.parcelize.Parcelize /** * Created by <NAME> on 04/11/21. * <EMAIL> */ @Entity @Parcelize data class Account( @PrimaryKey var username: String, var password: String, var profileUrl: String = "https://picsum.photos/200" ) : Parcelable <file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/data/model/HeaderImage.kt package dev.ecbn.rijksmuseum.data.model import android.os.Parcelable import com.google.gson.annotations.SerializedName import kotlinx.parcelize.Parcelize @Parcelize data class HeaderImage( @SerializedName("guid") var guid: String, @SerializedName("url") var url: String ): Parcelable<file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/data/remote/ArtApiService.kt package dev.ecbn.rijksmuseum.data.remote import com.skydoves.sandwich.ApiResponse import dev.ecbn.rijksmuseum.data.model.Art import dev.ecbn.rijksmuseum.data.model.ArtCollectionResponse import dev.ecbn.rijksmuseum.data.model.DataResponse import retrofit2.Call import retrofit2.http.GET /** * Created by <NAME> on 02/11/21. * <EMAIL> */ interface ArtApiService { @GET("collection") suspend fun getArtCollections(): ApiResponse<DataResponse<List<Art>>> }<file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/di/LocalDBModule.kt package dev.ecbn.rijksmuseum.di import androidx.room.Room import dev.ecbn.rijksmuseum.R import dev.ecbn.rijksmuseum.data.local.LocalDB import org.koin.android.ext.koin.androidApplication import org.koin.dsl.module /** * Created by <NAME> on 02/11/21. * <EMAIL> */ val localDBModule = module { single { Room.databaseBuilder( androidApplication(), LocalDB::class.java, androidApplication().getString(R.string.database) ) .fallbackToDestructiveMigration() .build() } single { get<LocalDB>().artDao() } single { get<LocalDB>().accountDao() } }<file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/view/home/ArtAdapter.kt package dev.ecbn.rijksmuseum.view.home import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import coil.load import dev.ecbn.rijksmuseum.data.model.Art import dev.ecbn.rijksmuseum.databinding.ItemArtVerticalBinding /** * Created by <NAME> on 04/11/21. * <EMAIL> */ class ArtAdapter(val listener: ArtSelectedListener) : RecyclerView.Adapter<ArtAdapter.ArtViewHolder>() { var mListMove: List<Art> = emptyList() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ArtViewHolder { val inflater = LayoutInflater.from(parent.context) return ArtViewHolder(ItemArtVerticalBinding.inflate(inflater)) } override fun onBindViewHolder(holder: ArtViewHolder, position: Int) { (holder as Binder<Art>).bind(mListMove[position]) holder.itemView.tag = mListMove[position] } override fun getItemCount() = mListMove.size fun setItem(list: List<Art>) { this.mListMove = list notifyDataSetChanged() } inner class ArtViewHolder(private val binding: ItemArtVerticalBinding) : RecyclerView.ViewHolder(binding.root), Binder<Art> { override fun bind(data: Art) { binding.apply { tvTitle.text = data.title ivPoster.load(data.webImage.url) root.setOnClickListener { listener.onArtSelected(data) } } } } } interface Binder<T> { fun bind(data: T) } interface ArtSelectedListener { fun onArtSelected(art: Art) }<file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/di/RepositoryModule.kt package dev.ecbn.rijksmuseum.di import dev.ecbn.rijksmuseum.data.repo.art.ArtRepository import dev.ecbn.rijksmuseum.data.repo.art.IArtRepository import dev.ecbn.rijksmuseum.data.repo.profile.AccountRepository import dev.ecbn.rijksmuseum.data.repo.profile.IAccountRepository import org.koin.dsl.module /** * Created by <NAME> on 02/11/21. * <EMAIL> */ val repositoryModule = module { single<IArtRepository> { ArtRepository(get()) } single<IAccountRepository> { AccountRepository(get()) } }<file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/data/repo/profile/IAccountRepository.kt package dev.ecbn.rijksmuseum.data.repo.profile import dev.ecbn.rijksmuseum.data.model.Account import dev.ecbn.rijksmuseum.data.model.Art import dev.ecbn.rijksmuseum.data.remote.Response /** * Created by <NAME> on 04/11/21. * <EMAIL> */ interface IAccountRepository { fun registerAccount(username: String, password: String, response: Response<Account>) fun loginAccount(username: String, password: String, response: Response<Account>) fun getAccount() }<file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/data/remote/GlobalResponseOperator.kt package dev.ecbn.rijksmuseum.data.remote import android.app.Application import android.widget.Toast import com.skydoves.sandwich.ApiResponse import com.skydoves.sandwich.StatusCode import com.skydoves.sandwich.message import com.skydoves.sandwich.operators.ApiResponseSuspendOperator import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.net.UnknownHostException /** * Created by <NAME> on 03/11/21. * <EMAIL> */ class GlobalResponseOperator<T> constructor( private val application: Application ) : ApiResponseSuspendOperator<T>() { override suspend fun onError(apiResponse: ApiResponse.Failure.Error<T>) = withContext(Dispatchers.Main) { apiResponse.run { when (statusCode) { StatusCode.InternalServerError -> toast("InternalServerError") StatusCode.BadGateway -> toast("BadGateway") else -> toast("$statusCode(${statusCode.code}): ${message()}") } } } override suspend fun onException(apiResponse: ApiResponse.Failure.Exception<T>) = withContext(Dispatchers.Main) { apiResponse.run { if (this.exception is UnknownHostException){ toast("No internet connection!") }else{ toast(message()) } } } override suspend fun onSuccess(apiResponse: ApiResponse.Success<T>) = Unit private fun toast(message: String) { Toast.makeText(application, message, Toast.LENGTH_SHORT).show() } }<file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/view/profile/ProfileViewState.kt package dev.ecbn.rijksmuseum.view.profile import dev.ecbn.rijksmuseum.data.model.Account /** * Created by <NAME> on 04/11/21. * <EMAIL> */ sealed class ProfileViewState { data class Success(val account: Account) : ProfileViewState() data class Loading(val isLoading: Boolean) : ProfileViewState() data class Error(val message: String) : ProfileViewState() object Logout : ProfileViewState() }<file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/di/ViewModelModule.kt package dev.ecbn.rijksmuseum.di import dev.ecbn.rijksmuseum.view.home.HomeViewModel import dev.ecbn.rijksmuseum.view.login.LoginViewModel import dev.ecbn.rijksmuseum.view.profile.ProfileViewModel import dev.ecbn.rijksmuseum.view.register.RegisterViewModel import dev.ecbn.rijksmuseum.view.splash.SplashViewModel import org.koin.android.viewmodel.dsl.viewModel import org.koin.dsl.module /** * Created by <NAME> on 02/11/21. * <EMAIL> */ val viewModelModule = module { viewModel { SplashViewModel() } viewModel { LoginViewModel(get()) } viewModel { RegisterViewModel(get()) } viewModel { HomeViewModel(get()) } viewModel { ProfileViewModel() } }<file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/data/local/AccountDao.kt package dev.ecbn.rijksmuseum.data.local import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import dev.ecbn.rijksmuseum.data.model.Account /** * Created by <NAME> on 02/11/21. * <EMAIL> */ @Dao interface AccountDao { @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertAccount(account: Account) @Query("SELECT * FROM Account WHERE username = :username") fun getAccount(username: String): Account? @Query("SELECT * FROM Account") fun getArtCollections(): List<Account> }<file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/data/remote/Response.kt package dev.ecbn.rijksmuseum.data.remote /** * Created by <NAME> on 02/11/21. * <EMAIL> */ interface Response<T> { fun onSuccess(data: T) fun onError(message: String) }<file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/data/model/Art.kt package dev.ecbn.rijksmuseum.data.model import android.os.Parcelable import androidx.room.Entity import androidx.room.PrimaryKey import androidx.room.TypeConverter import androidx.room.TypeConverters import com.google.gson.annotations.SerializedName import dev.ecbn.rijksmuseum.data.local.HeaderImageConverter import dev.ecbn.rijksmuseum.data.local.WebImageConverter import kotlinx.parcelize.Parcelize @Entity @Parcelize data class Art( @SerializedName("hasImage") var hasImage: Boolean, @SerializedName("headerImage") var headerImage: HeaderImage, @PrimaryKey @SerializedName("id") var id: String, @SerializedName("longTitle") var longTitle: String, @SerializedName("principalOrFirstMaker") var principalOrFirstMaker: String, @SerializedName("title") var title: String, @SerializedName("webImage") var webImage: WebImage ): Parcelable<file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/view/profile/ProfileViewModel.kt package dev.ecbn.rijksmuseum.view.profile import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import dev.ecbn.rijksmuseum.base.BaseViewModel /** * Created by <NAME> on 03/11/21. * <EMAIL> */ class ProfileViewModel : BaseViewModel() { private val _profileViewState: MutableLiveData<ProfileViewState> = MutableLiveData() val profileViewState: LiveData<ProfileViewState> = _profileViewState fun getAccount(){ val account = sessionHelper.getAccount() _profileViewState.postValue(ProfileViewState.Success(account)) } fun logout(){ sessionHelper.clearSession() _profileViewState.postValue(ProfileViewState.Logout) } }<file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/utils/Ext.kt package dev.ecbn.rijksmuseum.utils import android.content.Context import android.graphics.Rect import android.view.Gravity import android.view.View import android.widget.FrameLayout import android.widget.Toast import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.ItemDecoration import com.google.android.material.snackbar.Snackbar /** * Created by <NAME> on 26/10/21. * <EMAIL> */ fun <T> LifecycleOwner.observe(liveData: LiveData<T>, action: (t: T) -> Unit) { liveData.observe(this, { it?.let { t -> action(t) } }) } fun <T> LifecycleOwner.observe(liveData: MutableLiveData<T>, action: (t: T) -> Unit) { liveData.observe(this, { it?.let { t -> action(t) } }) } fun View.showIf(isShow: Boolean = true) { visibility = if (isShow) View.VISIBLE else View.GONE } fun Context?.toast(text: CharSequence, duration: Int = Toast.LENGTH_SHORT) = this?.let { Toast.makeText(it, text, duration).show() } fun Context.setupRecyclerViewList(recyclerView: RecyclerView) { recyclerView.apply { setHasFixedSize(true) layoutManager = this@setupRecyclerViewList.verticalLayout() itemAnimator = DefaultItemAnimator() } } fun Context.verticalLayout(): LinearLayoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false) class SpacesItemDecoration(space: Int) : ItemDecoration() { private val halfSpace: Int override fun getItemOffsets(outRect: Rect, itemPosition: Int, parent: RecyclerView) { if (parent.paddingLeft != halfSpace) { parent.setPadding(halfSpace, halfSpace, halfSpace, halfSpace) parent.clipToPadding = false } outRect.top = halfSpace outRect.bottom = halfSpace outRect.left = halfSpace outRect.right = halfSpace } init { halfSpace = space / 2 } } fun View.snackBarDismissAction(actionString: String, message: String?) { val sb = Snackbar.make(this, message.toString(), Snackbar.LENGTH_INDEFINITE) // val view = sb.view // val params = view.layoutParams as FrameLayout.LayoutParams // params.gravity = Gravity.TOP // view.layoutParams = params sb.setAction(actionString) { sb.dismiss() }.show() }<file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/base/BaseViewModel.kt package dev.ecbn.rijksmuseum.base import androidx.lifecycle.ViewModel import dev.ecbn.rijksmuseum.data.local.SessionHelper /** * Created by <NAME> on 02/11/21. * <EMAIL> */ abstract class BaseViewModel : ViewModel() { val sessionHelper = SessionHelper() }<file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/view/home/HomeViewModel.kt package dev.ecbn.rijksmuseum.view.home import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import dev.ecbn.rijksmuseum.base.BaseViewModel import dev.ecbn.rijksmuseum.data.model.Art import dev.ecbn.rijksmuseum.data.remote.Response import dev.ecbn.rijksmuseum.data.repo.art.IArtRepository import kotlinx.coroutines.launch /** * Created by <NAME> on 03/11/21. * <EMAIL> */ class HomeViewModel( private val artRepo: IArtRepository ): BaseViewModel() { private val _artViewState: MutableLiveData<ArtViewState> = MutableLiveData() val artViewState: LiveData<ArtViewState> = _artViewState fun fetchArtCollections(){ _artViewState.postValue(ArtViewState.Loading(true)) viewModelScope.launch { artRepo.getArtCollections(object : Response<List<Art>> { override fun onSuccess(data: List<Art>) { _artViewState.postValue(ArtViewState.Success(data)) _artViewState.postValue(ArtViewState.Loading(false)) } override fun onError(message: String) { _artViewState.postValue(ArtViewState.Error(message)) _artViewState.postValue(ArtViewState.Loading(false)) } }) } } }<file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/view/register/RegisterViewModel.kt package dev.ecbn.rijksmuseum.view.register import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import dev.ecbn.rijksmuseum.base.BaseViewModel import dev.ecbn.rijksmuseum.data.model.Account import dev.ecbn.rijksmuseum.data.remote.Response import dev.ecbn.rijksmuseum.data.repo.profile.IAccountRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch /** * Created by <NAME> on 04/11/21. * <EMAIL> */ class RegisterViewModel( private val accountRepo: IAccountRepository ) : BaseViewModel() { private val _registrationViewState: MutableLiveData<RegistrationViewState> = MutableLiveData() val registrationViewState: LiveData<RegistrationViewState> = _registrationViewState fun validate(username: String, password: String, isAgree: Boolean) { if (username.isEmpty()) { _registrationViewState.postValue( RegistrationViewState.ValidationError( "username", "Username should not be empty" ) ) return } if (password.isEmpty()) { _registrationViewState.postValue( RegistrationViewState.ValidationError( "password", "Password should not be empty" ) ) return } if (!isAgree) { _registrationViewState.postValue( RegistrationViewState.ValidationError( "agreement", "Agreement should be checked" ) ) return } _registrationViewState.postValue(RegistrationViewState.Loading(true)) viewModelScope.launch(Dispatchers.IO) { accountRepo.registerAccount(username, password, object : Response<Account> { override fun onSuccess(data: Account) { sessionHelper.setLogin(true) sessionHelper.setAccount(data) _registrationViewState.postValue(RegistrationViewState.Success(data)) } override fun onError(message: String) { _registrationViewState.postValue(RegistrationViewState.Error(message)) } }) } } }<file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/data/repo/art/IArtRepository.kt package dev.ecbn.rijksmuseum.data.repo.art import dev.ecbn.rijksmuseum.data.model.Art import dev.ecbn.rijksmuseum.data.remote.Response /** * Created by <NAME> on 02/11/21. * <EMAIL> */ interface IArtRepository { suspend fun getArtCollections(response: Response<List<Art>>) }<file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/base/BaseActivity.kt package dev.ecbn.rijksmuseum.base import android.os.Bundle import android.view.LayoutInflater import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.viewbinding.ViewBinding import org.koin.android.viewmodel.ext.android.viewModel import kotlin.reflect.KClass /** * Created by <NAME> on 02/11/21. * <EMAIL> */ abstract class BaseActivity<out VM : BaseViewModel, VB : ViewBinding>( kClass: KClass<VM>, private val mViewBinder: (LayoutInflater) -> ViewBinding ) : AppCompatActivity() { @Suppress("UNCHECKED_CAST") protected val binding by lazy(LazyThreadSafetyMode.NONE) { mViewBinder.invoke(layoutInflater) as VB } protected val viewModel: VM by viewModel(clazz = kClass) protected var mRootView: View? = null protected var mDataReceived: Bundle? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mRootView = binding.root mDataReceived = intent.extras setContentView(mRootView) onInitUI(savedInstanceState) onInitData() } abstract fun onInitUI(savedInstanceState: Bundle?) abstract fun onInitData() }<file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/view/detail/DetailActivity.kt package dev.ecbn.rijksmuseum.view.detail import android.os.Bundle import android.view.MenuItem import coil.load import dev.ecbn.rijksmuseum.base.BaseActivity import dev.ecbn.rijksmuseum.base.BaseViewModel import dev.ecbn.rijksmuseum.data.model.Art import dev.ecbn.rijksmuseum.databinding.ActivityDetailBinding /** * Created by <NAME> on 04/11/21. * <EMAIL> */ const val ART_DATA = "art_data" class DetailActivity : BaseActivity<BaseViewModel, ActivityDetailBinding>( BaseViewModel::class, ActivityDetailBinding::inflate ) { private val art: Art? by lazy { return@lazy mDataReceived?.getParcelable<Art>(ART_DATA) } override fun onInitUI(savedInstanceState: Bundle?) { with(binding){ setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) tvTitle.text = art?.title ivArt.load(art?.webImage?.url) } } override fun onInitData() { } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home){ finish() return true } return super.onOptionsItemSelected(item) } }<file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/data/local/ArtDao.kt package dev.ecbn.rijksmuseum.data.local import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import dev.ecbn.rijksmuseum.data.model.Art /** * Created by <NAME> on 02/11/21. * <EMAIL> */ @Dao interface ArtDao { @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertArtCollections(movies: List<Art>) @Query("SELECT * FROM Art WHERE id = :id_") fun getArt(id_: Long): Art @Query("SELECT * FROM Art") fun getArtCollections(): List<Art> }<file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/data/local/Converter.kt package dev.ecbn.rijksmuseum.data.local import androidx.room.TypeConverter import com.google.gson.Gson import dev.ecbn.rijksmuseum.data.model.HeaderImage import dev.ecbn.rijksmuseum.data.model.WebImage /** * Created by <NAME> on 03/11/21. * <EMAIL> */ class HeaderImageConverter { @TypeConverter fun storedStringToHeaderImage(json: String): HeaderImage { val gson = Gson() return gson.fromJson(json, HeaderImage::class.java) } @TypeConverter fun headerImageToStoredString(headerImage: HeaderImage): String { val gson = Gson() return gson.toJson(headerImage, HeaderImage::class.java) } } class WebImageConverter { @TypeConverter fun storedStringToWebImage(json: String): WebImage { val gson = Gson() return gson.fromJson(json, WebImage::class.java) } @TypeConverter fun webImageToStoredString(headerImage: WebImage): String { val gson = Gson() return gson.toJson(headerImage, WebImage::class.java) } }<file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/base/BaseFragment.kt package dev.ecbn.rijksmuseum.base import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.viewbinding.ViewBinding import org.koin.android.viewmodel.ext.android.viewModel import kotlin.reflect.KClass /** * Created by <NAME> on 03/11/21. * <EMAIL> */ abstract class BaseFragment<out VM : BaseViewModel, VB : ViewBinding>( kClass: KClass<VM>, private val mViewBinder: (LayoutInflater) -> ViewBinding ) : Fragment() { @Suppress("UNCHECKED_CAST") protected val binding by lazy(LazyThreadSafetyMode.NONE) { mViewBinder.invoke(layoutInflater) as VB } protected val viewModel: VM by viewModel(clazz = kClass) protected var mRootView: View? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? = binding.root override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) mRootView = binding.root onInitUI(savedInstanceState) onInitData() } abstract fun onInitUI(savedInstanceState: Bundle?) abstract fun onInitData() }<file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/view/register/RegisterActivity.kt package dev.ecbn.rijksmuseum.view.register import android.os.Bundle import android.view.MenuItem import dev.ecbn.rijksmuseum.base.BaseActivity import dev.ecbn.rijksmuseum.databinding.ActivityRegisterBinding import dev.ecbn.rijksmuseum.utils.observe import dev.ecbn.rijksmuseum.utils.snackBarDismissAction import dev.ecbn.rijksmuseum.utils.toast class RegisterActivity : BaseActivity<RegisterViewModel, ActivityRegisterBinding>( RegisterViewModel::class, ActivityRegisterBinding::inflate ) { override fun onInitUI(savedInstanceState: Bundle?) { with(binding) { setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) btnRegister.setOnClickListener { viewModel.validate( tilUsername.editText?.text.toString(), tilPassword.editText?.text.toString(), chkConfirm.isChecked ) } } } override fun onInitData() { with(viewModel) { observe(registrationViewState, ::onRegistrationViewStateReceived) } } private fun onRegistrationViewStateReceived(state: RegistrationViewState) { when (state) { is RegistrationViewState.ValidationError -> { removeError() with(binding) { when (state.type) { "username" -> tilUsername.error = state.message "password" -> tilPassword.error = state.message else -> mRootView?.snackBarDismissAction("OK", state.message) } } } is RegistrationViewState.Loading -> { removeError() } is RegistrationViewState.Error -> { mRootView?.snackBarDismissAction("OK", state.message) } is RegistrationViewState.Success -> { toast("Registration successfully, please login!") finish() } } } private fun removeError() { with(binding) { tilUsername.error = "" tilPassword.error = "" } } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { finish() return true } return super.onOptionsItemSelected(item) } }<file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/view/login/LoginViewModel.kt package dev.ecbn.rijksmuseum.view.login import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import dev.ecbn.rijksmuseum.base.BaseViewModel import dev.ecbn.rijksmuseum.data.model.Account import dev.ecbn.rijksmuseum.data.remote.Response import dev.ecbn.rijksmuseum.data.repo.profile.IAccountRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch /** * Created by <NAME> on 04/11/21. * <EMAIL> */ class LoginViewModel( private val accountRepo: IAccountRepository ) : BaseViewModel() { private val _loginViewState: MutableLiveData<LoginViewState> = MutableLiveData() val loginViewState: LiveData<LoginViewState> = _loginViewState fun validate(username: String, password: String) { if (username.isEmpty()) { _loginViewState.postValue( LoginViewState.ValidationError( "username", "Username should not be empty" ) ) return } if (password.isEmpty()) { _loginViewState.postValue( LoginViewState.ValidationError( "password", "Password should not be empty" ) ) return } _loginViewState.postValue(LoginViewState.Loading(true)) viewModelScope.launch(Dispatchers.IO) { accountRepo.loginAccount(username, password, object : Response<Account> { override fun onSuccess(data: Account) { sessionHelper.setLogin(true) sessionHelper.setAccount(data) _loginViewState.postValue(LoginViewState.Success(data)) } override fun onError(message: String) { _loginViewState.postValue(LoginViewState.Error(message)) } }) } } }<file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/data/remote/RequestInterceptor.kt package dev.ecbn.rijksmuseum.data.remote import dev.ecbn.rijksmuseum.BuildConfig import okhttp3.HttpUrl import okhttp3.Interceptor import okhttp3.Response import timber.log.Timber /** * Created by <NAME> on 02/11/21. * <EMAIL> */ class RequestInterceptor: Interceptor { override fun intercept(chain: Interceptor.Chain): Response { val originalRequest = chain.request() val originalHttpUrl: HttpUrl = originalRequest.url val url = originalHttpUrl.newBuilder() .addQueryParameter("key", BuildConfig.API_KEY) .build() val request = originalRequest.newBuilder().url(url) .build() Timber.d(request.toString()) return chain.proceed(request) } }<file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/view/home/HomeFragment.kt package dev.ecbn.rijksmuseum.view.home import android.content.Intent import android.os.Bundle import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.StaggeredGridLayoutManager import dev.ecbn.rijksmuseum.base.BaseFragment import dev.ecbn.rijksmuseum.data.model.Art import dev.ecbn.rijksmuseum.databinding.FragmentHomeBinding import dev.ecbn.rijksmuseum.utils.SpacesItemDecoration import dev.ecbn.rijksmuseum.utils.observe import dev.ecbn.rijksmuseum.utils.showIf import dev.ecbn.rijksmuseum.utils.toast import dev.ecbn.rijksmuseum.view.detail.ART_DATA import dev.ecbn.rijksmuseum.view.detail.DetailActivity class HomeFragment : BaseFragment<HomeViewModel, FragmentHomeBinding>( HomeViewModel::class, FragmentHomeBinding::inflate ), ArtSelectedListener { private val artAdapter: ArtAdapter by lazy { return@lazy ArtAdapter(this) } override fun onInitUI(savedInstanceState: Bundle?) { setupRecyclerView() } private fun setupRecyclerView() { with(binding) { rvArt.apply { layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL) itemAnimator = DefaultItemAnimator() if (itemDecorationCount == 0) addItemDecoration(SpacesItemDecoration(16)) setHasFixedSize(true) adapter = artAdapter } } } override fun onInitData() { with(viewModel) { observe(artViewState, ::onArtViewStateReceived) fetchArtCollections() } } private fun onArtViewStateReceived(artViewState: ArtViewState) { when (artViewState) { is ArtViewState.Success -> { artAdapter.setItem(artViewState.artCollections) } is ArtViewState.Error -> { binding.tvErrMessage.text = artViewState.message } is ArtViewState.Loading -> { binding.pbLoading.showIf(artViewState.isLoading) } } } override fun onArtSelected(art: Art) { val intent = Intent(requireContext(), DetailActivity::class.java) intent.putExtra(ART_DATA, art) startActivity(intent) } }<file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/data/repo/art/ArtRepository.kt package dev.ecbn.rijksmuseum.data.repo.art import com.skydoves.sandwich.suspendOnError import com.skydoves.sandwich.suspendOnException import com.skydoves.sandwich.suspendOnFailure import com.skydoves.sandwich.suspendOnSuccess import dev.ecbn.rijksmuseum.data.model.Art import dev.ecbn.rijksmuseum.data.remote.ArtApiService import dev.ecbn.rijksmuseum.data.remote.Response import java.net.UnknownHostException /** * Created by <NAME> on 02/11/21. * <EMAIL> */ class ArtRepository constructor( private val remote: ArtApiService ) : IArtRepository { override suspend fun getArtCollections(response: Response<List<Art>>) { //this is local data if you want to load local data just load it via response callback remote.getArtCollections() .suspendOnSuccess { val data = data.results ?: emptyList() response.onSuccess(data) } .suspendOnError { response.onError(raw.message) } .suspendOnFailure { response.onError(this.toString()) } .suspendOnException { if (this.exception is UnknownHostException){ response.onError("No internet connection!") }else{ response.onError(message.toString()) } } } }<file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/view/profile/ProfileFragment.kt package dev.ecbn.rijksmuseum.view.profile import android.content.Intent import android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP import android.content.Intent.FLAG_ACTIVITY_NEW_TASK import android.os.Bundle import coil.load import coil.transform.CircleCropTransformation import dev.ecbn.rijksmuseum.base.BaseFragment import dev.ecbn.rijksmuseum.databinding.FragmentProfileBinding import dev.ecbn.rijksmuseum.utils.observe import dev.ecbn.rijksmuseum.view.splash.SplashActivity /** * Created by <NAME> on 03/11/21. * <EMAIL> */ class ProfileFragment : BaseFragment<ProfileViewModel, FragmentProfileBinding>( ProfileViewModel::class, FragmentProfileBinding::inflate ) { override fun onInitUI(savedInstanceState: Bundle?) { binding.btnLogout.setOnClickListener { viewModel.logout() } } override fun onInitData() { with(viewModel) { observe(profileViewState, ::onAccountReceived) getAccount() } } private fun onAccountReceived(state: ProfileViewState) { with(binding) { when (state) { is ProfileViewState.Success -> { tvUsername.text = state.account.username ivProfile.load(state.account.profileUrl) { crossfade(true) transformations(CircleCropTransformation()) } } is ProfileViewState.Logout -> { gotoSplash() } else -> { } } } } private fun gotoSplash() { with(requireActivity()) { val intent = Intent(this, SplashActivity::class.java) intent.addFlags(FLAG_ACTIVITY_NEW_TASK) intent.addFlags(FLAG_ACTIVITY_CLEAR_TOP) startActivity(intent) finish() } } }<file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/di/NetworkModule.kt package dev.ecbn.rijksmuseum.di import com.skydoves.sandwich.coroutines.CoroutinesResponseCallAdapterFactory import dev.ecbn.rijksmuseum.BuildConfig import dev.ecbn.rijksmuseum.data.remote.ArtApiService import dev.ecbn.rijksmuseum.data.remote.RequestInterceptor import okhttp3.OkHttpClient import org.koin.dsl.module import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory /** * Created by <NAME> on 02/11/21. * <EMAIL> */ val networkModule = module { single { OkHttpClient.Builder() .addInterceptor(RequestInterceptor()) .build() } single { Retrofit.Builder() .client(get()) .baseUrl(BuildConfig.BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(CoroutinesResponseCallAdapterFactory.create()) .build() } single { get<Retrofit>().create(ArtApiService::class.java) } }<file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/App.kt package dev.ecbn.rijksmuseum import android.app.Application import com.orhanobut.hawk.Hawk import com.skydoves.sandwich.SandwichInitializer import dev.ecbn.rijksmuseum.data.remote.GlobalResponseOperator import dev.ecbn.rijksmuseum.di.localDBModule import dev.ecbn.rijksmuseum.di.networkModule import dev.ecbn.rijksmuseum.di.repositoryModule import dev.ecbn.rijksmuseum.di.viewModelModule import dev.ecbn.rijksmuseum.utils.timberInitialization import org.koin.android.ext.koin.androidContext import org.koin.core.context.startKoin /** * Created by <NAME> on 02/11/21. * <EMAIL> */ class App : Application() { override fun onCreate() { super.onCreate() startKoin { androidContext(this@App) modules(networkModule) modules(repositoryModule) modules(localDBModule) modules(viewModelModule) } Hawk.init(this).build() SandwichInitializer.sandwichOperator = GlobalResponseOperator<Any>(this) timberInitialization() } }<file_sep>/app/src/main/java/dev/ecbn/rijksmuseum/view/splash/SplashActivity.kt package dev.ecbn.rijksmuseum.view.splash import android.annotation.SuppressLint import android.content.Intent import android.os.Bundle import dev.ecbn.rijksmuseum.base.BaseActivity import dev.ecbn.rijksmuseum.databinding.ActivitySplashBinding import dev.ecbn.rijksmuseum.utils.observe import dev.ecbn.rijksmuseum.view.main.MainActivity import dev.ecbn.rijksmuseum.view.login.LoginActivity @SuppressLint("CustomSplashScreen") class SplashActivity : BaseActivity<SplashViewModel, ActivitySplashBinding>( SplashViewModel::class, ActivitySplashBinding::inflate ) { override fun onInitUI(savedInstanceState: Bundle?) { } override fun onInitData() { with(viewModel) { observe(isLoggedIn, ::onLoggedInReceived) checkSession() } } private fun onLoggedInReceived(isLoggedIn: Boolean) { if (isLoggedIn) { gotoMain() } else { gotoAuth() } } private fun gotoMain() { val intent = Intent(this, MainActivity::class.java) startActivity(intent) finish() } private fun gotoAuth() { val intent = Intent(this, LoginActivity::class.java) startActivity(intent) finish() } }
4c84108c9e1a9018955c2439a703f3c1af54d13c
[ "Kotlin" ]
43
Kotlin
ekhacahya/rijksmuseum
ac127ba987d2cfe7cfb33128e681e94f910be470
1773ae3db4cde50297c2f3e90ca98cd2f5a65ab7
refs/heads/master
<file_sep>apply plugin: 'com.android.application' android { signingConfigs { release { keyAlias 'genie' keyPassword '<PASSWORD>$' storeFile file('C:/Users/Raviteja/Documents/IVA_SDK/ivasdk.jks') storePassword '<PASSWORD>$' } internal { } } compileSdkVersion 23 buildToolsVersion "23.0.1" defaultConfig { applicationId "co.supergenie.iva.android" minSdkVersion 11 targetSdkVersion 23 versionCode 1 versionName '1.0.0.Default' signingConfig signingConfigs.internal } packagingOptions { exclude 'META-INF/services/javax.annotation.processing.Processor' } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } internal { debuggable true jniDebuggable false renderscriptDebuggable false minifyEnabled false zipAlignEnabled true } dubug { debuggable true jniDebuggable true renderscriptDebuggable false minifyEnabled true zipAlignEnabled true } } productFlavors { internalConfig { signingConfig signingConfigs.internal versionName '1.0.0.Internal' minSdkVersion 11 applicationId 'co.supergenie.iva.android' targetSdkVersion 23 versionCode 1 } releaseConfig { minSdkVersion 11 applicationId 'co.supergenie.iva.android' signingConfig signingConfigs.release targetSdkVersion 23 versionCode 1 versionName '1.0.0.Release' } } } dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') compile 'com.android.support:appcompat-v7:23.0.1' compile project(':library') } <file_sep>package co.supergenie.ivasdk.validations; /** * Created by Raviteja on 9/24/2015. IVA SDK */ public class APPRegistrationResponse { } <file_sep>package co.supergenie.ivasdk.database; import io.realm.RealmObject; import io.realm.annotations.PrimaryKey; /** * Created by Raviteja on 10/7/2015. IVA SDK */ public class MessagesTable extends RealmObject { private int messageType; private int direction; private String text; private String id; private long createdAt; public int getMessageType() { return messageType; } public void setMessageType(int messageType) { this.messageType = messageType; } public int getDirection() { return direction; } public void setDirection(int direction) { this.direction = direction; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getId() { return id; } public void setId(String id) { this.id = id; } public long getCreatedAt() { return createdAt; } public void setCreatedAt(long createdAt) { this.createdAt = createdAt; } } <file_sep>package co.supergenie.ivasdk.database; import co.supergenie.ivasdk.objects.ChatList; import io.realm.RealmObject; import io.realm.annotations.PrimaryKey; /** * Created by Raviteja on 10/7/2015. IVA SDK */ public class ChatListTable extends RealmObject { private String imageUrl; private String UUID; private String Title; private String LastMessage; private String GUID; private long createdAt; public ChatListTable(ChatList chatList) { this.imageUrl = chatList.getImageUrl(); this.UUID = chatList.getUUID(); this.GUID = chatList.getGUID(); this.Title = chatList.getTitle(); this.LastMessage = chatList.getLastMessage(); this.createdAt = chatList.getCreatedAt(); } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public String getUUID() { return UUID; } public void setUUID(String UUID) { this.UUID = UUID; } public String getTitle() { return Title; } public void setTitle(String title) { Title = title; } public String getLastMessage() { return LastMessage; } public void setLastMessage(String lastMessage) { LastMessage = lastMessage; } public String getGUID() { return GUID; } public void setGUID(String GUID) { this.GUID = GUID; } public long getCreatedAt() { return createdAt; } public void setCreatedAt(long createdAt) { this.createdAt = createdAt; } } <file_sep>package co.supergenie.ivasdk.gcmhandler; /** * Created by Raviteja on 9/24/2015. IVA SDK */ public class GCMResponse { private int cod; private String base; } <file_sep>package co.supergenie.ivasdk.gcmhandler; import android.os.Build; import org.json.JSONException; import org.json.JSONObject; import co.supergenie.ivasdk.IVA; import co.supergenie.ivasdk.extras.DataFields; /** * Created by Raviteja on 9/18/2015. IVA SDK */ public class GCMBuilder { private String REGISTRATIONKEY; private String APPVERSION; private long SAVEDTIME; /** * Set GCM registration key * * @param REGISTRATIONKEY * @return GCMBuilder object */ public GCMBuilder setREGISTRATIONKEY(String REGISTRATIONKEY) { this.REGISTRATIONKEY = REGISTRATIONKEY; return this; } /** * Set APP version for better control on notifications * * @param APPVERSION * @return GCMBuilder object */ public GCMBuilder setAPPVERSION(String APPVERSION) { this.APPVERSION = APPVERSION; return this; } /** * Save the GCM values to server. * If the Library failed to save the values. * Register for broadcast intent "co.supergenie.ivasdk.gcmregistrationfailed" * for successful transaction Register for broadcast intent "co.supergenie.ivasdk.gcmregistrationsuccess" (optional) * * @return result, false if registration key is missing */ public boolean build() { if (this.REGISTRATIONKEY == null) { return false; } if (this.APPVERSION == null) { this.APPVERSION = DataFields.DEFAULTAPPID; } this.SAVEDTIME = System.currentTimeMillis(); if (toJSON() == null) return false; // RestClient.get().registerGCM(toJSON(), new Callback<GCMResponse>() { // @Override // public void success(GCMResponse gcmResponse, Response response) { // // TODO: 9/24/2015 add success thing here // // // Intent intent = new Intent(); // intent.setAction("co.supergenie.ivasdk.gcmregistrationsuccess"); // new IVA().getContext().sendBroadcast(intent); // } // // @Override // public void failure(RetrofitError error) { // Intent intent = new Intent(); // intent.setAction("co.supergenie.ivasdk.gcmregistrationfailed"); // new IVA().getContext().sendBroadcast(intent); // } // }); return true; } /** * Construct JSON to send JSONObject to server * * @return JSON on success and null on failure * @throws JSONException */ private JSONObject toJSON() { JSONObject jsonObject = new JSONObject(); try { jsonObject.put(DataFields.REGISTRATIONKEY, REGISTRATIONKEY); jsonObject.put(DataFields.APPVERSION, APPVERSION); jsonObject.put(DataFields.APIKEY, new IVA().getSecurePrefs().getString(DataFields.APIKEY, null)); jsonObject.put(DataFields.USERID, new IVA().getSecurePrefs().getString(DataFields.USERID, null)); jsonObject.put(DataFields.DEVICESERIALNUMBER, Build.SERIAL); return jsonObject; } catch (JSONException e) { e.printStackTrace(); return null; } } }
e9a5b64f3d4c7e1b83a4e60d9ae7b4587bcb0c7e
[ "Java", "Gradle" ]
6
Gradle
raviteja06/IVA_SDK
f1a24c09c37b137c0fce4e5f431d787e48c4d5fb
efbf4b20dd0875a199b9f66e96945f0fd7e8d48a
refs/heads/master
<file_sep>from flask import Flask, render_template, request, redirect, session, flash from flask_bcrypt import Bcrypt from mysqlconnection import connectToMySQL import os, binascii import hashlib mysql = connectToMySQL('theGreatwall') app = Flask(__name__) bcrypt = Bcrypt(app) # creating an object called bcrypt app.secret_key = '1fish2fishredfishbluefish' #setting secret key @app.route('/') def index(user=None): return render_template('index.html') @app.route('/login', methods=['POST']) def login(): email = request.form['email'] password = request.form['password'] bytePassword = password.encode() query = f"SELECT * FROM users WHERE email='{email}'" data = { 'email': email } userResult = mysql.query_db(query, data) print(userResult) if not userResult: print("User not found!") return redirect('/') else: print("User found!") if hashlib.md5(bytePassword).hexdigest() == userResult[0]['password_hash']: session['userid'] = userResult[0]['email_id'] return redirect('/wall') else: print(hashlib.md5(bytePassword).hexdigest()) return redirect('/') # data = { "email" : request.form['email'], # "password_hash" : <PASSWORD> } # result = mysql.query_db(query, data) # if result: # if bcrypt.check_password_hash(result[0]['password'], request.form['password']): # session['userid'] = result[0]['id'] # return redirect('/success') @app.route('/wall') def wall(): query = "SELECT * FROM messages" posts = mysql.query_db(query) print(posts) return render_template('wall.html',posts=posts) @app.route('/register', methods=['POST']) def register(): email = request.form['email'] password = request.form['password'] first_name = request.form['first_name'] last_name = request.form['last_name'] bytePassword = password.encode() hashPassword=hashlib.md5(bytePassword).hexdigest() session['first_name'] = first_name session['last_name'] = last_name session['email'] = email session['password'] = <PASSWORD>Password data = { 'first_name': session['first_name'], 'last_name': session['last_name'], 'email': session['email'], 'password_hash': session['password'] } query = f"INSERT INTO users (email, password_hash, created_time, updated_time,first_name,last_name) VALUES('{email}','{hashPassword}',NOW(),NOW(),'{first_name}','{last_name}')" mysql.query_db(query, data) flash('Registered successfully. Please login') return redirect('/') @app.route('/message',methods=['POST']) def message(): message = request.form['message'] query = f"INSERT INTO `messages` (`user_id`, `message`, `create_time`, `update_time`) VALUES ('{session['userid']}', '{message}', NOW(), NOW() );" data = { 'user_id': session['userid'], 'message': message, } mysql.query_db(query, data) flash('Message Submitted.') return redirect('/wall') app.route('/comment',methods=['POST']) def comment(): comment = request.form['comment'] message_id = request.form['messageID'] query = 'INSERT INTO `comments` (`message_id`, `user_id`, `comment`, `create_time`, `update_time`) VALUES (:message_id, :user_id, :comment, now(), now());' data = { 'message_id': message_id, 'user_id': session['userid'], 'comment': comment, } mysql.query_db(query, data) flash('Comment Added.') return redirect('/wall') @app.route('/logout') def logout(): session.clear() return redirect('/') # @app.route('/createUser', methods=['POST']) # def createUser(): # pw_hash = bcrypt.generate_password_hash(request.form['password']) # print(pw_hash) # # query = "INSERT INTO users (username, password) VALUE (%(username)s, %(password_hash)s);" # data = { "username" : request.form['username'], # "password_hash" : <PASSWORD> } # result = mysql.query_db(query, data) # if result: # if bcrypt.check_password_hash(result[0]['password'], request.form['password']): # session['userid'] = result[0]['id'] # return redirect('/success') # # return redirect('/') # # flash("You could not be loggin in") # return redirect('/') #CANNOT USE /users as a name!!!!!! # @app.route('/users', methods=['POST']) # def create(): # print(request.form) # print('Name', request.form[name]) # print('') if __name__ =="__main__": app.run(debug=True) <file_sep>from flask import Flask # import the function connectToMySQL from the file mysqlconnection.py from mysqlconnection import connectToMySQL app = Flask(__name__) # invoke the connectToMySQL function and pass it the name of the database we're using # connectToMySQL returns an- instance of MySQLConnection, which we will store in the variable 'mysql' mysql = connectToMySQL('theGreatwall') # now, we may invoke the query_db method @app.route('/') def index(): print("all the users", mysql.query_db("SELECT * FROM users;")) return "How am I going to put this on my laptop?" if __name__ == "__main__": app.run(debug=True)
7f507258daa60b278a8c41ab6b2aa82301055ae1
[ "Python" ]
2
Python
YummyGoddess/TheWall
85825afbe113b492ba8fc9d063c93822809e6b7b
c3555545777472f47c9d4818ae607bfe1407fdcc
refs/heads/master
<repo_name>Borja15/Clase-Reloj<file_sep>/src/ejerreloj/EjerReloj.java package ejerreloj; public class EjerReloj { public static void main(String[] args) { //Declaramos un reloj con la hora en 0 Reloj reloj = new Reloj(); //Declaramos un reloj con una hora Reloj reloj2 = new Reloj(12,34,12); //Ponemos en hora el primer reloj reloj.ponerHora(); //Ponemos en hora el segundo reloj reloj2.ponerHora(); //Ponemos el reloj en una hora de la tarde reloj.ponerHora(15,34,34); //Ponemos el reloj en una hora de la mañana reloj.ponerHora(07,34,23); //Pasamos la hora segun el formato AM o PM // -- Que nos muestre las 10 de la noche Reloj reloj3 = new Reloj(15,23,12); reloj3.mostrarHora(true); } }
3cdfbc9126fc44a66f922f4790c7c7e520564af9
[ "Java" ]
1
Java
Borja15/Clase-Reloj
b9015b0c81d28b4fc85d10b89aff0df44bcda680
544cd02199fe5072b52acc3a49f438ec690f2bad
refs/heads/master
<repo_name>limjiayee/js<file_sep>/recyclegame_final/game.js let config = { type: Phaser.AUTO, parent : 'phaser-app', width: 1664, height: 1024, backgroundColor: '#000055', physics: { default: 'arcade', arcade: { gravity: false, debug: false } }, //scene: [mainScene, main2Scene, storyScene, story2Scene, level1] scene: [mainScene, main1aScene, main1bScene, main1cScene, main1dScene, main1eScene, main1fScene, main2Scene, main3Scene, level1, level2, loss, loss2, loss3, loss4, loss5, star_level1,star_level2, star_level3, star_level4, level3, level4, level5, last] }; let game = new Phaser.Game(config); // function resizeApp () // { // // Width-height-ratio of game resolution // // Replace 360 with your game width, and replace 640 with your game height // let game_ratio = 360 / 640; // // Make div full height of browser and keep the ratio of game resolution // let div = document.getElementById('phaser-app'); // div.style.width = (window.innerHeight * game_ratio) + 'px'; // div.style.height = window.innerHeight + 'px'; // // Check if device DPI messes up the width-height-ratio // let canvas = document.getElementsByTagName('canvas')[0]; // let dpi_w = parseInt(div.style.width) / canvas.width; // let dpi_h = parseInt(div.style.height) / canvas.height; // let height = window.innerHeight * (dpi_w / dpi_h); // let width = height * game_ratio; // // Scale canvas // canvas.style.width = width + 'px'; // canvas.style.height = height + 'px'; // } // window.addEventListener('resize', resizeApp); <file_sep>/recycle/level2.js // collect stars, no enemies class level2 extends Phaser.Scene { constructor () { super({ key: 'level2' }); // Put global variable here this.yellowCount = 0; this.redCount = 0; this.greenCount = 0; this.greyCount = 0; this.collectpaper=0 this.collectbluebottle=0 this.collectbrownbottle=0 } preload() { // map made with Tiled in JSON format this.load.tilemapTiledJSON('map1', 'assets/level1.json'); this.load.spritesheet('tiles', 'assets/fullset.png', {frameWidth: 64, frameHeight: 64}); this.load.atlas('boy', 'assets/boy.png', 'assets/boy.json'); //this.load.atlas('girl', 'assets/girl.png', 'assets/girl.json'); this.load.image('paper', 'assets/paper.png'); this.load.image('bluebottle', 'assets/bluebottle.png'); this.load.image('brownbottle', 'assets/brownbottle.png'); // this.load.image('toiletpaper', 'assets/toiletpaper.png'); this.load.image('red', 'assets/red_dusbin_v02.png'); this.load.image('green', 'assets/green_dusbin_v02a.png'); this.load.image('yellow', 'assets/yellow_dusbin_v02.png'); this.load.image('grey', 'assets/grey_dusbin_v02.png'); //this.load.image('coin', 'assets/goldCoin.png'); this.load.image('bg', 'assets/bg_dark_3.png'); //this.load.image('apple', 'assets/apple.png'); // Sound preload this.load.audio('correct', 'assets/correct.mp3'); this.load.audio('wrong', 'assets/wrong.mp3'); } create() { // Sound variable this.correctSnd = this.sound.add('correct'); this.wrongSnd = this.sound.add('wrong'); //bg this.bg=this.add.tileSprite(0, 0, game.config.width, game.config.height, 'bg'); this.bg.setOrigin(0, 0); //this.add.text(0,0, 'Level 1 - Collect stars', { font: '24px Courier', fill: '#000000' }).setScrollFactor(0); this.map = this.make.tilemap({key: 'map1'}); // Must match tileSets name let groundTiles = this.map.addTilesetImage('fullset','tiles'); // create the ground layer this.groundLayer = this.map.createDynamicLayer('ground', groundTiles, 0, 0); this.brownLayer = this.map.createDynamicLayer('brown_road', groundTiles, 0, 0); this.roadLayer = this.map.createDynamicLayer('road', groundTiles, 0, 0); this.platformLayer = this.map.createDynamicLayer('platform_layer', groundTiles, 0, 0); //this.dusbinLayer = this.map.createDynamicLayer('dusbin', groundTiles, 0, 0); //this.green_bottleLayer = this.map.createDynamicLayer('green_bottle', groundTiles, 0, 0); //this.paperLayer = this.map.createDynamicLayer('paper', groundTiles, 0, 0); //this.boneLayer = this.map.createDynamicLayer('bone', groundTiles, 0, 0); this.blackwhiteLayer = this.map.createDynamicLayer('blackwhite', groundTiles, 0, 0); this.alien_death1Snd = this.sound.add('alien'); // Make it global variable for troubleshooting //window.groundLayer = this.groundLayer; // Set starting and ending position using object names in tiles this.startPoint = this.map.findObject("objectLayer", obj => obj.name === "startpoint"); // Make it global variable for troubleshooting window.startPoint = this.startPoint; // create the player sprite this.player = this.physics.add.sprite(200, 200, 'boy'); this.player.setPosition(78,632); this.player.setBounce(0.1); // our this.player will bounce from items // small fix to our this.player images, we resize the physics body object slightly this.player.setScale(2); this.player.setCollideWorldBounds(true); // don't go out of the map // Set this.player to starting position //this.player.setPosition(this.startPoint.x, this.startPoint.y); //this.player.setPosition(0, 0); // Make it global variable for troubleshooting window.player = this.player; //console.log('player ', this.player.x, this.player.y); // set the boundaries of our game world this.physics.world.bounds.width = this.groundLayer.width; this.physics.world.bounds.height = this.groundLayer.height; // the this.player will collide with this layer this.groundLayer.setCollisionByProperty({ collides: true }); this.platformLayer.setCollisionByProperty({ collides: true }); this.physics.add.collider(this.groundLayer, this.player); this.physics.add.collider(this.platformLayer, this.player); // // Add random stars // this.stars = this.physics.add.group({ // key: 'toiletpaper', // repeat: 2, // setXY: { x: 0, y: 0, stepX: Phaser.Math.Between(200, 200) } // }); this.paper = this.physics.add.sprite(951, 644, 'paper'); this.bluebottle = this.physics.add.sprite(1100, 600, 'bluebottle'); this.brownbottle = this.physics.add.sprite(1300, 626, 'brownbottle'); //this.apple = this.physics.add.sprite(951, 644, 'apple'); this.red = this.physics.add.sprite(164, 950, 'red'); this.green = this.physics.add.sprite(600, 950, 'green'); this.yellow = this.physics.add.sprite(1000, 950, 'yellow'); this.grey = this.physics.add.sprite(1400, 950, 'grey'); // this text will show the score this.yellowText = this.add.text(20, 40, 'Recyclable waste 0', { fontSize: '30px', fill: '#ffffff' }); // fix the text to the camera this.yellowText.setScrollFactor(0); this.yellowText.visible = true; this.add.text(1500,40, 'Level 2', { font: '30px Courier', fill: '#ffffff' }); // this.anims.create({ // key: 'left', // frames: this.anims.generateFrameNumbers('boy', { // start: 0, // end: 3 // }), // frameRate: 10, // repeat: -1 // }); // this.anims.create({ // key: 'idle', // frames: [{ // key: 'boy', // frame: 'boy_01' // }], // frameRate: 10, // }); // this.anims.create({ // key: 'walk', // frames: this.anims.generateFrameNumbers('boy', {prefix: 'boy_', // start: 2, // end: 7, // zeroPad: 2, // }), // frameRate: 10, // repeat: -1 // }); // Create the idle animations, using first frame this.anims.create({ key: 'idle', frames: [{key: 'boy', frame: 'boy_01'}], frameRate: 10, }); // Create the walking animation with prefix of girl_ this.anims.create({ key: 'walk', frames: this.anims.generateFrameNames('boy', {prefix: 'boy_', start: 1, end: 8, zeroPad: 2}), frameRate: 10, repeat: -1 }); window.anim=this.anims this.cursors = this.input.keyboard.createCursorKeys(); // set bounds so the camera won't go outside the game world this.groundLayer.setCollisionByProperty({ ground: true }); // make the camera follow the this.player // this.cameras.main.startFollow(this.player); // // set background color, so the sky is not black // this.cameras.main.setBackgroundColor('#ccccff'); this.blackwhiteLayer.setCollisionByProperty({ black: true }); this.blackwhiteLayer.setCollisionByProperty({ white: true }); // Collide platform with stars //this.physics.add.collider(this.platformLayer, this.apple); //this.physics.add.collider(this.groundLayer, this.apple); this.physics.add.collider(this.blackwhiteLayer, this.player); //this.physics.add.overlap(this.player, this.apple,this.collectapple, null, this ); this.physics.add.overlap(this.player, this.paper,this.holdpaper, null, this ); this.physics.add.overlap(this.player, this.bluebottle,this.holdbluebottle, null, this ); this.physics.add.overlap(this.player, this.brownbottle,this.holdbrownbottle, null, this ); this.physics.add.overlap(this.player, this.red,this.dropred, null, this ); this.physics.add.overlap(this.player, this.green,this.dropgreen, null, this ); this.physics.add.overlap(this.player, this.yellow,this.dropyellow, null, this ); this.physics.add.overlap(this.player, this.grey,this.dropgrey, null, this ); // set the boundaries of our game world this.physics.world.bounds.width = this.groundLayer.width; this.physics.world.bounds.height = this.groundLayer.height; // set bounds so the camera won't go outside the game world this.cameras.main.setBounds(0, 0, this.map.widthInPixels, this.map.heightInPixels); // make the camera follow the player this.cameras.main.startFollow(player); // set background color, so the sky is not black this.cameras.main.setBackgroundColor('000000'); } //paper holdpaper(player) { this.paper.x = this.player.x+64 this.paper.y = this.player.y this.collectpaper=1 return false; } //blue holdbluebottle(player) { this.bluebottle.x = this.player.x+64 this.bluebottle.y = this.player.y this.collectbluebottle=1 return false; } //brown holdbrownbottle(player) { this.brownbottle.x = this.player.x+64 this.brownbottle.y = this.player.y this.collectbrownbottle=1 return false; } dropgreen(player) { if (this.collectpaper) { console.log('droppaper') this.paper.disableBody(true, true); this.collectpaper=0 this.yellowCount +=1; // Play sound this.correctSnd.play(); this.player.y-200; console.log(this.yellowCount); this.yellowText.setText(this.yellowCount); } else if (this.collectbluebottle) { console.log('dropbluebottle') this.bluebottle.disableBody(true, true); this.collectbluebottle=0 this.yellowCount +=1; // Play sound this.correctSnd.play(); this.player.y-200; console.log(this.yellowCount); this.yellowText.setText(this.yellowCount); } else if (this.collectbrownbottle) { console.log('dropbrownbottle') this.brownbottle.disableBody(true, true); this.collectbrownbottle=0 this.yellowCount +=1; // Play sound this.correctSnd.play(); this.player.y-200; console.log(this.yellowCount); this.yellowText.setText(this.yellowCount); } else { //this.wrongSnd.play(); //console.log('yellowwrongbin') } if (this.yellowCount >2 ) { this.scene.start("star_level2"); } return false; } dropyellow(player) { if (this.collect) { } else { this.wrongSnd.play(); console.log('wrongyellowbin') this.scene.start("loss2"); } return false; } dropred(player) { if (this.collect) { } else { this.wrongSnd.play(); console.log('wrongredbin') this.scene.start("loss2"); } return false; } dropgrey(player) { if (this.collect) { } else { this.wrongSnd.play(); console.log('wronggreybin') this.scene.start("loss2"); } return false; } update() { if (this.cursors.left.isDown) { console.log("left"); this.player.body.setVelocityX(-400); this.player.anims.play('walk', true); // walk left this.player.flipX = true; // flip the sprite to the left //this.alien_death1Snd.play(); //audio // this.player.flipX = true; // flip the sprite to the left } else if (this.cursors.right.isDown) { this.player.body.setVelocityX(400); this.player.anims.play('walk', true); this.player.flipX = false; // use the original sprite looking to the right //this.alien_death1Snd.play(); //audio //this.player.flipX = false; // use the original sprite looking to the right } else if (this.cursors.up.isDown) { console.log("up"); this.player.body.setVelocityY(-400); this.player.anims.play('walk', true); this.player.flipX = false; // use the original sprite looking to the right //this.player.flipX = false; // use the original sprite looking to the right } else if (this.cursors.down.isDown) { console.log("down"); this.player.body.setVelocityY(400); this.player.anims.play('walk', true); this.player.flipX = false; // use the original sprite looking to the right //this.player.flipX = false; // use the original sprite looking to the right } else { console.log("idle"); this.player.body.setVelocityX(0); this.player.body.setVelocityY(0); this.player.anims.play('idle', true); // use the original sprite looking to the right //this.player.flipX = false; // use the original sprite looking to the right } //console.log('Current this.player pos ', this.player.x, this.player.y); // Check for more then 5 stars if ( this.paperCount > 3 ) { console.log('Collected 1 star, jump to level 3'); this.scene.stop("level2"); this.scene.start("star_level2"); } } }
0a64220cb584f0aa6b00bed98a3f19a83fdac1b6
[ "JavaScript" ]
2
JavaScript
limjiayee/js
15e9fe494df537e7d856ec58c7744355f432884e
0f48261bb4ac20df6b9557dbfdc4bc68f67bbbc9
refs/heads/master
<repo_name>treeder/slackbots<file_sep>/guppy/guppy.rb require 'open-uri' require 'slack_webhooks' require 'json' # Comment out the next line and uncomment the one after to load the commands.json from your local file # rather than the URL responses = JSON.load(open('https://raw.githubusercontent.com/treeder/slackbots/master/guppy/commands.json')) # Use this one to load from file: responses = JSON.load(File.open('commands.json')) payload = STDIN.read STDERR.puts payload if payload == "" # then probably just testing puts "Need a payload from Slack... :(" return end sh = SlackWebhooks::Hook.new('guppy', payload, nil) attachment = { "fallback" => "wat?!", # "(╯°□°)╯︵ ┻━┻)", "image_url" => "http://i.imgur.com/7kZ562z.jpg" } r = responses[sh.text] if r attachment['image_url'] = r['image_url'] else # help help = "Available options are:\n" responses.each_key { |k| help << "* #{k}\n" } response = { "response_type" => "ephemeral", "text" => help, "attachments" => [attachment] } s = response.to_json STDERR.puts "responding with #{s}" puts s exit end s = "#{sh.command} #{sh.text}" response = { "response_type" => "in_channel", "text" => s, "attachments" => [attachment] } puts response.to_json <file_sep>/worker/worker.rb require_relative 'bundle/bundler/setup' require 'iron_worker' require 'slack_webhooks' project_id = nil token = nil worker_name = nil payload_for_worker = nil send_usage = false sh = SlackWebhooks::Hook.new('worker', IronWorker.payload, IronWorker.config['webhook_url']) ts = sh.text.split(' ') if ts.length < 3 send_usage = true else project_id = ts[0] token = ts[1] worker_name = ts[2] payload = ts[3..-1].join(' ') end puts "project_id=#{project_id} token=#{token} worker_name=#{worker_name} payload=#{payload_for_worker}" if send_usage puts "invalid params passed in, sending usage" sh.channel = sh.username sh.send("Usage: /worker <project_id> <token> <worker_name> <payload>") exit end puts "all good queuing task" wc = IronWorker::Client.new(project_id: project_id, token: token) task = wc.tasks.create(worker_name, payload) puts "task_id=#{task.id}" wc.tasks.wait_for(task.id) do |t| puts t.msg end log = wc.tasks.log(task.id) puts log attachment = { "fallback" => "wat?!", "title" => "Worker '#{worker_name}' executed", "title_link" => "https://hud.iron.io/tq/projects/#{project_id}/tasks/#{task.id}", "text" => log, # "image_url" => "http://i.imgur.com/7kZ562z.jpg" # "color": "#764FA5" } sh.send("/worker #{project_id} <TOKEN> #{worker_name} #{payload}", attachment: attachment) <file_sep>/uptime/main.go package main import ( "encoding/json" "fmt" "io/ioutil" "sort" "time" "github.com/iron-io/iron_go/cache" ) var c *cache.Cache var client *PingdomClient var slackClient *slackC type Config struct { Username string `json:"username"` Password string `json:"<PASSWORD>"` ApiKey string `json:"api_key"` WebhookUrl string `json:"webhook_url"` MqIds []int `json:"mq"` WorkerIds []int `json:"worker"` OtherIds []int `json:"other"` } func main() { c = cache.New("uptime_bot") b, err := ioutil.ReadFile("config.json") if err != nil { fmt.Println(err) return } cfg := &Config{} err = json.Unmarshal(b, cfg) if err != nil { fmt.Println(err) return } client = &PingdomClient{ Username: cfg.Username, Password: <PASSWORD>, ApiKey: cfg.ApiKey, } slackClient = &slackC{ url: cfg.WebhookUrl, } since := time.Now() mqUptimes := client.getUptimes(cfg.MqIds, since) workerUptimes := client.getUptimes(cfg.WorkerIds, since) otherUptimes := client.getUptimes(cfg.OtherIds, since) var attachments []Attachment attachments = append(attachments, buildReportsAttachment("IronMQ", mqUptimes)) attachments = append(attachments, buildReportsAttachment("IronWorker", workerUptimes)) attachments = append(attachments, buildReportsAttachment("Other", otherUptimes)) var reports UptimeReports reports = append(reports, mqUptimes...) reports = append(reports, workerUptimes...) reports = append(reports, otherUptimes...) sort.Sort(reports) if len(reports) > 2 { if reports[0].DayAgo.uptimePercentage() < 1 { attachments = append(attachments, buildReportAttachment(reports[0])) attachments = append(attachments, buildReportAttachment(reports[1])) } } // fmt.Println("", attachments) slackClient.post("", attachments) } func buildReportsAttachment(name string, u UptimeReports) Attachment { var attachment Attachment if u.dailyUptime() >= .9998 { attachment.Color = "#2DD700" } else { attachment.Color = "#BD2121" } attachment.Title = name attachment.Fields = append(attachment.Fields, Field{ Value: fmt.Sprintf("%.4f%% uptime over the last 24 hours (%s total downtime)", u.dailyUptime()*100, u.totalDailyDowntime()), Short: false, }) attachment.Fields = append(attachment.Fields, Field{ Title: "7 days", Value: fmt.Sprintf("%.4f%% (%s)", u.weeklyUptime()*100, u.totalWeeklyDowntime()), Short: true, }) attachment.Fields = append(attachment.Fields, Field{ Title: "1 month", Value: fmt.Sprintf("%.4f%% (%s)", u.monthlyUptime()*100, u.totalMonthlyDowntime()), Short: true, }) return attachment } // Build an attachment for a single report. func buildReportAttachment(u *UptimeReport) Attachment { var attachment Attachment attachment.Title = u.Name attachment.Color = "#C77838" attachment.Fields = append(attachment.Fields, Field{ Title: "24 hours", Value: fmt.Sprintf("%.4f%% (%s)", u.DayAgo.uptimePercentage()*100, (u.DayAgo.Downtime() * time.Second).String()), Short: true, }) attachment.Fields = append(attachment.Fields, Field{ Title: "7 Days", Value: fmt.Sprintf("%.4f%% (%s)", u.WeekAgo.uptimePercentage()*100, (u.WeekAgo.Downtime() * time.Second).String()), Short: true, }) return attachment } <file_sep>/salesforce/README.md ## Opportunity Bot Posts updates to Salesforce Opportunities to the Slack Channel of your choice. ![Oppbot Screenshot](oppbot-screenshot.png) This one is meant to be scheduled, not to be used as a slash command. After uploading, go into HUD and schedule it to run every hour. ## Additional steps required to run this Bot This bot uses [IronCache](http://www.iron.io/cache) to store results temporarily. Create an iron.json file in this directory with your Iron.io project_id and token. <file_sep>/guppy/Gemfile source "http://rubygems.org" gem 'slack_webhooks', '>= 0.2.1' gem 'json', '>2.0.0' <file_sep>/worker/Gemfile source "http://rubygems.org" gem 'slack_webhooks' gem 'iron_worker', '>= 3.0.2' <file_sep>/dicey/dicey.rb require_relative 'bundle/bundler/setup' require 'iron_worker' require 'slack_webhooks' sh = SlackWebhooks::Hook.new('dicey', IronWorker.payload, IronWorker.config['webhook_url']) sh.icon_url = "http://www.psdgraphics.com/file/red-dice-icon.jpg" max = 6 if sh.text != nil && sh.text != "" max = sh.text.to_i if max <= 0 max = 6 end end text = "#{sh.username} rolled a *#{1 + rand(max)}*" sh.send(text) <file_sep>/aws_cost_bot/costbot.rb require_relative 'bundle/bundler/setup' require 'iron_worker' require 'slack_webhooks' require 'iron_cache' require 'fog' require 'amazon-pricing' require 'slack' slack = Slack::Client.new(:token => IronWorker.config['slack_token']) channel = IronWorker.config['channel'] channel_id = "x" # apparently the only way to get the channel id is like this: slack.channels_list['channels'].each do |c| # puts "name: #{c['name']}, id: #{c['id']}" if c['name'] == channel || c['name'] == channel[1..channel.length] channel_id = c['id'] break end end # todo: since this one uses the api directly already, don't bother with incoming webhook sh = SlackWebhooks::Hook.new('costbot', IronWorker.payload, IronWorker.config['webhook_url']) sh.icon_url = "http://images.clipartpanda.com/save-money-icon-save-money-icon-iebaaazn.png" sh.channel = channel @ic = IronCache::Client.new @cache = @ic.cache("costbot") compute = Fog::Compute.new( :provider => :aws, :aws_secret_access_key => IronWorker.config['aws']['secret_key'], :aws_access_key_id => IronWorker.config['aws']['access_key'] ) reserved_hash = {} reserved = compute.describe_reserved_instances reserved.body['reservedInstancesSet'].each do |ris| next if ris['state'] != 'active' # p ris # todo: use offeringType, maybe use amount too? amount is hourly cost, fixed price is up front cost az = ris['availabilityZone'] itype = ris['instanceType'] azhash = reserved_hash[az] || {} itypehash = azhash[itype] || {} itypehash['count'] = (itypehash['count']||0) + ris['instanceCount'] azhash[itype] = itypehash reserved_hash[az] = azhash end # Retrieve pricing price_list = AwsPricing::Ec2PriceList.new byzone = {} projects = {} puts "Region,Availability Zone,Instance Id,Instance IP,Instance Type,On-Demand Price Per Month" compute.servers.each do |server| # p server region = server.availability_zone[0...server.availability_zone.length-1] # p region # r2 = price_list.get_region(region) # p r2.ec2_instance_types[0].name # exit az = server.availability_zone itype = server.flavor_id instance_type = price_list.get_instance_type(region, server.flavor_id) price_per_hour = instance_type.price_per_hour(:linux, :ondemand) price_per_month = price_per_hour*24*30.4 project_name = server.tags['Name'] project_hash = projects[project_name] || {} project_hash['price_per_month'] = (project_hash['price_per_month'] || 0.0) + price_per_month project_hash['count'] = (project_hash['count'] || 0) + 1 azs = project_hash['azs'] || {} azhash = azs[az] || {} itypehash = azhash[itype] || {} itypehash['count'] = (itypehash['count']||0) + 1 azhash[itype] = itypehash azs[az] = azhash project_hash['azs'] = azs projects[project_name] = project_hash # also aggregate by zone/type azhash = byzone[az] || {} itypehash = azhash[itype] || {} itypehash['count'] = (itypehash['count']||0) + 1 azhash[itype] = itypehash byzone[az] = azhash # puts "#{project_name}, #{region},#{az},#{server.id},#{server.public_ip_address},#{itype},$#{price_per_hour},$#{price_per_month}" end def write_table(filename, table) File.open(filename, 'w') do |file| table.each do |row| row.each do |c| file.write(c) file.write(',') end file.write("\n") end end end def stringify_table(table, separator=",") s = "" table.each do |row| row.each do |c| s << c << separator end s << "\n" end s end # Sort project costs by cost desc sorted_projects = projects.sort_by { |k,v| v['price_per_month'] }.reverse total_cost = 0.0 projects_costs_table = [["Project", "Servers", "Monthly Cost"]] sorted_projects.each_with_index do |a,i| k = a[0] v = a[1] total_cost += v['price_per_month'] puts "#{k}, count: #{v['count']}, price_per_month: #{sprintf('$%.2f', v['price_per_month'])}" # p v['azs'] projects_costs_table << ["#{k}", "#{v['count']}", "#{sprintf('$%.2f', v['price_per_month'])}"] end write_table('costs.csv', projects_costs_table) # Now for RI coverage total_servers = 0 total_covered = 0 extra_ris = 0 ri_table = [["Zone","Type","Count","RI's","NOT Covered"]] File.open('ri-coverage.csv', 'w') do |file| byzone.each_pair do |zone,v| ris = reserved_hash[zone] || {} v.each_pair do |itype,itv| # Now compare v to ris rit = ris[itype] || {} icount = itv['count'] ricount = rit['count'] || 0 uncovered = icount - ricount ri_table << ["#{zone}","#{itype}","#{icount}","#{ricount}","#{uncovered}"] total_servers += icount if uncovered < 0 extra_ris += -uncovered total_covered += icount else total_covered += ricount end end end end write_table('ri-coverage.csv', ri_table) # todo: Store yesterdays data then compare to show differences # expires_in = 86400 # users_vote_key = "#{votename}-user:#{sh.username}" # item = @cache.get(users_vote_key) # if item # end # @cache.put(users_vote_key, split[1], :expires_in => expires_in) attachments = [] percent_covered = 1.0 * total_covered / total_servers * 100.0 p percent_covered if percent_covered < 75.0 text = "Coverage is Bad!" color = "warning" else text = "Coverage is OK" color = "#00CC66" end fallback = text attachment = { "fallback" => fallback, "text" => text, "color" => color, "mrkdwn_in" => ["text", "pretext"], "fields" => [ { "title" => "Servers", "value" => "#{total_servers}", "short" => true }, { "title" => "Covered", "value" => "#{total_covered}", "short" => true }, { "title" => "Est. Monthly Cost", "value" => "#{sprintf('$%.2f', total_cost)}", "short" => true }, { "title" => "Percent Covered", "value" => "#{sprintf('%.0f', percent_covered)}%", "short" => true }, { "title" => "Unused Ri's", "value" => "#{extra_ris}", "short" => true }, ] } attachments << attachment channels = "#{channel_id}" # comma separated list content = stringify_table(projects_costs_table, "\t") p content p slack.files_upload(content: content, title: "Costs by Project.md", channels: channels) content = stringify_table(ri_table, "\t") p content p slack.files_upload(content: content, title: "RI Coverage.md", channels: channels) # my_file = Faraday::UploadIO.new("x.html", 'text/html') # p slack.files_upload(file: my_file, filetype: 'text/html') sh.send("This is your daily server report.", attachments: attachments) <file_sep>/tubey/README.md This is just like /giphy for videos. Will choose a random Youtube video. Example: ``` /tubey penguins ``` <file_sep>/guppy/README.md # Guppy - the predefined giphy Kind of like /giphy, but you can set your own keywords and responses. See commands.json to change it. If you want your own commands.json, change guppy.rb to use the file loading, by default it reads it directly from this repo on Github. <file_sep>/tubey/tubey.rb require_relative 'bundle/bundler/setup' require 'youtube_it' require 'iron_worker' require 'slack_webhooks' sh = SlackWebhooks::Hook.new('tubey', IronWorker.payload, IronWorker.config['webhook_url']) sh.icon_url = 'https://s3-us-west-2.amazonaws.com/slack-files2/avatars/2015-03-10/3999143873_e2fb4ca39b4876bb0bf2_48.jpg' client = YouTubeIt::Client.new vids = client.videos_by(:query => sh.text, :safe_search => "strict") # p vids puts "count: #{vids.total_result_count}" vids.videos.each do |v| puts "name: #{v.title}" end # Video object attributes: https://github.com/kylejginavan/youtube_it/blob/master/lib/youtube_it/model/video.rb v = vids.videos.sample puts "sample: #{v.title} #{v.player_url}" sh.send("#{sh.command} #{sh.text}\n#{v.player_url}") <file_sep>/uptime/README.md # Uptime bot Uptime bot uses pingdom checks to determing the total uptime for all services. Uptime is an aggregate, not an average. Pingdom requires your username, password, and api token in order to use their api. Due to the amount of redundant checks we have, this version requires you to supply the ids of the checks you want to use. In our specific case, we have three different sets: mq checks, worker checks, and other services. ## How to use #### Put your pingdom username, password, and api token in the config file. ```json { "username": "USERNAME", "password": "<PASSWORD>", "api_token": "API_TOKEN" ``` #### Put the slack webhook url you want to use ```json "webhook_url": "WEBHOOKURL" ``` #### Put in the ids of the checks you want to use. ```json "mq": [ 123, 123 ], "worker": [ 123, 123 ], "other": [ 123, 123 ] } ``` #### Build the bot using docker ``` docker run --rm -v "$GOPATH":/gopath -e "GOPATH=/gopath" -v "$(pwd)":/worker -w /worker iron/images:go-1.4 sh -c 'go build -o uptime' ``` ## Uploading to iron worker #### Zip the folder ``` zip -r uptime.zip . ``` #### Upload to ironworker ``` iron worker upload --zip uptime.zip --name uptime iron/images:go-1.4 ./uptime ``` #### Run the worker ``` iron worker queue uptime ``` <file_sep>/curlbot/README.md Run any curl command and post response back to slack. Examples: ``` /curl http://mq-v3-aws-us-east-1.iron.io ``` <file_sep>/votey/Gemfile source "http://rubygems.org" gem 'slack_webhooks' gem 'iron_worker' gem 'iron_cache' <file_sep>/aws_cost_bot/Gemfile source "http://rubygems.org" gem 'slack_webhooks' gem 'iron_worker' gem 'iron_cache' gem 'fog' gem 'amazon-pricing' gem 'slack-api' <file_sep>/README.md # Slackbots for Fn Project All of the examples in this repository follow the same pattern for testing and uploading to [Fn](https://fnproject.io). Assuming you have an Fn server running and the CLI installed, just `cd` into the bots directory and do the following: ## Deploy ```sh fn deploy --app slackbots BOTNAME ``` ## Create a Slash command in Slack If you don't have a Slack app already, [start here](https://api.slack.com/apps). In your app, click `Slash Commands` and create one that points to your deployed bot/function. ## Install the app into your team You'll see `Install App` on the left side of your app in the Slack console. Click that and follow the directions. ### 6) Try it out! Now in slack, type `/<BOTNAME> [options]` and you'll see the magic! <file_sep>/votey/votey.rb require_relative 'bundle/bundler/setup' require 'iron_worker' require 'slack_webhooks' require 'iron_cache' sh = SlackWebhooks::Hook.new('votey', IronWorker.payload, IronWorker.config['webhook_url']) sh.icon_url = "http://s2.hubimg.com/u/7842695_f260.jpg" sh.set_usage "Usage: /vote <vote_name> <yes/no>" exit if sh.help? @ic = IronCache::Client.new @cache = @ic.cache("votey") expires_in = 86400 split = sh.text.split(' ') if split.length < 2 sh.send_usage("Invalid parameters.") exit end votename = split[0] if split[1][0] != 'y' && split[1][0] != 'n' sh.send_usage("Must be yes or no") exit end # Ok, input looks ok, let's continue yes = split[1][0] == 'y' # Store what the user posted so we don't count it twice users_vote_key = "#{votename}-user:#{sh.username}" item = @cache.get(users_vote_key) changed = false already_voted = false if item already_voted = true # then user already voted, if it changed, we can change the counts if item.value[0] == split[1][0] # Same so do nothing else changed = true # change votes end end yinc = 0 ninc = 0 @cache.put(users_vote_key, split[1], :expires_in => expires_in) if already_voted if changed # need to update both if yes yinc = 1 ninc = -1 else yinc = -1 ninc = 1 end end else if yes yinc = 1 else ninc = 1 end end yeskey = "#{votename}-yes" nokey = "#{votename}-no" yr = nil nr = nil yeses = 0 nos = 0 if yinc != 0 yr = @cache.increment(yeskey, yinc, :expires_in => expires_in) end if ninc != 0 nr = @cache.increment(nokey, ninc, :expires_in => expires_in) end if yr.nil? yr = @cache.get(yeskey) end if nr.nil? nr = @cache.get(nokey) end if !yr.nil? yeses = yr.value end if !nr.nil? nos = nr.value end puts "yeses: #{yeses}" puts "nos: #{nos}" text = "" color = "warning" if yeses > nos color = "good" elsif yeses < nos color = "danger" end attachment = { "fallback" => text, "text" => "Voting results for `/vote #{votename}`", "color" => color, "mrkdwn_in" => ["text", "pretext"], "fields" => [ { "title" => "Yes", "value" => "#{yeses}", "short" => true }, { "title" => "No", "value" => "#{nos}", "short" => true }, ] } sh.send(text, attachment: attachment) <file_sep>/salesforce/opportunity_bot.rb require_relative 'bundle/bundler/setup' require 'iron_worker' require 'slack_webhooks' require 'restforce' require 'iron_cache' # Config models class SlackC attr_accessor :channel, :webhook_url end class SalesforceC attr_accessor :username, :password, :security_token, :client_id, :client_secret def set(h) h.each { |k, v| send("#{k}=", v) } end def to_hash # makes hash and symbolizes keys hash = {} instance_variables.each { |var| hash[var.to_s.delete("@").to_sym] = instance_variable_get(var) } hash end end class MyConfig attr_accessor :slack, :google, :salesforce def initialize @slack = SlackC.new @salesforce = SalesforceC.new end end config = MyConfig.new config.salesforce.set(IronWorker.config['salesforce']) config.slack.webhook_url = IronWorker.config['webhook_url'] config.slack.channel = IronWorker.config['channel'] @ic = IronCache::Client.new @cache = @ic.cache("salesbot") @last_check_key = "opportunity_bot_last_check" def get_last_check item = @cache.get(@last_check_key) if item != nil last_check = DateTime.parse(item.value) else last_check = Date.today.prev_day.to_datetime # "2015-01-01T00:00:01z" end puts "last_check: #{last_check.inspect} class=#{last_check.class.name}" return last_check end def insert_check_date @cache.put(@last_check_key, DateTime.now.rfc3339, :expires_in => 86400 * 7) end def get_opp_updates(config) client = Restforce.new(config.salesforce.to_hash) last_check = get_last_check # for testing: # last_check = Date.today.prev_day.to_datetime # "2015-01-01T00:00:01z" # Opportunity: https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_opportunity.htm query = "Select op.Id, op.Name, op.Amount, op.StageName, op.Probability, op.LastModifiedDate, op.CloseDate, op.AccountId, op.OwnerId from Opportunity op " + "where op.LastModifiedDate > #{last_check.to_datetime.rfc3339}" puts "query=#{query}" ops = client.query(query) posted = 0 ops.each_with_index do |op, i| break if posted >= 3 puts "op" p op puts "Op: id=#{op.Id} opname=#{op.Name} amount=#{op.Amount} probability=#{op.Probability}" p client.url(op) # Get account for the opp too query = "Select Id, Name, LastModifiedDate from Account where Id = '#{op.AccountId}'" puts "account query=#{query}" accounts = client.query(query) p accounts account = accounts.first # And owner query = "Select Id, Name, LastModifiedDate from User where Id = '#{op.OwnerId}'" puts "owner query=#{query}" owners = client.query(query) p owners owner = owners.first # OpportunityHistory: https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_opportunityhistory.htm history = client.query("select ID, StageName, Probability, Amount, ExpectedRevenue, CloseDate from OpportunityHistory where OpportunityId = '#{op.Id}' and CreatedDate > #{last_check.to_datetime.rfc3339}") history.each_with_index do |h, j| break if j >= 1 # only do one max puts "history" p h puts "History: id=#{h.Id} amount=#{h.Amount} stage=#{h.StageName} probability=#{h.Probability} closedate=#{h.CloseDate}" post_to_slack(config, client, op, account, owner, h) posted += 1 end end insert_check_date() puts "Posted #{posted} updates to slack. " end def post_to_slack(config, sclient, op, account, owner, h) if h.Amount.nil? puts "h.Amount is nil" return end # todo: ADD OWNER -author_name ? s = "Opportunity for <#{sclient.url(account)}|#{account.Name}> updated." attachment = { "fallback" => s, "pretext" => s, "title" => "#{op.Name}", "title_link" => sclient.url(op), # "text" => "Stage: #{h.StageName}", # "image_url" => "http://caldwelljournal.com/wp-content/uploads/2015/01/Boom.jpg", # "color": "#764FA5" "fields" => [ { "title" => "Stage", "value" => "#{h.StageName}", "short" => true }, { "title" => "Amount", "value" => "$#{'%.2f' % h.Amount}", "short" => true }, { "title" => "Close Date", "value" => "#{op.CloseDate}", "short" => true }, # { # "title" => "Probability", # "value" => "#{'%.0f' % h.Probability}%", # "short" => true # }, # { # "title" => "Expected Revenue", # "value" => "$#{'%.2f' % h.ExpectedRevenue}", # "short" => true # }, { "title" => "Owner", "value" => "#{owner.Name}", "short" => true }, ] } # if op.StageName.include? "11" # # there's also 'warning' # attachment["color"] = 'danger' # elsif op.StageName.include?("06") || op.StageName.include?("08") || op.StageName.include?("10") # attachment["color"] = 'good' # end if op.Probability >= 70 # there's also 'warning' attachment["color"] = 'good' elsif op.Probability <= 20 attachment["color"] = 'danger' elsif op.Probability <= 40 attachment["color"] = 'warning' end if op.Probability == 100 attachment["image_url"] = "http://caldwelljournal.com/wp-content/uploads/2015/01/Boom.jpg" end puts "posting #{attachment.inspect} to slack..." # uncomment line below for testing # sh.channel = sh.username # puts "Posting #{text} to #{channel}..." notifier = Slack::Notifier.new config.slack.webhook_url notifier.channel = "#{config.slack.channel}" if config.slack.channel notifier.username = 'salesbot' resp = notifier.ping "", attachments: [attachment] p resp p resp.message puts "done" end get_opp_updates(config) <file_sep>/tubey/Gemfile source "http://rubygems.org" gem 'slack_webhooks' gem 'youtube_it' gem 'iron_worker' <file_sep>/curlbot/curlbot.rb require_relative 'bundle/bundler/setup' require 'iron_worker' require 'slack_webhooks' sh = SlackWebhooks::Hook.new('curlbot', IronWorker.payload, IronWorker.config['webhook_url']) s = `curl --silent #{sh.text}` puts s attachment = { "fallback" => s, "title" => "Response:", # "title_link" => "somelink", # "text" => "```pre\n#{s}\n```", "text" => s, } sh.send("/curl #{sh.text}", attachment: attachment) <file_sep>/uptime/slack.go package main import ( "bytes" "encoding/json" "fmt" "net/http" ) type slackC struct { url string } type slackPayload struct { Text string `json:"text"` Attachments []Attachment `json:"attachments"` } type Attachment struct { Fallback string `json:"fallback"` Color string `json:"color"` Pretext string `json:"pretext"` AuthorName string `json:"author_name"` AuthorLink string `json:"author_link"` AuthorIcon string `json:"author_icon"` Title string `json:"title"` TitleLink string `json:"title_link"` Text string `json:"text"` Fields []Field `json:"fields"` ImageURL string `json:"image_url"` ThumbURL string `json:"thumb_url"` } type Field struct { Title string `json:"title"` Value string `json:"value"` Short bool `json:"short"` } func (s *slackC) post(text string, attachments []Attachment) { payload := slackPayload{Text: text, Attachments: attachments} b, err := json.Marshal(payload) if err != nil { fmt.Println(err) return } buf := bytes.NewBuffer(b) _, err = http.Post(s.url, "application/json", buf) if err != nil { fmt.Println(err) return } } <file_sep>/salesforce/google_datastore.rb # This is abstracted into it's own class so you could swap it out for any other datastore without having to change the bot. require 'google/api_client' class GoogleDatastore attr_accessor :config, :dataset_id, :datastore, :client def initialize(gconfig) @config = gconfig # Same as project_id @dataset_id = gconfig.project_id # Google::APIClient.logger.level = Logger::INFO gclient = Google::APIClient.new(:application_name => 'Slacker', :application_version => '1.0.0') @datastore = gclient.discovered_api('datastore', 'v1beta2') # Load our credentials for the service account key = Google::APIClient::KeyUtils.load_from_pkcs12("gkey.p12", "notasecret") # Set authorization scopes and credentials. gclient.authorization = Signet::OAuth2::Client.new( :token_credential_uri => 'https://accounts.google.com/o/oauth2/token', :audience => 'https://accounts.google.com/o/oauth2/token', :scope => ['https://www.googleapis.com/auth/datastore', 'https://www.googleapis.com/auth/userinfo.email'], :issuer => gconfig.service_account_id, :signing_key => key) # Authorize the client. puts "authorizing to google..." gclient.authorization.fetch_access_token! @client = gclient end def lckey return {:path => [{:kind => 'CheckDates', :name => 'last_check'}]} # this name should be unique per user end # Returns the last date we checked Salesforce def get_last_check resp = client.execute( :api_method => datastore.datasets.lookup, :parameters => {:datasetId => dataset_id}, :body_object => { # Set the transaction, so we get a consistent snapshot of the # value at the time the transaction started. # :readOptions => {:transaction => tx}, # Add one entity key to the lookup request, with only one # :path element (i.e. no parent) :keys => [lckey] }) if !resp.data.found.empty? # Get the entity from the response if found. entity = resp.data.found[0].entity puts "Found last_check entity: #{entity.inspect}" # Get `question` property value. last_check = entity.properties.last_check.dateTimeValue.to_datetime else last_check = Date.today.prev_day.to_datetime # "2015-01-01T00:00:01z" end puts "last_check: #{last_check.inspect} class=#{last_check.class.name}" return last_check end def insert_new_check_date(t=Time.now) # If the entity is not found create it. entity = { # Set the entity key with only one `path` element: no parent. :key => lckey, # Set the entity properties: # - a utf-8 string: `question` # - a 64bit integer: `answer` :properties => { :last_check => {:dateTimeValue => t.to_datetime.rfc3339()}, } } # Build a mutation to insert the new entity. mutation = {:upsert => [entity]} # Commit the transaction and the insert mutation if the entity was not found. resp = client.execute( :api_method => datastore.datasets.commit, :parameters => {:datasetId => dataset_id}, :body_object => { # :transaction => tx, # todo: I couldn't get transactions to work?!?! get this: \"reason\": \"INVALID_ARGUMENT\",\n \"message\": \"unknown transaction handle\"\n :mode => 'NON_TRANSACTIONAL', :mutation => mutation }) puts "body=#{resp.body.inspect}" end end <file_sep>/uptime/pingdom.go package main import ( "encoding/json" "fmt" "io/ioutil" "net/http" "strconv" "sync" "time" ) const host = "https://api.pingdom.com/api/2.0/" type PingdomClient struct { Username string Password string ApiKey string client http.Client } type Check struct { Id int `json:"id"` Name string `json:"name"` Status string `json:"status"` } func (c *PingdomClient) Get(endpoint string) (*http.Response, error) { req, err := http.NewRequest("GET", host+endpoint, nil) if err != nil { return nil, err } req.SetBasicAuth(c.Username, c.Password) req.Header.Set("App-Key", c.ApiKey) res, err := c.client.Do(req) return res, err } func (c *PingdomClient) getChecks() ([]Check, error) { res, err := c.Get("checks/") if err != nil { return nil, err } b, err := ioutil.ReadAll(res.Body) if err != nil { return nil, err } checkList := struct { Checks []Check `json:"checks"` }{} err = json.Unmarshal(b, &checkList) if err != nil { return nil, err } return checkList.Checks, err } func (c *PingdomClient) getCheckById(id int) (Check, error) { endpoint := fmt.Sprintf("checks/%d", id) res, err := c.Get(endpoint) if err != nil || res.StatusCode != 200 { return Check{}, err } b, err := ioutil.ReadAll(res.Body) if err != nil { return Check{}, err } check := struct { Check Check `json:"check"` }{} err = json.Unmarshal(b, &check) if err != nil { return Check{}, err } return check.Check, err } func (c *PingdomClient) getUptime(check *Check, from time.Time) (*Status, error) { fromString := strconv.FormatInt(from.Unix(), 10) endpoint := fmt.Sprintf("summary.average/%d?includeuptime=true&from=%s", check.Id, fromString) res, err := c.Get(endpoint) if err != nil || res.StatusCode != 200 { return &Status{}, err } b, err := ioutil.ReadAll(res.Body) if err != nil { return &Status{}, err } s := struct { S struct { Status Status `json:"status"` } `json:"summary"` }{} err = json.Unmarshal(b, &s) if err != nil { fmt.Println(err) } return &s.S.Status, err } func (c *PingdomClient) getUptimes(alertIds []int, since time.Time) UptimeReports { var checks []*Check for _, id := range alertIds { check, err := c.getCheckById(id) if err != nil { fmt.Println(err) } else { checks = append(checks, &check) } } var uptimeReports UptimeReports for _, check := range checks { // We don't want anything thats paused if check.Status != "paused" && check.Status != "unknown" { u := &UptimeReport{ Name: check.Name, Id: check.Id, } if ur, err := client.getUptime(check, since.AddDate(0, 0, -1)); err == nil { u.DayAgo = ur } if ur, err := client.getUptime(check, since.AddDate(0, 0, -7)); err == nil { u.WeekAgo = ur } if ur, err := client.getUptime(check, since.AddDate(0, -1, 0)); err == nil { u.MonthAgo = ur } uptimeReports = append(uptimeReports, u) } } return uptimeReports } type UptimeReport struct { Id int `json:"id"` Name string `json:"name"` DayAgo *Status WeekAgo *Status MonthAgo *Status } type Status struct { Totalup int64 `json:"totalup"` Totaldown int64 `json:"totaldown"` Totalunknown int64 `json:"totalunknown"` } type UptimeReports []*UptimeReport func (u *Status) uptimePercentage() float64 { if u.Totalup+u.Totaldown == 0 { return 1.0 } return float64(u.Totalup) / (float64(u.Totaldown) + float64(u.Totalup)) } func (u *Status) save(key string) { percentage := strconv.FormatFloat(u.uptimePercentage(), 'f', 8, 64) c.Set(key, percentage) } // Change in downtime percentage func (u *Status) delta(key string) float64 { value, err := c.Get(key) if err != nil { return 0.0 } old, err := strconv.ParseFloat(value.(string), 64) if err != nil { return 0.0 } // If our uptime is up, we want to show a positive change instead of negative return (u.uptimePercentage() - old) / old } func (u *Status) Downtime() time.Duration { return time.Duration(u.Totaldown) } func (u *UptimeReport) save() { // key-format is id-(days_ago) id := strconv.Itoa(u.Id) u.DayAgo.save(id + "1") u.WeekAgo.save(id + "7") u.MonthAgo.save(id + "30") } func (u *UptimeReport) deltas() []float64 { id := strconv.Itoa(u.Id) return []float64{ u.DayAgo.delta(id + "1"), u.WeekAgo.delta(id + "7"), u.MonthAgo.delta(id + "30"), } } func (ur UptimeReports) dailyUptime() float64 { var up int64 var down int64 for _, u := range ur { up += u.DayAgo.Totalup down += u.DayAgo.Totaldown } return float64(up) / float64(up+down) } func (ur UptimeReports) totalDailyDowntime() string { var sum time.Duration for _, u := range ur { sum += time.Duration(u.DayAgo.Totaldown) } sum = sum * time.Second return sum.String() } func (ur UptimeReports) weeklyUptime() float64 { var up int64 var down int64 for _, u := range ur { up += u.WeekAgo.Totalup down += u.WeekAgo.Totaldown } return float64(up) / float64(up+down) } func (ur UptimeReports) totalWeeklyDowntime() string { var sum time.Duration for _, u := range ur { sum += time.Duration(u.WeekAgo.Totaldown) } sum = sum * time.Second return sum.String() } func (ur UptimeReports) monthlyUptime() float64 { var up int64 var down int64 for _, u := range ur { up += u.MonthAgo.Totalup down += u.MonthAgo.Totaldown } return float64(up) / float64(up+down) } func (ur UptimeReports) totalMonthlyDowntime() string { var sum time.Duration for _, u := range ur { sum += time.Duration(u.MonthAgo.Totaldown) } sum = sum * time.Second return sum.String() } func (ur UptimeReports) save() { var wg sync.WaitGroup wg.Add(len(ur)) for _, u := range ur { go func(u *UptimeReport) { defer wg.Done() u.save() }(u) } wg.Wait() } // sort in ascending order func (ur UptimeReports) Len() int { return len(ur) } func (ur UptimeReports) Swap(i, j int) { ur[i], ur[j] = ur[j], ur[i] } func (ur UptimeReports) Less(i, j int) bool { return ur[i].DayAgo.uptimePercentage() < ur[j].DayAgo.uptimePercentage() } <file_sep>/salesforce/Gemfile source "http://rubygems.org" gem 'restforce' gem 'slack_webhooks' gem 'intercom' gem 'iron_worker' gem 'iron_cache' <file_sep>/echobot/echobot.rb require_relative 'bundle/bundler/setup' require 'uri' require 'slack-notifier' require 'iron_worker' require 'slack_webhooks' sh = SlackWebhooks::Hook.new('echobot', IronWorker.payload, IronWorker.config['webhook_url']) # Slice off the 'echo' text text = sh.text.split(' ')[1..-1].join(' ') sh.send(text) <file_sep>/hellobot/README.md This will simply reply with a `Hello @user!`. The simplest bot you can get. <file_sep>/aws_cost_bot/README.md Given a set of AWS credential, this bot will go check all your servers and the costs associated with them, aggregated by Name. ## Additional steps required to run this Bot ### 1) Make an iron.json file This bot uses [IronCache](http://www.iron.io/cache) to store results temporarily. Create an iron.json file in this directory with your Iron.io project_id and token. ### 2) Add your AWS credentials to config.json Copy `config-example.json` to `config.json` and fill it in. ### 3) Test it ``` docker run --rm -v "$(pwd)":/worker -w /worker iron/images:ruby-2.1 sh -c 'ruby costbot.rb -payload slack.payload -config config.json' ``` ### 4) Upload it ``` zip -r costbot.zip . iron worker upload --name costbot --zip costbot.zip iron/images:ruby-2.1 ruby costbot.rb ``` ### 5) Schedule it This bot is intended to be scheduled, rather than turned into a slash command so instead of making a slash command, schedule it. After you upload, you'll see a link on your console to HUD where you can schedule it in the UI or you can use the command below: ``` iron worker schedule --start-at 2015-06-24T08:00:00Z --run-every 86400 --payload-file slack.payload costbot ``` <file_sep>/dicey/README.md Roll the dice in slack. /roll [sides] Will post a number from 1-sides back to Slack. <file_sep>/worker/README.md Runs an IronWorker, returns results to Slack. Example: ``` /worker IRON_PROJECT_ID IRON_TOKEN MY_WORKER_NAME ``` ## Testing This one requires a change to the `slack.payload` file in this directory to include your [Iron.io](http://www.iron.io) credentials. Replace `IRON_PROJECT_ID` and `IRON_TOKEN` to your Iron credentials then test with the Docker run command. <file_sep>/hellobot/hellobot.rb require_relative 'bundle/bundler/setup' require 'iron_worker' require 'slack_webhooks' sh = SlackWebhooks::Hook.new('hellobot', IronWorker.payload, IronWorker.config['webhook_url']) text = "Hello #{sh.user_name}!" sh.send(text) <file_sep>/dicey/Gemfile source "http://rubygems.org" gem 'slack_webhooks' gem 'iron_worker' <file_sep>/echobot/README.md This one is a bit different, make an Outgoing Webhook in Slack rather than a Slash Command. Trigger it with `echo`. <file_sep>/hellobot/Gemfile source "http://rubygems.org" gem 'iron_worker' gem 'slack_webhooks' <file_sep>/votey/README.md Users can vote on something. ``` /vote <vote_name> yes/no ``` ## Additional steps required to run this Bot This bot uses [IronCache](http://www.iron.io/cache) to store results temporarily. Create an iron.json file in this directory with your Iron.io project_id and token.
21f8301f0e77af63d5389cf830ed7504c09a8d03
[ "Go", "Ruby", "Markdown" ]
34
Ruby
treeder/slackbots
70e47908e8b7f0bafca11e874d97ac2f6c18dc5b
88e8256084780c71df0bd9f61b2f28eaa39885b4
refs/heads/master
<repo_name>LeonID-11/Quiz<file_sep>/src/containers/QuizList/QuizList.js import React, {Component} from 'react'; import './QuizList.css'; import {NavLink} from 'react-router-dom'; class QuizList extends Component { renderQuizes(){ return [1,2,3].map((quiz, index)=>{ return( <li key={index} > <NavLink to={'/quiz/'+ quiz} > test {quiz} </NavLink> </li> ) }) } render(){ return ( <div className='QuizList'> <div> <h1>Quiz List</h1> <ul> {this.renderQuizes()} </ul> </div> </div> ); } } export default QuizList;
273a9e0fd8638d85ac2402c1d16ab2e133d11c43
[ "JavaScript" ]
1
JavaScript
LeonID-11/Quiz
7780e55825368a6ddbe18bd23213c2ad168bc166
f0f214a43fed7db2a425e50614273f6c022d5db8
refs/heads/master
<repo_name>stjordanis/catvae<file_sep>/catvae/models/tests/test_linear_vae.py import unittest import torch from catvae.models import LinearVAE, LinearBatchVAE import numpy as np import numpy.testing as npt class TestLinearVAE(unittest.TestCase): def test_sample(self): k, D = 10, 40 model = LinearVAE(D, k) x = torch.zeros(2, D) s = model.sample(x).detach().numpy() npt.assert_allclose(s.shape, np.array([2, k])) class TestLinearBatchVAE(unittest.TestCase): def test_sample(self): k, C, D = 10, 3, 40 prior = torch.randn(C, D) model = LinearBatchVAE(D, k, k, C, batch_prior=prior) x = torch.zeros(2, D) b = torch.Tensor([0, 1]).long() s = model.sample(x, b).detach().numpy() npt.assert_allclose(s.shape, np.array([2, k])) if __name__ == '__main__': unittest.main() <file_sep>/benchmarks/run.sh #SIM=sparse_sim SIM=dense_sim latent_dim=10 input_dim=100 samples=1000 depth=100000 echo "latent_dim ${latent_dim}" echo "input_dim ${input_dim}" echo "samples ${samples}" echo "depth ${depth}" # Simulate the counts simulate-counts.py \ --latent-dim $latent_dim \ --input-dim $input_dim \ --samples $samples \ --depth $depth \ --output-dir $SIM bases="$SIM/basis.nwk alr identity" analytic='True False' lr=1e-3 batch_size=100 epochs=1000 # Analytical Catvae for basis in $bases do OUT=catvae-analytic-$basis catvae-train.py \ --num-workers 30 \ --gpus 1 \ --eigvalues $SIM/eigvals.txt \ --eigvectors $SIM/eigvecs.txt \ --basis $basis \ --learning-rate $lr \ --batch-size $batch_size \ --train-biom $SIM/train.biom \ --test-biom $SIM/test.biom \ --val-biom $SIM/valid.biom \ --steps-per-batch 100 \ --bias False --epochs $epochs \ --output-dir $OUT done # Stochastic Catvae for basis in $bases do OUT=catvae-stochastic-$basis linear-vae-train.py \ --num-workers 30 \ --gpus 1 \ --eigvalues $SIM/eigvals.txt \ --eigvectors $SIM/eigvecs.txt \ --basis $basis \ --learning-rate $lr \ --batch-size $batch_size \ --use-analytic-elbo False \ --likelihood multinomial \ --bias False --train-biom $SIM/train.biom \ --test-biom $SIM/test.biom \ --val-biom $SIM/valid.biom \ --epochs $epochs \ --output-dir $OUT done # # Gaussian linear VAE # for basis in $bases # do # OUT=linear-vae-analytic-$basis # linear-vae-train.py \ # --num-workers 30 \ # --gpus 1 \ # --eigvalues $SIM/eigvals.txt \ # --eigvectors $SIM/eigvecs.txt \ # --basis $basis \ # --learning-rate $lr \ # --batch-size $batch_size \ # --use-analytic-elbo True \ # --likelihood gaussian \ # --train-biom $SIM/train.biom \ # --test-biom $SIM/test.biom \ # --val-biom $SIM/valid.biom \ # --epochs $epochs \ # --bias False \ # --output-dir $OUT # done # # for basis in $bases # do # OUT=linear-vae-stochastic-$basis # linear-vae-train.py \ # --num-workers 30 \ # --gpus 1 \ # --eigvalues $SIM/eigvals.txt \ # --eigvectors $SIM/eigvecs.txt \ # --basis $basis \ # --learning-rate $lr \ # --batch-size $batch_size \ # --use-analytic-elbo False \ # --likelihood gaussian \ # --train-biom $SIM/train.biom \ # --test-biom $SIM/test.biom \ # --val-biom $SIM/valid.biom \ # --epochs $epochs \ # --bias False \ # --output-dir $OUT # done <file_sep>/catvae/metrics.py import torch import torch.nn as nn import numpy as np from scipy.spatial import procrustes from scipy.spatial.distance import pdist from scipy.stats import pearsonr def get_weight_tensor_from_seq(weight_seq): if isinstance(weight_seq, nn.Linear): return weight_seq.weight.detach() elif isinstance(weight_seq, nn.Sequential): weight_tensor = None for layer in weight_seq: if isinstance(layer, nn.Linear): layer_weight = layer.weight.detach() if weight_tensor is None: weight_tensor = layer_weight else: weight_tensor = layer_weight @ weight_tensor elif isinstance(layer, nn.BatchNorm1d): bn_weight = layer.weight.detach() # ignore bias if weight_tensor is None: weight_tensor = torch.diag(bn_weight) else: weight_tensor = torch.diag(bn_weight) @ weight_tensor else: raise ValueError( "Layer type {} not supported!".format(type(layer))) return weight_tensor def metric_transpose_theorem(model): """ Metric for how close encoder and decoder.T are :param model: LinearAE model :return: ||W1 - W2^T||_F^2 / hidden_dim """ # encoder_weight = get_weight_tensor_from_seq(model.encoder) # decoder_weight = get_weight_tensor_from_seq(model.decoder) encoder_weight = model.encoder.weight.cpu().numpy() decoder_weight = model.decoder.weight.cpu().numpy() transpose_metric = np.linalg.norm(encoder_weight - decoder_weight.T) ** 2 return transpose_metric.item() / float(model.hidden_dim) def metric_orthogonality(model): """ Measures how orthogonal the decoder matrix is. """ W = model.decoder.weight.cpu().numpy() u, s, v = np.linalg.svd(W) eigvals = (W**2).sum(axis=0) Weig = W / np.sqrt(eigvals) Id = np.eye(Weig.shape[1]) eigvals = np.sqrt(np.sort(eigvals)[::-1]) hd = float(model.hidden_dim) ortho_err = np.linalg.norm(Weig.T @ Weig - Id) ** 2 / hd if len(s) < len(eigvals): eigvals = eigvals[:len(s)] eig_err = np.sum((s - eigvals) ** 2) / hd return ortho_err, eig_err def metric_alignment(model, gt_eigvectors): """ Metric for alignment of decoder columns to ground truth eigenvectors :param model: Linear AE model :param gt_eigvectors: ground truth eigenvectors (input_dims,hidden_dims) :return: sum_i (1 - max_j (cos(eigvector_i, normalized_decoder column_j))) """ decoder_np = model.decoder.weight.cpu().numpy()[:gt_eigvectors.shape[0], :] # normalize columns of gt_eigvectors norm_gt_eigvectors = gt_eigvectors / np.linalg.norm(gt_eigvectors, axis=0) # normalize columns of decoder norm_decoder = decoder_np / (np.linalg.norm(decoder_np, axis=0) + 1e-8) total_angles = 0.0 for eig_i in range(gt_eigvectors.shape[1]): eigvector = norm_gt_eigvectors[:, eig_i] total_angles += 1. - np.max(np.abs(norm_decoder.T @ eigvector)) ** 2 return total_angles / float(model.hidden_dim) def metric_subspace(model, gt_eigvectors, gt_eigs): decoder_np = model.decoder.weight.cpu().numpy()[:gt_eigvectors.shape[0], :] # if correction: # C = model.Psi.to_dense() # A = torch.svd(model.encode(C))[1].cpu() # A = torch.diag(A).detach().numpy() # decoder_np = decoder_np @ A # k - tr(UU^T WW^T), where W is left singular vector matrix of decoder u, s, vh = np.linalg.svd(decoder_np, full_matrices=False) hd = float(model.hidden_dim) return 1 - np.trace(gt_eigvectors @ gt_eigvectors.T @ u @ u.T) / hd def metric_procrustes(model, gt_eigvectors): W = model.decoder.weight.cpu().numpy()[:gt_eigvectors.shape[0], :] return procrustes(gt_eigvectors, W)[2] def metric_pairwise(model, gt_eigvectors, gt_eigs): W = model.decoder.weight.cpu().numpy()[:gt_eigvectors.shape[0], :] trueW = gt_eigvectors @ np.diag(gt_eigs) true_dW = pdist(trueW) est_dW = pdist(W) r, _ = pearsonr(true_dW, est_dW) return r <file_sep>/catvae/tests/test.sh simulate-counts.py \ --latent-dim 10 \ --input-dim 50 \ --samples 500 \ --depth 10000 \ --no-batch-effect \ --output-dir simulation_directory linear-vae-train.py \ --basis simulation_directory/tree.nwk \ --n-latent 10 \ --n-hidden 10 \ --dropout 0.5 \ --no-bias \ --no-batch-norm \ --encoder-depth 1 \ --learning-rate 1e-1 \ --transform pseudocount \ --scheduler cosine \ --train-biom simulation_directory/train.biom \ --test-biom simulation_directory/test.biom \ --val-biom simulation_directory/valid.biom \ --batch-size 50 \ --epochs 2 \ --num-workers 1 \ --gpus 0 \ --output-directory vae_results # test to make sure that it can load from checkpoint linear-vae-train.py \ --load-from-checkpoint vae_results/last_ckpt.pt \ --basis simulation_directory/tree.nwk \ --n-latent 10 \ --n-hidden 10 \ --dropout 0.5 \ --no-bias \ --no-batch-norm \ --encoder-depth 1 \ --learning-rate 1e-1 \ --transform pseudocount \ --scheduler cosine \ --train-biom simulation_directory/train.biom \ --test-biom simulation_directory/test.biom \ --val-biom simulation_directory/valid.biom \ --batch-size 50 \ --epochs 2 \ --num-workers 1 \ --gpus 0 \ --output-directory vae_results_2 # clean up rm -r vae_results rm -r vae_results_2 rm -r simulation_directory simulate-counts.py \ --latent-dim 10 \ --input-dim 50 \ --samples 500 \ --depth 10000 \ --batch-effect \ --batches 3 \ --output-dir simulation_directory linear-vae-batch-train.py \ --basis tree.nwk \ --n-latent 10 \ --n-hidden 10 \ --dropout 0.5 \ --no-bias \ --no-batch-norm \ --batch-size 50 \ --encoder-depth 1 \ --learning-rate 1e-1 \ --transform pseudocount \ --scheduler cosine \ --batch-category batch_category \ --sample-metadata simulation_directory/metadata.txt \ --batch-prior simulation_directory/batch_priors.txt \ --train-biom simulation_directory/train.biom \ --test-biom simulation_directory/test.biom \ --val-biom simulation_directory/valid.biom \ --epochs 3 \ --num-workers 1 \ --gpus 0 \ --output-directory vae_results # test checkpointing linear-vae-batch-train.py \ --load-from-checkpoint vae_results/last_ckpt.pt \ --basis tree.nwk \ --n-latent 10 \ --n-hidden 10 \ --dropout 0.5 \ --no-bias \ --no-batch-norm \ --batch-size 50 \ --encoder-depth 1 \ --learning-rate 1e-1 \ --transform pseudocount \ --scheduler cosine \ --batch-category batch_category \ --sample-metadata simulation_directory/metadata.txt \ --batch-prior simulation_directory/batch_priors.txt \ --train-biom simulation_directory/train.biom \ --test-biom simulation_directory/test.biom \ --val-biom simulation_directory/valid.biom \ --epochs 3 \ --num-workers 1 \ --gpus 0 \ --output-directory vae_results_2 # clean up rm -r vae_results rm -r vae_results_2 rm -r simulation_directory <file_sep>/benchmarks/encoder_run.slurm #!/bin/bash # #SBATCH -N 1 #SBATCH --mail-type=ALL # Mail events (NONE, BEGIN, END, FAIL, ALL) #SBATCH --mail-user=<EMAIL> source ~/.bashrc conda activate catvae SIM=sparse_sim n_latent=10 # Simulate the counts simulate-counts.py \ --latent-dim $n_latent \ --input-dim 200 \ --samples 1000 \ --depth 100 \ --output-dir $SIM #bases="$SIM/basis.nwk alr identity" basis=$SIM/basis.nwk analytic='True False' layers="1 3 5" lr=1e-3 batch_size=100 epochs=100 # Analytical Catvae # for depth in $layers # do # OUT=catvae-analytic-ilr-$depth-layers # sbatch -p gpu --gres=gpu:v100-32gb:1 --wrap "catvae-train.py --num-workers 10 --gpus 1 --eigvalues $SIM/eigvals.txt --eigvectors $SIM/eigvecs.txt --basis $basis --learning-rate $lr --batch-size $batch_size --train-biom $SIM/train.biom --test-biom $SIM/test.biom --val-biom $SIM/valid.biom --steps-per-batch 30 --encoder-depth $depth --n-latent $n_latent --epochs $epochs --output-dir $OUT" # done # Stochastic Catvae for depth in $layers do OUT=catvae-stochastic-ilr-$depth-layers sbatch -p gpu --gres=gpu:v100-32gb:1 --wrap "linear-vae-train.py --num-workers 10 --gpus 1 --eigvalues $SIM/eigvals.txt --eigvectors $SIM/eigvecs.txt --basis $basis --learning-rate $lr --batch-size $batch_size --use-analytic-elbo False --likelihood multinomial --train-biom $SIM/train.biom --test-biom $SIM/test.biom --val-biom $SIM/valid.biom --encoder-depth $depth --n-latent $n_latent --epochs $epochs --output-dir $OUT" done <file_sep>/scripts/lda.py import argparse from sklearn.decomposition import LatentDirichletAllocation as LDA import pickle from biom import load_table def main(args): model = LDA(n_components=args.n_latent, max_iter=args.iterations, verbose=1, learning_method='online') table = load_table(args.train_biom) X = table.matrix_data.T model.fit(X) with open(args.model_checkpoint, 'wb') as f: pickle.dump(model, f) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--train-biom', help='Training biom file', required=True) parser.add_argument('--n-latent', type=int, help='Number of components') parser.add_argument('--iterations', type=int, default=10000, required=False, help='Number of iterations.') parser.add_argument('--batch-size', type=int, default=256, required=False, help='Batch size') parser.add_argument('--n-jobs', type=int, default=-1, required=False, help='Number of concurrent jobs.') parser.add_argument('--model-checkpoint', required=True, help='Location of saved model.') args = parser.parse_args() main(args) <file_sep>/catvae/distributions/constraints.py r""" The following constraints are implemented - ``constraints.orthonormal`` - ``constraints.right_orthonormal`` - ``constraints.left_orthonormal`` """ from torch.distributions.constraints import Constraint import torch __all__ = ['orthonormal', 'right_orthonormal', 'left_orthonormal'] class _Orthonormal(Constraint): """ Make sure that matrix is orthonormal Specifically: `U @ UT = I` and `UT @ U = I` """ def check(self, value): n, d = value.shape[-2], value.shape[-1] In = torch.eye(n) Id = torch.eye(d) right_ortho = torch.allclose(value @ value.T, In) left_ortho = torch.allclose(value.T @ value, Id) return right_ortho and left_ortho class _RightOrthonormal(Constraint): """ Make sure that matrix is right orthonormal Specifically: `U @ UT = I` """ def check(self, value): n = value.shape[-2] In = torch.eye(n) right_ortho = torch.allclose(value @ value.T, In) return right_ortho class _LeftOrthonormal(Constraint): """ Make sure that matrix is left orthonormal Specifically: `UT @ U = I` """ def check(self, value): d = value.shape[-1] Id = torch.eye(d) left_ortho = torch.allclose(value.T @ value, Id) return left_ortho # Public interface orthonormal = _Orthonormal() right_orthonormal = _RightOrthonormal() left_orthonormal = _LeftOrthonormal() <file_sep>/catvae/models/batch_classifier.py from sklearn.pipeline import Pipeline import warnings try: from q2_sample_classifier.classify import predict_probabilities from q2_sample_classifier.utilities import _extract_features except: warnings.warn('q2_sample_classifier not installed.') import numpy as np import pandas as pd class Q2BatchClassifier(object): def __init__(self, model: Pipeline, categories: pd.Series, n_workers: int = 1): self.n_workers = n_workers self.sample_estimator = model self._categories = categories self.sample_estimator.set_params(est__n_jobs=self.n_workers) def __call__(self, feature_data: np.array): # Borrowed from # https://github.com/qiime2/q2-sample-classifier/blob/ # master/q2_sample_classifier/classify.py#L264 index = np.arange(len(feature_data)) probs = predict_probabilities( self.sample_estimator, feature_data, index) return probs[self._categories.index].values def biom_to_features(self, table): return _extract_features(table) <file_sep>/scripts/linear-vae-batch-train.py import os import argparse import numpy as np import pandas as pd from catvae.trainer import (MultVAE, MultBatchVAE, BiomDataModule, add_data_specific_args) from pytorch_lightning import Trainer from pytorch_lightning.callbacks.model_checkpoint import ModelCheckpoint from pytorch_lightning.profiler import AdvancedProfiler from pytorch_lightning import loggers as pl_loggers from biom import load_table from skbio import TreeNode import yaml def main(args): if args.load_from_checkpoint is not None: model = MultBatchVAE.load_from_checkpoint(args.load_from_checkpoint) else: table = load_table(args.train_biom) n_input = table.shape[0] sample_metadata = pd.read_table(args.sample_metadata, dtype=str) sample_metadata = sample_metadata.set_index(sample_metadata.columns[0]) sample_metadata = sample_metadata.loc[table.ids()] n_batches = len(sample_metadata[args.batch_category].value_counts()) model = MultBatchVAE( n_input, args.batch_prior, n_batches, n_latent=args.n_latent, n_hidden=args.n_hidden, basis=args.basis, dropout=args.dropout, bias=args.bias, batch_norm=args.batch_norm, encoder_depth=args.encoder_depth, learning_rate=args.learning_rate, vae_lr=args.vae_lr, scheduler=args.scheduler, transform=args.transform, grassmannian=args.grassmannian) if args.load_vae_weights is not None: # initialize encoder/decoder weights with pretrained VAE other_model = MultVAE.load_from_checkpoint(args.load_vae_weights) model.vae.encoder = other_model.vae.encoder model.vae.decoder = other_model.vae.decoder model.vae.log_sigma_sq = other_model.vae.log_sigma_sq model.vae.variational_logvars = other_model.vae.variational_logvars # Note that input_embed isn't handled here. print(args) print(model) if args.eigvectors is not None and args.eigvalues is not None: eigvectors = np.loadtxt(args.eigvectors) eigvalues = np.loadtxt(args.eigvalues) model.set_eigs(eigvectors, eigvalues) if args.profile: profiler = AdvancedProfiler() else: profiler = None dm = BiomDataModule( args.train_biom, args.test_biom, args.val_biom, metadata=args.sample_metadata, batch_category=args.batch_category, batch_size=args.batch_size, num_workers=args.num_workers) ckpt_path = os.path.join( args.output_directory, "checkpoints") checkpoint_callback = ModelCheckpoint( dirpath=ckpt_path, period=1, monitor='val_loss', mode='min', verbose=True) os.mkdir(args.output_directory) tb_logger = pl_loggers.TensorBoardLogger(f'{args.output_directory}/logs/') # save hyper-parameters to yaml file with open(f'{args.output_directory}/hparams.yaml', 'w') as outfile: yaml.dump(model._hparams, outfile, default_flow_style=False) # save batch class mappings dm.batch_categories.to_csv( f'{args.output_directory}/batch_categories.txt', sep='\t', header=None) # save tree to file if specified if os.path.exists(args.basis): tree = TreeNode.read(args.basis) tree.write(f'{args.output_directory}/tree.nwk') trainer = Trainer( max_epochs=args.epochs, gpus=args.gpus, check_val_every_n_epoch=1, gradient_clip_val=args.grad_clip, profiler=profiler, logger=tb_logger, callbacks=[checkpoint_callback]) trainer.fit(model, dm) trainer.save_checkpoint( args.output_directory + '/last_ckpt.pt') if __name__ == '__main__': parser = argparse.ArgumentParser(add_help=True) parser = MultBatchVAE.add_model_specific_args(parser, add_help=False) parser = add_data_specific_args(parser, add_help=False) args = parser.parse_args() main(args) <file_sep>/catvae/sim.py import numpy as np from skbio.stats.composition import closure from gneiss.cluster import random_linkage from gneiss.balances import _balance_basis from scipy.stats import ortho_group def multinomial_bioms(k, D, N, M, min_sv=0.11, max_sv=5.0, sigma_sq=0.1): """ Simulates biom tables from multinomial. Parameters ---------- k : int Number of latent dimensions. D : int Number of microbes. N : int Number of samples. M : int Average sequencing depth. Returns ------- dict of np.array Ground truth parameters. """ dims, hdims, total = D, k, N eigs = min_sv + (max_sv - min_sv) * np.linspace(0, 1, hdims) eigvectors = ortho_group.rvs(dims - 1)[:, :hdims] W = np.matmul(eigvectors, np.diag(np.sqrt(eigs - sigma_sq))) sigma_sq = sigma_sq sigma = np.sqrt(sigma_sq) z = np.random.normal(size=(total, hdims)) eta = np.random.normal(np.matmul(z, W.T), sigma).astype(np.float32) tree = random_linkage(D) Psi = _balance_basis(tree)[0] prob = closure(np.exp(eta @ Psi)) depths = np.random.poisson(M, size=N) Y = np.vstack([np.random.multinomial(depths[i], prob[i]) for i in range(N)]) return dict( sigma=sigma, W=W, Psi=Psi, tree=tree, eta=eta, z=z, Y=Y, depths=depths, eigs=eigs, eigvectors=eigvectors ) def multinomial_batch_bioms(k, D, N, M, C=2, min_sv=0.11, max_sv=5.0, sigma_sq=0.1): """ Simulates biom tables from multinomial with batch effects Parameters ---------- k : int Number of latent dimensions. D : int Number of microbes. N : int Number of samples. M : int Average sequencing depth. C : int Number of batches. Returns ------- dict of np.array Ground truth parameters. """ dims, hdims, total = D, k, N eigs = min_sv + (max_sv - min_sv) * np.linspace(0, 1, hdims) eigvectors = ortho_group.rvs(dims - 1)[:, :hdims] W = np.matmul(eigvectors, np.diag(np.sqrt(eigs - sigma_sq))) sigma_sq = sigma_sq sigma = np.sqrt(sigma_sq) z = np.random.normal(size=(total, hdims)) eta = np.random.normal(np.matmul(z, W.T), sigma).astype(np.float32) # Create ILR basis tree = random_linkage(D) Psi = _balance_basis(tree)[0] # add batch effects alpha = np.abs(np.random.normal(0, 0.5, size=(D))) alphaILR = np.abs(Psi) @ alpha # variances must always be positive m = np.zeros(D - 1) B = np.random.multivariate_normal(m, np.diag(alphaILR), size=C) batch_idx = np.random.randint(C, size=N) eta = np.vstack([eta[i] + B[batch_idx[i]] for i in range(N)]) # Convert latent variables to observed counts prob = closure(np.exp(eta @ Psi)) depths = np.random.poisson(M, size=N) Y = np.vstack([np.random.multinomial(depths[i], prob[i]) for i in range(N)]) return dict( sigma=sigma, W=W, Psi=Psi, tree=tree, eta=eta, z=z, Y=Y, alpha=alpha, alphaILR=alphaILR, B=B, batch_idx=batch_idx, depths=depths, eigs=eigs, eigvectors=eigvectors ) def normal_bioms(k, D, N, min_sv=0.11, max_sv=5.0, sigma_sq=0.1): """ Simulates biom tables from multivariate gaussian. Parameters ---------- k : int Number of latent dimensions. D : int Number of microbes. N : int Number of samples. Returns ------- dict of np.array Ground truth parameters. """ dims, hdims, total = D, k, N eigs = min_sv + (max_sv - min_sv) * np.linspace(0, 1, hdims) eigvectors = ortho_group.rvs(dims)[:, :hdims] W = np.matmul(eigvectors, np.diag(np.sqrt(eigs - sigma_sq))) sigma_sq = sigma_sq sigma = np.sqrt(sigma_sq) z = np.random.normal(size=(total, hdims)) x = np.random.normal(np.matmul(z, W.T), sigma).astype(np.float32) return dict( sigma=sigma, W=W, x=x, z=z, eigs=eigs, eigvectors=eigvectors ) <file_sep>/scripts/vae-stan-tune.py import os import torch import pystan import numpy as np import argparse from catvae.trainer import LightningCatVAE, LightningLinearVAE import pickle from biom import load_table model_code = """ data { int<lower=0> N; // number of samples int<lower=0> D; // number of dimensions int<lower=0> K; // number of latent dimensions matrix[D-1, D] Psi; // Orthonormal basis int y[N, D]; // observed counts } parameters { // parameters required for linear regression on the species means matrix[N, D-1] eta; // ilr transformed abundances matrix[D-1, K] W; real<lower=0> sigma; } transformed parameters { matrix[D-1, D-1] Sigma; matrix[D-1, D-1] I; vector[D-1] z; I = diag_matrix(rep_vector(1.0, D-1)); Sigma = W * W' + square(sigma) * I; z = rep_vector(0, D-1); } model { // generating counts for (n in 1:N){ eta[n] ~ multi_normal(z, Sigma); y[n] ~ multinomial(softmax(to_vector(eta[n] * Psi))); } } """ def main(args): if args.model == 'catvae': model = LightningCatVAE(args) elif args.model == 'linear-vae': model = LightningLinearVAE(args) else: raise ValueError(f'{args.model} is not supported') print(model) checkpoint = torch.load( args.torch_ckpt, map_location=lambda storage, loc: storage) model.load_state_dict(checkpoint['state_dict']) if args.stan_model is None: sm = pystan.StanModel(model_code=model_code) else: if os.path.exists(args.stan_model): # load compiled model from pickle sm = pickle.load(open(args.stan_model, 'rb')) else: sm = pystan.StanModel(model_code=model_code) with open(args.stan_model, 'wb') as f: pickle.dump(sm, f) W = model.model.decoder.weight.detach().cpu().numpy().squeeze() sigma = np.exp(0.5 * model.model.log_sigma_sq.detach().cpu().numpy()) table = load_table(args.train_biom) N, D, K = table.shape[1], table.shape[0], args.n_latent psi = np.array(model.set_basis(N, table).todense()) Y = np.array(table.matrix_data.todense()).T.astype(np.int64) fit_data = {'N': N, 'D': D, 'K': K, 'Psi': psi, 'y': Y} init = [{'W': W, 'sigma': sigma}] * args.chains if args.mode == 'hmc': fit = sm.sampling(data=fit_data, iter=args.iterations, chains=args.chains, init=init) print('Sampling from posterior distribution') # return a dictionary of arrays la = fit.extract(permuted=False, pars=['W', 'sigma']) print('Saving file') with open(f'{args.output_directory}/hmc-results.pkl', 'wb') as f: pickle.dump(la, f) elif args.mode == 'mle': la = sm.optimizing(data=fit_data, iter=args.iterations, init=init) with open(f'{args.output_directory}/mle-results.pkl', 'wb') as f: pickle.dump(la, f) else: raise ValueError(f'{args.mode} not implemented.') if __name__ == '__main__': parser = argparse.ArgumentParser(add_help=False) parser = LightningCatVAE.add_model_specific_args(parser) parser.add_argument('--torch-ckpt', type=str, required=True, help='Linear VAE checkpoint path.') parser.add_argument('--stan-model', type=str, default=None, required=False, help='Path to compiled Stan model.') parser.add_argument('--model', type=str, default='catvae', required=False) parser.add_argument('--checkpoint-interval', type=int, default=100, required=False, help='Number of iterations per checkpoint.') parser.add_argument('--iterations', type=int, default=1000, required=False, help='Number of iterations.') parser.add_argument('--mode', type=str, default='hmc', required=False, help='Specifies either `hmc` or `mle`.') parser.add_argument('--chains', type=int, default=4, required=False, help='Number of MCMC chains to run in Stan') args = parser.parse_args() main(args) <file_sep>/catvae/composition.py import numpy as np import torch import torch.nn as nn from torch.sparse import mm from gneiss.balances import sparse_balance_basis from skbio import TreeNode class pseudoCLR(nn.Module): def __init__(self): super(pseudoCLR, self).__init__() def forward(self, x): y = torch.log(x + 1) y = y - y.mean(axis=1).view(-1, 1) return y class pseudoALR(nn.Module): def __init__(self): super(pseudoALR, self).__init__() def forward(self, x): y = torch.log(x + 1) y = y[:, 1:] - y[:, 0].view(-1, 1) return y def closure(x): denom = torch.sum(x, dim=-1) if len(x.size()) == 3: b, n, d = x.size() denom = denom.reshape(b, n, 1) return x / denom elif len(x.size()) == 2: n, d = x.size() denom = denom.reshape(n, 1) return x / denom elif len(x.size()) == 1: denom = x.size() return x / denom else: raise ValueError(f'`x` has dimensions {x.shape}, which are too big') def ilr(p, basis): return mm(basis, torch.log(p).T).T def ilr_inv(eta, basis): return torch.nn.Softmax(eta @ basis, dim=-1) def ilr_basis(nwk): tree = TreeNode.read(nwk) t = tree.copy() t.bifurcate() basis = sparse_balance_basis(tree)[0] return basis def alr_basis(D, denom=0): """ Computes alr basis (in numpy) """ basis = np.eye(D - 1) z = - np.ones((D - 1, 1)) basis = np.hstack(( basis[:, :denom], z, basis[:, denom:])) return basis def identity_basis(D): basis = np.eye(D) return basis <file_sep>/catvae/distributions/utils.py import torch import numpy import random def seed_all(seed): if not seed: seed = 10 print("[ Using Seed : ", seed, " ]") torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) torch.cuda.manual_seed(seed) numpy.random.seed(seed) random.seed(seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False <file_sep>/catvae/dataset/tests/test_biom.py import unittest from skbio.util import get_data_path from biom import load_table import pandas as pd import numpy as np from catvae.dataset.biom import BiomDataset, Q2BiomDataset from catvae.dataset.biom import collate_q2_f import numpy.testing as npt class TestBiomDataset(unittest.TestCase): def setUp(self): self.table = load_table(get_data_path('table.biom')) self.metadata = pd.read_table(get_data_path('metadata.txt'), index_col=0) def test_biom(self): BiomDataset(self.table) def test_biom_getitem(self): data = BiomDataset(self.table, self.metadata, batch_category='batch') exp_sample = np.array([ 65., 66., 12., 94., 37., 43., 97., 69., 6., 22., 87., 43., 87., 5., 51., 53., 26., 54., 51., 76., 15., 92., 30., 43., 97., 98., 7., 43., 25., 51., 75., 39., 13., 90., 89., 48., 60., 79., 9., 97., 35., 47., 13., 44., 70., 94., 80., 62., 99., 73. ]) batch = data[0] npt.assert_allclose(batch[0], exp_sample) npt.assert_allclose(batch[1], np.array(0)) class TestQ2BiomDataset(unittest.TestCase): def setUp(self): self.table = load_table(get_data_path('table.biom')) self.metadata = pd.read_table(get_data_path('metadata.txt'), index_col=0) np.random.seed(0) def test_biom_getitem(self): data = Q2BiomDataset(self.table) exp_sample = np.array([ 65., 66., 12., 94., 37., 43., 97., 69., 6., 22., 87., 43., 87., 5., 51., 53., 26., 54., 51., 76., 15., 92., 30., 43., 97., 98., 7., 43., 25., 51., 75., 39., 13., 90., 89., 48., 60., 79., 9., 97., 35., 47., 13., 44., 70., 94., 80., 62., 99., 73. ]) ids = list(map(str, range(len(exp_sample)))) exp_sample = dict(zip(ids, exp_sample)) self.assertDictEqual(exp_sample, data[0][0]) def test_q2_collate_f(self): data = Q2BiomDataset(self.table) batch = (data[0], data[1], data[2]) features, sample_idx = collate_q2_f(batch) npt.assert_allclose(np.array([0, 1, 2]), sample_idx) exp_sample = np.array([ 65., 66., 12., 94., 37., 43., 97., 69., 6., 22., 87., 43., 87., 5., 51., 53., 26., 54., 51., 76., 15., 92., 30., 43., 97., 98., 7., 43., 25., 51., 75., 39., 13., 90., 89., 48., 60., 79., 9., 97., 35., 47., 13., 44., 70., 94., 80., 62., 99., 73. ]) ids = list(map(str, range(len(exp_sample)))) exp_sample = dict(zip(ids, exp_sample)) self.assertDictEqual(exp_sample, features[0]) if __name__ == '__main__': unittest.main() <file_sep>/catvae/models/__init__.py from catvae.models.linear_cat_vae import LinearCatVAE from catvae.models.linear_cat_vae import LinearBatchCatVAE from catvae.models.linear_vae import LinearVAE from catvae.models.linear_vae import LinearDLRVAE from catvae.models.linear_vae import LinearBatchVAE from catvae.models.batch_classifier import Q2BatchClassifier __all__ = ['LinearCatVAE', 'LinearBatchCatVAE', 'LinearVAE', 'LinearDLRVAE', 'LinearBatchVAE', 'Q2BatchClassifier'] <file_sep>/benchmarks/basis_run.slurm #!/bin/bash # #SBATCH -N 1 #SBATCH --mail-type=ALL # Mail events (NONE, BEGIN, END, FAIL, ALL) #SBATCH --mail-user=<EMAIL> source ~/.bashrc conda activate catvae # SIM=sparse_sim # n_latent=10 # # Simulate the counts # simulate-counts.py \ # --latent-dim $n_latent \ # --input-dim 200 \ # --samples 1000 \ # --depth 100 \ # --output-dir $SIM # SIM=dense_sim # # Simulate the counts # simulate-counts.py \ # --latent-dim 10 \ # --input-dim 100 \ # --samples 1000 \ # --depth 1000000 \ # --output-dir $SIM bases="$SIM/basis.nwk alr identity" analytic='True False' lr=1e-3 batch_size=100 epochs=100 # Analytical Catvae for basis in $bases do OUT=catvae-analytic-$basis sbatch -p gpu --gres=gpu:v100-32gb:1 --wrap "catvae-train.py --num-workers 10 --gpus 1 --eigvalues $SIM/eigvals.txt --eigvectors $SIM/eigvecs.txt --basis $basis --learning-rate $lr --batch-size $batch_size --train-biom $SIM/train.biom --test-biom $SIM/test.biom --val-biom $SIM/valid.biom --bias False --steps-per-batch 30 --epochs $epochs --output-dir $OUT" done # Stochastic Catvae for basis in $bases do OUT=catvae-stochastic-$basis sbatch -p gpu --gres=gpu:v100-32gb:1 --wrap "linear-vae-train.py --num-workers 10 --gpus 1 --eigvalues $SIM/eigvals.txt --eigvectors $SIM/eigvecs.txt --basis $basis --learning-rate $lr --batch-size $batch_size --use-analytic-elbo False --likelihood multinomial --train-biom $SIM/train.biom --test-biom $SIM/test.biom --val-biom $SIM/valid.biom --bias False --epochs $epochs --output-dir $OUT" done <file_sep>/scripts/linear-vae-train.py import os import argparse import numpy as np from catvae.trainer import MultVAE, BiomDataModule, add_data_specific_args from pytorch_lightning import Trainer from pytorch_lightning.callbacks.model_checkpoint import ModelCheckpoint from pytorch_lightning.profiler import AdvancedProfiler from pytorch_lightning import loggers as pl_loggers from biom import load_table from skbio import TreeNode import yaml def main(args): if args.load_from_checkpoint is not None: model = MultVAE.load_from_checkpoint(args.load_from_checkpoint) else: n_input = load_table(args.val_biom).shape[0] model = MultVAE(n_input, n_latent=args.n_latent, n_hidden=args.n_hidden, basis=args.basis, dropout=args.dropout, bias=args.bias, tss=args.tss, distribution=args.distribution, batch_norm=args.batch_norm, encoder_depth=args.encoder_depth, learning_rate=args.learning_rate, scheduler=args.scheduler, transform=args.transform, overdispersion=args.overdispersion, grassmannian=args.grassmannian) print(args) print(model) if args.eigvectors is not None and args.eigvalues is not None: eigvectors = np.loadtxt(args.eigvectors) eigvalues = np.loadtxt(args.eigvalues) model.set_eigs(eigvectors, eigvalues) if args.profile: profiler = AdvancedProfiler() else: profiler = None dm = BiomDataModule( args.train_biom, args.test_biom, args.val_biom, metadata=args.sample_metadata, batch_category=args.batch_category, batch_size=args.batch_size, num_workers=args.num_workers) ckpt_path = os.path.join( args.output_directory, "checkpoints") checkpoint_callback = ModelCheckpoint( dirpath=ckpt_path, period=1, monitor='val_loss', mode='min', verbose=True) os.mkdir(args.output_directory) tb_logger = pl_loggers.TensorBoardLogger(f'{args.output_directory}/logs/') # save hyper-parameters to yaml file with open(f'{args.output_directory}/hparams.yaml', 'w') as outfile: yaml.dump(model._hparams, outfile, default_flow_style=False) # save tree to file if specified if os.path.exists(args.basis): tree = TreeNode.read(args.basis) tree.write(f'{args.output_directory}/tree.nwk') trainer = Trainer( max_epochs=args.epochs, gpus=args.gpus, stochastic_weight_avg=False, auto_scale_batch_size='binsearch', check_val_every_n_epoch=10, gradient_clip_val=args.grad_clip, profiler=profiler, logger=tb_logger, callbacks=[checkpoint_callback]) trainer.fit(model, dm) trainer.save_checkpoint( args.output_directory + '/last_ckpt.pt') if __name__ == '__main__': parser = argparse.ArgumentParser(add_help=True) parser = MultVAE.add_model_specific_args(parser, add_help=False) parser = add_data_specific_args(parser, add_help=False) args = parser.parse_args() main(args) <file_sep>/catvae/distributions/mvn.py import math import torch from torch.distributions.distribution import Distribution from torch.distributions.multivariate_normal import _batch_mahalanobis from torch.distributions.multivariate_normal import _batch_mv from torch.distributions.utils import _standard_normal import numpy as np import functools torch.pi = torch.Tensor([torch.acos(torch.zeros(1)).item() * 2]) def _batch_mahalanobis_factor(L_inv, x): r""" Computes the squared Mahalanobis distance :math:`\mathbf{x}^\top\mathbf{M}^{-1}\mathbf{x}` for a factored :math:`\mathbf{M} = \mathbf{L}\mathbf{L}^\top`. """ xL = (x @ L_inv) xLxt = (xL * x).sum(-1) return xLxt def sparse_identity(d): # i = torch.arange(d) # idx = torch.stack((i, i)) # v = torch.ones(d) # Id = torch.sparse_coo_tensor(idx, v, requires_grad=False) Id = torch.eye(d) return Id class MultivariateNormalFactor(Distribution): def __init__(self, mu, U, diag, n, validate_args=False): """ Asymptotic approximation of the multinomial distribution. Parameters ---------- mu : torch.Tensor Mean of the distribution U : torch.Tensor Orthonormal factor matrix for decomposing covariance matrix. diag : torch.Tensor Diagonal matrix of eigenvalues for covariance decomposition n : torch.Tensor Number of multinomial observations Notes ----- Can incorporate the number of samples in the diagonal Important : this cannot handle batching """ if mu.dim() < 1: raise ValueError("`mu` must be at least one-dimensional.") d = U.shape[-1] if mu.shape[-1] != d - 1: raise ValueError(f"The last dimension of `mu` must be {d-1}") self.mu = mu self.U = U self.S = diag self.n = n batch_shape, event_shape = self.mu.shape[:-1], self.mu.shape[-1:] super(MultivariateNormalFactor, self).__init__( batch_shape, event_shape, validate_args=validate_args) @property def covariance_matrix(self): return (1 / self.n) * self.U @ torch.diag(self.S) @ self.U.t() @property def precision_matrix(self): return (self.n) * self.U @ torch.diag(1 / self.S) @ self.U.t() @property def mean(self): return self.mu @property def variance(self): raise NotImplementedError('`variance` is not implemented.') @functools.cached_property def cholesky(self): cov = self.covariance_matrix return torch.cholesky(cov) @property def log_det(self): d = self.U.shape[-1] return torch.sum(torch.log(self.S)) + d * np.log(1 / self.n) def rsample(self, sample_shape): """ Eigenvalue decomposition can also be used for sampling https://stats.stackexchange.com/a/179275/79569 """ L = self.cholesky shape = self._extended_shape(sample_shape) eps = _standard_normal(shape, dtype=self.mu.dtype, device=self.mu.device) return self.mu + _batch_mv(L, eps) def log_prob(self, value): if self._validate_args: self._validate_sample(value) diff = value - self.mu L = self.cholesky M = _batch_mahalanobis(L, diff) half_log_det = L.diagonal(dim1=-2, dim2=-1).log().sum(-1) p = - half_log_det - 0.5 * ( self._event_shape[0] * math.log(2 * math.pi) + M ) return p def entropy(self): raise NotImplementedError('`entropy` is not implemented.') class MultivariateNormalFactorSum(Distribution): def __init__(self, mu, U1, diag1, U2, diag2, n, validate_args=False): """ Multivariate normal distribution parameterized as the sum of two normal distributions whose covariances can be represented as an eigenvalue decomposition. Parameters ---------- mu1 : torch.Tensor Mean of the first distribution U1 : torch.Tensor Left orthonormal factor matrix for decomposing the first covariance matrix. diag1 : torch.Tensor ` Diagonal matrix of eigenvalues for the first covariance decomposition mu2 : torch.Tensor Mean of the second distribution U2 : torch.Tensor Left orthonormal factor matrix for decomposing the second covariance matrix. diag2 : torch.Tensor Diagonal matrix of eigenvalues for the second covariance decomposition n : torch.Tensor Number of multinomial observations. """ if mu.dim() < 1: raise ValueError("`mu` must be at least one-dimensional.") d = U1.shape[-1] if mu.shape[-1] != d - 1: raise ValueError(f"The last dimension of `mu` must be {d-1}") self.mu = mu self.U1 = U1 self.S1 = diag1 self.U2 = U2 self.S2 = diag2 self.n = n batch_shape, event_shape = self.mu.shape[:-1], self.mu.shape[-1:] super(MultivariateNormalFactorSum, self).__init__( batch_shape, event_shape, validate_args=validate_args) @property def covariance_matrix(self): if len(self.S1.shape) == 1: P = torch.diag(self.S1) invN = (1 / self.n) elif len(self.S1.shape) == 2: P = torch.stack([ torch.diag(self.S1[i, :].squeeze()) for i in range(self.S1.shape[0]) ], dim=0) invN = (1 / self.n).unsqueeze(1).unsqueeze(1) else: raise ValueError(f'Cannot handle dimensions {self.S1.shape}') sigmaU1 = invN * (self.U1 @ P @ self.U1.t()) sigmaU2 = self.U2 @ torch.diag(self.S2) @ self.U2.t() return sigmaU1 + sigmaU2 @property def precision_matrix(self): if len(self.S1.shape) == 1: invP = torch.diag(1 / self.S1) n = (1 / self.n) elif len(self.S1.shape) == 2: invP = torch.stack([ torch.diag(1 / self.S1[i, :].squeeze()) for i in range(self.S1.shape[0]) ], dim=0) n = (1 / self.n).unsqueeze(1).unsqueeze(1) else: raise ValueError(f'Cannot handle dimensions {self.S1.shape}') invS1 = n * self.U1 @ invP @ self.U1.t() W = self.U2 invD = torch.diag(1 / self.S2) # Woodbury identity C = torch.inverse(invD + W.t() @ invS1 @ W) invS = invS1 - invS1 @ W @ C @ W.t() @ invS1 return invS @property def log_det(self): if len(self.S1.shape) == 1: invP = torch.diag(1 / self.S1) n = (1 / self.n) elif len(self.S1.shape) == 2: invP = torch.stack([ torch.diag(1 / self.S1[i, :].squeeze()) for i in range(self.S1.shape[0]) ], dim=0) n = (1 / self.n).unsqueeze(1).unsqueeze(1) else: raise ValueError(f'Cannot handle dimensions {self.S1.shape}') # Matrix determinant lemma, similar to the Woodbury identity invS1 = n * self.U1 @ invP @ self.U1.t() W = self.U2 d = self.U1.shape[-1] invD = torch.diag(1 / self.S2) logdet_A = torch.sum(torch.log(self.S1)) + d * torch.log(1 / self.n) logdet_C = torch.log(torch.det(invD + W.t() @ invS1 @ W)) logdet_D = torch.sum(torch.log(self.S2)) return logdet_A + logdet_C + logdet_D @property def mean(self): return self.mu @functools.cached_property def cholesky(self): cov = self.covariance_matrix return torch.cholesky(cov) @property def variance(self): raise NotImplementedError('`variance` is not implemented.') def rsample(self, sample_shape): """ Eigenvalue decomposition can also be used for sampling https://stats.stackexchange.com/a/179275/79569 """ L = self.cholesky shape = self._extended_shape(sample_shape) eps = _standard_normal(shape, dtype=self.mu.dtype, device=self.mu.device) return self.mu + _batch_mv(L, eps) def log_prob(self, value): if self._validate_args: self._validate_sample(value) diff = value - self.mu L = self.cholesky M = _batch_mahalanobis(L, diff) half_log_det = L.diagonal(dim1=-2, dim2=-1).log().sum(-1) p = - half_log_det - 0.5 * ( self._event_shape[0] * math.log(2 * math.pi) + M ) return p def entropy(self): d = self.mu.shape[-1] half_logdet = self.log_det / 2 return half_logdet + (d / 2) * (torch.log(2 * torch.pi) + 1) class MultivariateNormalFactorIdentity(Distribution): def __init__(self, mu, sigma2, D, W, validate_args=False): """ Multivariate normal distribution with the form N(mu, sigma*I + W'DW)""" if mu.dim() < 1: raise ValueError("`mu` must be at least one-dimensional.") d = W.shape[0] self.mu = mu self.sigma2 = sigma2 self.D = D self.W = W self.d = d batch_shape, event_shape = self.mu.shape[:-1], self.mu.shape[-1:] super(MultivariateNormalFactorIdentity, self).__init__( batch_shape, event_shape, validate_args=validate_args) @property def covariance_matrix(self): wdw = self.W @ torch.diag(self.D) @ self.W.t() idx = torch.arange(self.d) wdw[idx, idx] += self.sigma2 return wdw @property def precision_matrix(self): # Woodbury identity # inv(A + WDWt) = invA - invA @ W inv(invD + Wt invA W) Wt invA W, D = self.W, self.D invD = torch.diag(1 / D) invAW = W / self.sigma2 C = invD + W.t() @ invAW invC = torch.inverse(C) cor = invAW @ invC @ invAW.t() idx = torch.arange(self.d) cor[idx, idx] -= (1 / self.sigma2) return -cor @property def log_det(self): # Matrix determinant lemma # det(A + WDWt) = det(invD + Wt invA W) det(D) det (A) W = self.W invD = torch.diag(1 / self.D) invAW = W / self.sigma2 logdet_A = torch.log(self.sigma2) * self.d logdet_C = torch.slogdet(invD + W.t() @ invAW)[1] logdet_D = torch.sum(torch.log(self.D)) res = logdet_A + logdet_C + logdet_D return res @property def mean(self): return self.mu @functools.cached_property def cholesky(self): cov = self.covariance_matrix return torch.cholesky(cov) @property def variance(self): raise NotImplementedError('`variance` is not implemented.') def rsample(self, sample_shape): L = self.cholesky shape = self._extended_shape(sample_shape) eps = _standard_normal(shape, dtype=self.mu.dtype, device=self.mu.device) return self.mu + _batch_mv(L, eps) def log_prob(self, value): if self._validate_args: self._validate_sample(value) diff = value - self.mu # L = self.W @ torch.diag(torch.sqrt(self.D)) M = _batch_mahalanobis_factor(self.precision_matrix, diff) p = - 0.5 * self.log_det - 0.5 * ( self._event_shape[0] * math.log(2 * math.pi) + M ) return p def entropy(self): pass <file_sep>/catvae/dataset/biom.py import biom import math import numpy as np import pandas as pd import torch from torch.utils.data import Dataset class BiomDataset(Dataset): """Loads a `.biom` file. Parameters ---------- filename : Path Filepath to biom table metadata_file : Path Filepath to sample metadata batch_category : str Column name forr batch indices """ def __init__( self, table: biom.Table, metadata: pd.DataFrame = None, batch_category: str = None): super(BiomDataset).__init__() self.table = table self.metadata = metadata self.batch_category = batch_category self.populate() def populate(self): if self.metadata is not None: # match the metadata with the table ids = set(self.table.ids()) & set(self.metadata.index) filter_f = lambda v, i, m: i in ids self.table = self.table.filter(filter_f, axis='sample') self.metadata = self.metadata.loc[self.table.ids()] if self.metadata.index.name is None: raise ValueError('`Index` must have a name either' '`sampleid`, `sample-id` or #SampleID') self.index_name = self.metadata.index.name self.metadata = self.metadata.reset_index() self.batch_indices = None if self.batch_category is not None and self.metadata is not None: batch_cats = np.unique(self.metadata[self.batch_category].values) self.batch_cats = pd.Series( np.arange(len(batch_cats)), index=batch_cats) self.batch_indices = np.array( list(map(lambda x: self.batch_cats.loc[x], self.metadata[self.batch_category].values))) def __len__(self) -> int: return len(self.table.ids()) def __getitem__(self, i): """ Returns all of the samples for a given subject Returns ------- counts : np.array OTU counts for specified samples. batch_indices : np.array Membership ids for batch samples. If not specified, return None. """ sample_idx = self.table.ids()[i] if self.batch_indices is not None: batch_indices = self.batch_indices[i] else: batch_indices = None counts = self.table.data(id=sample_idx, axis='sample') return counts, batch_indices def __iter__(self): worker_info = torch.utils.data.get_worker_info() start = 0 end = self.__len__() if worker_info is None: # single-process data loading for i in range(end): yield self.__getitem__(i) else: worker_id = worker_info.id w = float(worker_info.num_workers) t = (end - start) w = float(worker_info.num_workers) per_worker = int(math.ceil(t / w)) worker_id = worker_info.id iter_start = start + worker_id * per_worker iter_end = min(iter_start + per_worker, end) for i in range(iter_start, iter_end): yield self.__getitem__(i) def _sample2dict(feature_data, feature_ids, i, sample_ids=None): # This is taking code from here # https://github.com/qiime2/q2-sample-classifier/ # blob/master/q2_sample_classifier/utilities.py#L64 features = np.empty(1, dtype=dict) row = feature_data[i] features = {feature_ids[ix]: d for ix, d in zip(row.indices, row.data)} return features, i class Q2BiomDataset(BiomDataset): """ This is specific to q2 sample classifiers. """ def __init__(self, table: biom.Table): super(Q2BiomDataset).__init__() self.feature_ids = table.ids('observation') self.feature_data = table.matrix_data.T.tocsr() def __getitem__(self, i): return _sample2dict(self.feature_data, self.feature_ids, i) def collate_single_f(batch): counts_list = np.vstack([b[0] for b in batch]) counts = torch.from_numpy(counts_list).float() return counts def collate_batch_f(batch): counts_list = np.vstack([b[0] for b in batch]) batch_ids = np.vstack([b[1] for b in batch]) counts = torch.from_numpy(counts_list).float() batch_ids = torch.from_numpy(batch_ids).long() return counts, batch_ids.squeeze() def collate_q2_f(batch): features = [b[0] for b in batch] sample_idx = np.vstack([b[1] for b in batch]) return features, sample_idx.squeeze() <file_sep>/catvae/models/linear_vae.py import torch import torch.nn as nn from catvae.composition import closure from gneiss.cluster import random_linkage from gneiss.balances import sparse_balance_basis from torch.distributions import Multinomial, Normal from torch.distributions.kl import kl_divergence import numpy as np import geotorch LOG_2_PI = np.log(2.0 * np.pi) def get_basis(input_dim, basis=None): if basis is None: tree = random_linkage(input_dim) basis = sparse_balance_basis(tree)[0].copy() indices = np.vstack((basis.row, basis.col)) Psi = torch.sparse_coo_tensor( indices.copy(), basis.data.astype(np.float32).copy(), requires_grad=False).coalesce() return Psi class ArcsineEmbed(nn.Module): def __init__(self, input_dim, hidden_dim, dropout=0): super(ArcsineEmbed, self).__init__() self.embed = nn.Parameter( torch.zeros(input_dim, hidden_dim)) self.ffn = nn.Sequential( nn.Linear(hidden_dim, hidden_dim * 4, bias=True), nn.Softplus(), nn.Dropout(dropout), nn.Linear(hidden_dim * 4, 1, bias=True), ) def forward(self, x, Psi): a = torch.arcsin(torch.sqrt(closure(x))) # B x D x_ = a[:, :, None] * self.embed # B x D x H fx = self.ffn(x_).squeeze() fx = (Psi @ fx.T).T # B x D-1 return fx class CLREmbed(nn.Module): def __init__(self, input_dim, hidden_dim, dropout=0): super(CLREmbed, self).__init__() self.embed = nn.Parameter( torch.zeros(input_dim, hidden_dim)) self.ffn = nn.Sequential( nn.Linear(hidden_dim, hidden_dim * 4, bias=True), nn.Softplus(), nn.Dropout(dropout), nn.Linear(hidden_dim * 4, 1, bias=True), ) def forward(self, x, Psi): a = torch.arcsin(torch.sqrt(closure(x))) # B x D a = torch.log(closure(x + 1)) a = a - a.mean(axis=1).reshape(-1, 1) # center around mean x_ = a[:, :, None] * self.embed # B x D x H fx = self.ffn(x_).squeeze() fx = (Psi @ fx.T).T # B x D-1 return fx class Encoder(nn.Module): def __init__(self, input_dim: int, hidden_dim: int, latent_dim: int, bias: bool = False, dropout: float = 0, batch_norm: bool = True, depth: int = 1, init_scale: float = 0.001): super(Encoder, self).__init__() if depth > 1: first_encoder = nn.Linear( input_dim, hidden_dim, bias=bias) num_encoder_layers = depth layers = [] layers.append(first_encoder) layers.append(nn.Softplus()) layers.append(nn.Dropout(dropout)) for layer_i in range(num_encoder_layers - 2): layers.append( nn.Linear(hidden_dim, hidden_dim, bias=bias)) layers.append(nn.Softplus()) layers.append(nn.Dropout(dropout)) if batch_norm: layers.append(nn.BatchNorm1d(hidden_dim)) layers.append(nn.Linear(hidden_dim, latent_dim, bias=bias)) self.encoder = nn.Sequential(*layers) # initialize for encoder_layer in self.encoder: if isinstance(encoder_layer, nn.Linear): encoder_layer.weight.data.normal_(0.0, init_scale) elif depth == 2: layers = nn.Sequential(*[ nn.Linear(input_dim, hidden_dim, bias=bias), nn.Softplus(), nn.Linear(hidden_dim, latent_dim, bias=bias) ]) self.encoder = nn.Sequential(*layers) for encoder_layer in self.encoder: if isinstance(encoder_layer, nn.Linear): encoder_layer.weight.data.normal_(0.0, init_scale) elif depth == 1: self.encoder = nn.Linear( input_dim, latent_dim, bias=bias) self.encoder.weight.data.normal_(0.0, init_scale) else: raise ValueError(f'Depth of {depth} is not appropriate.') def forward(self, x): return self.encoder(x) class LinearVAE(nn.Module): def __init__(self, input_dim, hidden_dim, latent_dim=None, init_scale=0.001, encoder_depth=1, basis=None, bias=True, transform='pseudocount', distribution='multinomial', dropout=0, batch_norm=False, grassmannian=True): super(LinearVAE, self).__init__() if latent_dim is None: latent_dim = hidden_dim self.bias = bias self.hidden_dim = hidden_dim Psi = get_basis(input_dim, basis).coalesce() # note this line corresponds to the true input dim self.input_dim = Psi.shape[0] self.register_buffer('Psi', Psi) self.encoder = Encoder( self.input_dim, hidden_dim, latent_dim, bias=bias, depth=encoder_depth, init_scale=init_scale, dropout=dropout, batch_norm=batch_norm) self.decoder = nn.Linear( latent_dim, self.input_dim, bias=self.bias) if grassmannian: geotorch.grassmannian(self.decoder, 'weight') self.variational_logvars = nn.Parameter(torch.zeros(latent_dim)) self.transform = transform self.distribution = distribution if self.transform == 'arcsine': self.input_embed = ArcsineEmbed(self.input_dim + 1, hidden_dim, dropout) if self.transform == 'clr': self.input_embed = CLREmbed(self.input_dim + 1, hidden_dim, dropout) def gaussian_kl(self, z_mean, z_logvar): return 0.5 * (1 + z_logvar - z_mean * z_mean - torch.exp(z_logvar)) def gaussian_kl2(self, m1, s1, m2, s2): x = Normal(m1, torch.exp(0.5 * s1)) y = Normal(m2, torch.exp(0.5 * s2)) return - kl_divergence(x, y) def recon_model_loglik(self, x_in, x_out): logp = (self.Psi.t() @ x_out.t()).t() if self.distribution == 'multinomial': dist_loss = Multinomial( logits=logp, validate_args=False # weird ... ).log_prob(x_in).mean() elif self.distribution == 'gaussian': # MSE loss based out on DeepMicro # https://www.nature.com/articles/s41598-020-63159-5 dist_loss = Normal( loc=logp, scale=1, validate_args=False # weird ... ).log_prob(x_in).mean() else: raise ValueError( f'Distribution {self.distribution} is not supported.') return dist_loss def impute(self, x): if self.transform in {'arcsine', 'clr'}: hx = self.input_embed(x, self.Psi) elif self.transform == 'pseudocount': fx = torch.log(x + 1) # ILR transform for testing hx = (self.Psi @ fx.T).T # B x D-1 elif self.transform == 'none': hx = x else: raise ValueError(f'Unrecognzied transform {self.transform}') return hx def sample(self, x, size=None): # obtain mean of latent distribution z_mean = self.encode(x) if size is None: eps = torch.normal(torch.zeros_like(z_mean), 1.0) else: eps = torch.normal(torch.zeros(size), 1.0) z_sample = z_mean + eps * torch.exp(0.5 * self.variational_logvars) return z_sample def encode(self, x): hx = self.impute(x) z = self.encoder(hx) return z def forward(self, x): z_mean = self.encode(x) eps = torch.normal(torch.zeros_like(z_mean), 1.0) z_sample = z_mean + eps * torch.exp(0.5 * self.variational_logvars) x_out = self.decoder(z_sample) kl_div = self.gaussian_kl( z_mean, self.variational_logvars).mean(0).sum() recon_loss = self.recon_model_loglik(x, x_out).mean(0).sum() elbo = kl_div + recon_loss loss = - elbo return loss def get_reconstruction_loss(self, x): z_mean = self.encode(x) eps = torch.normal(torch.zeros_like(z_mean), 1.0) z_sample = z_mean + eps * torch.exp(0.5 * self.variational_logvars) x_out = self.decoder(z_sample) recon_loss = -self.recon_model_loglik(x, x_out) return recon_loss class LinearDLRVAE(LinearVAE): def __init__(self, input_dim, hidden_dim, latent_dim=None, init_scale=0.001, encoder_depth=1, basis=None, bias=True, transform='pseudocount', distribution='multinomial', dropout=0, batch_norm=False, grassmannian=True): super(LinearDLRVAE, self).__init__( input_dim, hidden_dim, latent_dim, init_scale=init_scale, basis=basis, encoder_depth=encoder_depth, bias=bias, transform=transform, dropout=dropout, batch_norm=batch_norm, grassmannian=grassmannian) self.log_sigma_sq = nn.Parameter(torch.ones(input_dim - 1)) def sample(self, x): z_mean = self.encode(x) eps = torch.normal(torch.zeros_like(z_mean), 1.0) z_sample = z_mean + eps * torch.exp(0.5 * self.variational_logvars) return z_sample def forward(self, x): z_mean = self.encode(x) eps = torch.normal(torch.zeros_like(z_mean), 1.0) z_sample = z_mean + eps * torch.exp(0.5 * self.variational_logvars) x_out = self.decoder(z_sample) delta = torch.normal(torch.zeros_like(x_out), 1.0) x_out += delta * torch.exp(0.5 * self.log_sigma_sq) kl_div = self.gaussian_kl( z_mean, self.variational_logvars).mean(0).sum() recon_loss = self.recon_model_loglik(x, x_out).mean(0).sum() elbo = kl_div + recon_loss loss = - elbo return loss def get_reconstruction_loss(self, x): z_sample = self.sample(x) x_out = self.decoder(z_sample) recon_loss = -self.recon_model_loglik(x, x_out) return recon_loss class LinearBatchVAE(LinearVAE): def __init__(self, input_dim, hidden_dim, latent_dim, batch_dim, batch_prior, init_scale=0.001, encoder_depth=1, basis=None, bias=True, transform='pseudocount', distribution='multinomial', batch_norm=False, dropout=0, grassmannian=True): """ Account for batch effects. Parameters ---------- input_dim : int Number of dimensions for input counts hidden_dim : int Number of hidden dimensions within encoder latent_dim : int Number of hidden dimensions within latent space batch_dim : int Number of batches (i.e. studies) to do batch correction batch_prior : np.array of float Normal variance priors for batch effects of shape D - 1. Note that these priors are assumed to be in ILR coordinates. transform : str Choice of input transform. Can choose from arcsine, pseudocount and rclr (TODO). """ super(LinearBatchVAE, self).__init__( input_dim, hidden_dim, latent_dim, init_scale=init_scale, basis=basis, encoder_depth=encoder_depth, bias=bias, transform=transform, dropout=dropout, batch_norm=batch_norm, grassmannian=grassmannian) self.batch_dim = batch_dim self.ilr_dim = input_dim - 1 batch_prior = batch_prior self.register_buffer('batch_prior', batch_prior) self.batch_logvars = nn.Parameter(torch.zeros(self.ilr_dim)) self.beta = nn.Embedding(batch_dim, self.ilr_dim) self.batch_embed = nn.Embedding(batch_dim, latent_dim) def encode(self, x, b): hx = self.impute(x) zb = self.batch_embed(b) z = self.encoder(hx) - zb return z def encode_marginalized(self, x, b): """ Marginalize over batch_effects given predictions This will compute the expected batch effect given the batch classification probabilities. Parameters ---------- x : torch.Tensor Counts of interest (B x D) b : torch.Tensor Batch effect prediction log probabilities (B x K) Notes ----- This assumes that the batch classifier is well-calibrated. """ # obtain expected batch effect beta_ = self.beta.weight m = nn.Softmax() batch_effects = b @ m(beta_) hx = self.impute(x) hx = hx - batch_effects z = self.encoder(hx) return z def sample(self, x, b, size=None): # obtain mean of latent distribution z_mean = self.encode(x, b) if size is None: eps = torch.normal(torch.zeros_like(z_mean), 1.0) else: eps = torch.normal(torch.zeros(size), 1.0) z_sample = z_mean + eps * torch.exp(0.5 * self.variational_logvars) return z_sample def forward(self, x, b): z_mean = self.encode(x, b) batch_effects = self.beta(b) eps = torch.normal(torch.zeros_like(z_mean), 1.0) z_sample = z_mean + eps * torch.exp(0.5 * self.variational_logvars) eps = torch.normal(torch.zeros_like(batch_effects), 1.0) b_sample = batch_effects + eps * torch.exp(0.5 * self.batch_logvars) x_out = self.decoder(z_sample) + b_sample kl_div_z = self.gaussian_kl( z_mean, self.variational_logvars).mean(0).sum() kl_div_b = self.gaussian_kl2( batch_effects, self.batch_logvars, torch.zeros_like(self.batch_prior), self.batch_prior ).mean(0).sum() recon_loss = self.recon_model_loglik(x, x_out).mean(0).sum() elbo = kl_div_z + kl_div_b + recon_loss loss = - elbo return loss, -recon_loss, -kl_div_z, -kl_div_b def get_reconstruction_loss(self, x, b): z_mean = self.encode(x, b) eps = torch.normal(torch.zeros_like(z_mean), 1.0) z_sample = z_mean + eps * torch.exp(0.5 * self.variational_logvars) batch_effects = self.beta(b) x_out = self.decoder(z_sample) x_out += batch_effects # Add batch effects back in recon_loss = -self.recon_model_loglik(x, x_out) return recon_loss <file_sep>/Makefile .DEFAULT_GOAL := help TEST_COMMAND = pytest RUN_COMMAND = sh help: @echo 'Use "make test" to run all the unit tests and docstring tests.' @echo 'Use "make pep8" to validate PEP8 compliance.' @echo 'Use "make html" to create html documentation with sphinx' @echo 'Use "make all" to run all the targets listed above.' test: $(TEST_COMMAND) catvae run: $(RUN_COMMAND) catvae/tests/test.sh pep8: pycodestyle catvae setup.py --ignore=E731,E722,W503 flake8 catvae setup.py scripts --ignore=E731,E722,W503 all: pep8 test run <file_sep>/scripts/ldvae.py import argparse import scvi from catvae.trainer import MultVAE, add_data_specific_args from biom import load_table import yaml import pandas as pd # This is derived from the scvi notebook # https://github.com/YosefLab/scvi-tutorials/blob/master/linear_decoder.ipynb # Note that this is not going to be supported in the future # so use at your own risk def main(args): print(args) output_dir = args.output_directory epochs = args.epochs lr = args.learning_rate # Need to hack in sample metadata metadata = pd.read_table(args.sample_metadata, dtype=str) index_name = metadata.columns[0] metadata = metadata.set_index(index_name) train_biom = load_table(args.train_biom) # test_biom = load_table(args.test_biom) valid_biom = load_table(args.val_biom) # looks like we can't specify splits # so we'll just combined train/validate tables # this could give scvi a slight advantage, but whatev t = train_biom.merge(valid_biom) D, _ = t.shape obs_md = {i: {'taxonomy': 'None'} for i in t.ids(axis='observation')} if args.batch_category is not None: batch_cats = metadata.loc[t.ids(), args.batch_category].values sample_md = {i: {'batch': v} for i, v in zip(t.ids(), batch_cats)} else: sample_md = {i: {'batch': 'None'} for i in t.ids()} t.add_metadata(sample_md, axis='sample') t.add_metadata(obs_md, axis='observation') # careful here, this requires at least biom 2.1.10 # https://github.com/biocore/biom-format/pull/845 adata = t.to_anndata() adata.layers["counts"] = adata.X.copy() # preserve counts if args.batch_category is not None: scvi.data.setup_anndata(adata, layer="counts", batch_key="batch") else: scvi.data.setup_anndata(adata, layer="counts") model = scvi.model.LinearSCVI( adata, dropout_rate=args.dropout, n_latent=args.n_latent, n_layers=args.encoder_depth, n_hidden=args.n_hidden) print(model) vargs = argparse.Namespace() hparams = vars(vargs) with open(f'{output_dir}/hparams.yaml', 'w') as outfile: yaml.dump(hparams, outfile, default_flow_style=False) model.train(max_epochs=epochs, plan_kwargs={'lr': lr}, check_val_every_n_epoch=50) path = f'{output_dir}/last_ckpt.pt' model.save(path, save_anndata=True) # this model can be loaded via # model = scvi.model.LinearSCVI.load(path) if __name__ == '__main__': parser = argparse.ArgumentParser(add_help=True) parser = MultVAE.add_model_specific_args(parser, add_help=False) parser = add_data_specific_args(parser, add_help=False) args = parser.parse_args() main(args) <file_sep>/README.md # catvae Categorical Variational Autoencoders # What are Categorical Variational Autoencoders? Variational Autoencoders (VAE) are one of the state-of-the-art methods applying neural networks to perform Bayesian inference to estimate complex high dimensional distributions, with recent techniques showing that Linear VAEs are mathematically equivalent to Principal Components Analysis. Categorical Variational Autoencoders or Multinomial Variational Autoencoders are extentions of VAEs applied to count data. These methods can estimate the moments of the Multinomial Logistic Normal distribution with thousands of dimensions and thousands of observations in the matter of hours. # Getting started ## Installation The dependencies to this package can be installed as follows ``` conda install pandas scipy biom-format gneiss pytorch pytorch-lightning -c pytorch -c conda-forge -c bioconda pip install geotorch==0.1.0 ``` The development branch of catvae can be installed via ``` pip install git+https://github.com/flatironinstitute/catvae.git ``` ## Downloading pretrained models [Pretrained Mouse VAE 128 latent dimensions](https://users.flatironinstitute.org/jmorton/public_www/catvae_models/catvae-mouse-z128-l5-deblur.tar.gz) ``` wget https://users.flatironinstitute.org/jmorton/public_www/catvae-mouse-z128-l5-deblur.tar.gz tar -zxvf catvae-mouse-z128-l5-deblur.tar.gz ``` [Pretrained Batch corrected Mouse VAE 128 latent dimensions](https://users.flatironinstitute.org/jmorton/public_www/catvae_models/catvae-mouse-z128-l5-deblur-batch.tar.gz) ``` wget https://users.flatironinstitute.org/jmorton/public_www/catvae-mouse-z128-l5-deblur-batch.tar.gz tar -zxvf catvae-mouse-z128-l5-deblur-batch.tar.gz ``` [Pretrained Human VAE 128 latent dimensions](https://users.flatironinstitute.org/jmorton/public_www/catvae_models/catvae-human-z128-l5-deblur.tar.gz) ``` wget https://users.flatironinstitute.org/jmorton/public_www/catvae-human-z128-l5-deblur.tar.gz tar -zxvf catvae-human-z128-l5-deblur-batch.tar.gz ``` [Pretrained Batch corrected Human VAE 128 latent dimensions](https://users.flatironinstitute.org/jmorton/public_www/catvae_models/catvae-human-z128-l5-deblur-batch.tar.gz) ``` wget https://users.flatironinstitute.org/jmorton/public_www/catvae-human-z128-l5-deblur-batch.tar.gz tar -zxvf catvae-human-z128-l5-deblur-batch.tar.gz ``` ## Pre processing your data All of the pretrained models were trained on 100bp 16S V4 deblurred data from [Qiita](https://qiita.ucsd.edu/). To use these models on your data, either upload your data to Qiita, or process your data using deblur. See the [qiime2 tutorial](https://docs.qiime2.org/2021.4/tutorials/moving-pictures/#option-2-deblur) for an example of how to deblur your amplicon data. ## Loading VAE models When processing your own data, it is important to note that you can only perform inference on the microbes that have been observed by the VAE. As a result, it is critical that your data is completely aligned with the VAE. Loading the VAE model and aligning your data against the VAE can be done as follows ```python import torch import biom from skbio from gneiss.util import match_tips from catvae.trainer import MultVAE # Load model files vae_model_path = 'catvae-mouse-z128-l5-deblur' ckpt_path = os.path.join(vae_model_path, 'last_ckpt.pt') params = os.path.join(vae_model_path, 'hparams.yaml') nwk_path = os.path.join(vae_model_path, 'tree.nwk') tree = skbio.TreeNode(nwk_path) with open(params, 'r') as stream: params = yaml.safe_load(stream) params['basis'] = nwk_path vae_model = MultVAE.load_from_checkpoint(ckpt_path, **params) # Load your dataset X_train = biom.load_table('<your biom table>') # Align your data against the VAE X_train, tree = match_tips(X_train, tree) ``` If you want to obtain a reduced dimension representation of your data, that can be done as follows ```python # Convert pandas dataframe to numpy array X_train = X_train.to_dataframe().to_dense().values # Obtain dimensionality reduced data X_embed = vae_model.to_latent( torch.Tensor(X_train).float()).detach().cpu().numpy() ``` You can also sample from these embeddings. Below is an example of how you would do that. ```python x = X_train[0, :] vae_model.sample(x) ``` If you want to obtain a CLR representation of the VAE decoder loadings, it can be done as follows ```python import pandas as pd from gneiss.balances import sparse_balance_basis Psi, int_nodes = sparse_balance_basis(tree) # ILR representation of the VAE decoder loadings W = vae_model.vae.decoder.weight.detach().numpy() # CLR representation of the VAE decoder loadings names = [n.name for n in tree.tips()] cW = pd.DataFrame(Psi.T @ W, index=names) ``` ## Loading Batch corrected VAE models The process is almost identical ```python import torch import biom from skbio from gneiss.util import match_tips from catvae.trainer import MultBatchVAE # Load model files vae_model_path = 'catvae-mouse-z128-l5-deblur-batch' ckpt_path = os.path.join(vae_model_path, 'last_ckpt.pt') params = os.path.join(vae_model_path, 'hparams.yaml') nwk_path = os.path.join(vae_model_path, 'tree.nwk') tree = skbio.TreeNode(nwk_path) with open(params, 'r') as stream: params = yaml.safe_load(stream) params['basis'] = nwk_path vae_model = MultBatchVAE.load_from_checkpoint(ckpt_path, **params) # Load your dataset X_train = biom.load_table('<your biom table>') # Align your data against the VAE X_train, tree = match_tips(X_train, tree) ``` Extracting latent representations and sampling is slightly different since the batch information needs to be specified. All of the batch names are under the `batch_categories.txt` file, but the model only takes numerical ids as shown in the first column. ```python batch_num = <your specified batch> X_embed = vae_model.to_latent( torch.Tensor(X_train).float(), batch_num).detach().cpu().numpy() x = X_train[0, :] vae_model.sample(x, batch_num) ``` ## Training the VAE models Please refer to the Jupyter notebooks under the `ipynb` folder. <file_sep>/catvae/models/linear_cat_vae.py import torch import torch.nn as nn from gneiss.cluster import random_linkage from gneiss.balances import sparse_balance_basis from scipy.sparse import coo_matrix import numpy as np from torch.distributions import Multinomial, Normal from catvae.composition import ilr from catvae.distributions.mvn import MultivariateNormalFactorIdentity from typing import Callable import warnings LOG_2_PI = np.log(2.0 * np.pi) class LinearCatVAE(nn.Module): def __init__(self, input_dim: int, hidden_dim: int, init_scale: float = 0.001, basis: coo_matrix = None, encoder_depth: int = 1, imputer: Callable[[torch.Tensor], torch.Tensor] = None, batch_size: int = 10, bias: bool = True): super(LinearCatVAE, self).__init__() warnings.warn('LinearCatVAE is going to be deprecated in a ' 'future version of this package', DeprecationWarning) self.initialize(input_dim, hidden_dim, init_scale, basis, encoder_depth, imputer, batch_size, bias) def initialize(self, input_dim: int, hidden_dim: int, init_scale: float = 0.001, basis: coo_matrix = None, encoder_depth: int = 1, imputer: Callable[[torch.Tensor], torch.Tensor] = None, batch_size: int = 10, bias: bool = True): self.hidden_dim = hidden_dim self.bias = bias # Psi must be dimension D - 1 x D if basis is None: tree = random_linkage(input_dim) basis = sparse_balance_basis(tree)[0].copy() indices = np.vstack((basis.row, basis.col)) Psi = torch.sparse_coo_tensor( indices.copy(), basis.data.astype(np.float32).copy(), requires_grad=False) # Psi.requires_grad = False self.input_dim = Psi.shape[0] if imputer is None: self.imputer = lambda x: x + 1 else: self.imputer = imputer if encoder_depth > 1: self.first_encoder = nn.Linear( self.input_dim, hidden_dim, bias=self.bias) num_encoder_layers = encoder_depth layers = [] layers.append(self.first_encoder) for layer_i in range(num_encoder_layers - 1): layers.append(nn.Softplus()) layers.append( nn.Linear(hidden_dim, hidden_dim, bias=self.bias)) self.encoder = nn.Sequential(*layers) # initialize for encoder_layer in self.encoder: if isinstance(encoder_layer, nn.Linear): encoder_layer.weight.data.normal_(0.0, init_scale) else: self.encoder = nn.Linear(self.input_dim, hidden_dim, bias=self.bias) self.encoder.weight.data.normal_(0.0, init_scale) self.decoder = nn.Linear(hidden_dim, self.input_dim, bias=False) self.variational_logvars = nn.Parameter(torch.zeros(hidden_dim)) self.log_sigma_sq = nn.Parameter(torch.tensor(0.01)) self.eta = nn.Parameter(torch.zeros(batch_size, self.input_dim)) self.eta.data.normal_(0.0, init_scale) zI = torch.ones(self.hidden_dim).to(self.eta.device) zm = torch.zeros(self.hidden_dim).to(self.eta.device) self.register_buffer('Psi', Psi) self.register_buffer('zI', zI) self.register_buffer('zm', zm) def encode(self, x): hx = ilr(self.imputer(x), self.Psi) z = self.encoder(hx) return z def forward(self, x): hx = ilr(self.imputer(x), self.Psi) z_mean = self.encoder(hx) mu = self.decoder(z_mean) W = self.decoder.weight # penalties D = torch.exp(self.variational_logvars) var = torch.exp(self.log_sigma_sq) qdist = MultivariateNormalFactorIdentity(mu, var, D, W) logp = self.Psi.t() @ self.eta.t() prior_loss = Normal(self.zm, self.zI).log_prob(z_mean).mean() logit_loss = qdist.log_prob(self.eta).mean() mult_loss = Multinomial(logits=logp.t()).log_prob(x).mean() loglike = mult_loss + logit_loss + prior_loss return -loglike def reset(self, x): hx = ilr(self.imputer(x), self.Psi) self.eta.data = hx.data def get_reconstruction_loss(self, x): hx = ilr(self.imputer(x), self.Psi) z_mean = self.encoder(hx) eta = self.decoder(z_mean) logp = self.Psi.t() @ eta.t() mult_loss = Multinomial(logits=logp.t()).log_prob(x).mean() return - mult_loss class LinearBatchCatVAE(LinearCatVAE): def __init__(self, input_dim: int, hidden_dim: int, init_scale: float = 0.001, basis: coo_matrix = None, encoder_depth: int = 1, imputer: Callable[[torch.Tensor], torch.Tensor] = None, batch_size: int = 10, bias: bool = True): super(LinearBatchCatVAE, self).__init__( input_dim, hidden_dim, init_scale, basis, encoder_depth, imputer, batch_size, bias ) def encode(self, x): hx = ilr(self.imputer(x), self.Psi) z = self.encoder(hx) return z def forward(self, x, B): hx = ilr(self.imputer(x), self.Psi) batch_effects = (self.Psi @ B.t()).t() hx -= batch_effects # Subtract out batch effects z_mean = self.encoder(hx) mu = self.decoder(z_mean) mu += batch_effects # Add batch effects back in W = self.decoder.weight # penalties D = torch.exp(self.variational_logvars) var = torch.exp(self.log_sigma_sq) qdist = MultivariateNormalFactorIdentity(mu, var, D, W) logp = self.Psi.t() @ self.eta.t() prior_loss = Normal(self.zm, self.zI).log_prob(z_mean).mean() logit_loss = qdist.log_prob(self.eta).mean() mult_loss = Multinomial(logits=logp.t()).log_prob(x).mean() loglike = mult_loss + logit_loss + prior_loss return -loglike def get_reconstruction_loss(self, x, B): hx = ilr(self.imputer(x), self.Psi) batch_effects = (self.Psi @ B.t()).t() hx -= batch_effects # Subtract out batch effects z_mean = self.encoder(hx) eta = self.decoder(z_mean) eta += batch_effects # Add batch effects back in logp = self.Psi.t() @ eta.t() mult_loss = Multinomial(logits=logp.t()).log_prob(x).mean() return - mult_loss <file_sep>/ci/q2_requirements.txt pyyaml decorator tzlocal dill python-dateutil bibtexparser networkx ijson jinja2 scikit-learn=0.23.1 https://github.com/qiime2/q2templates.git https://github.com/qiime2/qiime2.git https://github.com/qiime2/q2-types.git https://github.com/qiime2/q2-sample-classifier.git https://github.com/qiime2/q2-feature-table.git <file_sep>/catvae/trainer.py import datetime import argparse import torch from torch.utils.data import DataLoader from torch.utils.tensorboard import SummaryWriter from torch.optim.lr_scheduler import ( CosineAnnealingWarmRestarts, StepLR, CosineAnnealingLR) from catvae.dataset.biom import BiomDataset, collate_single_f, collate_batch_f # from catvae.models import LinearVAE, from catvae.models import LinearBatchVAE from catvae.models import LinearVAE, LinearDLRVAE from catvae.composition import (alr_basis, ilr_basis, identity_basis, closure) from catvae.metrics import ( metric_subspace, metric_pairwise, metric_procrustes, metric_alignment, # metric_orthogonality ) import pytorch_lightning as pl from biom import load_table import pandas as pd from scipy.sparse import coo_matrix import numpy as np import os class BiomDataModule(pl.LightningDataModule): def __init__(self, train_biom, test_biom, valid_biom, metadata=None, batch_category=None, batch_size=10, num_workers=1): super().__init__() self.train_biom = train_biom self.test_biom = test_biom self.val_biom = valid_biom self.batch_size = batch_size self.num_workers = num_workers if metadata is not None: self.metadata = pd.read_table( metadata, dtype=str) index_name = self.metadata.columns[0] self.metadata = self.metadata.set_index(index_name) else: self.metadata = None self.batch_category = batch_category if self.batch_category is None: self.collate_f = collate_single_f else: self.collate_f = collate_batch_f # collect class mappings if they exist if batch_category is not None: train_dataset = BiomDataset( load_table(self.train_biom), metadata=self.metadata, batch_category=self.batch_category) self.batch_categories = train_dataset.batch_cats def train_dataloader(self): train_dataset = BiomDataset( load_table(self.train_biom), metadata=self.metadata, batch_category=self.batch_category) train_dataloader = DataLoader( train_dataset, batch_size=self.batch_size, collate_fn=self.collate_f, shuffle=True, num_workers=self.num_workers, drop_last=True, pin_memory=True) return train_dataloader def val_dataloader(self): val_dataset = BiomDataset( load_table(self.val_biom), metadata=self.metadata, batch_category=self.batch_category) batch_size = min(len(val_dataset) - 1, self.batch_size) val_dataloader = DataLoader( val_dataset, batch_size=batch_size, collate_fn=self.collate_f, shuffle=False, num_workers=self.num_workers, drop_last=True, pin_memory=True) return val_dataloader def test_dataloader(self): test_dataset = BiomDataset( load_table(self.test_biom), metadata=self.metadata, batch_category=self.batch_category) test_dataloader = DataLoader( test_dataset, batch_size=self.batch_size, collate_fn=self.collate_f, shuffle=False, num_workers=self.num_workers, drop_last=True, pin_memory=True) return test_dataloader class MultVAE(pl.LightningModule): def __init__(self, n_input, n_latent=32, n_hidden=64, basis=None, dropout=0, bias=True, tss=False, batch_norm=False, encoder_depth=1, learning_rate=0.001, scheduler='cosine', transform='pseudocount', distribution='multinomial', overdispersion=True, grassmannian=True): super().__init__() # a hack to avoid the save_hyperparameters anti-pattern # https://github.com/PyTorchLightning/pytorch-lightning/issues/7443 self._hparams = { 'n_input': n_input, 'n_latent': n_latent, 'n_hidden': n_hidden, 'basis': basis, 'dropout': dropout, 'bias': bias, 'tss': tss, 'batch_norm': batch_norm, 'encoder_depth': encoder_depth, 'learning_rate': learning_rate, 'scheduler': scheduler, 'transform': transform, 'distribution': distribution, 'overdispersion': overdispersion, 'grassmannian': grassmannian, } basis = self.set_basis(n_input, basis) if overdispersion: self.vae = LinearDLRVAE( n_input, basis=basis, hidden_dim=n_hidden, latent_dim=n_latent, bias=bias, encoder_depth=encoder_depth, batch_norm=batch_norm, dropout=dropout, distribution=distribution, transform=transform, grassmannian=grassmannian) else: self.vae = LinearVAE( n_input, basis=basis, hidden_dim=n_hidden, latent_dim=n_latent, bias=bias, encoder_depth=encoder_depth, batch_norm=batch_norm, dropout=dropout, distribution=distribution, transform=transform, grassmannian=grassmannian) self.gt_eigvectors = None self.gt_eigs = None def set_basis(self, n_input, basis=None): # a sneak peek into file types to initialize model has_basis = basis is not None if (has_basis and os.path.exists(basis)): basis = ilr_basis(basis) assert basis.shape[1] == n_input, ( f'Basis shape {basis.shape} does ' f'not match tree dimension {n_input}. ' 'Also make sure if your tree if aligned correctly ' 'with `gneiss.util.match_tips`') elif basis == 'alr': basis = coo_matrix(alr_basis(n_input)) elif basis == 'identity': basis = coo_matrix(identity_basis(n_input)) else: basis = None return basis def set_eigs(self, gt_eigvectors, gt_eigs): self.gt_eigvectors = gt_eigvectors self.gt_eigs = gt_eigs def forward(self, X): return self.vae(X) def to_latent(self, X): return self.vae.encode(X) def initialize_logging(self, root_dir='./', logging_path=None): if logging_path is None: basename = "logdir" suffix = datetime.datetime.now().strftime("%y%m%d_%H%M%S") logging_path = "_".join([basename, suffix]) full_path = root_dir + logging_path writer = SummaryWriter(full_path) return writer def training_step(self, batch, batch_idx): self.vae.train() counts = batch.to(self.device) if self.hparams['tss']: # only for benchmarking counts = closure(counts) loss = self.vae(counts) assert torch.isnan(loss).item() is False if len(self.trainer.lr_schedulers) >= 1: lr = self.trainer.lr_schedulers[0]['scheduler'].get_last_lr()[0] current_lr = lr else: current_lr = self.hparams['learning_rate'] tensorboard_logs = { 'train_loss': loss, 'elbo': -loss, 'lr': current_lr } # log the learning rate return {'loss': loss, 'log': tensorboard_logs} def validation_step(self, batch, batch_idx): with torch.no_grad(): counts = batch if self.hparams['tss']: # only for benchmarking counts = closure(counts) loss = self.vae(counts) assert torch.isnan(loss).item() is False # Record the actual loss. rec_err = self.vae.get_reconstruction_loss(batch) tensorboard_logs = {'val_loss': loss, 'val_rec_err': rec_err} # log the learning rate return {'val_loss': loss, 'log': tensorboard_logs} def test_step(self, batch, batch_idx): pass def validation_epoch_end(self, outputs): loss_f = lambda x: x['log']['val_rec_err'] losses = list(map(loss_f, outputs)) rec_err = sum(losses) / len(losses) self.logger.experiment.add_scalar('val_rec_err', rec_err, self.global_step) loss_f = lambda x: x['log']['val_loss'] losses = list(map(loss_f, outputs)) loss = sum(losses) / len(losses) self.logger.experiment.add_scalar('val_loss', loss, self.global_step) self.log('val_loss', loss) # Commenting out, since it is too slow... # ortho, eig_err = metric_orthogonality(self.vae) # self.logger.experiment.add_scalar('orthogonality', # ortho, self.global_step) # tensorboard_logs = dict( # [('val_loss', loss), # ('orthogonality', ortho), # ('eigenvalue-error', eig_err)] # ) tensorboard_logs = {'val_loss': loss, 'val_rec_error': rec_err} if (self.gt_eigvectors is not None) and (self.gt_eigs is not None): ms = metric_subspace(self.vae, self.gt_eigvectors, self.gt_eigs) ma = metric_alignment(self.vae, self.gt_eigvectors) mp = metric_procrustes(self.vae, self.gt_eigvectors) mr = metric_pairwise(self.vae, self.gt_eigvectors, self.gt_eigs) tlog = {'subspace_distance': ms, 'alignment': ma, 'procrustes': mp} self.logger.experiment.add_scalar( 'procrustes', mp, self.global_step) self.logger.experiment.add_scalar( 'pairwise_r', mr, self.global_step) self.logger.experiment.add_scalar( 'subspace_distance', ms, self.global_step) self.logger.experiment.add_scalar( 'alignment', ma, self.global_step) tensorboard_logs = {**tensorboard_logs, **tlog} return {'val_loss': loss, 'log': tensorboard_logs} def test_epoch_end(self, outputs): pass def configure_optimizers(self): optimizer = torch.optim.AdamW( self.vae.parameters(), lr=self.hparams['learning_rate'], weight_decay=0) if self.hparams['scheduler'] == 'cosine_warm': scheduler = CosineAnnealingWarmRestarts( optimizer, T_0=2, T_mult=2) elif self.hparams['scheduler'] == 'cosine': scheduler = CosineAnnealingLR( optimizer, T_max=10) elif self.hparams['scheduler'] == 'steplr': scheduler = StepLR(optimizer, step_size=10, gamma=0.5) elif self.hparams['scheduler'] == 'none': return [optimizer] else: s = self.scheduler raise ValueError(f'{s} is not implemented.') return [optimizer], [scheduler] @staticmethod def add_model_specific_args(parent_parser, add_help=True): parser = argparse.ArgumentParser(parents=[parent_parser], add_help=add_help) parser.add_argument( '--basis', help=('Basis. Options include `alr`, `identity` or a file. ' 'If a file is specified, it is assumed to be in ' 'Newick file to specify basis from bifurcating tree. ' 'If not specified, a random basis will be defined.'), required=False, type=str, default=None) parser.add_argument( '--n-latent', help='Latent embedding dimension.', required=False, type=int, default=10) parser.add_argument( '--n-hidden', help='Encoder dimension.', required=False, type=int, default=64) parser.add_argument( '--dropout', help='Dropout probability', required=False, type=float, default=0) parser.add_argument('--bias', dest='bias', action='store_true') parser.add_argument('--no-bias', dest='bias', action='store_false') # https://stackoverflow.com/a/15008806/1167475 parser.set_defaults(bias=True) parser.add_argument('--tss', dest='tss', action='store_true', help=('Total sum scaling to convert counts ' 'to proportions. This option is highly ' 'recommended against and will not be ' 'supported in the future.')) parser.set_defaults(tss=False) parser.add_argument('--batch-norm', dest='batch_norm', action='store_true') parser.set_defaults(batch_norm=False) parser.add_argument( '--encoder-depth', help='Number of encoding layers.', required=False, type=int, default=1) parser.add_argument( '--learning-rate', help='Learning rate', required=False, type=float, default=1e-3) parser.add_argument( '--transform', help=('Specifies transform for preprocessing ' '(arcsine, pseudocount, clr)'), required=False, type=str, default='pseudocount') parser.add_argument( '--no-overdispersion', help=('Specifies if overdispersion estimates are disabled. '), required=False, dest='overdispersion', action='store_false') parser.set_defaults(overdispersion=True) parser.add_argument( '--no-grassmannian', help=('Specifies if grassmanian manifold optimization ' 'is disabled. Turning this off will remove unit norm ' 'constraint on decoder weights. '), required=False, dest='grassmanian', action='store_false') parser.set_defaults(grassmannian=True) parser.add_argument( '--distribution', help=('Specifies decoder distribution, either ' '`multinomial` or `gaussian`.'), required=False, type=str, default='multinomial') parser.add_argument( '--scheduler', help=('Learning rate scheduler ' '(choices include `cosine` and `steplr`'), default='cosine', required=False, type=str) return parser # Batch correction methods class MultBatchVAE(MultVAE): def __init__(self, n_input, batch_prior, n_batches, n_latent=32, n_hidden=64, basis=None, dropout=0, bias=True, batch_norm=False, encoder_depth=1, learning_rate=0.001, vae_lr=0.001, scheduler='cosine', distribution='multinomial', transform='pseudocount', grassmannian=True): super().__init__(n_input, n_latent, n_hidden, basis=basis, dropout=dropout, bias=bias, batch_norm=batch_norm, encoder_depth=encoder_depth, learning_rate=learning_rate, scheduler=scheduler, transform=transform) self._hparams = { 'n_input': n_input, 'n_latent': n_latent, 'n_hidden': n_hidden, 'basis': basis, 'dropout': dropout, 'bias': bias, 'batch_norm': batch_norm, 'encoder_depth': encoder_depth, 'n_batches': n_batches, 'batch_prior': batch_prior, 'learning_rate': learning_rate, 'vae_lr': vae_lr, 'scheduler': scheduler, 'distribution': distribution, 'transform': transform, 'grassmannian': grassmannian } self.gt_eigvectors = None self.gt_eigs = None batch_prior = pd.read_table(batch_prior, dtype=str) batch_prior = batch_prior.set_index(batch_prior.columns[0]) batch_prior = batch_prior.values.astype(np.float64) batch_prior = batch_prior.reshape(1, -1).squeeze() batch_prior = torch.Tensor(batch_prior).float() basis = self.set_basis(n_input, basis) self.vae = LinearBatchVAE( n_input, hidden_dim=n_hidden, latent_dim=n_latent, batch_dim=n_batches, batch_norm=batch_norm, batch_prior=batch_prior, basis=basis, encoder_depth=encoder_depth, bias=bias, distribution=distribution, transform=transform, grassmannian=grassmannian) self.gt_eigvectors = None self.gt_eigs = None def initialize_batch(self, beta): # apparently this is not recommended, but whatev self.vae.beta.weight.data = beta.data self.vae.beta.requires_grad = False self.vae.beta.weight.requires_grad = False def initialize_decoder(self, W): # can't initialize easily W due to geotorch # https://github.com/Lezcano/geotorch/issues/14 self.vae.decoder.weight = W self.vae.decoder.weight.requires_grad = False def to_latent(self, X, b): """ Casts to latent space using predicted batch probabilities. Parameters ---------- X : torch.Tensor Counts of interest (N x D) b : torch.Tensor Batch membership (N) """ return self.vae.encode(X, b) def to_latent_marginalized(self, X, b): """ Casts to latent space using predicted batch probabilities. Parameters ---------- X : torch.Tensor Counts of interest (N x D) b : torch.Tensor Class prediction probabilities for batch prediction (N x k) """ return self.vae.encode_marginalized(X, b) def training_step(self, batch, batch_idx, optimizer_idx): if len(self.trainer.lr_schedulers) >= 1: lr = self.trainer.lr_schedulers[0]['scheduler'].get_last_lr()[0] current_lr = lr else: current_lr = self.hparams['learning_rate'] counts, batch_ids = batch counts = counts.to(self.device) batch_ids = batch_ids.to(self.device) self.vae.train() losses = self.vae(counts, batch_ids) loss, recon_loss, kl_div_z, kl_div_b = losses assert torch.isnan(loss).item() is False tensorboard_logs = { 'lr': current_lr, 'train_loss': loss } # log the learning rate return {'loss': loss, 'log': tensorboard_logs} def configure_optimizers(self): encode_params = self.vae.encoder.parameters() decode_params = self.vae.decoder.parameters() opt_g = torch.optim.AdamW( list(encode_params) + list(decode_params), lr=self.hparams['vae_lr'], weight_decay=0) opt_b = torch.optim.AdamW( list(self.vae.beta.parameters()) + [self.vae.batch_logvars], lr=self.hparams['learning_rate'], weight_decay=0.001) if self.hparams['scheduler'] == 'cosine_warm': scheduler = CosineAnnealingWarmRestarts( opt_g, T_0=2, T_mult=2) elif self.hparams['scheduler'] == 'cosine': scheduler = CosineAnnealingLR( opt_g, T_max=10) elif self.hparams['scheduler'] == 'none': return [opt_g, opt_b] else: raise ValueError( f'Scheduler {self.scheduler} not defined.') scheduler_b = CosineAnnealingLR( opt_b, T_max=10) return [opt_g, opt_b], [scheduler, scheduler_b] def validation_step(self, batch, batch_idx): with torch.no_grad(): counts, batch_ids = batch counts = counts.to(self.device) batch_ids = batch_ids.to(self.device) losses = self.vae(counts, batch_ids) loss, rec_err, kl_div_z, kl_div_b = losses assert torch.isnan(loss).item() is False # Record the actual loss. tensorboard_logs = {'val_loss': loss, 'val/recon_loss': rec_err, 'val/kl_div_z': kl_div_z, 'val/kl_div_b': kl_div_b, 'val_rec_err': rec_err} # log the learning rate return {'val_loss': loss, 'log': tensorboard_logs} def validation_epoch_end(self, outputs): metrics = ['val_loss', 'val/recon_loss', 'val/kl_div_z', 'val/kl_div_b', 'val_rec_err'] tensorboard_logs = {} for m in metrics: loss_f = lambda x: x['log'][m] losses = list(map(loss_f, outputs)) rec_err = sum(losses) / len(losses) self.logger.experiment.add_scalar( m, rec_err, self.global_step) self.log(m, rec_err) tensorboard_logs[m] = rec_err if (self.gt_eigvectors is not None) and (self.gt_eigs is not None): ms = metric_subspace(self.vae, self.gt_eigvectors, self.gt_eigs) ma = metric_alignment(self.vae, self.gt_eigvectors) mp = metric_procrustes(self.vae, self.gt_eigvectors) mr = metric_pairwise(self.vae, self.gt_eigvectors, self.gt_eigs) tlog = {'subspace_distance': ms, 'alignment': ma, 'procrustes': mp} self.logger.experiment.add_scalar( 'procrustes', mp, self.global_step) self.logger.experiment.add_scalar( 'pairwise_r', mr, self.global_step) self.logger.experiment.add_scalar( 'subspace_distance', ms, self.global_step) self.logger.experiment.add_scalar( 'alignment', ma, self.global_step) tensorboard_logs = {**tensorboard_logs, **tlog} return {'val_loss': rec_err, 'log': tensorboard_logs} @staticmethod def add_model_specific_args(parent_parser, add_help=True): parser = MultVAE.add_model_specific_args( parent_parser, add_help=add_help) parser.add_argument( '--batch-prior', help=('Pre-learned batch effect priors' '(must have same number of dimensions as `train-biom`)'), required=True, type=str, default=None) parser.add_argument( '--load-vae-weights', help=('Pre-trained linear VAE weights.'), required=False, type=str, default=None) parser.add_argument( '--vae-lr', help=('Learning rate of VAE weights'), required=False, type=float, default=1e-3) return parser def add_data_specific_args(parent_parser, add_help=True): parser = argparse.ArgumentParser(parents=[parent_parser], add_help=add_help) # Arguments specific for dataloaders parser.add_argument( '--train-biom', help='Training biom file', required=True) parser.add_argument( '--test-biom', help='Testing biom file', required=True) parser.add_argument( '--val-biom', help='Validation biom file', required=True) parser.add_argument( '--sample-metadata', help='Sample metadata file', required=False) parser.add_argument( '--batch-category', help='Sample metadata column for batch effects.', required=False, type=str, default=None) parser.add_argument( '--class-category', help='Sample metadata column for class predictions.', required=False, type=str, default=None) parser.add_argument( '--batch-size', help='Training batch size', required=False, type=int, default=32) # Arguments specific for trainer parser.add_argument( '--epochs', help='Training batch size', required=False, type=int, default=100) parser.add_argument('--num-workers', type=int, default=1) parser.add_argument('--gpus', type=int) parser.add_argument('--profile', type=bool, default=False) parser.add_argument('--grad-clip', type=int, default=10) parser.add_argument('--eigvalues', type=str, default=None, help='Ground truth eigenvalues (optional)', required=False) parser.add_argument('--eigvectors', type=str, default=None, help='Ground truth eigenvectors (optional)', required=False) parser.add_argument('--load-from-checkpoint', type=str, default=None) parser.add_argument('--output-directory', type=str, default=None) return parser <file_sep>/scripts/simulate-counts.py import argparse import numpy as np from biom import Table from catvae.sim import multinomial_bioms, multinomial_batch_bioms from biom.util import biom_open import pandas as pd import os def save_bioms(args, sims): output_dir = args.output_dir Y = sims['Y'] parts = Y.shape[0] // 10 samp_ids = list(map(str, range(Y.shape[0]))) obs_ids = list(map(str, range(Y.shape[1]))) train = Table(Y[:parts * 8].T, obs_ids, samp_ids[:parts * 8]) test = Table(Y[parts * 8: parts * 9].T, obs_ids, samp_ids[parts * 8: parts * 9]) valid = Table(Y[parts * 9:].T, obs_ids, samp_ids[parts * 9:]) output_dir = args.output_dir with biom_open(f'{output_dir}/train.biom', 'w') as f: train.to_hdf5(f, 'train') with biom_open(f'{output_dir}/test.biom', 'w') as f: test.to_hdf5(f, 'test') with biom_open(f'{output_dir}/valid.biom', 'w') as f: valid.to_hdf5(f, 'valid') tree = sims['tree'] tree.write(f'{output_dir}/basis.nwk') np.savetxt(f'{output_dir}/eigvals.txt', sims['eigs']) np.savetxt(f'{output_dir}/eigvecs.txt', sims['eigvectors']) np.savetxt(f'{output_dir}/W.txt', sims['W']) def no_batch_main(args): sims = multinomial_bioms( k=args.latent_dim, D=args.input_dim, N=args.samples, M=args.depth) save_bioms(args, sims) def batch_main(args): sims = multinomial_batch_bioms( k=args.latent_dim, D=args.input_dim, N=args.samples, M=args.depth, C=args.batches) save_bioms(args, sims) Y = sims['Y'] samp_ids = list(map(str, range(Y.shape[0]))) md = pd.DataFrame({'batch_category': sims['batch_idx']}, index=samp_ids) md.index.name = 'sampleid' md.to_csv(f'{args.output_dir}/metadata.txt', sep='\t') batch_priors = pd.Series(sims['alphaILR']) batch_priors.to_csv(f'{args.output_dir}/batch_priors.txt', sep='\t') if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--seed', type=int, default=0, required=False) parser.add_argument('--batch-effect', dest='batch_effect', action='store_true') parser.add_argument('--no-batch-effect', dest='batch_effect', action='store_false') parser.add_argument('--batches', type=int, default=1, required=False) parser.add_argument('--latent-dim', type=int, default=10, required=False) parser.add_argument('--input-dim', type=int, default=100, required=False) parser.add_argument('--samples', type=int, default=1000, required=False) parser.add_argument('--depth', type=int, default=10000, required=False) parser.add_argument('--output-dir', type=str) args = parser.parse_args() os.mkdir(args.output_dir) np.random.seed(args.seed) if args.batch_effect: batch_main(args) else: no_batch_main(args) <file_sep>/catvae/tests/test_trainer.py import unittest import os import shutil import torch from catvae.trainer import MultVAE, MultBatchVAE, BiomDataModule from catvae.sim import multinomial_bioms, multinomial_batch_bioms from biom import Table from biom.util import biom_open import numpy as np from pytorch_lightning import Trainer import pandas as pd from scipy.stats import pearsonr from scipy.spatial.distance import pdist class TestVAEModel(unittest.TestCase): def setUp(self): np.random.seed(1) torch.manual_seed(1) self.k, self.D, self.N, self.M = 10, 50, 500, 100000 self.sims = multinomial_bioms(k=self.k, D=self.D, N=self.N, M=self.M) Y = self.sims['Y'] parts = Y.shape[0] // 10 samp_ids = list(map(str, range(Y.shape[0]))) obs_ids = list(map(str, range(Y.shape[1]))) train = Table(Y[:parts * 8].T, obs_ids, samp_ids[:parts * 8]) test = Table(Y[parts * 8: parts * 9].T, obs_ids, samp_ids[parts * 8: parts * 9]) valid = Table(Y[parts * 9:].T, obs_ids, samp_ids[parts * 9:]) with biom_open('train.biom', 'w') as f: train.to_hdf5(f, 'train') with biom_open('test.biom', 'w') as f: test.to_hdf5(f, 'test') with biom_open('valid.biom', 'w') as f: valid.to_hdf5(f, 'valid') self.sims['tree'].write('basis.nwk') def tearDown(self): if os.path.exists('lightning_logs'): shutil.rmtree('lightning_logs') if os.path.exists('summary'): shutil.rmtree('summary') os.remove('basis.nwk') os.remove('train.biom') os.remove('test.biom') os.remove('valid.biom') def test_run(self): model = MultVAE(n_input=self.D, n_latent=self.k, n_hidden=16, basis='basis.nwk', dropout=0.5, bias=True, batch_norm=True, encoder_depth=1, learning_rate=0.1, scheduler='cosine', transform='pseudocount') model.set_eigs(self.sims['eigvectors'], self.sims['eigs']) dm = BiomDataModule('train.biom', 'test.biom', 'valid.biom', batch_size=50) trainer = Trainer( max_epochs=50, gpus=0, check_val_every_n_epoch=10, fast_dev_run=False, ) trainer.fit(model, dm) # Make sure that the estimates are darn close W = model.vae.decoder.weight.detach().cpu().numpy() d_estW = pdist(W) simW = self.sims['W'] / np.sqrt(self.sims['eigs']) dW = pdist(simW) r, p = pearsonr(dW, d_estW) self.assertGreater(r, 0.9) self.assertLess(p, 1e-8) class TestBatchVAEModel(unittest.TestCase): def setUp(self): np.random.seed(0) torch.manual_seed(0) self.k, self.D, self.N, self.M, self.C = 10, 50, 500, 100000, 3 self.sims = multinomial_batch_bioms(k=self.k, D=self.D, N=self.N, M=self.M, C=self.C) Y = self.sims['Y'] parts = Y.shape[0] // 10 samp_ids = list(map(str, range(Y.shape[0]))) obs_ids = list(map(str, range(Y.shape[1]))) train = Table(Y[:parts * 8].T, obs_ids, samp_ids[:parts * 8]) test = Table(Y[parts * 8: parts * 9].T, obs_ids, samp_ids[parts * 8: parts * 9]) valid = Table(Y[parts * 9:].T, obs_ids, samp_ids[parts * 9:]) with biom_open('train.biom', 'w') as f: train.to_hdf5(f, 'train') with biom_open('test.biom', 'w') as f: test.to_hdf5(f, 'test') with biom_open('valid.biom', 'w') as f: valid.to_hdf5(f, 'valid') md = pd.DataFrame({'batch_category': self.sims['batch_idx']}, index=samp_ids) md.index.name = 'sampleid' md.to_csv('metadata.txt', sep='\t') batch_priors = pd.Series(self.sims['alphaILR']) batch_priors.to_csv('batch_priors.txt', sep='\t') self.sims['tree'].write('basis.nwk') def tearDown(self): os.remove('basis.nwk') os.remove('batch_priors.txt') os.remove('metadata.txt') os.remove('train.biom') os.remove('test.biom') os.remove('valid.biom') if os.path.exists('lightning_logs'): shutil.rmtree('lightning_logs') def test_fit(self): model = MultBatchVAE(n_input=self.D, n_latent=self.k, n_hidden=16, n_batches=self.C, basis='basis.nwk', batch_prior='batch_priors.txt', dropout=0.5, bias=True, batch_norm=True, encoder_depth=1, learning_rate=0.1, scheduler='cosine', transform='pseudocount') model.set_eigs(self.sims['eigvectors'], self.sims['eigs']) print(model) dm = BiomDataModule('train.biom', 'test.biom', 'valid.biom', metadata='metadata.txt', batch_category='batch_category', batch_size=50) trainer = Trainer( max_epochs=50, gpus=0, check_val_every_n_epoch=1, fast_dev_run=False, ) trainer.fit(model, dm) # See if the model can approximately recover W W = model.vae.decoder.weight.detach().cpu().numpy() d_estW = pdist(W) simW = self.sims['W'] / np.sqrt(self.sims['eigs']) dW = pdist(simW) r, p = pearsonr(dW, d_estW) self.assertGreater(r, 0.15) self.assertLess(p, 0.001) # See if the model can approximately remove beta B = model.vae.beta.weight.detach().cpu().numpy().T d_estB = pdist(B) simB = self.sims['B'].T dB = pdist(simB) r, p = pearsonr(dB, d_estB) self.assertGreater(r, 0.3) self.assertLess(p, 1e-8) if __name__ == '__main__': unittest.main() <file_sep>/catvae/distributions/tests/test_mvn.py import unittest from catvae.distributions.mvn import MultivariateNormalFactorIdentity from torch.distributions import MultivariateNormal from catvae.distributions.utils import seed_all import torch import torch.testing as tt import math class TestMultivariateNormalFactorIdentity(unittest.TestCase): def setUp(self): n = 200 d = 100 k = 4 seed_all(0) self.W = torch.randn((d, k)) self.D = torch.rand(k) self.n = n self.d = d self.s2 = torch.Tensor([3]) self.Id = torch.eye(self.d) def test_covariance_matrix(self): loc = torch.zeros(self.d) exp = (self.W @ torch.diag(self.D) @ self.W.t() + self.s2 * self.Id) dist = MultivariateNormalFactorIdentity( loc, self.s2, self.D, self.W) cov = dist.covariance_matrix self.assertEqual(cov.shape, (self.d, self.d)) tt.assert_allclose(exp, cov) def test_precision_matrix(self): # tests how accurately the inverse covariance matrix can be computed loc = torch.zeros(self.d) dist = MultivariateNormalFactorIdentity( loc, self.s2, self.D, self.W) r = self.W @ torch.diag(self.D) @ self.W.t() + self.s2 * self.Id exp = torch.inverse(r) tt.assert_allclose(exp, dist.precision_matrix, rtol=1, atol=1 / (math.sqrt(self.d))) @unittest.skip("This test is currently broken ...") def test_log_det(self): loc = torch.zeros(self.d) dist = MultivariateNormalFactorIdentity( loc, self.s2, self.D, self.W) cov = dist.covariance_matrix res = dist.log_det exp = torch.slogdet(cov)[1] tt.assert_allclose(res, exp) def test_rsample(self): loc = torch.ones(self.d) dist = MultivariateNormalFactorIdentity( loc, self.s2, self.D, self.W) samples = dist.rsample([10000]) self.assertAlmostEqual(float(samples.mean()), 1, places=2) def test_log_prob(self): loc = torch.ones(self.d) wdw = self.W @ torch.diag(self.D) @ self.W.t() sI = self.s2 * self.Id sigma = sI + wdw dist2 = MultivariateNormal(loc, covariance_matrix=sigma) samples = dist2.rsample([10000]) exp_logp = dist2.log_prob(samples) dist1 = MultivariateNormalFactorIdentity( loc, self.s2, self.D, self.W) res_logp = dist1.log_prob(samples) self.assertAlmostEqual(float(exp_logp.mean()), float(res_logp.mean()), places=3) def test_entropy(self): pass if __name__ == '__main__': unittest.main()
c6df86bb440d5a7ab18ff08dbf922a071c61987b
[ "Markdown", "Makefile", "Python", "Text", "Shell" ]
29
Python
stjordanis/catvae
218d678868aab02ab985c42d377c2da6f8aef2a5
17f499171e559a4f41d3d1e18d07131c5169d3dd
refs/heads/main
<file_sep># Generated by Django 3.1.2 on 2020-10-29 10:45 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('poll_app', '0001_initial'), ] operations = [ migrations.RenameField( model_name='choice', old_name='choices', new_name='choice_name', ), ] <file_sep>{% extends 'poll_app/base.html' %} {% block title %}Results{% endblock %} {% block main %} <h1 class="text-center">Results</h1> <hr /> <div class=row> <div class="col-md-6"> <h2 class="mb-5 text-center">{{ question.question_name }}</h2> <ul class="list-group mb-5"> {% for choice in choices_order %} <li class="list-group-item {% if forloop.first %}bg-warning{% endif %}"> {{ choice.choice_name }} <span class="badge badge-success float-right">{{ choice.votes }} vote{{ choice.votes | pluralize }}</span> </li> {% endfor %} </ul> </div> <div class="col-md-6"> <h2 class="mb-2 text-center">Pie Chart Visualisation</h2> <canvas id="pie-chart"></canvas> </div> </div> <hr /> <a class="btn btn-secondary" href="{% url 'home' %}">Back To Polls</a> <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script> <script> var config = { type: 'pie', data: { datasets: [{ data: {{ data| safe }}, backgroundColor: ['#ff0000', '#0000ff', '#ff0080', '#73ffff',], label: 'Population' }], labels: {{ labels | safe }} }, options: { responsive: true } }; window.onload = function () { var ctx = document.getElementById('pie-chart').getContext('2d'); window.myPie = new Chart(ctx, config); }; </script> </script> {% endblock %}<file_sep>from django.db import models class Question(models.Model): question_name = models.CharField(max_length=200) def __str__(self): return self.question_name class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_name = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_name<file_sep>asgiref==3.2.10 autopep8==1.5.4 Django==3.1.2 django-extensions==3.0.9 pycodestyle==2.6.0 pygraphviz==1.6 pytz==2020.1 sqlparse==0.4.1 toml==0.10.1 <file_sep>from django.shortcuts import get_object_or_404, render from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from .models import Question, Choice from django.db.models import Max def home(request): question_list = Question.objects.all() context = {'question_list': question_list} return render(request, 'poll_app/home.html', context) def results(request, question_id): labels = [] data = [] question = get_object_or_404(Question, pk=question_id) choices_order = question.choice_set.order_by('-votes') for choice in choices_order: labels.append(choice.choice_name) data.append(choice.votes) return render(request, 'poll_app/results.html', {'question': question, "choices_order": choices_order, 'labels': labels, 'data': data, }) def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): return render(request, 'poll_app/home.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('results', args=(question.id,))) <file_sep># Opinion Poll A simple opinion poll app to collect visitor responses on different situations developed using Django with Bootstrap. The Demo of the web app is available at [Demo] # Instructions to run on your local 1. Create virtual environment using the command "virtualenv my_env" 2. Activate using "source my_env/bin/activate" 3. Install the requirements "pip install -r requirements.txt" 4. Database setup using: python manage.py migrate 5. Run the server : python manage.py runserver # The Database Schema <img style="margin: 10px" src="https://github.com/warisanwar/opinion_poll/blob/main/database_schema.png" alt="DB Schema" /> [Demo]: http://warisanwar.pythonanywhere.com/
d4ad029b8e5297b285ee9e5fc7df03892b42fd44
[ "Markdown", "Python", "Text", "HTML" ]
6
Python
warisanwar/opinion_poll
d32f596230e9c4abcf5e1afc3d5232265c82e75b
708a078d37c8ca97826bd9b3a8adf49dd1208081
refs/heads/master
<file_sep>times = 0; puts "How many times?" times = gets.chomp.to_i candidates = (2..times).to_a primes = [] def getNextPrime(candidates, primes) return primes if !candidates.any? nextPrime = candidates[0]; primes.push(nextPrime); candidates.delete_if { |element| element%nextPrime == 0 } return getNextPrime(candidates, primes); end puts "Found #{getNextPrime(candidates, primes).size} primes." <file_sep>/** * ExampleTemplate.js * * This is the template view to be populated with specific examples. When * displayed it should enable/disable the buttons appropriate for the types of * code snippet set in the 'rubyCode' and 'jsCode' properties. */ Ext.define('JavascriptShowcase.view.ExampleTemplate', { extend : 'Ext.Container', alias : 'widget.template', config : { layout : 'fit', rubyCode : undefined, jsCode : undefined, items : [ { // The container to be filled with the example code. xtype : 'container', cssClass : 'func_fillMe', html : 'Select a View' }, { // A toolbar containing the buttons for controlling what to populate // the container with. xtype : 'toolbar', docked : 'bottom', defaults : { xtype : 'button' }, items : [ { text : 'Ruby', action : 'showRubyCode' }, { text : 'JS', action : 'showJavascriptCode' } ] } ] } }); <file_sep># showcase Some sample code <file_sep>puts "\aHowdy!\a" (1..100).each do |i| modThree = i%3==0; modFour = i%4==0; if modThree and modFour puts "FizzBuzz"; elsif modThree puts "Fizz" elsif modFour puts "Buzz" else puts i; end end <file_sep>/* * When true flatten array will ignore non integer values in the array variable, * when false processing will stop and an exception will be thrown. */ var runPassively = true; /** * flattenArray: convert a nested array into a flattened single depth array. * * @param array: the nested multi depth array to flatten. * @param flatArray: Optional. a starting point for the recursive call, the flattened array will be added to this recursively and returned. * * @return : the single depth, flattened array. */ function flattenArray(array, flatArray) { if (!Array.isArray(array)) { throw "flattenArray needs to be passed an array as the first argument."; } if (flatArray == undefined) { // Initialize flatArray if a starting point was not provided. flatArray = []; } /* * Iterate array either adding to flatArray an int element or calling flattenArray on an array element. */ for (var element of array) { if (Array.isArray(element)) { // element is array, make recursive call. flattenArray(element, flatArray); } else if (!isInt(element)) { // This is not an integer and cannot be added to the array. console.error("Array element " + element + " cannot be parsed into a number!"); // If the option is set to die here do so, otherwise ignore and move on. if (!runPassively) { throw "Array element " + element + " cannot be parsed into a number!"; } } else { // Element is an int, push it onto the flat array. flatArray.push(parseInt(element)); } } // Return the flattened array. return flatArray; } /** * isInt : a helper method to determing whether an object is an int. Return true for integers and their string counterparts (1, 1.0 '1.0' and '1') * @param element : the element to test * @return false for non integer values ('1.1' and 3.2 and 'a') */ function isInt(element) { return parseInt(element, 10) == element; } var test1 = [1,2,3,4,[5,6,[7,[8,9,[0]]]]]; var test2 = [1,2,[3,4],5,[6,[7,8],9,[0]]]; var test3 = ['1','2',['3.0','4'],'5',[6.0,["7",'8'],9,[0]]]; var test4 = [1.2,3.4,[5.6, 6.0], 7.8, ['9.0']]; var test5 = [1,2.3,[4.5,6,[7,8],9.0],'a','b','c']; // Test with flattenArray(test1); etc. <file_sep>/** * A fizz bang puzzle I solved from HackerRank. getPools takes * a space separated list of data representing a map of land and * water (1's and 0's) and finds the pools of water and tracks * them in the pools array. * * Test with the following data: * 01100 11001 01111 * * 00111110010 10001110000 00001100011 00011100110 00111111000 11110011111 00111100000 * * 111111100000000111111111100000000000000000 000000000011111111111111010000000000000000 000000011111111000111111110001111111110000 000110100000011111111111111100000000000000 000011111111111111111111111111111111100000 111111111111111111100111111111111111111111 000011111111111110000001111111111111111000 000000000000111111111111111111111111110000 000000000000000000000000000000000000000000 */ var map = []; var pools = []; function getPools(input) { // Data comes as 2d array, rows seperated by new lines and columns by spaces. map = []; // reset the map pools = []; // reset the pools populateMap(input); for (var rowIndex=0; rowIndex < map.length; rowIndex++) { for (var colIndex=0; colIndex < map[rowIndex].length; colIndex++) { if (map[rowIndex][colIndex] == 0 && !isMapped(rowIndex, colIndex, [])) { var newPool = mapPool(rowIndex, colIndex, []); console.log("Found New Pool:", newPool); pools.push(newPool); } } } } function populateMap(mapData) { var rows = mapData.split(' '); for (var rowIndex=0; rowIndex < rows.length; rowIndex++) { map.push(rows[rowIndex].split('')); } } function isMapped(row, column, poolsToCheck) { if (map[row][column] != 0) { console.error("map[" + row + "][" + column + "] != 0!"); } var localPools = poolsToCheck.slice(0); var coordinate = row + "," + column; for (var poolIndex = 0; poolIndex < pools.length; poolIndex++) { localPools = localPools.concat(pools[poolIndex]); } console.log("Checking LocalPools: ", localPools); return localPools.indexOf(coordinate) != -1; } function mapPool(row, column, pool) { pool.push(row + "," + column); // Look Up if (row > 0) { // Straight Up if (map[row-1][column]==0 && !isMapped(row-1, column, pool)) { console.log("Straight Up"); mapPool(row-1, column, pool); } // Up Left if (column > 0 && map[row-1][column-1] == 0 && !isMapped(row-1, column-1, pool)) { console.log("Up Left"); mapPool(row-1, column-1, pool); } // Up Right if (column < map[row-1].length-1 && map[row-1][column+1] == 0 && !isMapped(row-1, column+1, pool)) { console.log("Up Right"); mapPool(row-1, column+1, pool); } } // Straight Left if (column > 0 && map[row][column-1] == 0 && !isMapped(row, column-1, pool)) { console.log("Straight Left"); mapPool(row, column-1, pool); } // Straight Right if (column < map[row].length-1 && map[row][column+1] == 0 && !isMapped(row, column+1, pool)) { console.log("Straight Right"); mapPool(row, column+1, pool); } // Down if (row < map.length-1) { // Down Left if (column > 0 && map[row+1][column-1] == 0 && !isMapped(row+1, column-1, pool)) { console.log("Down Left"); mapPool(row+1, column-1, pool); } // Straight Down if (map[row+1][column] == 0 && !isMapped(row+1, column, pool)) { console.log("Stright Down"); mapPool(row+1, column, pool); } // Down Right if (column < map[row+1].length-1 && map[row+1][column+1] == 0 && !isMapped(row+1, column+1, pool)) { console.log("Down Right"); mapPool(row+1, column+1, pool); } } console.log("Created Pool:", pool); return pool; } <file_sep>/** * A reverse polish notation calculator. * * Test by passing the strings: * '5 2 3 ^ + 5 8 + = 13' * '3 2 * 11 - = -5' * '4 - + 2 -3 + = -1' */ var operators = ['+', '-', '*', '/']; function evalRPN(rpn) { var rpnArray = rpn.split(' '); var equation = ""; for (var rpnIndex=0; rpnIndex<rpnArray.length; rpnIndex++) { if (operators.indexOf(rpnArray[rpnIndex + 1]) != -1) { equation = equation + rpnArray[rpnIndex + 1] + " " + rpnArray[rpnIndex]; rpnIndex++; } else { equation = equation + rpnArray[rpnIndex]; } } console.log("Evaluating '" + equation + "'"); var result = eval(equation); console.log("Result '" + result + "'"); } <file_sep>// @tag full-page // @require /data/bradwagoner/senchaShowcase/app.js <file_sep>function fizzbuzz(times) { var result = []; for (var i = 1; i < times; i++) { var modThree = i % 3 == 0; var modFour = i % 4 == 0; if (modThree && modFour) { result.push("FizzBuzz"); } else if (modThree) { result.push("Fizz"); } else if (modFour) { result.push("Buzz"); } else { result.push(i); } } return result; }
4db7adb7417996379138b3fca74616e2aaaf2f7a
[ "JavaScript", "Ruby", "Markdown" ]
9
Ruby
bradwagoner/showcase
d36ede4622e37667fe4e0643d522f932bbcb9325
1946ab1f6b0f4524ca73fb0786bb467ee0ec98f8
refs/heads/master
<repo_name>arimakaoru/learn-python<file_sep>/algorithm/selection_sort.py array = [4,2,7,8,0,5,1,3,6,9] n = len(array) print(array) for i in range(n-1): min = i for j in range(i+1, n): if array[j] < array[min]: min = j tmp = array[i] array[i] = array[min] array[min] = tmp print(array) <file_sep>/books/introducing_python3/boxes/sources/weekly.py def forecast(): '''ニセの週間天気予報''' return ['snow', 'more snow', 'sleet', 'freezeing rain', 'rain', 'fog', 'haill'] <file_sep>/other/janken.py ''' じゃんけん ''' import random print("--------------------じゃんけん--------------------") hand = {'1':"グー", '2':"チョキ", '3':"パー"} while True: player = input("\nグー:1, チョキ:2, パー:3, やめる:q => ") if player == 'q': judge = "終了" break elif (player in hand) == False: print("無効な入力です") continue else: cpu = random.choice(list(hand.keys())) if player == cpu: judge = "あいこでしょっ!" elif ((player == '1' and cpu == '2') or (player == '2' and cpu == '3') or (player == '3' and cpu == '1')): judge = "勝ち!" else: judge = "負け!" print("あなた:%s 相手:%s\n%s" %(hand[player], hand[cpu], judge)) <file_sep>/algorithm/bubble_sort.py array = [2,5,1,9,7,8,3,0,6,4] n = len(array) print(array) for i in range(0, n-1): for j in range(n-1, i, -1): if array[j] < array[j-1]: array[j], array[j-1] = array[j-1], array[j] print(array) <file_sep>/other/number_guessing_game.py ''' 数当てゲーム ''' import random print(''' 数当てゲーム ランダムで決められる1〜100までの数字を当ててください。 0を入力すると終了します。''') right_number = random.randint(1,100) while True: input_number = int(input("数字を入力:")) if input_number == 0: print("終了") break elif input_number == right_number: print("正解!") break elif input_number < right_number: print("%sより大きい" %input_number) else: print("%sより小さい" %input_number) <file_sep>/web_scraping/sample.py import requests from bs4 import BeautifulSoup def main(): r = requests.get('http://www.google.com/') soup = BeautifulSoup(r.text, 'html.parser') print(soup.prettify()) if __name__ == '__main__': main()<file_sep>/clapp/my_ls.py #!/usr/bin/env python3 import os def main(): current_dir = os.getcwd() file_list_all = os.listdir(current_dir) file_list_all.sort() # 隠しファイルを除く file_list = [f for f in file_list_all if f[0] != '.'] for f in file_list: print(f) if __name__ == '__main__': main()<file_sep>/books/introducing_python3/test2.py import sys print('Program argments:', sys.argv)
191dd21af85729c39a611ab34b45903d88b9dd0a
[ "Python" ]
8
Python
arimakaoru/learn-python
bbc373e586859061832b3373839178db97297598
cf8c2b19c890091e8da0d4fcc9ff1504346f0cf2
refs/heads/master
<repo_name>Micik2/WyboryElektroniczne<file_sep>/README.md Wymagane komponenty: - Python 2.7 - microframework Flask - PonyORM - MySQL Server 5.7 Po uruchomieniu komendą "python 'nazwa pliku'", można zobaczyć stronę prototypową na "127.0.0.1:5000". Do uzupełnienia dane odnośnie adresu mejlowego (nadawcy i odbiorcy), wymagane w domenie "gmail.com". Aktualny plik do uruchomienia to git.py <file_sep>/git.py #!/usr/bin/env python # -*- coding: utf-8 -*- from flask import Flask, render_template, request, json, session, redirect from flask.ext.mysql import MySQL import random import smtplib from pony.orm import * #from werkzeug import generate_password_hash, check_password_hash # sql alchemy i sql object mysql = MySQL() app = Flask(__name__) app.secret_key = 'sekret' tas = Database() class Obywatele(tas.Entity): PESEL = PrimaryKey(str) email = Required(str, unique=True) haslo = Optional(str) wyborcy = Optional("Wyborcy") class Wyborcy(tas.Entity): imie = Optional(unicode) nazwisko = Optional(unicode) nr_dowodu = Optional(str, unique=True) ulica = Optional(unicode) nr_lokalu = Optional(str) kod_pocztowy = Optional(str) miejscowosc = Optional(unicode) czy_glosowal = Optional(bool) wyksztalcenie = Optional(unicode) kraj_pochodzenia = Optional(str) wiek = Optional(int) czy_ubezwlasnowolniony = Optional(bool) haslo_tymczasowe = Required(str) nr_telefonu = Optional(int, unique=True) OBYWATELE_PESEL = PrimaryKey(Obywatele) # MySQL configurations app.config['MYSQL_DATABASE_USER'] = 'root' #app.config['MYSQL_DATABASE_USER'] = 'Micik' app.config['MYSQL_DATABASE_PASSWORD'] = 'localhost' app.config['MYSQL_DATABASE_DB'] = 'tas' app.config['MYSQL_DATABASE_HOST'] = 'localhost' mysql.init_app(app) tas.bind("mysql", host = "localhost", user = "root", passwd = "<PASSWORD>", db = "tas") tas.generate_mapping(create_tables = True) @app.route("/") def main(): return render_template('index.html') @app.route('/showSignUp') def showSignUp(): return render_template('signup.html') @app.route('/showSignIn') def showSignIn(): return render_template('signin.html') @app.route('/signUp',methods=['POST','GET']) def signUp(): try: _pesel = request.form['inputPesel'] _email = request.form['inputEmail'] # validate the received values if _pesel and _email: '''with open("test.txt", 'a+') as plik: plik.write(_pesel + ":" + _email + "\n")''' #plik = open('test.txt', 'a+') #plik.write(_pesel + ":" + _email + " \n") #plik.close() haslo = random.getrandbits(128) #print "haslo value: %032x" % haslo h = "%032x" % haslo has = str(h) link = "127.0.0.1:5000/showSignIn" #link = "127.0.0.1:5000/showSignIn/" + str(h) wiadomosc = ["From: Wybory Elektroniczne", #"To: /email/", "Subject: Rejestracja", "", "Do zalogowania się użyj podanego niżej hasła:", has, "Wchodząc w ten link:", link] msg = "\r\n".join(wiadomosc)#[ #"From: WyboryElektroniczne", #"To: /email/", #"Subject: Rejestracja na Wyborcę", #"", #"Why, oh why" #]) fromaddr = toaddrs = _email username = password = server = smtplib.SMTP('smtp.gmail.com:587') server.ehlo() server.starttls() server.login(username,password) server.sendmail(fromaddr, toaddrs, msg) server.quit() # All Good, let's call MySQL ''' conn = mysql.connect() cursor = conn.cursor() #_hashed_password = generate_password_hash(_password) #cursor.callproc('rejestracja4',(_name,_email,_hashed_password)) #cursor.callproc('rejestracja4',(_name,_email,_password)) insert_stmt = ( "INSERT INTO Obywatele (PESEL, email, haslo) " "VALUES (%s, %s, %s)" ) data = (_pesel, _email, has) cursor.execute(insert_stmt, data) #cursor.execute("INSERT INTO WYBORCY(PESEL, email, haslo) values ") #cursor.callproc('dodajUzytkownika', (_email, _password, _type, _organization, _name, _surname)) data = cursor.fetchall() if len(data) is 0: conn.commit() return json.dumps({'message':'User created successfully !'}) else: return json.dumps({'error':str(data[0])}) else: return json.dumps({'html':'<span>Enter the required fields</span>'}) ''' with db_session: Obywatele(PESEL = _pesel, email = _email, haslo = has) commit() except Exception as e: return json.dumps({'error':str(e)}) finally: cursor.close() conn.close() '''@app.route('/error') def err(): return render_template('error.html') ''' @app.route('/validateLogin',methods=['POST']) def validateLogin(): n = 0 _pesel = request.form['inputPesel'] _password = request.form['inputPassword'] try: if _pesel and _password: '''with open('test.txt', 'r') as plik: for line in plik: if _pesel + ":" + _password in line: n = 1 if n: return redirect('/userHome') else: #return redirect('/error') return render_template('error.html', error = "Zły pesel lub hasło!") #//////////////////////////////////////////////////////////////////////// con = mysql.connect() cursor = con.cursor() #cursor.callproc('logowanie',(_username,)) select_stmt = "SELECT * FROM Obywatele WHERE PESEL = " + _pesel cursor.execute(select_stmt) print "HALO" data = cursor.fetchall() if len(data) > 0: #if check_password_hash(str(data[0][3]),_password): if str(data[0][2]) == _password: session['user'] = data[0][0] #return render_template('userHome.html') return redirect('/userHome') else: return render_template('error.html',error = 'Zły PESEL lub hasło!') else: return render_template('error.html',error = 'Zły PESEL lub hasło!')''' with db_session: h = tas.select("haslo from Obywatele where PESEL = $_pesel") print h[0] print _password print type(h[0]) print type(_password) #r = select(p for p in Person if p.PESEL==_pesel)[:] #commit() #u = r[0] #print u.haslo #if u.haslo == _password: if h[0] == _password: print "TU JESTEM" session['user'] = _pesel return redirect('/userHome') else: return render_template("error.html", error = "Zły PESEL lub hasło!") else: return render_template("error.html", error = "Zły PESEL lub hasło!") except Exception as e: return render_template('error.html',error = str(e)) finally: cursor.close() con.close() @app.route('/userHome') def userHome(): if session.get('user'): return render_template('userHome.html') else: return render_template('error.html', error = 'Nieautoryzowany dostep!') return render_template('userHome.html') if __name__ == "__main__": #app.run() app.run(host='0.0.0.0', port = 5000)<file_sep>/Aktualne/tas.py #!/usr/bin/env python # -*- coding: utf-8 -*- import random import smtplib hash = random.getrandbits(128) print "hash value: %032x" % hash h = "%032x" % hash link = "127.0.0.1:5000/signup/" + str(h) wiadomosc = ["From: Wybory Elektroniczne", "To: /gmail/", "Subject: Rejestracja na Wyborcę", "", "Aby dokończyć rejestrację kliknij w link poniżej:", link] msg = "\r\n".join(wiadomosc)#[ #"From: WyboryElektroniczne", #"To: /gmail/", #"Subject: Rejestracja na Wyborcę", #"", #"Why, oh why" #]) fromaddr = toaddrs = #msg = 'Why,Oh why!' username = password = server = smtplib.SMTP('smtp.gmail.com:587') server.ehlo() server.starttls() server.login(username,password) server.sendmail(fromaddr, toaddrs, msg) server.quit()<file_sep>/Prototyp/test2.py #!/usr/bin/env python # -*- coding: utf-8 -*- from flask import Flask, render_template, request, json, session, redirect, url_for, send_from_directory from pony.orm import * from werkzeug import secure_filename from flask_images import * import os import sys import random import smtplib from datetime import date reload(sys) sys.setdefaultencoding("utf8") app = Flask(__name__) app.secret_key = "sekret" app.config["DEBUG"] = True app.config["UPLOAD_FOLDER"] = "static/" #app.config["ALLOWED_EXTENSIONS"] = set(["png", "jpg", "jpeg"]) images = Images(app) tas = Database() class Obywatele(tas.Entity): PESEL = PrimaryKey(str) #email = Required(str) email = Optional(str) haslo = Optional(str) wyborcy = Optional("Wyborcy") zdjecie = Required(unicode, default="default.jpg") class Wyborcy(tas.Entity): imie = Optional(unicode) nazwisko = Optional(unicode) nr_dowodu = Optional(str, unique=True) ulica = Optional(unicode) nr_lokalu = Optional(str) kod_pocztowy = Optional(str) miejscowosc = Optional(unicode) czy_glosowal = Optional(bool) wyksztalcenie = Optional(unicode) kraj_pochodzenia = Optional(str) wiek = Optional(int) czy_ubezwlasnowolniony = Optional(bool, default=0) #haslo_tymczasowe = Required(str) haslo_tymczasowe = Optional(str) nr_telefonu = Optional(int, unique=True) OBYWATELE_PESEL = PrimaryKey(Obywatele) #tas.bind("mysql", host = "localhost", user = "root", passwd = "<PASSWORD>", db = "tas") tas.bind("sqlite", "database.sqlite", create_db=True) tas.generate_mapping(create_tables=True) def format(nazwa_pliku): return '.' in nazwa_pliku and nazwa_pliku.rsplit('.', 1)[1] in app.config["ALLOWED_EXTENSIONS"] @app.route('/') def main(): if "username" in session: pesel = session["username"] return render_template("index.html", pesel = pesel) return render_template("index.html") @app.route("/wybory") def wybory(): if "username" in session: pesel = session["username"] lista_wyborow = [] # ze względu na wymóg braku spacji w linku musiałem dodać '_' lista_wyborow.append("wybory_na_kanclerza") lista_wyborow.append("wybory_na_prezydenta") return render_template("wybory.html", pesel = pesel, wyb = lista_wyborow) else: return redirect("main") #lista_wyborow = [] # z bazy trzeba będzie pobierać wszystkie wybory dziejące się aktualnie # aktualnie przykładowe, bez użycia bazy #lista_wyborow.append("Wybory na kanclerza") #lista_wyborow.append("Wybory na prezydenta") #return redirect("wylistowanieWyborow") #return render_template("wybory.html", wyb = lista_wyborow, pesel = session["username"] ''' @app.route("/kandydaci") def kandydaci(): @app.route("/kandydat") def kandydat(): @app.route("/glosowanie") def glosowanie(): #@app.route("/panel") #def panel(): ''' @app.route("/pokazLogowanie/") def pokazLogowanie(): return render_template("logowanie.html") @app.route("/pokazRejestracja/") def pokazRejestracja(): return render_template("rejestracja.html") @app.route("/pokazProfil", methods = ["POST", "GET"]) def pokazProfil(): with db_session: obywatel = Obywatele.get(PESEL = session["username"]) wyborca = Wyborcy.get(OBYWATELE_PESEL = session["username"]) img_url = url_for("static", filename = obywatel.zdjecie) if obywatel: return render_template("profil.html", pesel = session["username"], imie = wyborca.imie, nazwisko = wyborca.nazwisko, nr_dowodu = wyborca.nr_dowodu, ulica = wyborca.ulica, nr_lokalu = wyborca.nr_lokalu, kod_pocztowy = wyborca.kod_pocztowy, miejscowosc = wyborca.miejscowosc, wyksztalcenie = wyborca.wyksztalcenie, kraj_pochodzenia = wyborca.kraj_pochodzenia, wiek = wyborca.wiek, nr_telefonu = wyborca.nr_telefonu, img_url = img_url) #return render_template("profil.html", pesel = session["username"], imie = "Jan", # nazwisko = "Nowak", img_url = img_url) else: #return redirect("edycjaProfilu") return redirect("main") @app.route("/zmianaZdjecia", methods = ["POST", "GET"]) def zmianaZdjecia(): f = request.files["zdjecie"] nazwa = secure_filename(f.filename) #f.save(secure_filename(f.filename)) #f.save(secure_filename(os.path.join(app.config["UPLOAD_FOLDER"], nazwa))) f.save("static/" + secure_filename(nazwa)) with db_session: Obywatele[session["username"]].zdjecie = nazwa commit() return redirect("pokazProfil") @app.route("/pokazEdycjaProfilu") def pokazEdycjaProfilu(): return render_template("edycjaProfilu.html", wiadomosc = "Uzupełnij swoje dane, aby mieć możliwość brania udziału w głosowaniach") @app.route("/edycjaProfilu", methods = ["POST", "GET"]) def edycjaProfilu(): dzisiaj = date.today() rok = dzisiaj.year miesiac = dzisiaj.month dzien = dzisiaj.day #Ze względu na to, że nie żyje żaden obywatel Polski urodzony w XVIII wieku, dodaję 1900 rok_urodzenia = 1900 + int(session["username"][:2]) miesiac_urodzenia = int(session["username"][2:4]) dzien_urodzenia = int(session["username"][4:6]) lata = dzisiaj.year - rok_urodzenia if miesiac_urodzenia > miesiac: lata -= 1 elif miesiac_urodzenia == miesiac: if dzien_urodzenia > dzien: lata -= 1 _imie = request.form["imie"] _nazwisko = request.form["nazwisko"] _nr_dowodu = request.form["nr_dowodu"] _ulica = request.form["ulica"] _nr_lokalu = request.form["nr_lokalu"] _kod_pocztowy = request.form["kod_pocztowy"] _miejscowosc = request.form["miejscowosc"] _wyksztalcenie = request.form["wyksztalcenie"] _kraj_pochodzenia = request.form["kraj_pochodzenia"] _haslo_tymczasowe = session["password"] _nr_telefonu = request.form["nr_telefonu"] with db_session: #Wybory(imie = _imie, nazwisko = _nazwisko, nr_dowodu = _nr_dowodu, ulica = _ulica, # nr_lokalu = _nr_lokalu, kod_pocztowy = _kod_pocztowy, # miejscowosc = _miejscowosc, czy_glosowal = 0, wyksztalcenie = _wyksztalcenie, # kraj_pochodzenia = _kraj_pochodzenia, wiek = lata, # haslo_tymczasowe = session["password"], nr_telefonu = _nr_telefonu, ) obywatel = Obywatele.get(PESEL = session["username"]) img_url = url_for("static", filename = obywatel.zdjecie) Wyborcy[session["username"]].imie = _imie Wyborcy[session["username"]].nazwisko = _nazwisko Wyborcy[session["username"]].nr_dowodu = _nr_dowodu Wyborcy[session["username"]].ulica = _ulica Wyborcy[session["username"]].nr_lokalu = _nr_lokalu Wyborcy[session["username"]].kod_pocztowy = _kod_pocztowy Wyborcy[session["username"]].miejscowosc = _miejscowosc Wyborcy[session["username"]].czy_glosowal = 0 Wyborcy[session["username"]].wyksztalcenie = _wyksztalcenie Wyborcy[session["username"]].kraj_pochodzenia = _kraj_pochodzenia Wyborcy[session["username"]].wiek = lata Wyborcy[session["username"]].haslo_tymczasowe = session["password"] Wyborcy[session["username"]].nr_telefonu = _nr_telefonu commit() return redirect("pokazProfil") @app.route("/rejestracja", methods = ["POST", "GET"]) def rejestracja(): _pesel = request.form["inputPesel"] _email = request.form["inputEmail"] #_haslo = request.form["inputPassword"] haslo = random.getrandbits(128) h = "%032x" % haslo has = str(h) link = "127.0.0.1:5000/pokazLogowanie" wiadomosc = ["From: <NAME>", "To: <EMAIL>", "Subject: Rejestracja", "", "Do zalogowania się użyj podanego niżej hasła:", has, "Wchodząc w ten link:", link] msg = "\r\n".join(wiadomosc) fromaddr = "<EMAIL>" toaddrs = _email username = "<EMAIL>" password = "<PASSWORD>" server = smtplib.SMTP("smtp.gmail.com:587") server.ehlo() server.starttls() server.login(username, password) server.sendmail(fromaddr, toaddrs, msg) server.quit() #if _pesel and _email and _haslo: if _pesel and _email: with db_session: #Obywatele(PESEL = _pesel, email = _email, haslo = _haslo) Obywatele(PESEL = _pesel, email = _email, haslo = has) Wyborcy(OBYWATELE_PESEL = _pesel) #Wyborcy(OBYWATELE_PESEL = _pesel) commit() #return json.dumps({"message": "Użytkownik stworzony pomyślnie."}) return json.dumps("Użytkownik stworzony pomyślnie.").encode("utf8") @app.route("/logowanie", methods = ["POST"]) def logowanie(): _pesel = request.form["inputPesel"] _haslo = request.form["inputPassword"] #haslo = "" pro = "" wynik = "" if _pesel and _haslo: with db_session: wynik = Obywatele.get(PESEL = _pesel, haslo = _haslo) if wynik: session["username"] = wynik.PESEL session["password"] = <PASSWORD> with db_session: pro = Wyborcy.get(OBYWATELE_PESEL = wynik.PESEL) # return render_template("profil.html", pesel = wynik.PESEL, imie = pro.imie, # nazwisko = pro.nazwisko, nr_dowodu = pro.nr_dowodu, # ulica = pro.ulica, nr_lokalu = pro.nr_lokalu, # kod_pocztowy = pro.kod_pocztowy, miejscowosc = pro.miejscowosc, # wyksztalcenie = pro.wyksztalcenie, # kraj_pochodzenia = pro.kraj_pochodzenia, wiek = pro.wiek, # nr_telefonu = pro.nr_telefonu) #return redirect("profil") if pro.imie: return redirect("pokazProfil") return redirect("pokazEdycjaProfilu") else: return render_template("error.html", error = "Błędne dane!") #return json.dumps({"message": "Błędne dane!"}).encode("utf8") '''return render_template("profil.html", pesel = session["username"], imie = "Jan", nazwisko = "Nowak", nr_dowodu = "ABC123456", ulica = "Testowa", nr_lokalu = "0", kod_pocztowy = "12-345", miejscowosc = "ąćęłńóśżź", wyksztalcenie = "Podstawowe", kraj_pochodzenia = "Polska", wiek = "20", nr_telefonu = "123456789")''' if __name__ == "__main__": app.run(host="0.0.0.0", port = 5000) <file_sep>/we (nieaktualne).py #!/usr/bin/env python # -*- coding: utf-8 -*- from flask import Flask, render_template, request, json, session, redirect #from werkzeug import generate_password_hash, check_password_hash app = Flask(__name__) app.secret_key = 'sekret' @app.route("/") def main(): return render_template('index.html') @app.route('/showSignUp') def showSignUp(): return render_template('signup.html') @app.route('/showSignIn') def showSignIn(): return render_template('signin.html') @app.route('/signUp',methods=['POST','GET']) def signUp(): _pesel = request.form['inputPesel'] _email = request.form['inputEmail'] # validate the received values if _pesel and _email: with open("test.txt", 'a+') as plik: plik.write(_pesel + ":" + _email + "\n") #plik = open('test.txt', 'a+') #plik.write(_pesel + ":" + _email + " \n") #plik.close() @app.route('/validateLogin',methods=['POST']) def validateLogin(): n = 0 _pesel = request.form['inputPesel'] _password = request.form['inputPassword'] if _pesel and _password: with open('test.txt', 'r') as plik: for line in plik: if _pesel + ":" + _password in line: n = 1 if n: return redirect('/userHome') else: #return redirect('/error') return render_template('error.html', error = "Zły pesel lub hasło!") @app.route('/userHome') def userHome(): return render_template('userHome.html') if __name__ == "__main__": #app.run() app.run(host='0.0.0.0', port=5000)<file_sep>/Aktualne/wybory_poczatek.sql -- MySQL Workbench Forward Engineering SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0; SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0; SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES'; -- ----------------------------------------------------- -- Schema mydb -- ----------------------------------------------------- -- ----------------------------------------------------- -- Schema mydb -- ----------------------------------------------------- CREATE SCHEMA IF NOT EXISTS `tas` DEFAULT CHARACTER SET utf8 ; USE `tas` ; -- ----------------------------------------------------- -- Table `mydb`.`OBYWATELE` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `tas`.`OBYWATELE` ( `PESEL` VARCHAR(11) NOT NULL, `email` VARCHAR(45) NOT NULL, `haslo` VARCHAR(45) NULL, PRIMARY KEY (`PESEL`), UNIQUE INDEX `email_UNIQUE` (`email` ASC)) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `mydb`.`WYBORCY` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `tas`.`WYBORCY` ( `imie` NVARCHAR(45) NULL, `nazwisko` NVARCHAR(45) NULL, `nr_dowodu` VARCHAR(9) NULL, `ulica` NVARCHAR(45) NULL, `nr_lokalu` VARCHAR(45) NULL, `kod_pocztowy` VARCHAR(6) NULL, `miejscowosc` NVARCHAR(45) NULL, `czy_glosowal` TINYINT(1) NULL, `wyksztalcenie` NVARCHAR(45) NULL, `kraj_pochodzenia` VARCHAR(45) NULL, `wiek` INT NULL,obywatele `czy_ubezwlasnowolniony` TINYINT(1) NULL, `haslo_tymczasowe` VARCHAR(45) NOT NULL, `nr_telefonu` INT NULL, `OBYWATELE_PESEL` VARCHAR(11) NOT NULL, INDEX `fk_WYBORCY_OBYWATELE_idx` (`OBYWATELE_PESEL` ASC), UNIQUE INDEX `nr_dowodu_UNIQUE` (`nr_dowodu` ASC), UNIQUE INDEX `nr_telefonu_UNIQUE` (`nr_telefonu` ASC), CONSTRAINT `fk_WYBORCY_OBYWATELE` FOREIGN KEY (`OBYWATELE_PESEL`) REFERENCES `tas`.`OBYWATELE` (`PESEL`) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB; SET SQL_MODE=@OLD_SQL_MODE; SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS; SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS; /*fffffffffffffffffffffffffffffffffffffffffffffffffffffff*/ SELECT * from Obywatele<file_sep>/Prototyp/test.py #!/usr/bin/env python # -*- coding: utf-8 -*- from flask import Flask, render_template, request, json, session, redirect, url_for, send_from_directory from pony.orm import * from werkzeug import secure_filename from flask_images import * import os import sys reload(sys) sys.setdefaultencoding("utf8") app = Flask(__name__) app.secret_key = "sekret" app.config["DEBUG"] = True app.config["UPLOAD_FOLDER"] = "static/" app.config["ALLOWED_EXTENSIONS"] = set(["png", "jpg", "jpeg"]) images = Images(app) tas = Database() class Obywatele(tas.Entity): PESEL = PrimaryKey(str) email = Required(str) #email = Required(str) haslo = Optional(str) wyborcy = Optional("Wyborcy") zdjecie = Required(unicode, default="default.jpg") class Wyborcy(tas.Entity): imie = Optional(unicode) nazwisko = Optional(unicode) nr_dowodu = Optional(str, unique=True) ulica = Optional(unicode) nr_lokalu = Optional(str) kod_pocztowy = Optional(str) miejscowosc = Optional(unicode) czy_glosowal = Optional(bool) wyksztalcenie = Optional(unicode) kraj_pochodzenia = Optional(str) wiek = Optional(int) czy_ubezwlasnowolniony = Optional(bool) #haslo_tymczasowe = Required(str) haslo_tymczasowe = Optional(str) nr_telefonu = Optional(int, unique=True) OBYWATELE_PESEL = PrimaryKey(Obywatele) ''' class Obywatele(tas.Entity): PESEL = PrimaryKey(str) email = Required(str, unique=True) haslo = Required(str, unique=True) #haslo = Optional(str) ''' #tas.bind("mysql", host = "localhost", user = "root", passwd = "<PASSWORD>", db = "tas") tas.bind("sqlite", "database2.sqlite", create_db=True) tas.generate_mapping(create_tables=True) def format(nazwa_pliku): return '.' in nazwa_pliku and nazwa_pliku.rsplit('.', 1)[1] in app.config["ALLOWED_EXTENSIONS"] @app.route('/') def main(): if "username" in session: pesel = session["username"] return render_template("index.html", pesel = pesel) return render_template("index.html") ''' @app.route("/wylistowanieWyborow") def wylistowanieWyborow(): lista_wyborow = [] lista_wyborow.append("Wybory na kanclerza") lista_wyborow.append("Wybory na prezydenta") return render_template("wybory.html", wyb = lista_wyborow, pesel = session["username"]) ''' @app.route("/wybory") def wybory(): if "username" in session: pesel = session["username"] lista_wyborow = [] # ze względu na wymóg braku spacji w linku musiałem dodać '_' lista_wyborow.append("wybory_na_kanclerza") lista_wyborow.append("wybory_na_prezydenta") return render_template("wybory.html", pesel = pesel, wyb = lista_wyborow) else: return redirect("main") #lista_wyborow = [] # z bazy trzeba będzie pobierać wszystkie wybory dziejące się aktualnie # aktualnie przykładowe, bez użycia bazy #lista_wyborow.append("Wybory na kanclerza") #lista_wyborow.append("Wybory na prezydenta") #return redirect("wylistowanieWyborow") #return render_template("wybory.html", wyb = lista_wyborow, pesel = session["username"]) ''' @app.route("/zdjecie", methods = ["POST"]) def zdjecie(): file = request.files["plik"] #f.save(secure_filename(f.filename)) if file and format(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config["UPLOAD_FOLDER"], filename)) return redirect(url_for("profil", filename = filename)) with db_session: print f.filename Obywatele[session["username"]].zdjecie = f.filename commit() return redirect("profil") #sciezka = "/static/" + f.filename #if "username" in session: # with db_session: # pro = Wyborcy.get(OBYWATELE_PESEL = session["username"]) # return redirect("profil") return render_template("profil.html", pesel = session["username"], imie = "Jan", nazwisko = "Nowak", nr_dowodu = "ABC123456", ulica = "Testowa", nr_lokalu = "0", kod_pocztowy = "12-345", miejscowosc = "ąćęłńóśżź", wyksztalcenie = "Podstawowe", kraj_pochodzenia = "Polska", wiek = "20", nr_telefonu = "123456789", zdjecie = sciezka) # return render_template("profil.html", pesel = session["username"], imie = pro.imie, # nazwisko = pro.nazwisko, nr_dowodu = pro.nr_dowodu, # ulica = pro.ulica, nr_lokalu = pro.nr_lokalu, # kod_pocztowy = pro.kod_pocztowy, miejscowosc = pro.miejscowosc, # wyksztalcenie = pro.wyksztalcenie, # kraj_pochodzenia = pro.kraj_pochodzenia, wiek = pro.wiek, # nr_telefonu = pro.nr_telefonu, zdjecie = ) #return redirect("profil") ''' ''' @app.route("/kandydaci") def kandydaci(): @app.route("/kandydat") def kandydat(): @app.route("/glosowanie") def glosowanie(): #<EMAIL>("/panel") #def panel(): ''' @app.route("/pokazLogowanie/") def pokazLogowanie(): return render_template("logowanie.html") @app.route("/pokazRejestracja/") def pokazRejestracja(): return render_template("rejestracja.html") #AKTUALNA FUNKCJA NA DOLE @app.route("/pokazProfil", methods = ["POST", "GET"]) def pokazProfil(): with db_session: obywatel = Obywatele.get(PESEL = session["username"]) wyborca = Wyborcy.get(OBYWATELE_PESEL = session["username"]) #img_url = url_for("static", filename = obywatel.zdjecie) img_url = url_for("static", filename = obywatel.zdjecie) if obywatel: #if wyborca: #return render_template("profil.html", ...) # PRZYKŁAD: return render_template("profil.html", pesel = session["username"], imie = "Jan", nazwisko = "Nowak", img_url = img_url) else: #return redirect("edycjaProfilu") return redirect("main") #return render_template("profil.html", ...) ''' @app.route("/pokazProfil", methods = ["POST", "GET"]) def pokazProfil(): f = request.files["zdjecie"] f.save(secure_filename(f.filename)) nazwa = secure_filename(f.filename) with db_session: Obywatele[session["username"]].zdjecie = nazwa commit() with db_session: obywatel = Obywatele.get(PESEL = session["username"]) wyborca = Wyborcy.get(OBYWATELE_PESEL = session["username"]) img_url = url_for("static", filename = obywatel.zdjecie) if obywatel: #if wyborca: #return render_template("profil.html", ...) # PRZYKŁAD: return render_template("profil.html", imie = "Jan", nazwisko = "Nowak", img_url = img_url) else: #return redirect("edycjaProfilu") return redirect("main") #return render_template("profil.html", ...) ''' @app.route("/zmianaZdjecia", methods = ["POST", "GET"]) def zmianaZdjecia(): f = request.files["zdjecie"] nazwa = secure_filename(f.filename) #f.save(secure_filename(f.filename)) #f.save(secure_filename(os.path.join(app.config["UPLOAD_FOLDER"], nazwa))) f.save("static/" + secure_filename(nazwa)) with db_session: Obywatele[session["username"]].zdjecie = nazwa commit() return redirect("pokazProfil") # @app.route("/zmianaZdjecia") # def zmianaZdjecia(): # f = request.files["zdjecie"] # f.save(secure_filename(f.filename)) # nazwa = secure_filename(f.filename) # with db_session: # Obywatele[session["username"]].zdjecie = nazwa # commit() # print nazwa # return redirect("pokazProfil") @app.route("/edycjaProfilu") def edycjaProfilu(): return render_template("edycjaProfilu.html") @app.route("/rejestracja", methods = ["POST", "GET"]) def rejestracja(): _pesel = request.form["inputPesel"] _email = request.form["inputEmail"] _haslo = request.form["inputPassword"] print "Wpisany PESEL: " + _pesel if _pesel and _email and _haslo: with db_session: Obywatele(PESEL = _pesel, email = _email, haslo = _haslo) commit() #return json.dumps({"message": "Użytkownik stworzony pomyślnie."}) return json.dumps("Użytkownik stworzony pomyślnie.").encode("utf8") ''' @app.route("/profil", methods = ["GET", "POST"]) def profil(): if request.method == "GET": f = request.files["plik"] f.save(secure_filename(f.filename)) with db_session: Obywatele[session["username"]].zdjecie = f.filename commit() #if session["image"] == "default.jpg": #session["image"] = "default.jpg" #img_url = url_for("static", filename=os.path.join('imgs', choice(names))) #<img src={{ url_for("static", filename={{ img }} ) }} /> if "username" in session: with db_session: wynik = Wyborcy.get(OBYWATELE_PESEL = session["username"]) obywatel = Obywatele.get(PESEL = session["username"]) img_url = url_for("static", filename = obywatel.zdjecie) # return render_template("profil.html", pesel = wynik.PESEL, imie = pro.imie, # nazwisko = pro.nazwisko, nr_dowodu = pro.nr_dowodu, # ulica = pro.ulica, nr_lokalu = pro.nr_lokalu, # kod_pocztowy = pro.kod_pocztowy, miejscowosc = pro.miejscowosc, # wyksztalcenie = pro.wyksztalcenie, # kraj_pochodzenia = pro.kraj_pochodzenia, wiek = pro.wiek, # nr_telefonu = pro.nr_telefonu) return render_template("profil.html", pesel = session["username"], imie = "Jan", nazwisko = "Nowak", nr_dowodu = "ABC123456", ulica = "Testowa", nr_lokalu = "0", kod_pocztowy = "12-345", miejscowosc = "ąćęłńóśżź", wyksztalcenie = "Podstawowe", kraj_pochodzenia = "Polska", wiek = "20", nr_telefonu = "123456789", img_url = img_url) else: return render_template("profil.html") ''' @app.route("/logowanie", methods = ["POST"]) def logowanie(): _pesel = request.form["inputPesel"] _haslo = request.form["inputPassword"] #haslo = "" pro = "" wynik = "" if _pesel and _haslo: with db_session: wynik = Obywatele.get(PESEL = _pesel, haslo = _haslo) if wynik: session["username"] = wynik.PESEL with db_session: pro = Wyborcy.get(OBYWATELE_PESEL = wynik.PESEL) # return render_template("profil.html", pesel = wynik.PESEL, imie = pro.imie, # nazwisko = pro.nazwisko, nr_dowodu = pro.nr_dowodu, # ulica = pro.ulica, nr_lokalu = pro.nr_lokalu, # kod_pocztowy = pro.kod_pocztowy, miejscowosc = pro.miejscowosc, # wyksztalcenie = pro.wyksztalcenie, # kraj_pochodzenia = pro.kraj_pochodzenia, wiek = pro.wiek, # nr_telefonu = pro.nr_telefonu) #return redirect("profil") return redirect("pokazProfil") else: return json.dumps({"message": "Błędne dane!"}).encode("utf8") #return redirect("logowanie") #print "TO CIEKAWE" #print session["username"] #return render_template("profil.html", pesel = session["username"]) #return redirect("profil") '''return render_template("profil.html", pesel = session["username"], imie = "Jan", nazwisko = "Nowak", nr_dowodu = "ABC123456", ulica = "Testowa", nr_lokalu = "0", kod_pocztowy = "12-345", miejscowosc = "ąćęłńóśżź", wyksztalcenie = "Podstawowe", kraj_pochodzenia = "Polska", wiek = "20", nr_telefonu = "123456789")''' #return render_template("profil.html") #return json.dumps({"message": "Użytkownik zalogowany pomyślnie."}) #return render_template("profil.html", imie=, nazwisko=,) #return render_template("index.html") #return redirect(url_for(haslo)) ''' @app.route("/logowanie/<obywatel>", methods = ["POST"]) def logowanie(obywatel): _pesel = request.form["inputPesel"] _haslo = request.form["inputPassword"] haslo = "" if _pesel and _haslo: with db_session: wynik = select(o for o in Obywatele if getattr(o, haslo) == _haslo) pesel = wynik.PESEL haslo = wynik.haslo #return json.dumps({"message": "Użytkownik zalogowany pomyślnie."}) #return redirect(url_for(haslo)) @app.route("/profil/<obywatel>/", methods = ["GET", "POST"]) def profil(obywatel): with db_session: wynik = select(o for o in Obywatele) wynik.PESEL ''' if __name__ == "__main__": app.run(host="0.0.0.0", port = 5000) """ @app.route('/login/', methods=["GET","POST"]) def login_page(): error = '' try: c, conn = connection() if request.method == "POST": data = c.execute("SELECT * FROM users WHERE username = (%s)", thwart(request.form['username'])) data = c.fetchone()[2] if sha256_crypt.verify(request.form['password'], data): session['logged_in'] = True session['username'] = request.form['username'] flash("You are now logged in") return redirect(url_for("dashboard")) else: error = "Invalid credentials, try again." gc.collect() return render_template("login.html", error=error) except Exception as e: #flash(e) error = "Invalid credentials, try again." return render_template("login.html", error = error) """
ade4f7a0f3c335b08830d503ad862982324edbfe
[ "Markdown", "SQL", "Python" ]
7
Markdown
Micik2/WyboryElektroniczne
4f219b74a02d79774b90ba575641785f7c41679e
d2d6948f5dd5051233c97bb8d37c64bb583081ed
refs/heads/main
<repo_name>ahmetbozaci/testing-practise<file_sep>/string-capitalize.test.js const capitalize = require('./string-capitalize'); test('Argument first letter should capitalized', () => { expect(capitalize('hello')).toBe('Hello') }) test('Argument should be a string', () => { expect(() => { capitalize(41); }).toThrow(); }) <file_sep>/string-reverse.js const reverseString = (string) => { let arr = []; arr = string.split(''); arr.reverse() return arr.join('') } module.exports = reverseString <file_sep>/string-length.test.js // Arrange const stringLength = require('./string-length'); it('"Hello" length equal to 5', () => { expect(stringLength("Hello")).toBe(5); }); it('String length cannot less than 1', () => { expect(() => { stringLength("");}).toThrow(); }); it('String length cannot longer than 10', () => { expect(() => { stringLength("Hello world");}).toThrow(); }); <file_sep>/README.md ### Unit test practise for Javascript using Jest <file_sep>/string-length.js const stringLength = (string) => { if (string.length > 1 && string.length < 10) { return string.length } throw new Error('The length of the string has to be between 1 and 10.'); } module.exports = stringLength;<file_sep>/calculator.js class Calculator { add(num1, num2) { return num1 + num2; } subtract(num1, num2) { return num1 - num2; } divide(num1, num2) { return num1 / num2; } multiply(num1, num2) { return num1 * num2; } } const cal = new Calculator() console.log(cal.multiply(1.8,0.5)) module.exports = new Calculator();<file_sep>/calculator.test.js const Calculator = require('./calculator') describe('Add', () => { it('10+20 equal to 30', () => { expect(Calculator.add(10,20)).toBe(30) }); it('10+20.5 equal to 30.5', () => { expect(Calculator.add(10,20.5)).toBe(30.5) }); it('0.1+0.2 equal to 0.3', () => { expect(Calculator.add(0.1,0.2)).toBeCloseTo(0.3) }); }) describe('Subtract', () => { it('20-10 equal to 10', () => { expect(Calculator.subtract(20,10)).toBe(10) }); it('10-20 equal to -10', () => { expect(Calculator.subtract(10,20)).toBe(-10) }); it('50-20 equal to 30', () => { expect(Calculator.subtract(50,20)).toBe(30) }); }) describe('Divide', () => { it('20/10 equal to 2', () => { expect(Calculator.divide(20,10)).toBe(2) }); it('10/20 equal to 0.5', () => { expect(Calculator.divide(10,20)).toBe(0.5) }); it('50/0 equal to Infinity', () => { expect(Calculator.divide(50,0)).toBe(Infinity) }); }) describe('Multiply', () => { it('20*10 equal to 200', () => { expect(Calculator.multiply(20,10)).toBe(200) }); it('0.5*0.3 equal to 0.15', () => { expect(Calculator.multiply(0.5,0.3)).toBe(0.15) }); it('50*0 equal to 0', () => { expect(Calculator.multiply(50,0)).toBe(0) }); })<file_sep>/string-reverse.test.js const reverseString = require('./string-reverse'); it('"Langugage" reverse is egaugnaL', () => { expect(reverseString('Language')).toBe('egaugnaL'); });
528c9369a28de7a2207d76b7ef8955346f84af7e
[ "JavaScript", "Markdown" ]
8
JavaScript
ahmetbozaci/testing-practise
600d35207e3b4bb08c4c90ce91c6c9711bffdced
10e070a33aabeebec9a3599dae602e6b34cf2317
refs/heads/master
<repo_name>Dev-Daljeet/CarDealershipSystem<file_sep>/src/main/java/com/devdaljeet/cardealershipsystem/database/DatabaseAccess.java package com.devdaljeet.cardealershipsystem.database; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.stereotype.Repository; import com.devdaljeet.cardealershipsystem.beans.Car; /**Represents the access class which manipulates the database * @author <NAME> * @version 1.0 */ @Repository public class DatabaseAccess { @Autowired NamedParameterJdbcTemplate jdbc; /**Adds a car to database * @param car An instance of class Car */ public void addCar(Car car) { MapSqlParameterSource parameters = new MapSqlParameterSource(); //query is not vulnerable to sql injection because all dealership inputs are taken from valid array String query = String.format("INSERT INTO %s (make, model, colour, price, vin) VALUES (:make, :model, :colour, :price, :vin)",car.getDealership()); parameters.addValue("make",car.getMake()); parameters.addValue("model",car.getModel()); parameters.addValue("colour",car.getColour()); parameters.addValue("price",car.getPrice()); parameters.addValue("vin",car.getVin()); jdbc.update(query, parameters); } /**Returns/gets all cars from database * @param dealership A string which represents the name of car dealership * @return cars An array list of all cars */ public ArrayList<Car> getCars(String dealership){ ArrayList<Car> cars = new ArrayList<>(); String query = String.format("SELECT * FROM %s", dealership); List<Map<String, Object>> rows = jdbc.queryForList(query, new HashMap<String,Object>()); for(Map<String, Object> row: rows) { Car car= new Car(); car.setId((Integer)(row.get("id"))); car.setMake((String)(row.get("make"))); car.setModel((String)(row.get("model"))); car.setColour((String)(row.get("colour"))); car.setPrice(((BigDecimal)(row.get("price"))).doubleValue()); car.setVin((String)(row.get("vin"))); car.setDealership((String)dealership); cars.add(car); } return cars; } /**Returns/gets a car of specific ID from database * @param id An integer which represents the ID of a car in dealership * @param dealership A string which represents the name of car dealership * @return car An instance of class Car */ public Car getCarById(int id, String dealership) { MapSqlParameterSource parameters = new MapSqlParameterSource(); ArrayList<Car> cars = new ArrayList<>(); String query = String.format("SELECT * FROM %s WHERE id=:id", dealership); parameters.addValue("id",id); List<Map<String, Object>> rows = jdbc.queryForList(query, parameters); for(Map<String, Object> row: rows) { Car car= new Car(); car.setId((Integer)(row.get("id"))); car.setMake((String)(row.get("make"))); car.setModel((String)(row.get("model"))); car.setColour((String)(row.get("colour"))); car.setPrice(((BigDecimal)(row.get("price"))).doubleValue()); car.setVin((String)(row.get("vin"))); car.setDealership((String)dealership); cars.add(car); } if(cars.size()>0) { return cars.get(0); } else { return null; } } /**Edits/Updates a car in database * @param car An instance of class Car * @return A boolean value which checks if car is transfered to new dealership or not */ public boolean editCar(Car car) { MapSqlParameterSource parameters = new MapSqlParameterSource(); String query; if(car.getDealership().equals(car.getNewDealership())) { query = String.format("UPDATE %s SET make=:make,model=:model,colour=:colour,price=:price,vin=:vin where id=:id",car.getDealership()); parameters.addValue("make",car.getMake()); parameters.addValue("model",car.getModel()); parameters.addValue("colour",car.getColour()); parameters.addValue("price",car.getPrice()); parameters.addValue("vin",car.getVin()); parameters.addValue("id",car.getId()); jdbc.update(query, parameters); return false; } else { query = String.format("INSERT INTO %s (make, model, colour, price, vin) VALUES (:make, :model, :colour, :price, :vin)",car.getNewDealership()); parameters.addValue("make",car.getMake()); parameters.addValue("model",car.getModel()); parameters.addValue("colour",car.getColour()); parameters.addValue("price",car.getPrice()); parameters.addValue("vin",car.getVin()); parameters.addValue("id",car.getId()); jdbc.update(query, parameters); return true; } } /**Delete a car from database * @param id An integer which represents the ID of a car in dealership * @param dealership A string which represents the name of car dealership */ public void deleteCar(int id, String dealership) { MapSqlParameterSource parameters = new MapSqlParameterSource(); String query = String.format("DELETE FROM %s WHERE id=:id",dealership); parameters.addValue("id",id); jdbc.update(query, parameters); } /**Returns/gets cars of specific ID from database * @param id An integer which represents the ID of a car in dealership * @param dealership A string which represents the name of car dealership * @return cars An array list of cars */ public ArrayList<Car> searchCarById(int id, String dealership) { MapSqlParameterSource parameters = new MapSqlParameterSource(); ArrayList<Car> cars = new ArrayList<>(); String query = String.format("SELECT * FROM %s WHERE id=:id", dealership); parameters.addValue("id",id); List<Map<String, Object>> rows = jdbc.queryForList(query, parameters); for(Map<String, Object> row: rows) { Car car= new Car(); car.setId((Integer)(row.get("id"))); car.setMake((String)(row.get("make"))); car.setModel((String)(row.get("model"))); car.setColour((String)(row.get("colour"))); car.setPrice(((BigDecimal)(row.get("price"))).doubleValue()); car.setVin((String)(row.get("vin"))); car.setDealership((String)dealership); cars.add(car); } return cars; } /**Returns/gets cars of specific make from database * @param make A String which represents the make of a car in dealership * @param dealership A string which represents the name of car dealership * @return cars An array list of cars */ public ArrayList<Car> searchCarByMake(String make, String dealership) { MapSqlParameterSource parameters = new MapSqlParameterSource(); ArrayList<Car> cars = new ArrayList<>(); String query = String.format("SELECT * FROM %s WHERE make=:make", dealership); parameters.addValue("make",make); List<Map<String, Object>> rows = jdbc.queryForList(query, parameters); for(Map<String, Object> row: rows) { Car car= new Car(); car.setId((Integer)(row.get("id"))); car.setMake((String)(row.get("make"))); car.setModel((String)(row.get("model"))); car.setColour((String)(row.get("colour"))); car.setPrice(((BigDecimal)(row.get("price"))).doubleValue()); car.setVin((String)(row.get("vin"))); car.setDealership((String)dealership); cars.add(car); } return cars; } /**Returns/gets cars of specific model from database * @param modelForCar A String which represents the model of a car in dealership * @param dealership A string which represents the name of car dealership * @return cars An array list of cars */ public ArrayList<Car> searchCarByModel(String modelForCar, String dealership) { MapSqlParameterSource parameters = new MapSqlParameterSource(); ArrayList<Car> cars = new ArrayList<>(); String query = String.format("SELECT * FROM %s WHERE model=:model", dealership); parameters.addValue("model",modelForCar); List<Map<String, Object>> rows = jdbc.queryForList(query, parameters); for(Map<String, Object> row: rows) { Car car= new Car(); car.setId((Integer)(row.get("id"))); car.setMake((String)(row.get("make"))); car.setModel((String)(row.get("model"))); car.setColour((String)(row.get("colour"))); car.setPrice(((BigDecimal)(row.get("price"))).doubleValue()); car.setVin((String)(row.get("vin"))); car.setDealership((String)dealership); cars.add(car); } return cars; } /**Returns/gets cars of specific price from database * @param min An double which represents the minimum price of a car * @param max An double which represents the maximum price of a car * @param dealership A string which represents the name of car dealership * @return cars An array list of cars */ public ArrayList<Car> searchCarByPrice(double min, double max, String dealership) { MapSqlParameterSource parameters = new MapSqlParameterSource(); ArrayList<Car> cars = new ArrayList<>(); String query = String.format("SELECT * FROM %s WHERE price BETWEEN :min AND :max", dealership); parameters.addValue("min",min); parameters.addValue("max",max); List<Map<String, Object>> rows = jdbc.queryForList(query, parameters); for(Map<String, Object> row: rows) { Car car= new Car(); car.setId((Integer)(row.get("id"))); car.setMake((String)(row.get("make"))); car.setModel((String)(row.get("model"))); car.setColour((String)(row.get("colour"))); car.setPrice(((BigDecimal)(row.get("price"))).doubleValue()); car.setVin((String)(row.get("vin"))); car.setDealership((String)dealership); cars.add(car); } return cars; } } <file_sep>/src/main/resources/schema.sql CREATE TABLE Deals_on_Wheels (id INT NOT NULL Primary Key AUTO_INCREMENT, make VARCHAR(100), model VARCHAR(100), colour VARCHAR(100), price DECIMAL(12,2), vin VARCHAR(100)); INSERT INTO Deals_on_Wheels (make, model, colour, price, vin) VALUES ('Audi','Q5 Kmofort','Black',31900.00,'2FMZA53441BB85939'), ('Arctic Cat',' JAGUAR Z1 1100 EFI SNO PRO','Silver',5555.11,'1C3EL554X1N596684'), ('Sterling Truck','CONDOR','Grey',12500.00,'5TDZK3EH0AS022676'), ('<NAME>', 'GATOR HPX 4X4','Green',200000.00,'4T1BF3EKXAU500241'), ('Sea-Doo', 'GTX LIMITED IS 260' ,'Black',100000.00,'1FTWW3BR9AEA82577'), ('Ford', 'E-250 ECONOLINE','Brown',3342.50,'2G1WT58K469257903'), ('Audi', 'A3','Red',22200.00,'3GCPKSE78CG269227'), ('Can-Am', 'OUTLANDER MAX 500 HO EFI','Red',34000.50,'4T1BG22K4YU930756'), ('Kawasaki', 'KX65','White',44000.50,'JHMES155X5S093338'), ('Ski-Doo', 'ELITE', 'Blue',5000.00,'5N1AN08W15C645434'); CREATE TABLE Steals_and_Deals (id INT NOT NULL Primary Key AUTO_INCREMENT, make VARCHAR(100), model VARCHAR(100), colour VARCHAR(100), price DECIMAL(12,2), vin VARCHAR(100)); INSERT INTO Steals_and_Deals (make, model, colour, price, vin) VALUES ('Sea-Doo', 'GTI RFI', 'Green', 12000.50, '1G8ZP128XXZ300334'), ('Ferrari', '599 GTB', 'Red', 22500.00, '1FTHF25M5RNB23608'), ('Ud', '2300DH', 'Black', 20000.00, '1FDKF37G0VEB60218'), ('Arctic Cat', 'JAGUAR Z1 1100 EFI SNO PRO','Silver',5555.11,'4T1BG22K1XU418953'), ('Arctic Cat', 'FIRECAT 600', 'Grey', 23300.50,'1GNSKCE04DR286926'), ('<NAME>', 'GATOR HPX 4X4','Green',200000.00,'4T1BF3EKXAU500241'), ('Suzuki', 'GSX1300R HAYABUSA', 'Blue', 14000.00, '1J8HG58256C284291'), ('Sea-Doo', 'GTX LIMITED IS 260' ,'Black',100000.00,'KLATA52611B629899'), ('Honda', 'AQUATRAX R-12', 'Silver', 23000.00, '1C3CDFBA1DD312227'), ('Ford', 'E-250 ECONOLINE','Brown',3344.50,'5N1AA08A46N713649'); CREATE TABLE Rhyme_and_Crime (id INT NOT NULL Primary Key AUTO_INCREMENT, make VARCHAR(100), model VARCHAR(100), colour VARCHAR(100), price DECIMAL(12,2), vin VARCHAR(100)); INSERT INTO Rhyme_and_Crime (make, model, colour, price, vin) VALUES ('Honda', 'GL1800 GOLD WING AIRBAG', 'Green',4000.00, '1FAFP66L0XK281117'), ('Sea-Doo', 'GTI RFI', 'Green', 12500.00, '1G8ZP128XXZ300334'), ('Aprilia', 'ETV 1000 CAPONORD', 'White', 23400.50, 'JF2SJADC9FH462228'), ('Ferrari', '599 GTB', 'Red', 22000.00, '5YFBURHE0EP122632'), ('Chevrolet', 'OPTRA', 'Yellow', 43000.00, '2CNFLEEW1A6241405'), ('Ud', '2300DH', 'Silver', 20000.00, '1FDKF37G0VEB60218'), ('Peugeot', 'PARTNER', 'Black', 34500.50, '4T4BE46K29R024916'), ('<NAME>', 'GATOR HPX 4X4','Green',204000.00,'5XYZU3LB6EG175235'), ('Ford', 'E-250 ECONOLINE','Brown',3344.50,'1HTWEAAR94J033399'), ('Audi','Q5 Kmofort','Black',31900.00,'2T2HA31U44C082535'); <file_sep>/src/main/java/com/devdaljeet/cardealershipsystem/controllers/HomeController.java package com.devdaljeet.cardealershipsystem.controllers; import java.text.DecimalFormat; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestParam; import com.devdaljeet.cardealershipsystem.beans.Car; import com.devdaljeet.cardealershipsystem.database.DatabaseAccess; /**Represents a controller which has all URL mappings * @author <NAME> * @version 1.0 */ @Controller public class HomeController { @Autowired private DatabaseAccess dataObj; /**Directs to home page of application * @return A HTML page which acts as home page */ @GetMapping("/") public String goHome(Model model) { return "home.html"; } /**Directs to add page through which user can add a car * @return A HTML page which acts as add car page */ @GetMapping("/list") public String goToAddCarPage(Model model) { model.addAttribute("car", new Car()); return "addCar.html"; } /**Adds the car to the database * @return A HTML page which acts as add car page */ @GetMapping("/add") public String addCar(Model model, @ModelAttribute Car car) { dataObj.addCar(car); model.addAttribute("car",new Car()); return "addCar.html"; } /**Views/Returns all cars present in database * @return A HTML page which acts as view car page */ @GetMapping("/view") public String viewCars(Model model) { model.addAttribute("carsFromD1",dataObj.getCars("Deals_on_Wheels")); model.addAttribute("carsFromD2",dataObj.getCars("Steals_and_Deals")); model.addAttribute("carsFromD3",dataObj.getCars("Rhyme_and_Crime")); return "viewCar.html"; } /**Directs to edit car page for editing the properties of car * @return A HTML page which acts as edit car page */ @GetMapping("/edit/{dealership}/{id}") public String goToEditPage(Model model, @PathVariable String dealership, @PathVariable int id){ Car car = dataObj.getCarById(id, dealership); car.setNewDealership(dealership); model.addAttribute("car", car); return "editCar.html"; } /**Saves the edited properties of a car to database * @return (Redirects to) A HTML page which acts as view car page */ @GetMapping("/edit") public String editCar(Model model, @ModelAttribute Car car) { boolean checkTransfer = dataObj.editCar(car); if(checkTransfer == true) { dataObj.deleteCar(car.getId(), car.getDealership()); } return "redirect:/view"; } /**Delete the car from database * @return (Redirects to) A HTML page which acts as view car page */ @GetMapping("/delete/{dealership}/{id}") public String deleteCar(Model model, @PathVariable String dealership, @PathVariable int id){ dataObj.deleteCar(id, dealership); return "redirect:/view"; } /**Directs to search page for searching a car * @return A HTML page which acts as search car page */ @GetMapping("/search") public String goToSearchPage() { return "searchCar.html"; } /**Searches the car by ID and returns the result * @return A HTML page which acts as view car page */ @GetMapping("/searchId") public String searchCarId(Model model, @RequestParam int id) { model.addAttribute("carsFromD1",dataObj.searchCarById(id,"Deals_on_Wheels")); model.addAttribute("carsFromD2",dataObj.searchCarById(id,"Steals_and_Deals")); model.addAttribute("carsFromD3",dataObj.searchCarById(id,"Rhyme_and_Crime")); return "viewCar.html"; } /**Searches the car by make and returns the result * @return A HTML page which acts as view car page */ @GetMapping("/searchMake") public String searchCarMake(Model model, @RequestParam String make) { model.addAttribute("carsFromD1",dataObj.searchCarByMake(make,"Deals_on_Wheels")); model.addAttribute("carsFromD2",dataObj.searchCarByMake(make,"Steals_and_Deals")); model.addAttribute("carsFromD3",dataObj.searchCarByMake(make,"Rhyme_and_Crime")); return "viewCar.html"; } /**Searches the car by model and returns the result * @return A HTML page which acts as view car page */ @GetMapping("/searchModel") public String searchCarModel(Model model, @RequestParam String modelForCar) { model.addAttribute("carsFromD1",dataObj.searchCarByModel(modelForCar,"Deals_on_Wheels")); model.addAttribute("carsFromD2",dataObj.searchCarByModel(modelForCar,"Steals_and_Deals")); model.addAttribute("carsFromD3",dataObj.searchCarByModel(modelForCar,"Rhyme_and_Crime")); return "viewCar.html"; } /**Searches the car by price range (min-max) and returns the result * @return A HTML page which acts as view car page */ @GetMapping("/searchPrice") public String searchCarPrice(Model model, @RequestParam double min, @RequestParam double max ) { model.addAttribute("carsFromD1",dataObj.searchCarByPrice(min,max,"Deals_on_Wheels")); model.addAttribute("carsFromD2",dataObj.searchCarByPrice(min,max,"Steals_and_Deals")); model.addAttribute("carsFromD3",dataObj.searchCarByPrice(min,max,"Rhyme_and_Crime")); return "viewCar.html"; } /**Return a receipt page of the car and delete the car from database * @return A HTML page which acts as receipt page for car */ @GetMapping("/purchase/{dealership}/{id}") public String purchaseCar(Model model, @PathVariable String dealership, @PathVariable int id) { Car car = dataObj.getCarById(id, dealership); DecimalFormat decimalFormat = new DecimalFormat("#########0.##"); double taxes=Double.parseDouble(decimalFormat.format(car.getPrice()*0.13)); car.setPrice(Double.parseDouble(decimalFormat.format(car.getPrice()+taxes))); model.addAttribute("car",car); model.addAttribute("taxes",taxes); dataObj.deleteCar(id, dealership); return "receipt.html"; } } <file_sep>/README.md # Car Dealership System This project is a web application which manages the cars sold at three different car dealerships. It performs CRUD (Create, read, update and delete), search and purchase functions/operations on any car from any dealerships. Programming language: Java Java Framework: Spring Boot Type: Maven Dependencies used: Spring Web, Thymeleaf, Lombok, Spring data JDBC and H2 database ## Some sample screenshots of Project ### Homepage ![Screesshot of Homepage](https://github.com/Dev-Daljeet/Screenshots/blob/master/CarDealership/Deafult.jpg?raw=true) ### Add page ![Screesshot of add page](https://github.com/Dev-Daljeet/Screenshots/blob/master/CarDealership/add.jpg?raw=true) ### View page ![Screesshot of view page](https://github.com/Dev-Daljeet/Screenshots/blob/master/CarDealership/view.jpg?raw=true) ### Search page ![Screesshot of search page](https://github.com/Dev-Daljeet/Screenshots/blob/master/CarDealership/search.jpg?raw=true) ## Usage examples (How to use): [![CarDealership](https://res.cloudinary.com/marcomontalbano/image/upload/v1605137890/video_to_markdown/images/youtube--Wh6eOBVedmg-c05b58ac6eb4c4700831b2b3070cd403.jpg)](https://youtu.be/Wh6eOBVedmg "CarDealership") ## Run: ### Prerequisites (Requirements): For building and running the application you need: - [JDK 1.8](http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html) - [Maven 3](https://maven.apache.org) ### Running the application with IDE There are several ways to run a Spring Boot application on your local machine. One way is to execute the `main` method in the `com.devdaljeet.cardealershipsystem.CarDealershipSystemApplication` class from your IDE (Eclipse). * Download the zip or clone the Git repository. * Unzip the zip file (if you downloaded one) * Open Command Prompt and Change directory (cd) to folder containing pom.xml * Open Eclipse * File -> Import -> Existing Maven Project -> Navigate to the folder where you unzipped the zip * Select the project * Choose the Spring Boot Application file (search for @SpringBootApplication) * Right Click on the file and Run as Java Application ### Running the application with Maven Alternatively you can use the [Spring Boot Maven plugin](https://docs.spring.io/spring-boot/docs/current/reference/html/build-tool-plugins-maven-plugin.html) like so: ```shell $ git clone https://github.com/Dev-Daljeet/CarDealershipSystem.git $ cd CarDealershipSystem $ mvn spring-boot:run ``` # License MIT License Copyright (c) 2020 Dev-Daljeet Refer to **LICENSE** file for full information. <file_sep>/src/main/java/com/devdaljeet/cardealershipsystem/controllers/package-info.java package com.devdaljeet.cardealershipsystem.controllers;
1674b4fd4af27c38535f4553e4c252990cecb146
[ "Markdown", "Java", "SQL" ]
5
Java
Dev-Daljeet/CarDealershipSystem
47d13509e9997e4b51d0dbb37727ef35fab314c1
0da02605953fe84a9775cbb798f4db78e03be479
refs/heads/master
<repo_name>Amankaium/cloud<file_sep>/mainapp/admin.py from django.contrib import admin from .models import * # Register your models here. class OrderAdmin(admin.ModelAdmin): model = Order list_display = ['username', 'date_create', 'date_update', 'email', 'phone'] admin.site.register(Order, OrderAdmin) <file_sep>/mainapp/models.py from django.db import models # Create your models here. class Order(models.Model): username = models.CharField(max_length=50) email = models.EmailField(max_length=50) phone = models.CharField(max_length=50) text = models.TextField(null=True, blank=True) date_create = models.DateTimeField(null=True, blank=True, auto_now_add=True) date_update = models.DateTimeField(null=True, blank=True, auto_now=True) def __str__(self): return self.email <file_sep>/mainapp/views.py from django.shortcuts import render from .forms import * # Create your views here. def home(request): return render(request, 'mainapp/home.html') def contact_us(request): form = ContactForm() context = {} context['form'] = form return render(request, 'mainapp/contact_us.html', context) <file_sep>/mainapp/urls.py from django.urls import path from .views import * urlpatterns = [ path('', home, name='home'), path('contact_us/', contact_us, name='contact_us') ]
a4f05bc53d3e20da4d088ccfdc94efc0fddf1d35
[ "Python" ]
4
Python
Amankaium/cloud
ce8598980a7399f23ad5d6756787ded44bdb2f31
e0b71d4e72b6e817d2c6029a72921a0435d4a065
refs/heads/master
<file_sep># gulp-continuation > A compiler for JavaScript asynchronous Continuation-Passing Style transformation ## Installation Install package with NPM and add it to your development dependencies: `npm install --save-dev gulp-continuation` ## Usage For using with browserify there is [continuatify](https://github.com/alhimik45/continuatify) transformer. It supports [gulp-sourcemaps](https://github.com/floridoo/gulp-sourcemaps), so use it if you want source maps. ```javascript var gulp = require('gulp'); var continuation = require('gulp-continuation'); gulp.task('js', function () { return gulp.src(['js/**/*.js']) .pipe(continuation()) .pipe(gulp.dest('build')) }); ``` ## Options You can pass all options available for [continuation.js](https://github.com/BYVoid/continuation/) ## Errors `gulp-continuation` emits an 'error' event if there is unparseable code in the passed file. `message` property of 'error' contains description. <file_sep>var continuation = require('continuation'); var through = require('through2'); var gutil = require('gulp-util'); var applySourceMap = require('vinyl-sourcemaps-apply'); var PluginError = gutil.PluginError; var PLUGIN_NAME = 'gulp-continuation'; function gulpContinuation(options) { return through.obj(function (file, enc, cb) { if (file.isNull()) { // return empty file return cb(null, file); } if (file.isStream()) { this.emit('error', new PluginError(PLUGIN_NAME, 'Streaming not supported')); return cb(); } if (file.isBuffer()) { if (file.sourceMap) { if(!options){ options = {}; } options.sourceMap = true; } var code = file.contents.toString('utf8'); var compiled = code; try { compiled = continuation.compile(code, options); if (file.sourceMap) { var sourceMap = continuation.getSourceMap(file.sourceMap.file, [file.sourceMap.file]); applySourceMap(file, sourceMap); } } catch (e) { this.emit('error', new PluginError(PLUGIN_NAME, e.message)); return cb(); } file.contents = Buffer.from(compiled); } cb(null, file); }); } module.exports = gulpContinuation; <file_sep>/* global describe, it */ var assert = require('assert'); var File = require('vinyl'); var stream = require('stream'); var gulpContinuation = require('./index'); var continuation = require('continuation'); var code = `function fibonacci() { var a = 0, current = 1; while (true) { var b = a; a = current; current = a + b; setTimeout(cont(), 1000); console.log(current); } };`; var malformedCode = `function fibonacci) { var a = 0, current = 1; while (true) { var b = a; a = current; current = a + b; setTimeout(cont(), 1000); console.log(current); } };`; describe('gulp-continuation', function () { it('should emit same code as plain continuation', function (done) { // create the fake file var fakeFile = new File({ contents: Buffer.from(code) }); // Create a continuation plugin stream var myContinuation = gulpContinuation(); myContinuation.write(fakeFile); myContinuation.once('data', function (file) { assert(file.isBuffer()); assert.equal(file.contents.toString('utf8'), continuation.compile(code)); done(); }); }); it('should emit error if stream passed', function (done) { // create the fake file var fakeFile = new File({ contents: new stream.PassThrough() }); // Create a continuation plugin stream var myContinuation = gulpContinuation(); myContinuation.once('error', function (err) { assert.equal(err.message, 'Streaming not supported'); done(); }); myContinuation.write(fakeFile); }); it('should emit error if malformed code passed', function (done) { // create the fake file var fakeFile = new File({ contents: Buffer.from(malformedCode) }); // Create a continuation plugin stream var myContinuation = gulpContinuation(); myContinuation.once('error', function (err) { assert.equal(err.message, 'Line 1: Unexpected token ) in undefined'); done(); }); myContinuation.write(fakeFile); }); it('should emit same source map as plain continuation', function (done) { // create the fake file var fakeFile = new File({ contents: Buffer.from(code), sourceMap: { file: 'test.js', mappings: '', names: [], sources: ['test1.js'], sourcesContent: [code], version: 3 } }); var plainCompiled = continuation.compile(code, {sourceMap: true}); var plainSourceMap = JSON.parse(continuation.getSourceMap('test.js', ['test.js'])); // Create a continuation plugin stream var myContinuation = gulpContinuation(); myContinuation.write(fakeFile); myContinuation.once('data', function (file) { assert(file.isBuffer()); assert.equal(file.contents.toString('utf8'), plainCompiled); assert.deepEqual(file.sourceMap, plainSourceMap); done(); }); }); });
3e9dd49cbbd14b55fe52b90d05770a30f3eff4ce
[ "Markdown", "JavaScript" ]
3
Markdown
alhimik45/gulp-continuation
fcf43ec8f8cb6d84e5ac8925bd25cdbc97fab1cc
2f79dbae852876191af1a08c27471192328c6c6e
refs/heads/master
<repo_name>summerwind/h2-test-assets<file_sep>/gen.sh #!/bin/bash if [ $# -ne 1 ]; then echo "Usage: $0 [COUNT]" exit 1 fi echo "File size: ${1} KiB" for dir in "js" "css" "images" do for path in `ls -1 ${dir}` do echo -n "Generating ${dir}/${path}..." dd if=/dev/zero of=${dir}/${path} bs=1024 count=${1} > /dev/null 2>&1 echo "done" done done
6d5152f4734f8ba24e2c027dc33e2ad8604f0ad3
[ "Shell" ]
1
Shell
summerwind/h2-test-assets
773d87a697a58e837b30a853f5dadeae5240fa2d
cbbc97410e740f12d009c96ef3fb2e2bf085d353
refs/heads/master
<file_sep>"""personalblogsyte URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include from django.conf.urls import url from blog import views from django.views.generic.base import TemplateView from blog.models import Blog from rest_framework import routers, serializers, viewsets appname = 'blog' # Serializers define the API representation. class BlogSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Blog fields = ['id', 'post', 'author', 'blog_date'] # ViewSets define the view behavior. class BlogViewSet(viewsets.ModelViewSet): queryset = Blog.objects.all() serializer_class = BlogSerializer # Routers provide an easy way of automatically determining the URL conf. router = routers.DefaultRouter() router.register(r'api', BlogViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ path('admin/', admin.site.urls), url(r'^$', views.home, name='home'), path("register/", views.signup, name="signup"), url(r'^index$', views.index, name="index"), url(r'^login$', views.login, name="login"), path('src/templates/login', include('django.contrib.auth.urls')), url(r'^posts$', views.posts, name="posts"), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^', include(router.urls)), ] <file_sep>{% load static %} <!DOCTYPE html> <html lang="en"> <head > <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="{% static 'posts_styles.css' %}"> <title>posts</title> </head> {% block content %} <body> <section> <nav> <div class="dropdown"> <button class="dropbtn">More</button> <div class="dropdown-content"> <a href="{% url 'index'%}">Main page</a> <!--<a href="#">Link 2</a> <a href="#">Link 3</a>--> </div> </nav> </section> {% for post in posts %} <div class="posts"> <h1>Post: {{ post.post }}</h1> <p> Date: {{ post.blog_date }}</p> <p> Author: {{ post.author }}</p> </div> {% endfor %} </body> {% endblock%} </html> <file_sep>from django.contrib.auth import login, authenticate from django.contrib.auth.forms import UserCreationForm from django.shortcuts import render, redirect from django.template import RequestContext from .models import Registration from django.contrib.auth.decorators import login_required from django.http import Http404 from .models import Blog @login_required def home(request): return render(request, 'index.html') @login_required def index(request): return render(request, 'index.html') @login_required def posts(request): posts = Blog.objects.all() return render(request, 'posts.html', {'posts': posts}) def login(request): if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): user = form.save() login(request, user) return redirect("index") else: return redirect("login") form = UserCreationForm() return render(request, 'login.html', {'form': form}) def acc_detail(request, id): try: acc = Registration.objects.get(id=-id) except Registration.DoesNotExist: raise Http404('Acc not found') return render(render, 'acc_detail.html', {'acc': acc}) def signup(request): if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): user = form.save() login(request) return redirect("index") else: for msg in form.error_messages: print(form.error_messages[msg]) form = UserCreationForm return render(request, 'signup.html', {'form': form}) @login_required def post(request): posts = Blog.objects.all() return render(request, 'posts.html', {'posts': posts}) <file_sep># Generated by Django 3.0.2 on 2020-01-22 05:01 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Blog', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('blog_date', models.DateTimeField(verbose_name='Date time')), ('post', models.TextField(blank=True)), ('author', models.CharField(blank=True, max_length=50)), ], ), migrations.CreateModel( name='Registration', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('acc', models.CharField(max_length=50)), ('pas', models.CharField(max_length=50)), ], ), migrations.CreateModel( name='Total', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('total_posts', models.IntegerField()), ], ), ] <file_sep>from django.db import models from django.contrib.auth.models import User from django.db import models from django.db.models import TextField class Registration(models.Model): acc = models.CharField(max_length=50) pas = models.CharField(max_length=50) class Blog(models.Model): blog_date = models.DateTimeField('Date time') post = models.TextField(blank=True) author = models.CharField(max_length=50, blank=True) def __str__(self): return self.post def __int__(self): return self.total_posts
6e23d3a982e4228f7439e772b923435efbe49940
[ "Python", "HTML" ]
5
Python
viktta/pbs
b4a7d24379d8c44bfc2fa979307627fbf8bef3fa
4a1436790ed1d16e8ad784df48274996bd529a33
refs/heads/master
<file_sep>############################################################################ # Created by: Prof. <NAME>, D.Sc. # UFF - Universidade Federal Fluminense (Brazil) # email: <EMAIL> # Course: Metaheuristics # Lesson: Differential Evolution # Citation: # PEREIRA, V. (2018). Project: Metaheuristic-Differential_Evolution, File: Python-MH-Differential Evolution.py, GitHub repository: <https://github.com/Valdecy/Metaheuristic-Differential_Evolution> ############################################################################ # Required Libraries import math import numpy as np import random import os # Function def target_function(): return # Function: Initialize Variables def initial_position(n = 3, min_values = [-5,-5], max_values = [5,5], target_function = target_function): position = np.zeros((n, len(min_values) + 1)) for i in range(0, n): for j in range(0, len(min_values)): position[i,j] = random.uniform(min_values[j], max_values[j]) position[i,-1] = target_function(position[i,0:position.shape[1]-1]) return position # Function: Velocity def velocity(position, best_global, k0 = 0, k1 = 1, k2 = 2, F = 0.9, min_values = [-5,-5], max_values = [5,5], Cr = 0.2, target_function = target_function): v = np.copy(best_global) for i in range(0, len(best_global)): ri = int.from_bytes(os.urandom(8), byteorder = "big") / ((1 << 64) - 1) if (ri <= Cr): v[i] = best_global[i] + F*(position[k1, i] - position[k2, i]) else: v[i] = position[k0, i] if (i < len(min_values) and v[i] > max_values[i]): v[i] = max_values[i] elif(i < len(min_values) and v[i] < min_values[i]): v[i] = min_values[i] v[-1] = target_function(v[0:len(min_values)]) return v # DE Function. DE/Best/1/Bin Scheme. def differential_evolution(n = 3, min_values = [-5,-5], max_values = [5,5], iterations = 50, F = 0.9, Cr = 0.2, target_function = target_function): count = 0 position = initial_position(n = n, min_values = min_values, max_values = max_values, target_function = target_function) best_global = np.copy(position [position [:,-1].argsort()][0,:]) while (count <= iterations): print("Iteration = ", count) for i in range(0, position.shape[0]): k1 = int(np.random.randint(position.shape[0], size = 1)) k2 = int(np.random.randint(position.shape[0], size = 1)) while k1 == k2: k1 = int(np.random.randint(position.shape[0], size = 1)) vi = velocity(position, best_global, k0 = i, k1 = k1, k2 = k2, F = F, min_values = min_values, max_values = max_values, Cr = Cr, target_function = target_function) if (vi[-1] <= position[i,-1]): for j in range(0, position.shape[1]): position[i,j] = vi[j] if (best_global[-1] > position [position [:,-1].argsort()][0,:][-1]): best_global = np.copy(position [position [:,-1].argsort()][0,:]) count = count + 1 print(best_global) return best_global ######################## Part 1 - Usage #################################### # Function to be Minimized (Six Hump Camel Back). Solution -> f(x1, x2) = -1.0316; x1 = 0.0898, x2 = -0.7126 or x1 = -0.0898, x2 = 0.7126 def six_hump_camel_back(variables_values = [0, 0]): func_value = 4*variables_values[0]**2 - 2.1*variables_values[0]**4 + (1/3)*variables_values[0]**6 + variables_values[0]*variables_values[1] - 4*variables_values[1]**2 + 4*variables_values[1]**4 return func_value de = differential_evolution(n = 15, min_values = [-5,-5], max_values = [5,5], iterations = 100, F = 0.5, Cr = 0.2, target_function = six_hump_camel_back) # Function to be Minimized (Rosenbrocks Valley). Solution -> f(x) = 0; xi = 1 def rosenbrocks_valley(variables_values = [0,0]): func_value = 0 last_x = variables_values[0] for i in range(1, len(variables_values)): func_value = func_value + (100 * math.pow((variables_values[i] - math.pow(last_x, 2)), 2)) + math.pow(1 - last_x, 2) return func_value de = differential_evolution(n = 25, min_values = [-5,-5,-5], max_values = [5,5,5], iterations = 1000, F = 0.5, Cr = 0.2, target_function = rosenbrocks_valley)
a6eb6176f7d0ddf77a50d4b6fda99314c2be8cef
[ "Python" ]
1
Python
Valdecy/Metaheuristic-Differential_Evolution
f7d0527b00ec0d22ef4be4ab927165f96f0ff5bc
43a8013e5bd9d878ca4baf93836beccd647128db
refs/heads/master
<repo_name>TraySe7en/Black-Jack<file_sep>/Black Jack/src/me/trayseven/blackjack/Player.java package me.trayseven.blackjack; import java.util.List; public class Player { private List<Card> hand; private int totalPoints; public Player(List<Card> hand, int totalPoints) { this.hand = hand; this.totalPoints = totalPoints; } public void addCard(Card card) { hand.add(card); } public void increaseTotal(int amount) { totalPoints += amount; } } <file_sep>/README.md # Black-Jack Learning experience <file_sep>/Black Jack/src/me/trayseven/blackjack/Deck.java package me.trayseven.blackjack; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Deck { private List<Card> deck; public Deck() { buildDeck(); } public void shuffle() { Collections.shuffle(deck); } public Card draw() { Card draw = deck.get(0); deck.remove(0); return draw; } public void buildDeck() { deck = new ArrayList<>(); for(Value value : Value.values()) { for(Suit suit : Suit.values()) { Card card = new Card(value, suit); deck.add(card); } } } }
186937a23f0cc75324b1cd5cc5719564200252ec
[ "Markdown", "Java" ]
3
Java
TraySe7en/Black-Jack
b989c9170c2fc08e253efb29ad61384186cd9075
3a356e4bead05fd037e2272eb318adf3f0d8fd34
refs/heads/master
<repo_name>VyacheslavBorisovskiy/GitHello02<file_sep>/GitHello02/src/GitHello02.java /* This is a short comment */ /* The second comment */ /* The third comment */ public class GitHello02 { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("Hello, Vyacheslav :)" ); System.out.println("Have a nice day" ); } } <file_sep>/GitHello02/src/Test2.java // Comment 01 into Test2 public class Test2 { }
3441db39c3d058157f0f2640a4859691622896a8
[ "Java" ]
2
Java
VyacheslavBorisovskiy/GitHello02
f8b508babf87c15dd81f3385f62ad5eed902f0af
2dd69693ad6c064f3dafe9d32dac6e4778474cdf
refs/heads/master
<repo_name>karol-preiskorn/php-db-classes<file_sep>/class.db_edit.php <?php //require_once ('funkcje/auth.php'); //require_once ('funkcje/functions.php'); require_once ('class.db.php'); //require_once ('header.php'); /** * * Klasa opracje edycji na bazie danych Oracle 10.2 * 2014-08-27 init * */ class db_edit extends db { public $name = __CLASS__; public $pk; public $operations; public $rights; public $no_rows; public $operations_run; public $action; public function get_pk() { return $this->pk; } /* * set and check exist promary key of table */ public function set_pk($l_pk) { //if (in_array($l_pk, $this->get_name_fields())) { $this->pk = $l_pk; // } else { // throw new Exception('Nie prwidłowy klucz primary key.'); //} } public function get_operations() { return $this->operations; } public function set_operations($l_operations) { $this->operations = $l_operations; } public function set_action($l_action) { $this->action = $l_action; } public function get_action() { return $this->action; } public function get_rights() { return $this->rights; } public function set_rights($l_rights) { $this->rights = $l_rights; } function __construct() { $l_args = func_get_args(); call_user_func_array(array($this, 'parent::__construct'), $l_args); //print "In " . $this->name . " constructor\n"; //print "In " . self::pk . " constructor\n"; //print_pre($l_args, 'l_args'); //print_pre($this, 'this'); //print "arguments " . func_num_args(); if (func_num_args() >= 4) { $this->set_pk(func_get_arg(3)); } if (func_num_args() >= 5) { $this->set_operations(func_get_arg(4)); } if (func_num_args() == 6) { $this->set_rights(func_get_arg(5)); } } /* * Print PK in EDIT url */ public function print_pk_in_edit_url($p_i) { $l_return = ''; $l_rows = $this->get_rows(); $l_pk = $this->get_pk(); $l_return .= "OPERATION=" . $this->operations_run; for ($i = 0; $i <= count($this->pk) - 1; $i++) { if ($i >= 0) { $l_return .= "&"; } //print_pre($l_rows, 'variable: l_rows'); $l_return .= "P_" . $this->pk[$i] . "=" . $l_rows[$p_i][$this->pk[$i]]; } return $l_return; } public function edit_table() { $l_rows = $this->get_rows(); $l_columns = $this->get_columns(); $l_pk = $this->get_pk(); //print_pre($l_columns['name'], 'variable: l_columns[name]'); //print_pre($this->get_fields_num(), 'field_num'); //print_pre($l_rows, 'variable: l_rows'); //print_pre($this->pk, 'variable: l_pk'); //print_pre($l_columns, 'variable: l_columns'); //print $this->print_pk_in_edit_url(1); print "<h1 id=" . $this->get_sql_name() . ">" . $this->get_title() . " (Last: " . $this->get_rows_num() . " rows)</h1>\n"; print "<p>" . $this->get_description() . "</p>\n"; // print " (action " . $this->get_action() . ")</p>"; $this->add_select_where(); print "<table cellspacing=0 cellpadding=1 onMouseOut = 'javascript:highlightTableRowVersionA(0);'>\n"; print "<tr onclick='miniTable(this);'>\n"; print "<th><a href='#' TITLE='Row number'>#</a></th>\n"; for ($i = 1; $i <= $this->get_fields_num(); $i++) { if (!strstr($l_columns['name'][$i], 'ROWIDTOCHAR(ROWID)')) { print "<th><a href='#' TITLE='" . $l_columns['type'][$i] . " (" . $l_columns['size'][$i] . ")'>" . $l_columns['name'][$i] . "</a></th>\n"; } else { print "<th></th>\n"; } } print "<th>Operations</th>\n"; print "</tr>\n"; if ($this->get_rows_num() > 0) { for ($i = 0; $i <= $this->get_rows_num() - 1; $i++) { if ((bool) ($i & 1)) { $l_bg = " bgcolor='#FFF7DC' "; } else { $l_bg = ''; } print "<tr " . $l_bg . " onMouseOver=\"javascript:highlightTableRowVersionA(this, '#F9EFFF');\">\n"; /* * druk kolumn do edycji */ if (in_array('EDIT', $this->operations) or in_array('DELETE', $this->operations)) { print "<form name='form_edit_" . $this->get_sql_name() . "_" . $i . "' action='" . $this->get_action() . $this->get_sql_name() . "_" . $i . "' method='POST'>\n"; print "<td>" . ($i + 1) . "</td>\n"; for ($j = 1; $j <= $this->get_fields_num(); $j++) { //$l_rows[$i][($l_columns['name'][$j])]; //print_pre($l_columns['name'][$j], 'l_columns[name][j]'); //print_pre($l_fields[$j - 1], 'l_fields[j-1]'); //print_pre($l_columns['size'][$j], 'l_columns[size][j]'); if (!in_array($l_columns['name'][$j], $l_pk) and ( trim($l_columns['name'][$j]) <> 'ROWIDTOCHAR(ROWID)')) { if ($l_columns['name'][$j] == 'S_NAME') { $c1 = connectToDB('INACTTST'); $sqlQry = "select short_name FROM INACT.REC_SUPPLIERS order by short_name"; $qry = oci_parse($c1, $sqlQry); oci_execute($qry); print "<td><select name='S_NAME'>\n"; while (oci_fetch($qry)) { print "<option "; if ($l_rows[$i][$l_columns['name'][$j]] == oci_result($qry, 1)) print "SELECTED"; print " value='" . oci_result($qry, 1) . "'>" . oci_result($qry, 1) . "</option>\n"; } print "</select>\n"; print "</td>\n"; } else { print "<td><input type='text' name='" . $l_columns['name'][$j] . "' value='" . $l_rows[$i][$l_columns['name'][$j]] . "' size='" . $l_columns['size'][$j] . "' maxlength='" . $l_columns['size'][$j] . "' /></td>\n"; } } else { print "<td><input type='hidden' readonly style='background: #eeeeee' name='" . $l_columns['name'][$j] . "' value=" . $l_rows[$i][($l_columns['name'][$j])] . " size='" . ($l_columns['size'][$j] + 6) . "' maxlength='" . $l_columns['size'][$j] . "' /></td>\n"; } } print "<td>\n"; print "<input type='hidden' name='ROW' value='" . $i . "'>\n"; if (in_array('EDIT', $this->operations)) { print '<input type = "submit" value = "EDIT" name = "SUBMIT" />' . "\n"; } if (in_array('DELETE', $this->operations)) { print '<input type = "submit" value = "DELETE" name = "SUBMIT" />' . "\n"; } print "</td>\n"; print '</form>' . "\n"; } if (in_array('SEND', $this->operations)) { $this->operations_run = 'SEND'; print "<td align = 'right'>" . "<a class = 'css_btn_class' " . "href = 'http://inactsrv/inact/TIBCO/sap_send_clear_m.php?" . $this->print_pk_in_edit_url($i) . "'>SEND to SAP</a>" . "</td>\n"; } print "</tr>\n"; } } else { print "<h4>Table is empty</h4>\n"; } if (in_array('INSERT', $this->operations)) { print "<tr>\n"; print "<td></td>\n"; print "<td></td>\n"; $this->operations_run = 'INSERT'; //print_pre($l_columns['name'], 'variable: l_columns[name]'); //print_pre($l_pk, 'variable: get_pk'); //print_pre(trim($l_columns['name'][1]) == 'ROWIDTOCHAR(ROWID)', 'PK'); print "<form name='form_insert_" . $this->get_sql_name() . "' action='" . $this->get_action() . $this->get_sql_name() . "' method='POST'>" . "\n"; for ($j = 1; $j <= $this->get_fields_num(); $j++) { if (!in_array($l_columns['name'][$j], $l_pk) and ( trim($l_columns['name'][$j]) <> 'ROWIDTOCHAR(ROWID)')) { if ($l_columns['name'][$j] == 'S_NAME') { $c1 = connectToDB('INACTTST'); $sqlQry = "select short_name FROM INACT.REC_SUPPLIERS order by short_name"; $qry = oci_parse($c1, $sqlQry); oci_execute($qry); print "<td><select name='S_NAME'>\n"; while (oci_fetch($qry)) { print "<option "; //if ($l_rows[$i][$l_columns['name'][$j]] == oci_result($qry, 1)) //print "SELECTED"; print " value='" . oci_result($qry, 1) . "'>" . oci_result($qry, 1) . "</option>\n"; } print "</select>\n"; print "</td>\n"; } else { print "<td><input type='text' name='" . $l_columns['name'][$j] . "' value='' size='" . $l_columns['size'][$j] . "' maxlength='" . $l_columns['size'][$j] . "' required /></td>" . "\n"; } } else { if (trim($l_columns['name'][$j]) <> 'ROWIDTOCHAR(ROWID)') { print "<td><input type='text' readonly style='background: #abcdef' name='" . $l_columns['name'][$j] . "' value='' size='" . $l_columns['size'][$j] . "' maxlength='" . $l_columns['size'][$j] . "' /></td>" . "\n"; } } } print ""; print "<td>\n" . "<input type = 'submit' value = 'INSERT' name = 'SUBMIT' />" . "</td>\n"; print "</form>\n"; print "</tr>\n"; } print "</table>\n"; } public function get_info() { parent::get_info(); $l_ret = "<table><tr><td>Primary Key</td><td>"; $l_ret .= "<pre>" . print_r($this->pk, TRUE) . "</pre>"; // liczba wierszy $l_ret .= "</td></tr>"; $l_ret .= "<tr><td>Operations</td><td>"; $l_ret .= "<pre>" . print_r($this->operations, TRUE) . "</pre>"; // liczba wierszy $l_ret .= "</td></tr>"; $l_ret .= "</table>"; print $l_ret; } } IF (FALSE) { // // Dismantle Orders // 2014-08-18 add button to update // if (FALSE) { $cl_do_err = new db_edit('inacttst.inact', 'do_errors', 'DISMANTLE ORDERS errors INACTTST', array('M_ID', 'ADB_SEQUENCE'), array('SEND', 'EDIT', 'INSERT')); $cl_do_err->set_sql("SELECT ROWIDTOCHAR(MOE.ROWID), MOE.M_ID, MOE.MO_ID, MO.DESCRIPTION, to_char(MOE.OPER_DATE,'YYYY-MM-DD HH24:MI:SS') as OPER_DATE, MOE.REFERENCE, MOE.ADB_L_DELIVERY_STATUS, to_char(moe.adb_timestamp,'YYYY-MM-DD HH24:MI:SS') as adb_timestamp, ADB_SEQUENCE FROM inact.material_operations_export moe, inact.material_operations mo WHERE moe.ADB_L_DELIVERY_STATUS <> 'C' and MO.ID = MOE.MO_ID ORDER BY oper_date desc"); //$cl_do_err->sql_overlap(); $cl_do_err->FetchAll(); //$cl_do_err->get_info(); $cl_do_err->edit_table(); //TODO dodać operację show-table $cl_supplier = new db_edit('inacttst.inact', 'supplier_lists', 'SUPPLIER_LISTS [db: INACTTST]', array(), array('EDIT', 'INSERT', 'DELETE')); $cl_supplier->set_description("Edycja tabeli SUPPLIERS_LIST"); $cl_supplier->set_sql("select ROWIDTOCHAR(ROWID), S.LIFNR, S.SORTL, S.NAME1 FROM INACT.SUPPLIERS_LISTS s order by S.SORTL"); //$cl_supplier->sql_overlap(); $cl_supplier->FetchAll(); //$cl_do_err->get_info(); $cl_supplier->edit_table(); } } //include ('footer.php'); ?><file_sep>/class.db.php <?php /** * * Klasa opracje na bazie danych Oracle 10.2 * * autor: <NAME> * * 2010-08-13 +num_rows * 2012-07-29 poprawki i robudowa o fetch all * 2012-11-12 przebudowa i upgrade do PHP 5.3 * 2013-03-11 zmina adresu bazy testowej inacttst * 2013-03-28 doadanie metody set_rows * 2014-09-15 KP usunięcie fields_names * */ class db { private $db; // schemat private $db_name; // schemat i nazwa bazy private $conn; // połączenie private $stid; private $sql; // sql private $rows = array(); // result fetch all liczone w wierszach private $rows_num; // liczba zwracanych w zapytaniu wierszy private $fields_num; // liczba pól w wyniku zapytania private $columns = array(); // name, type, size public $title; // subject sql public $description; // description what sql do private $sql_name; public function __construct($db_name = 'inacttst.inact_1', $sql_name = 'sql', $title = 'sql_title') { // clear $columns = ''; $args = func_get_args(); $args_no = func_num_args(); //print_r($args); foreach (array("db_name", "sql_name", "title") as $i) { //if ($args_no < 3) { // print("<div class='error'>Error: No arguments <i>db_name</i>, <i>sql_name</i>, <i>title</i> in class constructor " . __CLASS__ . "</div>"); //} $this->$i = array_shift($args); } $this->db_name = $db_name; // exaple rest in 'class.passwords.php' switch ($this->db_name) { case 'dbname': $this->db = "(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=adress)(PORT=1521)))(CONNECT_DATA=(SID=siddb)(SERVER=DEDICATED)))"; $this->conn = oci_connect("user", "pass", $this->db); break; default: exit("<div id='error'>Class DB error: brak bazy o nazwie " . $this->db_name . "</div>"); } include_once 'class.passwords.php'; if (!$this->conn) { $e = oci_error(); trigger_error(htmlentities('<h2><b>Error calss.db->_constuctor</b> @ logon to ' . $p_db . 'oracle: ' . $e['message'] . '</h2>', ENT_QUOTES), E_USER_ERROR); } } public function __destruct() { //print "desctuct!"; if (isset($this->stid)) oci_free_statement($this->stid); if (isset($this->conn)) oci_close($this->conn); } public function parse() { if (!isset($this->sql) or ! isset($this->conn)) exit('class DB->parse: not set sql or conn: '); $l_stid = oci_parse($this->conn, $this->sql); if (!$l_stid) { $e = oci_error($this->conn); // For oci_parse errors pass the connection handle trigger_error('<b>Error class.db->parse</b> Could not parse <pre>' . htmlentities($e['message']), E_USER_ERROR); die(oci_error()); } $this->stid = $l_stid; return $l_stid; } /* * ograniczenie wyniku zapytania * @package classes */ public function sql_overlap($p_n_rows = 10) { IF (isset($_REQUEST["value_" . $this->get_sql_name()])) { if ($_REQUEST["value_" . $this->get_sql_name()] <> '') { $this->sql = "SELECT * FROM (" . $this->sql . ") WHERE ROWNUM <= 100 AND " . $_REQUEST["select_" . $this->get_sql_name()] . " " . $_REQUEST ["relation_" . $this->get_sql_name()] . " " . $_REQUEST["value_" . $this->get_sql_name()]; } else { $this->sql = "SELECT * FROM (" . $this->sql . ") WHERE ROWNUM <= " . $p_n_rows; } } else { $this->sql = "SELECT * FROM (" . $this->sql . ") WHERE ROWNUM <= " . $p_n_rows; } } public function execute_sql($p_mode = OCI_DEFAULT) { if (!isset($this->sql)) { exit('class DB: execute_sql: SQL: <pre>' . $this->sql . '</pre> not set.' . print_r(error_get_last(), TRUE)); } $this->parse(); $r = oci_execute($this->stid, $p_mode); if (!$r) { $e = oci_error($this->stid); // For oci_execute errors pass the statement handle print htmlentities($e['message']); print "\n<pre>\n"; print htmlentities($e['sqltext']); printf("\n%" . ($e['offset'] + 1) . "s", "^"); print "\n</pre>\n"; } $this->rows_num = oci_num_rows($this->stid); $this->set_name_fields(); $r = oci_commit($this->conn); if (!$r) { $e = oci_error($this->conn); trigger_error(htmlentities($e['message']), E_USER_ERROR); print "Class DB->execute_sql: " . htmlentities($e['message']); exit(); } } public function execute($p_sql) { if (!isset($p_sql) or $p_sql == '') exit('class DB: execute_sql: SQL: <pre>' . $this->sql . '</pre> not set.' . print_r(error_get_last(), TRUE)); $this->set_sql($p_sql); $this->parse(); $r = oci_execute($this->stid); if (!$r) { $e = oci_error($this->stid); // For oci_execute errors pass the statement handle print htmlentities($e['message']); print "\n<pre>\n"; print htmlentities($e['sqltext']); printf("\n%" . ($e['offset'] + 1) . "s", "^"); print "\n</pre>\n"; } $this->rows_num = oci_num_rows($this->get_stid()); $this->set_name_fields(); $r = oci_commit($this->conn); if (!$r) { $e = oci_error($this->conn); trigger_error(htmlentities($e['message']), E_USER_ERROR); } } public function execute_stid($p_stid) { $this->set_stid($p_stid); oci_execute($this->stid) or die('DB ERROR: Could not oci_execute (SQL) <pre>' . $this->get_sql() . '</pre> : ' . ocierror()); $this->rows_num = oci_num_rows($this->get_stid()); $this->set_name_fields(); } public function get_result($p_field) { return oci_result($this->stid, $p_field); } public function get_db() { return $this->db_name; } public function set_sql($p_sql) { $this->sql = $p_sql; } public function set_stid($p_stid) { $this->stid = $p_stid; } public function get_sql() { return $this->sql; } public function get_rows_num() { return $this->rows_num; } public function get_fields_num() { return $this->fields_num; } public function fetch_array() { $this->rows = oci_fetch_array($this->stid, OCI_ASSOC + OCI_RETURN_NULLS); } public function set_name_fields() { for ($i = 1; $i <= $this->fields_num; $i++) { $this->columns['name'][$i] = oci_field_name($this->stid, $i); $this->columns['type'][$i] = oci_field_type($this->stid, $i); $this->columns['size'][$i] = oci_field_size($this->stid, $i); } } public function get_primary_keys() { $sql = "SELECT cols.table_name, cols.column_name, cols.position, cons.status, cons.owner FROM all_constraints cons, all_cons_columns cols WHERE cols.table_name = 'PURCHASE_ORDERS' AND cons.constraint_type = 'P' AND cons.constraint_name = cols.constraint_name AND cons.owner = cols.owner ORDER BY cols.table_name, cols.position"; } /* * * * Run a query and return all rows. * @param string $sql A query to run and return all rows * @param string $action Action text for End-to-End Application Tracing * @param array $bindvars Binds. An array of (bv_name, php_variable, length) * @return array An array of rows * * */ public function execFetchAll($p_sql) { $this->execute($p_sql); $this->rows_num = oci_fetch_all($this->stid, $this->rows, 0, -1, OCI_FETCHSTATEMENT_BY_ROW); $this->fields_num = oci_num_fields($this->stid); $this->set_name_fields(); return($this->rows); } /* * Run a query and return all rows with parse paramteres * @param string $p_sql A query to run and return all rows * @param array $p_bindvars Binds. An array of (bv_name, php_variable, length) * @return array An array of rows */ public function FetchAll() { if (!isset($this->sql) or ! isset($this->conn)) exit('class.db->fetchall: not set sql or conn: '); $this->execute_sql(); $this->rows_num = oci_fetch_all($this->stid, $this->rows, 0, -1, OCI_FETCHSTATEMENT_BY_ROW); //$this->rows_num = oci_fetch_all($this->stid, $this->rows); $this->fields_num = oci_num_fields($this->stid); $this->set_name_fields(); return($this->rows); } public function get_stid() { return $this->stid; } public function get_rows() { return $this->rows; } public function set_rows($p_rows) { $this->rows = $p_rows; } public function get_db_name() { return $this->db_name; } public function get_conn() { return $this->conn; } /* * title and description */ public function get_title() { return $this->title; } public function set_title($p_title) { $this->title = $p_title; } public function get_description() { return $this->description; } public function set_description($p_description) { $this->description = $p_description; } public function get_sql_name() { return $this->sql_name; } public function get_columns() { return $this->columns; } /* * Output */ public function output_cvs($p_name) { $filename = $p_name . "_" . date('Y-m-d_Hi'); header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check = 0, pre-check = 0"); header("Cache-Control: private", false); header("Content-Type: application/octet-stream"); header("Content-Disposition: attachment;filename = \"$filename.csv\";"); header("Content-Transfer-Encoding: binary"); $outstream = fopen( "php://output", "w+"); function __outputCSV(&$vals, $key, $filehandler) { fputcsv($filehandler, $vals, ';'); // add parameters if you want } // error (*) print_r($this->columns['names']); fputcsv($outstream, $this->columns['name'], ';'); array_walk($this->rows, "__outputCSV", $outstream); fclose($outstream); } public function add_select_where() { if (!isset($_REQUEST[('select_' . $this->get_sql_name())])) { $_REQUEST[('select_' . $this->get_sql_name())] = $this->columns['name'][1]; } if (!isset($_REQUEST[('value_' . $this->get_sql_name())])) { $_REQUEST[('value_' . $this->get_sql_name())] = ''; } if (!isset($_REQUEST[('relation_' . $this->get_sql_name())])) { $_REQUEST [('relation_' . $this->get_sql_name())] = ''; } print '<form action="#' . $this->title . '" method="post" name="' . 'form_' . $this->get_sql_name() . '">' . "\n"; // KPe opcja onchange_="javascript: document.form_' . $this->get_sql_name() . '.submit() print '<select name="' . "select_" . $this->get_sql_name() . '">' . "\n"; for ($i = 1; $i <= $this->fields_num; $i++) { if ($this->columns['name'][$i] <> 'ROWIDTOCHAR(ROWID)') { print '<option value = "' . $this->columns['name'][$i] . '" '; if ($_REQUEST[('select_' . $this->get_sql_name())] == $this->columns['name'][$i]) { print "SELECTED"; } print '>' . $this->columns ['name'][$i] . ' ' . $this->columns ['type'][$i] . ' (' . $this->columns['size'] [$i] . ')</option>' . "\n"; } } print '</select>' . "\n" . "\n"; print '<select name = "' . "relation_" . $this->get_sql_name() . '">' . "\n"; print ' <option value = "=">=</option>' . "\n"; print ' <option value = "<">></option>' . "\n"; print ' <option value = ">"><</option>' . "\n"; print ' <option value = "LIKE">LIKE</option>' . "\n"; print '</select>' . "\n"; print '<input type = "text" name = "value_' . $this->get_sql_name() . '" value = "' . $_REQUEST[('value_' . $this->get_sql_name() )] . '" size = "20" />' . "\n"; print "<input type = \"submit\" />" . "\n"; print '</form>' . "\n" . "\n"; } public function output_html_table() { print "<h2 id=" . $this->sql_name . ">" . $this->title . " (" . $this->rows_num . " rows)</h1>\n"; //print_pre($this->rows); $this->add_select_where(); print "<table cellspacing=0 cellpadding=1 onMouseOut = \"javascript:highlightTableRowVersionA(0);\">"; print "<tr onclick=\"miniTable(this)\">"; for ($i = 1; $i <= $this->fields_num; $i++) { print "<th> <a href='#' TITLE='" . $this->columns ['type'][$i] . " (" . $this->columns ['size'][$i] . ")'>" . $this->columns['name'][$i] . "</a> </th>"; } print "</tr>"; if ($this->get_rows_num() > 0) { for ($i = 0; $i <= $this->get_rows_num(); $i++) { if ((bool) ($i & 1)) { $l_bg = " bgcolor='#FFF7DC' "; } else { $l_bg = ''; } print "<tr " . $l_bg . " onMouseOver=\"javascript:highlightTableRowVersionA(this, '#F9EFFF');\">"; for ($j = 1; $j <= $this->fields_num; $j++) { print "<td>" . $this->rows[$i][($this->columns['name'][$j])] . "</td>"; } print "</tr>"; } print "</table>"; } else { print "Table is empty"; } } public function get_info() { $l_ret = "<table cellpading=1><tr><td>Connection</td><td>"; $l_ret .= $this->sql_name; $l_ret .= "</td></tr><tr><td>Database</td><td>"; $l_ret .= $this->db_name; $l_ret .= "</td></tr><tr><td>Title</td><td>"; $l_ret .= $this->title; $l_ret .= "</td></tr><tr><td>SQL</td><td>"; $l_ret .= "<pre>" . $this->sql . "</pre>"; // sql $l_ret .= "</td></tr><tr><td>Num rows</td><td>"; $l_ret .= $this->rows_num; // liczba zwracanych w zapytaniu wierszy $l_ret .= "<tr><td>Columns</td><td>"; $l_ret .= "<pre>" . print_r($this->columns, TRUE) . "</pre>"; // liczba wierszy $l_ret .= "</td></tr>"; $l_ret .= "</table>"; print $l_ret; } } ?><file_sep>/README.md php-db-classes ============== Operation on Oracle database. Update, insert, delete. Present data in table form. <file_sep>/class.autenticate.php <?php /** * class.autenticate.php * --------------------- * autentykacja użytkowników poprzez LDAP oraz sprawdzenie ról jakie mają na bazie. * * @author <NAME> * * @version 1.0 2010-05-06 Create item * @version 2.0 2010-08-17 Wykorzystanie klasy do autentykacji tmo_reporting * * @todo sprawdzanie uprawnień do plików */ //require_once 'PHP/Compat.php'; //PHP_Compat::loadFunction('file_get_contents'); require_once "class.db.php"; class autenticate extends db { private $domain; private $userldap; private $roles; private $corponet; private $granted = FALSE; public function __construct($db = 'inactprd.inact_1') { parent::__construct($db); if (!isset($_SERVER['REMOTE_USER'])) $_SERVER['REMOTE_USER'] = ''; $cred = explode('\\', $_SERVER['REMOTE_USER']); if (count($cred) == 1) array_unshift($cred, "(no domain info - perhaps SSPIOmitDomain is On)"); list($this->domain, $this->userldap) = $cred; if (isset($this->domain) and isset($this->userldap)) $this->corponet = TRUE; else $this->corponet = FALSE; if ($this->corponet) print "Autenticate in " . strtoupper($this->domain) . "/" . strtoupper($this->userldap) . ". "; } public function set_domian($p_domain) { $this->domain = $p_domain; } public function set_userldap($p_userldap) { $this->userldap = $p_user_ldap; } public function get_domian() { return $this->domain; } public function get_granted() { return $this->granted; } public function get_userldap() { return $this->userldap; } public function check_role($p_roles) { /** * @var sprawdznie czy parametr jest wypełniony. */ if (!isset($p_roles)) { throw new Exception('<b>Warning: Brak pdania roli</b><br>'); } $this->set_sql("select count(*) count " . " from inact.v_all_role_privs " . " where upper(grantee) = upper('" . $this->userldap . "') " . " and GRANTED_ROLE IN (" . $p_roles . ")"); $this->execute_sql(); $this->fetch_array(); $l_rows = $this->get_rows(); if ($l_rows['COUNT'] > 0) { //echo "User: " . $this->userldap . " ROLES: (" . $p_roles . "), "; $this->granted = TRUE; return TRUE; } else { //echo "User: " . $this->domain . "/" . $this->userldap . " have NOT required roles (" . $p_roles . ") on " . $this->get_db() . ": " . $p_roles . ", coprponet " . $this->corponet . ", roles: " . $l_rows['COUNT']; //echo "<pre>"; //print $this->get_sql(); //PRINT "<BR>"; //print_r($this->get_rows()); //echo "</pre>"; $this->granted = FALSE; return FALSE; } } } if (TRUE) try { $autenticate = new autenticate(); $autenticate->check_role("'INACT_DATA_VIEWER'"); } catch (exception $e) { die('Error: ' . $e->getmessage()); } ?><file_sep>/class.auth.php <?php /* * TMPL All Rights Reserved 2014 (c) */ /** * Authoryzacja dostÍpu do apliacji webowej * * @author KPreiskorn */ class auth extends db { public function hasRoles($p_usr, $p_role, $p_conn) { $sql = "select count(*) cnt from inact.v_all_role_privs v, inact.users u where u.DOMAIN_USERNAME = '" . $p_usr . "' AND v.GRANTEE = u.USERNAME AND v.GRANTED_ROLE IN (" . $p_role . ")"; //debug('SQL', $sql); $qry = oci_parse($p_conn, $sql); oci_execute($qry); oci_fetch($qry); //debug('Roles counter', oci_result($qry, 'CNT')); if (oci_result($qry, 'CNT') > 0) { return true; } return false; } public function countRoles($p_usr, $p_conn) { $sql = "select count(*) cnt from inact.v_all_role_privs v, inact.users u where u.DOMAIN_USERNAME = '" . $p_usr . "' AND v.GRANTEE = u.USERNAME"; //debug('', $sql); $qry = oci_parse($p_conn, $sql); oci_execute($qry); oci_fetch($qry); //debug("Test count:", oci_result($qry, 'CNT')); if (oci_result($qry, 'CNT') > 0) { return true; } return false; } public function listRoles($p_usr, $p_conn) { $ret = 'Role InAcT: '; $sql = "select * from inact.v_all_role_privs v, inact.users u where u.DOMAIN_USERNAME = '" . $p_usr . "' AND v.GRANTEE = u.USERNAME"; //debug('', $sql); $stid = oci_parse($p_conn, $sql); oci_execute($stid); while (($row = oci_fetch_array($stid, OCI_BOTH))) { $ret = $ret . $row[1] . ", "; } oci_free_statement($stid); return $ret; } } <file_sep>/class.db_table.php <?php /* * Program do zapisu do konkretnej tabeli danych do przerobienia na klase * */ //TODO do przerobienia na klase $title = 'Operacje na tabeli SUPLLIER_LISTS'; include 'header.php'; include ('funkcje/auth.php'); require_once ('funkcje/functions.php'); require_once ('class.db.php'); include("connect.php"); include ('funkcje/auth_header.php'); $l_conn = connectToSchema('INACTTST', 'INACT_1'); if (!countRoles($_SESSION['INACT_USER'], $l_conn)) { ?> /* @var $_REQUEST type */ <h1>Wykasowanie znacznika wysłania materiału do SAP dla <?php print $_SESSION['INACT_USER'] . " na " . $_REQUEST['database']; ?></h1> <div> <h1>Nie masz wystarczających uprawnień do InAcT</h1> <a href="password.php">Powrót</a>. </div> <?php return; } if (!hasRoles($_SESSION['INACT_USER'], "'INACT_DATA_VIEWER', 'INACT_INV_ROL_STOREKEEPER'", $conn)) { print "<h1>Brak uprawnień</h1>"; exit(); } /* * operacje na tabeli oracle * * */ class db_table extends db_edit { public function update($param) { } public function insert($param) { } public function delete($param) { } } if (isset($_REQUEST['SUBMIT'])) { if (isset($_REQUEST['LIFNR']) AND isset($_REQUEST['SORTL'])) { if ($_REQUEST['SUBMIT'] == 'INSERT') { $query = "INSERT INTO INACT.SUPPLIERS_LISTS (NAME1, SORTL, LIFNR) VALUES ('" . $_REQUEST['NAME1'] . "', '" . $_REQUEST['SORTL'] . "','" . $_REQUEST['LIFNR'] . "')"; print $query; $cl_db = new db('inacttst.inact_1', 'update supplier', '1'); $cl_db->set_sql($query); $cl_db->execute_sql(); print "<h2>Poprawny " . $_REQUEST['SUBMIT'] . "</h2>"; } elseif ($_REQUEST['SUBMIT'] == 'EDIT' AND isset($_REQUEST['ROWIDTOCHAR(ROWID)'])) { $query = "UPDATE INACT.SUPPLIERS_LISTS SET SORTL = '" . $_REQUEST['NAME1'] . "', NAME1 = '" . $_REQUEST['NAME1'] . "', LIFNR = '" . $_REQUEST['LIFNR'] . "' WHERE LIFNR = '" . $_REQUEST['LIFNR'] . "' and ROWID = CHARTOROWID('" . $_REQUEST['ROWIDTOCHAR(ROWID)'] . "')"; print $query; $cl_db = new db('inacttst.inact_1', 'update supplier', '1'); $cl_db->set_sql($query); $cl_db->execute_sql(); print "<h2>Poprawna operacja " . $_REQUEST['SUBMIT'] . "</h2>"; } elseif ($_REQUEST['SUBMIT'] == 'DELETE' AND isset($_REQUEST['ROWIDTOCHAR(ROWID)'])) { $query = "DELETE FROM INACT.SUPPLIERS_LISTS WHERE LIFNR = '" . $_REQUEST['LIFNR'] . "' and ROWID = CHARTOROWID('" . $_REQUEST['ROWIDTOCHAR(ROWID)'] . "')"; print $query; $cl_db = new db('inacttst.inact_1', 'update supplier', '1'); $cl_db->set_sql($query); $cl_db->execute_sql(); print "<h2>Poprawna operacja " . $_REQUEST['SUBMIT'] . "</h2>"; } else { print "<h2>Błędna operacja " . $_REQUEST['SUBMIT'] . "</h2>"; } } else { print "<h1>Nie ma takiej operacji: " . $_REQUEST['SUBMIT'] . "</h1>"; } } else { print "<h1>Brak wywołania SUBMIT</h1>"; } print "<a href='javascript:history.go(-1)'>Back...</a>"; include 'footer.php'; ?><file_sep>/class.reports.php <?php require_once ('class.db.php'); /** * * Wyświetlanie raportów bazodanowych * * @author <NAME> <<EMAIL>> * @version 1.2 * @link http://ips/reports.php * @param string pc_name nazwa raportu * * @todo wywalic phpmanual z katalogu głównego * */ function issetor(&$variable, $or = NULL) { return $variable === NULL ? $or : $variable; } class html_select { public $array; public function __construct() { echo "construct::db(" . $this->db_name . ") \n"; echo '<form method="get" action="#"> <select name="day"> <option value="1">Monday/Wednesday <option value="2">Tuesday/Thursday <option value="3">Friday/Sunday <option value="4">Saturday </select> <input type="submit" value="Send"> </form>'; } } class format { public function size_readable($size, $max = null, $system = 'si', $retstring = '%01.2f %s') { // Pick units $systems['si']['prefix'] = array('B', 'K', 'MB', 'GB', 'TB', 'PB'); $systems['si']['size'] = 1000; $systems['bi']['prefix'] = array('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'); $systems['bi']['size'] = 1024; $sys = isset($systems[$system]) ? $systems[$system] : $systems['si']; // Max unit to display $depth = count($sys['prefix']) - 1; if ($max && false !== $d = array_search($max, $sys['prefix'])) { $depth = $d; } // Loop $i = 0; while ($size >= $sys['size'] && $i < $depth) { $size /= $sys['size']; $i++; } return sprintf($retstring, $size, $sys['prefix'][$i]); } } class error { private $log; public function set($p_log) { } } class raports extends db { public $result; public $title; public $subtitle; public $name; public $column; public $primary_key = array(); public function __construct($p_raports_name = 'tf_', $p_db = 'inacttst.inact') { parent::__construct($p_db); $this->name = $p_raports_name; echo "construct::reports ".$this->name." (".parent::get_db_name().") \n"; } public function set_primary_key($p_key) { $this->primary_key[] = $p_key; } public function set_title($p_title) { $this->title = $p_title; } public function set_subtitle($p_subtitle) { $this->subtitle = $p_subtitle; } public function get_title() { return $this->title; } public function get_subtitle($p_subtitle) { return $this->subtitle; } public function set_name($p_name) { $this->name = $p_name; } public function get_name() { return $this->name; } public function show($p_link_details = FALSE, $p_hide = 'show', $p_show_sql = TRUE) { $ncols = oci_num_fields(parent::get_stid()); echo "\n<h3>" . $this->title . "</h3>\n"; echo issetor($this->subtitle, "\n<p>" . $this->subtitle . "</p>\n"); // show - pernametnie pokazuje tabele bez linku // hide - link do ukrywania i odkrywania widoczy tabela schowana // unhide - link do ukrywania i odkrywania widoczy tabela widoczna if ($p_hide <> 'show') echo "[<a href=\"javascript:unhide('" . $this->name . "_tab');\">Show table data</a>] <div id='" . $this->name . "_tab' class='" . $p_hide . "'>"; echo "\n<table class='tr' id='" . $this->name . "' cellpadding='0' cellspacing='0'>\n"; echo "<tr class='tf'>\n"; for ($i = 1; $i <= $ncols; $i++) { $this->column['name'][$i] = oci_field_name(parent::get_stid(), $i); $this->column['type'][$i] = oci_field_type(parent::get_stid(), $i); $this->column['size'][$i] = oci_field_size(parent::get_stid(), $i); echo "<th>" . $this->column['name'][$i] . "</th>\n"; } echo "</tr>\n"; $l_row = 0; while (($row = oci_fetch_array(parent::get_stid(), OCI_ASSOC + OCI_RETURN_NULLS))) { $this->result[$l_row++] = $row; if ($p_link_details == TRUE) echo "<tr class='tf' onclick=\"window.location='details.php?p1=" . $row[$this->primary_key[0]] . "&p2=" . $row[$this->primary_key[1]] . "&p3=" . $row[$this->primary_key[2]] . "'\">"; else echo "<tr class='tf'>"; foreach ($row as $val_row) { echo "<td calss='tf'>" . $val_row . "</td>"; } echo "</tr>\n"; } echo "</tbody></table>\n"; print "<script language=\"javascript\" type=\"text/javascript\"> //<![CDATA[ var props_" . $this->name . " = { sort: true, filters_row_index:1, remember_grid_values: true, alternate_rows: true, rows_counter: true, rows_counter_text: \"Displayed rows: \", btn_reset: true, btn_reset_text: \"Clear\", loader: true, loader_html: '<img src=\"../../images/load_icon.gif\" alt=\"\" style=\"vertical-align:middle; margin:0 5px 0 5px\" /><span>Loading...</span>', loader_css_class: 'myLoader', status_bar: true, display_all_text: \"< Show all >\", extensions: { name:['ColumnsResizer'], src:['TFExt_ColsResizer/TFExt_ColsResizer.js'], description:['Columns Resizing'], initialize:[function(o){o.SetColsResizer();}] }, col_resizer_all_cells: true } var tf_" . $this->name . " = setFilterGrid(\"" . $this->name . "\", props_" . $this->name . "); //]]> </script>"; // show hide SQL if ($p_show_sql == TRUE) echo "[<a href=\"javascript:unhide('" . $this->name . "_sql');\">Show SQL</a>]<div id='" . $this->name . "_sql' class='hidden'><pre>" . $this->get_sql() . "</pre></div>"; echo "</div>"; } public function __destruct() { //echo "destruct::reports ".$this->name." (" . $this->db_name . ") \n"; } } ?>
3385bb99650c5c84cf422cb73f84f47257561ca1
[ "Markdown", "PHP" ]
7
PHP
karol-preiskorn/php-db-classes
1871e791e7304d711b959d4afccf62ad67f2e36e
5fd8dc75f67272af5f3f4d0c976ed82e80a3495b
refs/heads/master
<repo_name>hcavalle/mopact_hapi<file_sep>/README.md # mopact_hapi hapi based rest api for mopact app <file_sep>/env.sh #!/bin/bash if [ -z "$NODE_ENV" ] then #dev db export NODE_HOST='localhost' export NODE_PORT='8081' export DB_DEV_HOST='localhost' export DB_DEV_USER='postgres' export DB_DEV_PASS='' export DB_DEV_NAME='mopact_hapi_dev' else if [ $NODE_ENV -eq 'production' ] then #prod db export NODE_HOST='localhost' export NODE_PORT='8080' export DB_DEV_HOST='localhost' export DB_DEV_USER='mopact' export DB_DEV_PASS='' export DB_DEV_NAME='mopact_prod' else [ $NODE_ENV -eq 'test' ] #stage db export NODE_HOST='localhost' export NODE_PORT='8081' export DB_DEV_HOST='localhost' export DB_DEV_USER='postgres' export DB_DEV_PASS='' export DB_DEV_NAME='mopact_hapi_stage' fi fi <file_sep>/deploy/Dockerfile FROM centos:centos6 # Enable EPEL for Node.js RUN rpm -Uvh http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm # Install Node.js and npm RUN yum install -y npm # Install apache RUN yum install -y httpd #env vars RUN export NODE_HOST='localhost' RUN export NODE_PORT='8081' #dev db RUN export DB_DEV_HOST='localhost' RUN export DB_DEV_USER='postgres' RUN export DB_DEV_PASS='' RUN export DB_DEV_NAME='mopact_hapi_dev' #test db RUN export DB_DEV_HOST='localhost' RUN export DB_DEV_USER='postgres' RUN export DB_DEV_PASS='' RUN export DB_DEV_NAME='mopact_hapi_dev' #prod db RUN export DB_DEV_HOST='localhost' RUN export DB_DEV_USER='postgres' RUN export DB_DEV_PASS='' RUN export DB_DEV_NAME='mopact_hapi_dev' # Bundle app source COPY ../ /src # Install app dependencies RUN cd /src; npm install RUN cd /src; source ./env.sh EXPOSE 8081 CMD [ "node", "/src/app.js" ] <file_sep>/models/impactmodel.js "use strict"; module.exports = function(sequelize, DataTypes) { var ImpactModel = sequelize.define("ImpactModel", { name: DataTypes.STRING, definition: DataTypes.TEXT, category: DataTypes.ENUM('Market','Inventory/Goods','Jobs','Cash','Awareness','Services','Additional/Broad Models'), type: DataTypes.ENUM('product', 'service'), brands: DataTypes.JSON }, { classMethods: { associate: function(models) { // associations can be defined here } } }); return ImpactModel; }; <file_sep>/app.js var Hapi = require('hapi'); var config = require('./appconf.js'); var models = require('./models'); console.log(config); var server = new Hapi.Server(); server.connection(config.application); server.route(require('./lib/routes')); models.sequelize.sync({force: true}).then(function() { server.start(function () { console.log('running on '+config.application.port); }); }).catch(function(error) { console.log(error); }); <file_sep>/deploy/docker-compose.yml db: image: hcavalle/postgres ports: - "5432" web: build: . volumes: - .:/src ports: - "8081:8081" links: - db
e23f8959afa64096ee0785249d585d2f60927bf8
[ "YAML", "Markdown", "JavaScript", "Dockerfile", "Shell" ]
6
Markdown
hcavalle/mopact_hapi
37fb988436ab6d829e55da0bb3b37af2b8d748bb
7c278e86180fac1c8a004e6957c6b91b6c4c3b5a
refs/heads/master
<repo_name>YiFanChen99/strings-concatenation-example<file_sep>/Main.cpp #include <iostream> #include <string> #include <chrono> #include <sstream> #include <functional> typedef std::chrono::duration<float, std::milli> MILLI; const int kLoop=1000000; const std::string kStrUid("idid"); const std::string kStrDest("target"); const int kTaskId=1999; template <typename F> MILLI TimeMeasurement(F f) { typedef std::chrono::high_resolution_clock clock; std::string r; auto t0 = clock::now(); f(r); auto t1 = clock::now(); return MILLI(t1-t0); } void Comment(const std::string &strComment) { std::cout << "\n-------------------------" << strComment << "-------------------\n"; } void Cost(const MILLI &milli) { std::cout << milli.count() << "ms\n"; } void TestString() { { auto f=[](std::string& l_czTempStr) { std::string s1="Test data1"; for (int i = 0; i < kLoop; ++i) { l_czTempStr = s1 + "Test data2" + "Test data3"; } }; Comment("string, plain addition \"+\""); Cost(TimeMeasurement(f)); } { auto f=[](std::string& l_czTempStr) { for (int i = 0; i < kLoop; ++i) { l_czTempStr = "Test data1"; l_czTempStr += "Test data2"; l_czTempStr += "Test data3"; } }; Comment("string, incremental \"+=\""); Cost(TimeMeasurement(f)); } { auto f=[](std::string& l_czTempStr) { for (int i = 0; i < kLoop; ++i) { l_czTempStr = "Test data1"; l_czTempStr.append("Test data2"); l_czTempStr.append("Test data3"); } }; Comment("string, \"append\""); Cost(TimeMeasurement(f)); } { auto f=[](std::string& l_czTempStr) { for (int i = 0; i < kLoop; ++i) { std::ostringstream oss; oss << "Test data1"; oss << "Test data2"; oss << "Test data3"; l_czTempStr = oss.str(); } }; Comment("oss, creation in each loop, incremental"); Cost(TimeMeasurement(f)); } { auto f=[](std::string& l_czTempStr) { std::ostringstream oss; for (int i = 0; i < kLoop; ++i) { oss.str(""); oss.clear(); oss << "Test data1" << "Test data2" << "Test data3"; } l_czTempStr = oss.str(); }; Comment("oss, 1 creation, plain addition"); Cost(TimeMeasurement(f)); } { auto f=[](std::string& l_czTempStr) { std::ostringstream oss; for (int i = 0; i < kLoop; ++i) { oss.str(""); oss.clear(); oss << "Test data1"; oss << "Test data2"; oss << "Test data3"; } l_czTempStr = oss.str(); }; Comment("oss, 1 creation, incremental"); Cost(TimeMeasurement(f)); } { auto f=[](std::string& l_czTempStr) { std::stringstream ss; for (int i = 0; i < kLoop; ++i) { ss.str(""); ss.clear(); ss << "Test data1"; ss << "Test data2"; ss << "Test data3"; } l_czTempStr = ss.str(); }; Comment("ss, 1 creation, incremental"); Cost(TimeMeasurement(f)); } } void TestStringWithConversion() { { auto f=[](std::string& l_czTempStr) { for (int i = 0; i < kLoop; ++i) { std::string strBase("asdfghjkl"); std::ostringstream oss; oss << kTaskId; strBase += "|uid="; strBase += kStrUid; strBase += "|destination="; strBase += kStrDest; strBase += "|taskid="; strBase += oss.str(); } }; Comment("string, incremental by \"+\" with one oss conversion."); Cost(TimeMeasurement(f)); } { auto f=[](std::string& l_czTempStr) { for (int i = 0; i < kLoop; ++i) { std::string strBase("asdfghjkl"); std::ostringstream oss; oss << "|uid="; oss << kStrUid; oss << "|destination="; oss << kStrDest; oss << "|taskid="; oss << kTaskId; strBase += oss.str(); } }; Comment("string, incremental all by oss."); Cost(TimeMeasurement(f)); } { auto f=[](std::string& l_czTempStr) { for (int i = 0; i < kLoop; ++i) { std::string strBase("asdfghjkl"); std::stringstream ss; ss << kTaskId; strBase += "|uid="; strBase += kStrUid; strBase += "|destination="; strBase += kStrDest; strBase += "|taskid="; strBase += ss.str(); } }; Comment("string, incremental by \"+\" with one ss conversion."); Cost(TimeMeasurement(f)); } { auto f=[](std::string& l_czTempStr) { for (int i = 0; i < kLoop; ++i) { std::string strBase("asdfghjkl"); std::stringstream ss; ss << "|uid="; ss << kStrUid; ss << "|destination="; ss << kStrDest; ss << "|taskid="; ss << kTaskId; strBase += ss.str(); } }; Comment("string, incremental all by ss."); Cost(TimeMeasurement(f)); } } int main () { std:: cout << std::endl << "----------------String Comparison with " << kLoop << " loops ---------------- " << std::endl; // TestString(); TestStringWithConversion(); } <file_sep>/README.md # strings-concatenation-example Based on [DrHell's answer](https://stackoverflow.com/a/49267798) on [Most optimized way of concatenation in strings](https://stackoverflow.com/questions/18892281/most-optimized-way-of-concatenation-in-strings).
2fbb9b29d4ebad3f85a80f4c097666aec081a2a8
[ "Markdown", "C++" ]
2
C++
YiFanChen99/strings-concatenation-example
7587e93aeb50944b4baed40b457af5dded7cdbe4
2eec540f83b633a806d6c9ec9e2ff75a57450df2
refs/heads/master
<repo_name>christianbradley/boco-mdd-jasmine-js<file_sep>/npm/test #!/bin/bash DIR="$(cd "$(dirname "$0")/.." && pwd)" jasmine="$DIR/node_modules/.bin/jasmine" NODE_PATH=$NODE_PATH:$DIR $jasmine "$@"
6e1b25eb06e457d9ebf56641eef778387513083d
[ "Shell" ]
1
Shell
christianbradley/boco-mdd-jasmine-js
551fb15ad46d070d3607a4c0fa6641f71faf23ca
3203ab5148f20f40fe99f452d330932d7306a002
refs/heads/master
<repo_name>lionicsheriff/literate-dotfiles<file_sep>/README.md # literate-dotfiles An experiment in dotfile management ## What? A system to manage configuration files in a 'Personal Information Manager' ## Why? I'm not too sure. I have never clicked with more file based solutions to dotfile management (e.g. symlink scripts, git repositories). I get the feeling that a dotfile is more than just a file that changes a program, but an opinion on a workflow. Since they are an opinion they belong with all the other personal information. At the very least this is an approach I haven't seen before. ## How? Currently I'm going to create a plugin for WikidPad that will use the attributes on a WikiWord to publish a page into the correct dotfile. <file_sep>/publishDotfile.py import os import platform ## Set up menu item WIKIDPAD_PLUGIN = (("MenuModifier", 1), ("MenuItemProvider", 1)) ID_CMD_PUBLISHCONFIG = "menuItem/editor/textArea/plugin/publishConfigContext/publishCurrent" def modifyMenuV01(contextName, contextDict, menu): if contextName == "contextMenu/editor/textArea": # We want to handle this menu # Append a separator (if necessary) menu.appendNecessarySeparator() # We wish to append an item (this in turn calls provideMenuItemV01() menu.appendProvidedItem(ID_CMD_PUBLISHCONFIG) # Return False to inform WikidPad that we handled the menu return False # Default reaction to inform that we don't handle anything else return None def provideMenuItemV01(menuItemUnifName, contextName, contextDict, menu, insertIdx): if menuItemUnifName == ID_CMD_PUBLISHCONFIG: # We want to provide this menu item # preparePlgMenuItem creates a menu item and returns it. Furthermore # it registers event handlers to call evtfct and updatefct if given theItem = menu.preparePlgMenuItem("Publish config", "Publishes the current page into the location specified in the location attribute", evtfct=cmdPublish, menuID=ID_CMD_PUBLISHCONFIG, updatefct=enableMenu) # Usual wxPython call to insert the item menu.InsertItem(insertIdx, theItem) # Return False to inform WikidPad that we handled the item return False # Default reaction to inform that we don't handle anything else return None # menu item handler def cmdPublish(evt, menuItemUnifName, contextName, contextDict, menu): txtCtrl = contextDict["txtCtrl"] mainCtrl = txtCtrl.getMainControl() metadata = getCurrentMetadata(mainCtrl) wiki = mainCtrl.getWikiDocument() publishConfig(wiki, metadata['location'][0]) # assuming you can't get here without a location # controls whether the menu item is active def enableMenu(evt, menuItemUnifName, contextName, contextDict, menu): txtCtrl = contextDict["txtCtrl"] metadata = getCurrentMetadata(txtCtrl.getMainControl()) # do I really need to go through the main control to get the current page? evt.Enable(canPublish(metadata)) ## Actually do the stuff def getCurrentMetadata(mainCtrl): return mainCtrl.getCurrentDocPage().getAttributes() def getDotfileText(page): text = page.getLiveText() split = text.partition("\n\n") # TODO: do I need to use os.linesep? return split[2] def publishConfig(wiki, location): body = composeDotfile(wiki, location) writeDotfile(location, body) def writeDotfile(path, body): path = os.path.expanduser(path) # make the directories for the file if they do not exist # attempting to create the directory and then apoligising is easier, and less prone to # race conditions than checking if the directory exists (dirs, _) = os.path.split(path) try: os.makedirs(dirs) except OSError: # unless there is already a directory at that path, something has probably gone wrong if not os.path.isdir(dirs): raise # finally write the config with open(path, 'w+') as file: file.write(body) def composeDotfile(wiki, location): pages = wiki.getAttributeTriples(None, 'location', location) body = "" for page in pages: wikiWord = wiki.getWikiPage(page[0]) if (canPublish(wikiWord.getAttributes())): body += getDotfileText(wikiWord) return body def canPublish(metadata): isValid = True if "enabled" in metadata: isValid = isValid and testEnabled(metadata["enabled"]) if "host" in metadata: isValid = isValid and testHost(metadata["host"]) if "os" in metadata: isValid = isValid and testOs(metadata["os"]) return isValid def testOs(os): return platform.system() in os def testHost(host): return platform.node in host.join(",").split(",") def testEnabled(enabled): return "yes" in enabled
24c1b81dcf39f1618f00a8c1c1c50dd28966da88
[ "Markdown", "Python" ]
2
Markdown
lionicsheriff/literate-dotfiles
0f2b7600a7ecb5303fd8961a1853d014279b8ee1
e2d351a1936892453fcf080712c326a501d1c9fb
refs/heads/master
<repo_name>MidnightDrifter/CS529Proj3Collisions<file_sep>/Project 3 - Template/GameState_Play.c // --------------------------------------------------------------------------- // Project Name : Cage Game // File Name : GameState_Menu.cpp // Author : <NAME> // Creation Date : 2012/03/16 // Purpose : implementation of the 'play' game state // History : // - // --------------------------------------------------------------------------- #include "main.h" // --------------------------------------------------------------------------- // Defines #define SHAPE_NUM_MAX 32 // The total number of different vertex buffer (Shape) #define GAME_OBJ_INST_NUM_MAX 2048 // The total number of different game object instances // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // object flag definition #define FLAG_ACTIVE 0x00000001 #define TEST_PART_2 1 #define DRAW_DEBUG 1 // Set this to 1 in order to draw debug data #define LINE_SEGMENTS_NUM 5 // Don't change #define BALL_RADIUS 15.0f #define PILLARS_NUM 6 // Don't change // --------------------------------------------------------------------------- enum OBJECT_TYPE { OBJECT_TYPE_BALL, OBJECT_TYPE_LINE, OBJECT_TYPE_PILLAR, OBJECT_TYPE_DEBUG_LINE, }; // Struct/Class definitions typedef struct GameObjectInstance GameObjectInstance; // Forward declaration needed, since components need to point to their owner "GameObjectInstance" // --------------------------------------------------------------------------- typedef struct { unsigned long mType; // Object type (Ship, bullet, etc..) AEGfxVertexList* mpMesh; // This will hold the triangles which will form the shape of the object }Shape; // --------------------------------------------------------------------------- typedef struct { Shape *mpShape; GameObjectInstance * mpOwner; // This component's owner }Component_Sprite; // --------------------------------------------------------------------------- typedef struct { Vector2D mPosition; // Current position float mAngle; // Current angle float mScaleX; // Current X scaling value float mScaleY; // Current Y scaling value Matrix2D mTransform; // Object transformation matrix: Each frame, calculate the object instance's transformation matrix and save it here GameObjectInstance * mpOwner; // This component's owner }Component_Transform; // --------------------------------------------------------------------------- typedef struct { Vector2D mVelocity; // Current velocity GameObjectInstance * mpOwner; // This component's owner }Component_Physics; // --------------------------------------------------------------------------- //Game object instance structure struct GameObjectInstance { unsigned long mFlag; // Bit mFlag, used to indicate if the object instance is active or not Component_Sprite *mpComponent_Sprite; // Sprite component Component_Transform *mpComponent_Transform; // Transform component Component_Physics *mpComponent_Physics; // Physics component }; // --------------------------------------------------------------------------- // Static variables // List of original vertex buffers static Shape sgShapes[SHAPE_NUM_MAX]; // Each element in this array represents a unique shape static unsigned long sgShapeNum; // The number of defined shapes // list of object instances static GameObjectInstance sgGameObjectInstanceList[GAME_OBJ_INST_NUM_MAX]; // Each element in this array represents a unique game object instance static unsigned long sgGameObjectInstanceNum; // The number of active game object instances static Vector2D gRoomPoints[LINE_SEGMENTS_NUM * 2]; static LineSegment2D gRoomLineSegments[LINE_SEGMENTS_NUM]; #if(TEST_PART_2) static Vector2D gPillarsCenters[PILLARS_NUM]; static float gPillarsRadii[PILLARS_NUM]; static LineSegment2D gPillarsWalls[PILLARS_NUM / 2]; #endif // functions to create/destroy a game object instance static GameObjectInstance* GameObjectInstanceCreate(unsigned int ObjectType); // From OBJECT_TYPE enum static void GameObjectInstanceDestroy(GameObjectInstance* pInst); // --------------------------------------------------------------------------- // Functions to add/remove components static void AddComponent_Transform(GameObjectInstance *pInst, Vector2D *pPosition, float Angle, float ScaleX, float ScaleY); static void AddComponent_Sprite(GameObjectInstance *pInst, unsigned int ShapeType); static void AddComponent_Physics(GameObjectInstance *pInst, Vector2D *pVelocity); static void RemoveComponent_Transform(GameObjectInstance *pInst); static void RemoveComponent_Sprite(GameObjectInstance *pInst); static void RemoveComponent_Physics(GameObjectInstance *pInst); static GameObjectInstance *spBall; static GameObjectInstance *spBallVelocityDebugLine; // --------------------------------------------------------------------------- static int sgStopped = 0; // --------------------------------------------------------------------------- void GameStatePlayLoad(void) { unsigned int i; float CircleAngleStep; int Parts; Shape* pShape; // Zero the shapes array memset(sgShapes, 0, sizeof(Shape)* SHAPE_NUM_MAX); // No shapes at this point sgShapeNum = 0; // =============== // create the ball // =============== pShape = sgShapes + sgShapeNum++; pShape->mType = OBJECT_TYPE_BALL; AEGfxMeshStart(); CircleAngleStep = PI / 12.0f, i; Parts = 24; for (i = 0; i < Parts; ++i) { AEGfxTriAdd( 0.0f, 0.0f, 0xFFFFFF00, 0.0f, 0.0f, cosf(i * 2 * PI / Parts)*0.5f, sinf(i * 2 * PI / Parts)*0.5f, 0xFFFFFF00, 0.0f, 0.0f, cosf((i + 1) * 2 * PI / Parts)*0.5f, sinf((i + 1) * 2 * PI / Parts)*0.5f, 0xFFFFFF00, 0.0f, 0.0f); } pShape->mpMesh = AEGfxMeshEnd(); // =============== // create the line // =============== pShape = sgShapes + sgShapeNum++; pShape->mType = OBJECT_TYPE_LINE; AEGfxMeshStart(); AEGfxVertexAdd(0.0f, 0.0f, 0xFFFFFFFF, 0.0f, 0.0f); AEGfxVertexAdd(1.0f, 0.0f, 0xFFFFFFFF, 0.0f, 0.0f); pShape->mpMesh = AEGfxMeshEnd(); // ================= // create the pillar // ================= pShape = sgShapes + sgShapeNum++; pShape->mType = OBJECT_TYPE_PILLAR; AEGfxMeshStart(); CircleAngleStep = PI / 12.0f, i; Parts = 24; for (i = 0; i < Parts; ++i) { AEGfxTriAdd( 0.0f, 0.0f, 0xFFFFFF00, 0.0f, 0.0f, cosf(i * 2 * PI / Parts)*0.5f, sinf(i * 2 * PI / Parts)*0.5f, 0xFFFFFF00, 0.0f, 0.0f, cosf((i + 1) * 2 * PI / Parts)*0.5f, sinf((i + 1) * 2 * PI / Parts)*0.5f, 0xFFFFFF00, 0.0f, 0.0f); } pShape->mpMesh = AEGfxMeshEnd(); // ===================== // create the debug line // ===================== pShape = sgShapes + sgShapeNum++; pShape->mType = OBJECT_TYPE_DEBUG_LINE; AEGfxMeshStart(); AEGfxVertexAdd(0.0f, 0.0f, 0xFFFFFFFF, 0.0f, 0.0f); AEGfxVertexAdd(1.0f, 0.0f, 0xFFFFFFFF, 0.0f, 0.0f); pShape->mpMesh = AEGfxMeshEnd(); // Building map boundaries Vector2DSet(&gRoomPoints[0], -350.0f, 100.0f); Vector2DSet(&gRoomPoints[1], 0, 250.0f); Vector2DSet(&gRoomPoints[2], 0, 250.0f); Vector2DSet(&gRoomPoints[3], 350.0f, 100.0f); Vector2DSet(&gRoomPoints[4], 350.0f, 100.0f); Vector2DSet(&gRoomPoints[5], 275.0f, -250.0f); Vector2DSet(&gRoomPoints[6], 275.0f, -250.0f); Vector2DSet(&gRoomPoints[7], -275.0f, -250.0); Vector2DSet(&gRoomPoints[8], -275.0f, -250.0f); Vector2DSet(&gRoomPoints[9], -350.0f, 100.0f); // Build line segments for(i = 0; i < LINE_SEGMENTS_NUM; ++i) BuildLineSegment2D(&gRoomLineSegments[i], &gRoomPoints[i*2], &gRoomPoints[i*2 + 1]); #if(TEST_PART_2) // Pillars Vector2DSet(&gPillarsCenters[0], -200.0f, 0.0f); gPillarsRadii[0] = 15; Vector2DSet(&gPillarsCenters[1], -150.0f, 100.0f); gPillarsRadii[1] = 20; Vector2DSet(&gPillarsCenters[2], -100.0f, -150.0f); gPillarsRadii[2] = 15; Vector2DSet(&gPillarsCenters[3], 100.0f, -175.0f); gPillarsRadii[3] = 10; Vector2DSet(&gPillarsCenters[4], 175.0f, 100.0f); gPillarsRadii[4] = 20; Vector2DSet(&gPillarsCenters[5], 225.0f, -25.0f); gPillarsRadii[5] = 10; // Pillars walls for(i = 0; i < PILLARS_NUM/2; ++i) BuildLineSegment2D(&gPillarsWalls[i], &gPillarsCenters[i*2], &gPillarsCenters[i*2 + 1]); #endif } // --------------------------------------------------------------------------- void GameStatePlayInit(void) { unsigned int i; // zero the game object instance array memset(sgGameObjectInstanceList, 0, sizeof(GameObjectInstance)* GAME_OBJ_INST_NUM_MAX); // No game object instances (sprites) at this point sgGameObjectInstanceNum = 0; spBall = GameObjectInstanceCreate(OBJECT_TYPE_BALL); Vector2DSet(&spBall->mpComponent_Transform->mPosition, 0.0f, 0.0f); spBall->mpComponent_Transform->mScaleX = BALL_RADIUS * 2; spBall->mpComponent_Transform->mScaleY = BALL_RADIUS * 2; Vector2DSet(&spBall->mpComponent_Physics->mVelocity, 130.0f, 110.0f); // Wall instances for(i = 0; i < LINE_SEGMENTS_NUM; ++i) { float length, angle; Vector2D v; GameObjectInstance *pWall; length = Vector2DDistance(&gRoomPoints[2*i], &gRoomPoints[2*i + 1]); Vector2DSub(&v, &gRoomPoints[2*i + 1], &gRoomPoints[2*i]); Vector2DNormalize(&v, &v); angle = atan2(v.y, v.x); pWall = GameObjectInstanceCreate(OBJECT_TYPE_LINE); pWall->mpComponent_Transform->mPosition = gRoomPoints[2 * i]; pWall->mpComponent_Transform->mScaleX = length; pWall->mpComponent_Transform->mScaleY = 5.0f; pWall->mpComponent_Transform->mAngle = angle; } #if(TEST_PART_2) // Segments between pillars instances, and pillars instances for(i = 0; i < (PILLARS_NUM >> 1); ++i) { float length, angle; Vector2D v; GameObjectInstance *pInst; // segments length = Vector2DDistance(&gPillarsCenters[2*i], &gPillarsCenters[2*i + 1]); Vector2DSub(&v, &gPillarsCenters[2*i + 1], &gPillarsCenters[2*i]); Vector2DNormalize(&v, &v); angle = atan2(v.y, v.x); pInst = GameObjectInstanceCreate(OBJECT_TYPE_LINE); pInst->mpComponent_Transform->mPosition = gPillarsCenters[2 * i]; pInst->mpComponent_Transform->mScaleX = length; pInst->mpComponent_Transform->mScaleY = 5.0f; pInst->mpComponent_Transform->mAngle = angle; // Pillars pInst = GameObjectInstanceCreate(OBJECT_TYPE_PILLAR); pInst->mpComponent_Transform->mPosition = gPillarsCenters[2 * i]; pInst->mpComponent_Transform->mScaleX = gPillarsRadii[2 * i] * 2; pInst->mpComponent_Transform->mScaleY = gPillarsRadii[2 * i] * 2; pInst = GameObjectInstanceCreate(OBJECT_TYPE_PILLAR); pInst->mpComponent_Transform->mPosition = gPillarsCenters[2 * i + 1]; pInst->mpComponent_Transform->mScaleX = gPillarsRadii[2 * i + 1] * 2; pInst->mpComponent_Transform->mScaleY = gPillarsRadii[2 * i + 1] * 2; } #endif #if(DRAW_DEBUG) // Normals of the outer lines for(i = 0; i < LINE_SEGMENTS_NUM; ++i) { Vector2D pos; float angle; GameObjectInstance *pInst; pos.x = (gRoomPoints[2*i].x + gRoomPoints[2*i + 1].x) / 2.0f; pos.y = (gRoomPoints[2*i].y + gRoomPoints[2*i + 1].y) / 2.0f; angle = AEVec2AngleFromVec2(&gRoomLineSegments[i].mN); //CHECK THIS AAAA pInst = GameObjectInstanceCreate(OBJECT_TYPE_DEBUG_LINE); pInst->mpComponent_Transform->mPosition = pos; pInst->mpComponent_Transform->mScaleX = 25.0f; pInst->mpComponent_Transform->mScaleY = 5.0f; pInst->mpComponent_Transform->mAngle = angle; } spBallVelocityDebugLine = GameObjectInstanceCreate(OBJECT_TYPE_DEBUG_LINE); spBallVelocityDebugLine->mpComponent_Transform->mScaleX = 50.0f; spBallVelocityDebugLine->mpComponent_Transform->mScaleY = 1.0f; #if(TEST_PART_2) // Normals of the inner lines for(i = 0; i < (PILLARS_NUM >> 1); ++i) { Vector2D pos; float angle; GameObjectInstance *pInst; pos.x = (gPillarsCenters[2*i].x + gPillarsCenters[2*i + 1].x) / 2.0f; pos.y = (gPillarsCenters[2*i].y + gPillarsCenters[2*i + 1].y) / 2.0f; angle = AEVec2AngleFromVec2(&gPillarsWalls[i].mN); pInst = GameObjectInstanceCreate(OBJECT_TYPE_DEBUG_LINE); pInst->mpComponent_Transform->mPosition = pos; pInst->mpComponent_Transform->mScaleX = 25.0f; pInst->mpComponent_Transform->mScaleY = 5.0f; pInst->mpComponent_Transform->mAngle = angle; } #endif #endif AEGfxSetBackgroundColor(0.0f, 0.0f, 0.0f); } // --------------------------------------------------------------------------- void GameStatePlayUpdate(void) { float smallestT; Vector2D closestIntersectionPoint, r; unsigned int i; Vector2D newBallPos; Vector2D intersectionPoint; float frameTime = AEFrameRateControllerGetFrameTime(); int stopStep = 0; if (0 == sgStopped) { if (AEInputCheckTriggered('S')) // 'S' to stop the simulation sgStopped = 1; } else { if (AEInputCheckTriggered('R')) // 'R' to let the simulation run sgStopped = 0; else if (AEInputCheckTriggered('S')) // 1 step per 'S' trigger { frameTime = 0.016f; stopStep = 1; } else if (AEInputCheckCurr('G')) // Simulation runs as long as 'G' is pressed { frameTime = 0.016f; stopStep = 1; } } if (0 == sgStopped || 1 == stopStep) { // ================= // update the input // ================= // Update the positions of objects Vector2DScaleAdd(&newBallPos, &spBall->mpComponent_Physics->mVelocity, &spBall->mpComponent_Transform->mPosition, frameTime); smallestT = -1.0f; // Collision with line segments for(i = 0; i < LINE_SEGMENTS_NUM; ++i) { float t = ReflectAnimatedCircleOnStaticLineSegment(&spBall->mpComponent_Transform->mPosition, &newBallPos, BALL_RADIUS, &gRoomLineSegments[i], &intersectionPoint, &r); if(t > 0.0f && (t < smallestT || smallestT < 0.0f)) { closestIntersectionPoint = intersectionPoint; smallestT = t; } } #if(TEST_PART_2) // Collision with pillars (Static circles) for(i = 0; i < PILLARS_NUM; ++i) { float t = ReflectAnimatedCircleOnStaticCircle(&spBall->mpComponent_Transform->mPosition, &newBallPos, BALL_RADIUS, &gPillarsCenters[i], gPillarsRadii[i], &intersectionPoint, &r); if(t > 0.0f && (t < smallestT || smallestT < 0.0f)) { closestIntersectionPoint = intersectionPoint; smallestT = t; } } // Collision with pillars' walls (Line segments between the static circles) for (i = 0; i < PILLARS_NUM / 2; ++i) { float t = ReflectAnimatedCircleOnStaticLineSegment(&spBall->mpComponent_Transform->mPosition, &newBallPos, BALL_RADIUS, &gPillarsWalls[i], &intersectionPoint, &r); if (t > 0.0f && (t < smallestT || smallestT < 0.0f)) { closestIntersectionPoint = intersectionPoint; smallestT = t; } } #endif if (smallestT > 0.0) { Vector2DAdd(&spBall->mpComponent_Transform->mPosition, &closestIntersectionPoint, &r); Vector2DNormalize(&r, &r); Vector2DScale(&spBall->mpComponent_Physics->mVelocity, &r, Vector2DLength(&spBall->mpComponent_Physics->mVelocity)); } Vector2DScaleAdd(&spBall->mpComponent_Transform->mPosition, &spBall->mpComponent_Physics->mVelocity, &spBall->mpComponent_Transform->mPosition, frameTime); #if(DRAW_DEBUG) { float cosine, sine, velLength, angle; velLength = Vector2DLength(&spBall->mpComponent_Physics->mVelocity); cosine = spBall->mpComponent_Physics->mVelocity.x / velLength; sine = spBall->mpComponent_Physics->mVelocity.y / velLength; angle = acosf(cosine); if (sine < 0) angle = -angle; spBallVelocityDebugLine->mpComponent_Transform->mPosition = spBall->mpComponent_Transform->mPosition; spBallVelocityDebugLine->mpComponent_Transform->mAngle = angle; } #endif } //Computing the transformation matrices of the game object instances for (i = 0; i < GAME_OBJ_INST_NUM_MAX; ++i) { Matrix2D scale, rot, trans; GameObjectInstance* pInst = sgGameObjectInstanceList + i; // skip non-active object if (0 == (pInst->mFlag & FLAG_ACTIVE)) continue; Matrix2DScale(&scale, pInst->mpComponent_Transform->mScaleX, pInst->mpComponent_Transform->mScaleY); Matrix2DRotRad(&rot, pInst->mpComponent_Transform->mAngle); //CHECK THIS AAAA Matrix2DTranslate(&trans, pInst->mpComponent_Transform->mPosition.x, pInst->mpComponent_Transform->mPosition.y); Matrix2DConcat(&pInst->mpComponent_Transform->mTransform, &trans, &rot); Matrix2DConcat(&pInst->mpComponent_Transform->mTransform, &pInst->mpComponent_Transform->mTransform, &scale); } } // --------------------------------------------------------------------------- void GameStatePlayDraw(void) { unsigned int i; AEGfxSetRenderMode(AE_GFX_RM_COLOR); // draw all object in the list for (i = 0; i < GAME_OBJ_INST_NUM_MAX; i++) { GameObjectInstance* pInst = sgGameObjectInstanceList + i; // skip non-active object if (0 == (pInst->mFlag & FLAG_ACTIVE)) continue; AEGfxSetTransform(pInst->mpComponent_Transform->mTransform.m); switch (pInst->mpComponent_Sprite->mpShape->mType) { case OBJECT_TYPE_BALL: case OBJECT_TYPE_PILLAR: AEGfxMeshDraw(pInst->mpComponent_Sprite->mpShape->mpMesh, AE_GFX_MDM_TRIANGLES); break; case OBJECT_TYPE_LINE: case OBJECT_TYPE_DEBUG_LINE: AEGfxMeshDraw(pInst->mpComponent_Sprite->mpShape->mpMesh, AE_GFX_MDM_LINES); break; } } } // --------------------------------------------------------------------------- void GameStatePlayFree(void) { unsigned int i; // kill all object in the list for (i = 0; i < GAME_OBJ_INST_NUM_MAX; i++) GameObjectInstanceDestroy(sgGameObjectInstanceList + i); sgGameObjectInstanceNum = 0; } // --------------------------------------------------------------------------- void GameStatePlayUnload(void) { unsigned int i; // free all mesh for (i = 0; i < sgShapeNum; i++) AEGfxMeshFree(sgShapes[i].mpMesh); } // --------------------------------------------------------------------------- GameObjectInstance* GameObjectInstanceCreate(unsigned int ObjectType) // From OBJECT_TYPE enum) { unsigned long i; // loop through the object instance list to find a non-used object instance for (i = 0; i < GAME_OBJ_INST_NUM_MAX; i++) { GameObjectInstance* pInst = sgGameObjectInstanceList + i; // Check if current instance is not used if (pInst->mFlag == 0) { // It is not used => use it to create the new instance // Active the game object instance pInst->mFlag = FLAG_ACTIVE; pInst->mpComponent_Transform = 0; pInst->mpComponent_Sprite = 0; pInst->mpComponent_Physics = 0; // Add the components, based on the object type switch (ObjectType) { case OBJECT_TYPE_BALL: AddComponent_Sprite(pInst, OBJECT_TYPE_BALL); AddComponent_Transform(pInst, 0, 0.0f, 1.0f, 1.0f); AddComponent_Physics(pInst, 0); break; case OBJECT_TYPE_LINE: AddComponent_Sprite(pInst, OBJECT_TYPE_LINE); AddComponent_Transform(pInst, 0, 0.0f, 1.0f, 1.0f); break; case OBJECT_TYPE_PILLAR: AddComponent_Sprite(pInst, OBJECT_TYPE_PILLAR); AddComponent_Transform(pInst, 0, 0.0f, 1.0f, 1.0f); break; case OBJECT_TYPE_DEBUG_LINE: AddComponent_Sprite(pInst, OBJECT_TYPE_DEBUG_LINE); AddComponent_Transform(pInst, 0, 0.0f, 1.0f, 1.0f); break; } ++sgGameObjectInstanceNum; // return the newly created instance return pInst; } } // Cannot find empty slot => return 0 return 0; } // --------------------------------------------------------------------------- void GameObjectInstanceDestroy(GameObjectInstance* pInst) { // if instance is destroyed before, just return if (pInst->mFlag == 0) return; // Zero out the mFlag pInst->mFlag = 0; RemoveComponent_Transform(pInst); RemoveComponent_Sprite(pInst); RemoveComponent_Physics(pInst); --sgGameObjectInstanceNum; } // --------------------------------------------------------------------------- void AddComponent_Transform(GameObjectInstance *pInst, Vector2D *pPosition, float Angle, float ScaleX, float ScaleY) { if (0 != pInst) { if (0 == pInst->mpComponent_Transform) { pInst->mpComponent_Transform = (Component_Transform *)calloc(1, sizeof(Component_Transform)); } Vector2D zeroVec2; Vector2DZero(&zeroVec2); pInst->mpComponent_Transform->mScaleX = ScaleX; pInst->mpComponent_Transform->mScaleY = ScaleY; pInst->mpComponent_Transform->mPosition = pPosition ? *pPosition : zeroVec2;; pInst->mpComponent_Transform->mAngle = Angle; pInst->mpComponent_Transform->mpOwner = pInst; } } // --------------------------------------------------------------------------- void AddComponent_Sprite(GameObjectInstance *pInst, unsigned int ShapeType) { if (0 != pInst) { if (0 == pInst->mpComponent_Sprite) { pInst->mpComponent_Sprite = (Component_Sprite *)calloc(1, sizeof(Component_Sprite)); } pInst->mpComponent_Sprite->mpShape = sgShapes + ShapeType; pInst->mpComponent_Sprite->mpOwner = pInst; } } // --------------------------------------------------------------------------- void AddComponent_Physics(GameObjectInstance *pInst, Vector2D *pVelocity) { if (0 != pInst) { if (0 == pInst->mpComponent_Physics) { pInst->mpComponent_Physics = (Component_Physics *)calloc(1, sizeof(Component_Physics)); } Vector2D zeroVec2; Vector2DZero(&zeroVec2); pInst->mpComponent_Physics->mVelocity = pVelocity ? *pVelocity : zeroVec2; pInst->mpComponent_Physics->mpOwner = pInst; } } // --------------------------------------------------------------------------- void RemoveComponent_Transform(GameObjectInstance *pInst) { if (0 != pInst) { if (0 != pInst->mpComponent_Transform) { free(pInst->mpComponent_Transform); pInst->mpComponent_Transform = 0; } } } // --------------------------------------------------------------------------- void RemoveComponent_Sprite(GameObjectInstance *pInst) { if (0 != pInst) { if (0 != pInst->mpComponent_Sprite) { free(pInst->mpComponent_Sprite); pInst->mpComponent_Sprite = 0; } } } // --------------------------------------------------------------------------- void RemoveComponent_Physics(GameObjectInstance *pInst) { if (0 != pInst) { if (0 != pInst->mpComponent_Physics) { free(pInst->mpComponent_Physics); pInst->mpComponent_Physics = 0; } } } // ---------------------------------------------------------------------------<file_sep>/Project 3 - Template/main.c // --------------------------------------------------------------------------- // Project Name : Platformer // File Name : main.h // Author : <NAME> // Creation Date : 2007/04/26 // Purpose : main entry point for the test program // History : // - 2007/04/26 : - initial implementation // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // includes #include "AEEngine.h" #include "GameStateMgr.h" // Libraries #pragma comment (lib, "Alpha_Engine.lib") // --------------------------------------------------------------------------- // Static function protoypes // --------------------------------------------------------------------------- // main // --------------------------------------------------------------------------- // main int WINAPI WinMain(HINSTANCE instanceH, HINSTANCE prevInstanceH, LPSTR command_line, int show) { // Initialize the system AESysInitInfo sysInitInfo; sysInitInfo.mAppInstance = instanceH; sysInitInfo.mShow = show; sysInitInfo.mWinWidth = 800; sysInitInfo.mWinHeight = 600; sysInitInfo.mCreateConsole = 1; sysInitInfo.mMaxFrameRate = 60; sysInitInfo.mpWinCallBack = NULL;//MyWinCallBack; sysInitInfo.mClassStyle = CS_HREDRAW | CS_VREDRAW; sysInitInfo.mWindowStyle = WS_OVERLAPPEDWINDOW;//WS_POPUP | WS_VISIBLE | WS_SYSMENU | WS_CLIPCHILDREN | WS_CLIPSIBLINGS; sysInitInfo.mCreateWindow = 1; sysInitInfo.mWindowHandle = NULL; sysInitInfo.mHandleWindowMessages = 1; // Initialize the system if (0 != AESysInit(&sysInitInfo)) return 1; GameStateMgrInit(GS_PLAY); GSM_MainLoop(); // free the system AESysExit(); return 1; } // ---------------------------------------------------------------------------<file_sep>/Project 3 - Template/Vector2D.c #include "Vector2D.h" #include "Vector2D.h" #define EPSILON 0.0001 // --------------------------------------------------------------------------- void Vector2DZero(Vector2D *pResult) { pResult->x = 0; pResult->y = 0; } // --------------------------------------------------------------------------- void Vector2DSet(Vector2D *pResult, float x, float y) { pResult->x = x; pResult->y = y; } // --------------------------------------------------------------------------- void Vector2DNeg(Vector2D *pResult, Vector2D *pVec0) { pResult->x = -1 * pVec0->x; pResult->y = -1 * pVec0->y; } // --------------------------------------------------------------------------- void Vector2DAdd(Vector2D *pResult, Vector2D *pVec0, Vector2D *pVec1) { pResult->x = pVec0->x + pVec1->x; pResult->y = pVec0->y + pVec1->y; } // --------------------------------------------------------------------------- void Vector2DSub(Vector2D *pResult, Vector2D *pVec0, Vector2D *pVec1) { pResult->x = pVec0->x - pVec1->x; pResult->y = pVec0->y - pVec1->y; } // --------------------------------------------------------------------------- void Vector2DNormalize(Vector2D *pResult, Vector2D *pVec0) { float magnitude = sqrtf(powf(pVec0->x, 2) + powf(pVec0->y, 2)); pResult->x = pVec0->x / magnitude; pResult->y = pVec0->y / magnitude; } // --------------------------------------------------------------------------- void Vector2DScale(Vector2D *pResult, Vector2D *pVec0, float c) { pResult->x = pVec0->x * c; pResult->y = pVec0->y *c; } // --------------------------------------------------------------------------- //Scale THEN add void Vector2DScaleAdd(Vector2D *pResult, Vector2D *pVec0, Vector2D *pVec1, float c) { pResult->x = c * pVec0->x + pVec1->x; pResult->y = c*pVec0->y + pVec1->y; } // --------------------------------------------------------------------------- void Vector2DScaleSub(Vector2D *pResult, Vector2D *pVec0, Vector2D *pVec1, float c) { pResult->x = c * pVec0->x - pVec1->x; pResult->y = c*pVec0->y - pVec1->y; } // --------------------------------------------------------------------------- float Vector2DLength(Vector2D *pVec0) { return sqrtf(powf(pVec0->x, 2) + powf(pVec0->y, 2)); } // --------------------------------------------------------------------------- float Vector2DSquareLength(Vector2D *pVec0) { return powf(pVec0->x, 2) + powf(pVec0->y, 2); } // --------------------------------------------------------------------------- float Vector2DDistance(Vector2D *pVec0, Vector2D *pVec1) { return sqrtf(powf((pVec0->x - pVec1->x), 2) + powf(pVec0->y - pVec1->y, 2)); } // --------------------------------------------------------------------------- float Vector2DSquareDistance(Vector2D *pVec0, Vector2D *pVec1) { return (powf((pVec0->x - pVec1->x), 2) + powf(pVec0->y - pVec1->y, 2)); } // --------------------------------------------------------------------------- float Vector2DDotProduct(Vector2D *pVec0, Vector2D *pVec1) { return pVec0->x * pVec1->x + pVec1->y * pVec0->y; } // --------------------------------------------------------------------------- void Vector2DFromAngleDeg(Vector2D *pResult, float angle) { Vector2DFromAngleRad(pResult, angle * 3.14159265358979323846f / 180.f); } // --------------------------------------------------------------------------- void Vector2DFromAngleRad(Vector2D *pResult, float angle) { pResult->x = cosf(angle); pResult->y = sinf(angle); } // --------------------------------------------------------------------------- <file_sep>/Project 3 - Template/Math2D.c #include "Math2D.h" #include "stdio.h" int StaticPointToStaticCircle(Vector2D *pP, Vector2D *pCenter, float Radius) { if (Vector2DSquareDistance(pP, pCenter) > Radius*Radius) { return 0; } return 1; } /* This function checks if the point Pos is colliding with the rectangle whose center is Rect, width is "Width" and height is Height */ int StaticPointToStaticRect(Vector2D *pPos, Vector2D *pRect, float Width, float Height) { if (pPos->x < pRect->x - Width / 2 || pPos->x > pRect->x + Width / 2 || pPos->y < pRect->y - Height / 2 || pPos->y > pRect->y + Height / 2) { return 0; } return 1; } /* This function checks for collision between 2 circles. Circle0: Center is Center0, radius is "Radius0" Circle1: Center is Center1, radius is "Radius1" */ int StaticCircleToStaticCircle(Vector2D *pCenter0, float Radius0, Vector2D *pCenter1, float Radius1) { if (Vector2DSquareDistance(pCenter0, pCenter1) > powf(Radius0 + Radius1, 2)) { return 0; } return 1; } /* This functions checks if 2 rectangles are colliding Rectangle0: Center is pRect0, width is "Width0" and height is "Height0" Rectangle1: Center is pRect1, width is "Width1" and height is "Height1" */ int StaticRectToStaticRect(Vector2D *pRect0, float Width0, float Height0, Vector2D *pRect1, float Width1, float Height1) { if (pRect0->x - Width0 / 2 > pRect1->x + Width1 / 2 || pRect1->x - Width1 / 2 > pRect0->x + Width0 / 2 || pRect0->y - Height0 / 2 > pRect1->y + Height1 / 2 || pRect1->y - Height1 / 2 > pRect0->y + Height0 / 2) { return 0; } return 1; } ////////////////////// // New to Project 2 // ////////////////////// /* This function checks if a static circle is intersecting with a static rectangle Circle: Center is "Center", radius is "Radius" Rectangle: Center is "Rect", width is "Width" and height is "Height" Function returns true is the circle and rectangle are intersecting, otherwise it returns false */ int StaticCircleToStaticRectangle(Vector2D *pCenter, float Radius, Vector2D *pRect, float Width, float Height) { Vector2D closestPoint; Vector2DSet(&closestPoint, 0, 0); // SetVector2D(closestPoint, pRect->x, pRect->y); if (pCenter->x > pRect->x + 0.5*Width) { closestPoint.x = pRect->x + 0.5*Width; } else if (pCenter->x < pRect->x - 0.5*Width) { closestPoint.x = pRect->x - 0.5*Width; } else { closestPoint.x = pCenter->x; } if (pCenter->y > pRect->y + 0.5*Height) { closestPoint.y = pRect->y + 0.5*Height; } else if (pCenter->y < pRect->y - 0.5*Height) { closestPoint.y = pRect->y - 0.5*Height; } else { closestPoint.y = pCenter->y; } int output = StaticPointToStaticCircle(&closestPoint, pCenter, Radius); return output; //return 0; } ////////////////////// // New to project 3 // ////////////////////// /* This function determines the distance separating a point from a line - Parameters - P: The point whose location should be determined - LS: The line segment - Returned value: The distance. Note that the returned value should be: - Negative if the point is in the line's inside half plane - Positive if the point is in the line's outside half plane - Zero if the point is on the line */ float StaticPointToStaticLineSegment(Vector2D *P, LineSegment2D *LS) { //return 0.0f; return (Vector2DDotProduct(&LS->mN, P) - LS->mNdotP0); } /* This function checks whether an animated point is colliding with a line segment - Parameters - Ps: The point's starting location - Pe: The point's ending location - LS: The line segment - Pi: This will be used to store the intersection point's coordinates (In case there's an intersection) - Returned value: Intersection time t - -1.0f: If there's no intersection - Intersection time: If there's an intersection */ float AnimatedPointToStaticLineSegment(Vector2D *Ps, Vector2D *Pe, LineSegment2D *LS, Vector2D *Pi) { if( (Pe->x == Ps->x && Pe->y == Ps->y) ||(Vector2DDotProduct(&LS->mN, Ps) > LS->mNdotP0 && Vector2DDotProduct(&LS->mN, Pe) > LS->mNdotP0) || (Vector2DDotProduct(&LS->mN, Ps) < LS->mNdotP0 && Vector2DDotProduct(&LS->mN, Pe) < LS->mNdotP0)) { return -1.f; } //return -1.0f; Vector2D v; v.x = Pe->x - Ps->x; v.y = Pe->y - Ps->y; float t = Vector2DDotProduct(&LS->mN, &v); if ( t == 0.f) { return -1; } t = ((LS->mNdotP0 - Vector2DDotProduct(&LS->mN, Ps))/ Vector2DDotProduct(&LS->mN, &v)); if (t > 1 || t < 0) { return -1.f; } Vector2D tempI, line, nLine, ItoP1, ItoP0; Vector2DScaleAdd(&tempI, &v, Ps, t); Vector2DSub(&line, &LS->mP1, &LS->mP0); Vector2DSub(&ItoP1, &tempI, &LS->mP1); Vector2DSub(&ItoP0, &tempI, &LS->mP0); Vector2DSub(&nLine, &LS->mP0, &LS->mP1); if (Vector2DDotProduct(&line, &ItoP0) < 0 || Vector2DDotProduct(&nLine, &ItoP1) < 0) { return -1.f; } Vector2DSet(Pi, tempI.x, tempI.y); return t; } /* This function checks whether an animated circle is colliding with a line segment - Parameters - Ps: The center's starting location - Pe: The center's ending location - Radius: The circle's radius - LS: The line segment - Pi: This will be used to store the intersection point's coordinates (In case there's an intersection) - Returned value: Intersection time t - -1.0f: If there's no intersection - Intersection time: If there's an intersection */ float AnimatedCircleToStaticLineSegment(Vector2D *Ps, Vector2D *Pe, float Radius, LineSegment2D *LS, Vector2D *Pi) { //return -1.0f; float nR = -1 * Radius; if ((Pe->x == Ps->x && Pe->y == Ps->y) || (Vector2DDotProduct(&LS->mN, Ps) - LS->mNdotP0) < nR && (Vector2DDotProduct(&LS->mN, Pe) - LS->mNdotP0 < nR) || (Vector2DDotProduct(&LS->mN, Ps)- LS->mNdotP0 > Radius && Vector2DDotProduct(&LS->mN, Pe) - LS->mNdotP0 > Radius)) { return -1.f; } //return -1.0f; float d=Radius; if (StaticPointToStaticLineSegment(Ps, LS) < 0) { d *= -1; } Vector2D v; v.x = Pe->x - Ps->x; v.y = Pe->y - Ps->y; float t = Vector2DDotProduct(&LS->mN, &v); if (t == 0.f) { return -1; } t = (((LS->mNdotP0 - Vector2DDotProduct(&LS->mN, Ps) + d)) / Vector2DDotProduct(&LS->mN, &v)); if (t > 1 || t < 0) { return -1.f; } Vector2D tempI, line,nLine, ItoP1, ItoP0; Vector2DScaleAdd(&tempI, &v, Ps, t); Vector2DSub(&line, &LS->mP1, &LS->mP0); Vector2DSub(&ItoP1, &tempI, &LS->mP1); Vector2DSub(&ItoP0, &tempI, &LS->mP0); Vector2DSub(&nLine, &LS->mP0, &LS->mP1); if (Vector2DDotProduct(&line, &ItoP0) < 0 || Vector2DDotProduct(&nLine, &ItoP1) < 0) { return -1.f; } Vector2DSet(Pi, tempI.x, tempI.y); return t; } /* This function reflects an animated point on a line segment. It should first make sure that the animated point is intersecting with the line - Parameters - Ps: The point's starting location - Pe: The point's ending location - LS: The line segment - Pi: This will be used to store the intersection point's coordinates (In case there's an intersection) - R: Reflected vector R - Returned value: Intersection time t - -1.0f: If there's no intersection - Intersection time: If there's an intersection */ float ReflectAnimatedPointOnStaticLineSegment(Vector2D *Ps, Vector2D *Pe, LineSegment2D *LS, Vector2D *Pi, Vector2D *R) { float f = AnimatedPointToStaticLineSegment(Ps, Pe, LS, Pi); if (f < 0) { return -1.0f; } float speed = sqrtf(((Ps->x - Pe->x)*(Ps->x - Pe->x)) + ((Ps->y - Pe->y)*(Ps->y - Pe->y))); //Scale down by a factor of 1-t ? Vector2D i, r; Vector2DSet(&i, Pe->x - Pi->x, Pe->y - Pi->y); Vector2DScale(&r, &LS->mN, 2 * Vector2DDotProduct(&i, &LS->mN)); //Vector2DAdd(&i, Pi, &i); Vector2DSub(&r, &i, &r); Vector2DSet(R, r.x, r.y); Vector2DNormalize(R, R); //Vector2DScale(R, R, speed); //Vector2DAdd(Pe, &r, Pi); return f; } /* This function reflects an animated circle on a line segment. It should first make sure that the animated point is intersecting with the line - Parameters - Ps: The center's starting location - Pe: The center's ending location - Radius: The circle's radius - LS: The line segment - Pi: This will be used to store the intersection point's coordinates (In case there's an intersection) - R: Reflected vector R - Returned value: Intersection time t - -1.0f: If there's no intersection - Intersection time: If there's an intersection */ float ReflectAnimatedCircleOnStaticLineSegment(Vector2D *Ps, Vector2D *Pe, float Radius, LineSegment2D *LS, Vector2D *Pi, Vector2D *R) { //return -1.0f; float f = AnimatedCircleToStaticLineSegment(Ps, Pe,Radius, LS, Pi); if (f < 0) { return -1.0f; } float speed = sqrtf(((Ps->x - Pe->x)*(Ps->x - Pe->x)) + ((Ps->y - Pe->y)*(Ps->y - Pe->y))); //Scale down by a factor of 1-t ? Vector2D i, r; Vector2DSet(&i, Pe->x - Pi->x, Pe->y - Pi->y); Vector2DScale(&r, &LS->mN, 2 * Vector2DDotProduct(&i, &LS->mN)); // Vector2DAdd(&i, Pi, &i); Vector2DSub(&r, &i, &r); Vector2DNormalize(&r, &r); Vector2DSet(R, r.x, r.y); //Vector2DNormalize(R, R); //Vector2DScale(&r, &r, speed); //Vector2DAdd(Pe, &r, Pi); return f; } /* This function checks whether an animated point is colliding with a static circle - Parameters - Ps: The point's starting location - Pe: The point's ending location - Center: The circle's center - Radius: The circle's radius - Pi: This will be used to store the intersection point's coordinates (In case there's an intersection) - Returned value: Intersection time t - -1.0f: If there's no intersection - Intersection time: If there's an intersection */ float AnimatedPointToStaticCircle(Vector2D *Ps, Vector2D *Pe, Vector2D *Center, float Radius, Vector2D *Pi) { //return -1.0f; Vector2D v, bc, vUnit; float f, disc, a, b, c,m,n; Vector2DSub(&v, Pe, Ps); Vector2DSub(&bc, Center, Ps); Vector2DNormalize(&vUnit, &v); m = Vector2DDotProduct(&bc, &vUnit); n = ((v.x * v.x) + (v.y * v.y)) - (m*m); if ((Pe->x == Ps->x && Pe->y == Ps->y) || (n > Radius*Radius) || (m < 0 && Vector2DSquareDistance(Ps,Center) > Radius*Radius)) { return -1.f; } //Vector2D bc2; //Vector2DScale(&bc2, &bc, -2.f); a = Vector2DDotProduct(&v, &v); b = -2* Vector2DDotProduct(&bc, &v); c = (Vector2DDotProduct(&bc, &bc)) - (Radius * Radius); disc = (b*b) - (4.f * a*c); if(disc<0) { return -1.f; } else if (disc ==0) { f = b / (-2 * a); } else { float f1, f2; f1 = ((-1 * b) + sqrtf(disc)) / (2 * a); f2 = ((-1 * b) - sqrtf(disc)) / (2 * a); f = fminf(f1,f2); } if (f > 1.f || f < 0.f) { return -1; } Vector2DScaleAdd(Pi, &v, Ps, f); return f; } /* This function reflects an animated point on a static circle. It should first make sure that the animated point is intersecting with the circle - Parameters - Ps: The point's starting location - Pe: The point's ending location - Center: The circle's center - Radius: The circle's radius - Pi: This will be used to store the intersection point's coordinates (In case there's an intersection) - R: Reflected vector R - Returned value: Intersection time t - -1.0f: If there's no intersection - Intersection time: If there's an intersection */ float ReflectAnimatedPointOnStaticCircle(Vector2D *Ps, Vector2D *Pe, Vector2D *Center, float Radius, Vector2D *Pi, Vector2D *R) { //return -1.0f; float f = AnimatedPointToStaticCircle(Ps, Pe,Center, Radius, Pi); if(f<0) { return -1.f; } //float speed = sqrtf(((Ps->x - Pe->x)*(Ps->x - Pe->x)) + ((Ps->y - Pe->y)*(Ps->y - Pe->y))); //speed *= (1.f - f); Vector2D m, n,nS; Vector2DSub(&m, Ps, Pi); Vector2DSub(&n, Pi, Center); Vector2DNormalize(&n, &n); Vector2DScale(&nS, &n, 2 * Vector2DDotProduct(&m, &n)); Vector2DSub(R, &nS, &m); Vector2DNormalize(R, R); //Vector2DSet(R, nS.x, n.y); //Vector2DScale(&n, &n, speed); //Vector2DAdd(R, Pi, &n); return f; } /* This function checks whether an animated circle is colliding with a static circle - Parameters - Center0s: The starting position of the animated circle's center - Center0e: The ending position of the animated circle's center - Radius0: The animated circle's radius - Center1: The static circle's center - Radius1: The static circle's radius - Pi: This will be used to store the intersection point's coordinates (In case there's an intersection) - Returned value: Intersection time t - -1.0f: If there's no intersection - Intersection time: If there's an intersection */ float AnimatedCircleToStaticCircle(Vector2D *Center0s, Vector2D *Center0e, float Radius0, Vector2D *Center1, float Radius1, Vector2D *Pi) { //return -1.0f; return AnimatedPointToStaticCircle(Center0s, Center0e, Center1, (Radius0 + Radius1), Pi); } /* This function reflects an animated circle on a static circle. It should first make sure that the animated circle is intersecting with the static one - Parameters - Center0s: The starting position of the animated circle's center - Center0e: The ending position of the animated circle's center - Radius0: The animated circle's radius - Center1: The static circle's center - Radius1: The static circle's radius - Pi: This will be used to store the intersection point's coordinates (In case there's an intersection) - R: Reflected vector R - Returned value: Intersection time t - -1.0f: If there's no intersection - Intersection time: If there's an intersection */ float ReflectAnimatedCircleOnStaticCircle(Vector2D *Center0s, Vector2D *Center0e, float Radius0, Vector2D *Center1, float Radius1, Vector2D *Pi, Vector2D *R) { // return -1.0f; return ReflectAnimatedPointOnStaticCircle(Center0s, Center0e, Center1, (Radius0 + Radius1), Pi, R); } <file_sep>/Project 3 - Template/LineSegment2D.c #include "LineSegment2D.h" int BuildLineSegment2D(LineSegment2D *LS, Vector2D *Point0, Vector2D *Point1) { if (Point0->x == Point1->x && Point0->y == Point1->y) { return 0; } else { LS->mP0.x = Point0->x; LS->mP0.y = Point0->y; LS->mP1.x = Point1->x; LS->mP1.y = Point1->y; LS->mN.x = LS->mP1.y - LS->mP0.y; LS->mN.y = (LS->mP0.x - LS->mP1.x); Vector2DNormalize(&LS->mN, &LS->mN); LS->mNdotP0 = Vector2DDotProduct(&LS->mN, &LS->mP0); return 1; } //return 0; }
c90283506807befb17c1b69c91d17fb658b81b58
[ "C" ]
5
C
MidnightDrifter/CS529Proj3Collisions
0cb44f90d9b7b74956e37f1f0cf97dab50aaccae
f1f9e510edfff77e80de8161d09f9fc6d016d412
refs/heads/master
<file_sep>import time import logging from newspaper import Article import newspaper from datetime import datetime from pymongo import MongoClient from time import sleep import json logging.basicConfig(level=logging.INFO) mongo_server = "mongo" myclient = MongoClient("mongodb://{}:5003/".format(mongo_server)) mydb = myclient["mydatabase"] mycol = mydb["prueba"] #web_news = {'theguardian': 'https://www.theguardian.com/international/'} web_news = {'huffpost': 'https://www.huffpost.com/','theguardian': 'https://www.theguardian.com/international/', 'latimes':'https://www.latimes.com/'} def retrieve_elements(article): try: article.download() article.parse() return article except Exception as e: logging.info(e) logging.info(f"Failed fetching url {article}. Retrying in 10 seconds") #sleep(10) #return retrieve_elements(article) def extract_articles(): newspapers = [] for company, link in web_news.items(): i = 0 paper = newspaper.build(link, memoize_articles=True) for content in paper.articles: content = retrieve_elements(paper.articles[i]) if content is not None: i = i + 1 if content.publish_date is None: logging.info(f"nonetype {content.publish_date}") continue elif content.publish_date.strftime("%Y%m%d") == datetime.today().strftime("%Y%m%d"): logging.info(f"Downloading article {content.url}") newspapers.append({'Title':content.title, 'Text': content.text, 'Link': content.url, 'Time': content.publish_date}) # try: # with open('articles.json', 'w') as outfile: # json.dump(newspapers, outfile) # except Exception as e: logging.info(e) return newspapers <file_sep>#******************************************************* # Necessary packages import sys import re from pprint import pprint from collections import defaultdict import json import os import numpy as np import pandas as pd import statistics # nltk import nltk nltk.download('stopwords') nltk.download('punkt') from nltk.corpus import stopwords from nltk.tokenize import word_tokenize # Gensim import gensim import gensim.corpora as corpora from gensim.utils import simple_preprocess from gensim.models import CoherenceModel # Plotting tools import pyLDAvis import pyLDAvis.gensim import matplotlib.pyplot as plt from pymongo import MongoClient mongo_server = "mongo" #*********************************************************************** # Functions to get categories def clean_data(text): text = re.sub('[" ]', '', text) sprt = text.split('+') list_data=[] for i in range(0,len(sprt)): ap = sprt[i].split('*') list_data.append(ap) return list_data def find_max_mode(list1): list_table = statistics._counts(list1) len_table = len(list_table) if len_table == 1: max_mode = statistics.mode(list1) else: new_list = [] for i in range(len_table): new_list.append(list_table[i][0]) max_mode = max(new_list) # use the max value here return max_mode def analize(aux,categories): decition = [] for i in aux: flag = 0 val=0 tag = 'default' for x,y in categories.items(): #Just use y for z in y: if i[1]==z: flag = 1 tag = x break if flag != 0: break decition.append(tag) categorie=[] for i in decition: if i != 'default': categorie.append(i) if len(categorie)==0: categorie.append('default') categorie_topic = find_max_mode(categorie) return categorie_topic def get_cat(text,categories): text = list(text) data = clean_data(text[1]) categorie = analize(data,categories) return categorie #*********************************************************************** # Model function def model_function(): #*********************************************************************** # Defining the different news categories categories = {'Sports': ['football','ball','team','play','win','season','fan','run','scoore','athletics','spectator', 'competition','tennis','yard','game','fun','cricket','stadium','uefa','concacaf','player', 'game','referee'], 'Medical': ['patient','study','slave','food','eat','pain','treatment','syndrome','therapy','medicine', 'health','doctor','diagnosis','clinical','biomedical'], 'World News': ['israel','war','kill','soldier','attack','war','government','racism','internet','newpaper', 'journalism','telephone','earth','country','conflict','civil','military','peace','war', 'hurt','army'], 'Religion': ['god','evidence','christian','believe','reason','faith','exist','bible','religion', 'judaism','cult','belief','theology','church','symbol','homosexuality','hell'], 'Lifestyle': ['trending','fashion','entertainment','society','person','mode','lifestyles','casual', 'healthy','chic','cosmopolitan','popular','social','fashionable','celebrity','carpet', 'red','body','dress','business','workplace','fun','holiday','buy','living','hobbies','hipster'], 'Culture': ['education','knowledge','learn','learning','literacy','urbanity','class','civility','ignorance', 'civilization','life','values','legacy','tradition','society','philosophy','religion','nationalism', 'art','music','ritual','concept','humanism','classical'], 'Politics': ['government','diplomatic','law','political','politics','governance','republic','state', 'police','monarchy','democratic','federation','city','company','country','latin','uk','usa'], 'Technology': ['videogame','xbox','play','station','video','smartphone','nintendo','shooter','mobile', 'sony','gaming','electronics','engineering','science','robot','robotics','internet', 'computer','industry','automation','technological','energy','device','devices','application', 'app','technology'], 'Entertainment': ['television','film','movie','animation','comedy','cinema','media','show','circus','dance', 'concert','online','radio','party','ceremony','tourist'], 'Food': ['nutrition','rice','nutrient','beef','meat','cook','cooking','seafood','cereal','fat', 'soup','pasta','butter','agriculture','meal','milk','animals','chicken','plant','energy', 'vegetarian','protein','vitamin','nutriment','aliment','fruit','vegetable','restaurant', 'restaurants','eat','kitchen','pizza','taste'], } #*********************************************************************** # For eliminating unnecessary words add_stop_words = ['said','would','one','even','really','could','also'] stop_words = stopwords.words('english') [stop_words.append(i) for i in add_stop_words] stop_words_set = set(stop_words) #*********************************************************************** # Preparing the texts #*********************************************************************** # Pulling Mongo Data myclient = MongoClient("mongodb://{}:5003/".format(mongo_server)) mydb = myclient["mydatabase"] mycol = mydb["prueba"] res = mycol.find({}, {"Text": 1, "Title": 1, "Link": 1, "Time": 1}) res_data_frame=pd.DataFrame(list(res)) textos = res_data_frame["Text"] names = res_data_frame["Title"] urls = res_data_frame["Link"] time = res_data_frame["Time"] texts = [] documents = [] for t in textos: string = ''.join(t.splitlines()) string = string.lower() word_tokens = word_tokenize(string) filtered_sentence = [w for w in word_tokens if not w in stop_words_set] documents.append(" ".join(filtered_sentence)) texts.append(filtered_sentence) #*********************************************************************** # Model training and graph representation tokenized_list = [simple_preprocess(doc) for doc in documents] mydict = corpora.Dictionary() mycorpus = [mydict.doc2bow(doc, allow_update=True) for doc in tokenized_list] word_counts = [[(mydict[id], count) for id, count in line] for line in mycorpus] lda_model = gensim.models.ldamodel.LdaModel(corpus=mycorpus, id2word=corpora.Dictionary(tokenized_list), num_topics=len(categories), random_state=100,update_every=1, chunksize=100, passes=30, alpha='auto', per_word_topics=True) vis = pyLDAvis.gensim.prepare(lda_model, mycorpus, corpora.Dictionary(tokenized_list),n_jobs=2) graphhtml=pyLDAvis.prepared_data_to_html(vis) table_data=[] for topic in lda_model.print_topics(): topic_data=list(topic) cate = get_cat(topic,categories) table_data.append(topic_data) topic_data.append(cate) #******************************************************************** # DataFrame that tells the categories, # their ID's and the words that create them df_categories = pd.DataFrame(table_data,columns = ['ID','Words','Categorie']) #******************************************************************** get_document_topics = lda_model.get_document_topics(mycorpus) news_classification=[] for n in range(len(get_document_topics)): for i in range(len(table_data)): if get_document_topics[n][0][0]==table_data[i][0]: news_classification.append([get_document_topics[n][0][1],table_data[i][2],names[n],urls[n],time[n]]) #******************************************************************** # DataFrame that tells the categories for each article and its url df_classification=pd.DataFrame(news_classification,columns=['Belonging','Classification','Title','Link','Time']) df_classification=df_classification.sort_values(by="Time",ascending=True) df_classification["Time"]=df_classification["Time"].apply(lambda x: x.ctime()) return [df_categories,df_classification,graphhtml] <file_sep># FRONTEND This just does the frontend, and communicates it to the different steps of the program <file_sep>from scraper import app def scraper_app(): app.run( host='0.0.0.0', port='5002', debug=True, ) <file_sep>FROM python:3.7 WORKDIR /app ADD . /app RUN pip install --upgrade pip RUN python setup.py develop EXPOSE 5000 CMD ["start-frontend"] <file_sep>FROM python:3.7 WORKDIR /app ADD . /app RUN pip install --upgrade pip RUN pip install gensim pyldavis nltk RUN python setup.py develop EXPOSE 5000 CMD ["start-lda"] <file_sep>from lda import app def lda_app(): app.run( host='0.0.0.0', port='5001', debug=True, ) <file_sep>from flask import Flask,jsonify, render_template,request,Response import pandas as pd import logging import requests import json logging.basicConfig(level=logging.INFO) scraper_server = "scraper" lda_server = "lda" app = Flask(__name__, template_folder="templates") @app.route("/", methods=["GET"]) def index(): if request.method == "GET": return render_template( "index.html" ) @app.route("/extract", methods=["GET"]) def extract(): if request.method=="GET": logging.info("Extracting ...") res = requests.get("http://{}:5002/loading".format(scraper_server)) if res.status_code < 300: logging.info("Finish Extracting ...") return Response(status=200) else: logging.info("There was an error when extracting") return Response(status=400) @app.route("/result", methods=["GET", "POST"]) def get_result_from_model(): if request.method == "POST": logging.info("Going to LDA") req = requests.get("http://{}:5001/lda".format(lda_server)) logging.info("Going back from LDA") respuesta = json.loads(req.text) df_categories = pd.read_json(respuesta["df_categories"]) df_classification = pd.read_json(respuesta["df_classification"]) graphhtml = respuesta["graphhtml"] logging.info("I got the resulting dataframes") rows_categories, col_categories = df_categories.shape rows_classification, col_classification = df_classification.shape #******************************************************************** # Returning dataframes of categories and news classification return render_template("result.html",df_categories=df_categories,df_classification=df_classification, rows_categories=rows_categories,col_categories=col_categories, rows_classification=rows_classification,col_classification=col_classification,graphhtml=graphhtml) @app.route('/about') def about_page(): return render_template('about.html') <file_sep># Web Crawler Flask app applying Latent Dirichlet Allocation (LDA) in order to classify the topic of daily news. <file_sep># LDA This microservice gets the News Database from mongo and does the LDA algorithm <file_sep># SCRAPER This microservice does the scrapping of the different news web pages, and uploads the database created with them to Mongo <file_sep>FROM python:3.7 WORKDIR /app ADD . /app RUN pip install --upgrade pip RUN pip install newspaper3k RUN python setup.py develop EXPOSE 5000 CMD ["start-scraper"] <file_sep>import lda_functions from flask import Flask,jsonify, render_template,request,Response import json import logging logging.basicConfig(level=logging.INFO) app = Flask(__name__) @app.route("/lda", methods = ["GET", "POST"]) def get_result_from_model(): if request.method == "GET": logging.info("Starting LDA") #******************************************************************** # Returning dataframes of categories and news classification [df_categories, df_classification,graphhtml] = lda_functions.model_function() logging.info("Getting categories and classification dataframes") return json.dumps({ "df_categories": df_categories.to_json(), "df_classification": df_classification.to_json(), "graphhtml": graphhtml, }) <file_sep>import scraper_functions from flask import Flask,request,Response import logging import pymongo from pymongo import MongoClient logging.basicConfig(level=logging.INFO) mongo_server = "mongo" myclient = MongoClient("mongodb://{}:5003/".format(mongo_server)) mydb = myclient["mydatabase"] mycol = mydb["prueba"] app = Flask(__name__) @app.route("/loading", methods=["GET"]) def scraper(): logging.info("I will see if there are new articles") if request.method == "GET": my_list = scraper_functions.extract_articles() if len(my_list) > 0: x = mycol.insert_many(my_list) logging.info("I updated the mongo database") else: logging.info("No new articles") return Response(status=200) else: logging.info("You screw up") return Response(status=400)
41287d0fac638a772acd4d331b60229d9ec0688b
[ "Markdown", "Python", "Dockerfile" ]
14
Python
bazickoff/WebCrawler
d312ad7056470fe8abb159f2b8ddf01f323865fc
6caf7487c1643cbdd7991e2d9c8a831ab7b80ac4
refs/heads/master
<file_sep><!DOCTYPE html> <head> <meta charset="utf-8"> <title>СуперФотографии</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> body { background-image: url(bck.jpg); /* Путь к фоновому изображению */ } </style> <style type="text/css"> #featured { width: 940px; height: 450px; background: #009cff url('loading.gif') no-repeat center center; overflow: hidden; } </style> <!-- Attach our CSS --> <link rel="stylesheet" href="orbit.css"> <!--[if IE]> <style type="text/css"> .timer { display: none !important; } div.caption { background:transparent; filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000,endColorstr=#99000000);zoom: 1; } </style> <![endif]--> <!-- Attach necessary scripts --> <script type="text/javascript" src="jquery-1.4.1.min.js"></script> <script type="text/javascript" src="jquery.orbit.min.js"></script> <!-- Run the plugin --> <script type="text/javascript"> $(window).load(function() { $('#featured').orbit({ 'bullets': true, 'timer' : true, 'animation' : 'horizontal-slide' }); }); </script> </head> <body> <div class="container"> <a href="mbl1.html"><button><img class="mg" src="menubtn.png"></button></a> <div id="featured" class="fe"> <img src="link.jpg" alt="Link" /> <a href="#"><img src="ezio.jpg" alt="Ezio" rel="ezioCaption" /></a> <img src="masterchief.jpg" alt="Master Chief" /> <img src="marcusfenix.jpg" alt="<NAME>" rel="marcusCaption" /> </div> <p class="btxt">С другой стороны постоянный количественный рост и сфера нашей активности представляет собой интересный эксперимент проверки направлений прогрессивного развития. Идейные соображения высшего порядка, а также сложившаяся структура организации позволяет оценить значение позиций, занимаемых участниками в отношении поставленных задач. Товарищи! укрепление и развитие структуры обеспечивает широкому кругу (специалистов) участие в формировании форм развития. Значимость этих проблем настолько очевидна, что рамки и место обучения кадров обеспечивает широкому кругу (специалистов) участие в формировании форм развития. Задача организации, в особенности же новая модель организационной деятельности способствует подготовки и реализации системы обучения кадров, соответствует насущным потребностям. Задача организации, в особенности же реализация намеченных плановых заданий влечет за собой процесс внедрения и модернизации систем массового участия. Разнообразный и богатый опыт начало повседневной работы по формированию позиции позволяет оценить значение направлений прогрессивного развития. Равным образом рамки и место обучения кадров позволяет выполнять важные задания по разработке системы обучения кадров, соответствует насущным потребностям. Задача организации, в особенности же реализация намеченных плановых заданий позволяет выполнять важные задания по разработке системы обучения кадров, соответствует насущным потребностям. Значимость этих проблем настолько очевидна, что сложившаяся структура организации позволяет выполнять важные задания по разработке форм развития. Не следует, однако забывать, что начало повседневной работы по формированию позиции обеспечивает широкому кругу (специалистов) участие в формировании соответствующий условий активизации. Равным образом дальнейшее развитие различных форм деятельности требуют от нас анализа существенных финансовых и административных условий. Таким образом начало повседневной работы по формированию позиции обеспечивает </p> </body> </html><file_sep>$(document).ready(function(){ $("carusel-slider").flickity({ cellSelector: '.carusel-cell', }); });<file_sep><!DOCTYPE html> <html> <head> <link rel="stylesheet" href="buy.css"> <title>Купить/Скачать</title> <meta charset="utf-8"> </head> <body> <div class="nav-wrap"> <ul class="group" id="menu"> <li class="current_page_item"> <a href="index.html">Домашняя страница</a> </li> <li><a href="">Скачать\Купить</a></li> <li><a href="instruction.html">Туториал</a></li> <li><a href="about_us.html">О нас</a></li> </ul> </nav> <pre>Нашу игру можно скачать здесь ->></pre> <button><a href="index.html">Скачать</a></button> <footer> &copy;ProGame </footer> </body> </html><file_sep># from math import * # h = 9 # m = 0 # k = 0 # a = int(input()) # if a % 2 == 0: # k = int((a / 2 - 1)) * 15 + ((a / 2) * 5) + (45 * a) # elif a%2 !=0: # k = ceil((a/2-1))*15 + (a/2)*5 + 45 *a # print(a/2-1) # # # h += int(k//60) # m += int(k%60) # # print(h," ",m) # # a = int(input()) # b = int(input()) # n = int(input()) # # a1 = a*n # b1 = b*n # b1 = b1/100 # a1 += int(b1//100) # print(a1," ", b1) # h = int(input()) # a = int(input()) # b = int(input()) # k = 0 # while a<=h: # k+=1 # a += a-b # print(k) # # A = int(input()) # B = int(input()) # a = [] # for i in range(B,A+1): # if i%2!=0: # a.append(i) # a.reverse() # for i in range(0, len(a)): # print(a[i]) # # a = int(inpur()) # arr = [] # for i in range(0,a): # arr.append(i*i*i) # print(sum(arr)) k = 0 c = int(input()) for i in range(0,c): a = int(input()) if a == 0: k+=1 print(k)<file_sep>import sys from PIL import Image from PyQt5.QtWidgets import QWidget, QToolTip, QPushButton, QApplication,QDesktopWidget,QHBoxLayout from PyQt5.QtWidgets import QLabel,QGridLayout,QLabel,qApp,QAction,QMainWindow,QFileDialog,QMessageBox from PyQt5.QtGui import QFont from PyQt5.QtGui import QIcon,QColor from PyQt5.QtCore import QCoreApplication from PyQt5.QtGui import QPixmap class MyWindow(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): exitAction = QAction("&Выход", self) exitAction.setShortcut('Ctrl+Q') exitAction.setStatusTip("Выход") exitAction.triggered.connect(qApp.quit) openAction = QAction("&Открыть", self) openAction.setShortcut('Ctrl+O') openAction.setStatusTip("Открытие") openAction.triggered.connect(self.openPhoto) self.statusBar() menu = self.menuBar() fileMenu = menu.addMenu("&Файл") fileMenu.addAction(exitAction) fileMenu.addAction(openAction) grid = QGridLayout() grid.setSpacing(60) self.question = QLabel() grid.addWidget(self.question,5,5) self.nextButton = QPushButton("Оттенок серого") self.nextButton.resize(self.nextButton.sizeHint()) self.nextButton.move(1, 800) self.nextButton.clicked.connect(self.setFiltr_grown) btn = QPushButton('Просто кнопка', self) btn.resize(btn.sizeHint()) btn.move(90, 800) btn = QPushButton('', self) btn.resize(btn.sizeHint()) btn.move(180, 800) pixmap = QPixmap("photo_edit_icon.png") self.lbl = QLabel(self) self.lbl.setPixmap(pixmap) self.setCentralWidget(self.lbl) self.move(500, 500) self.setWindowTitle('') self.setWindowIcon(QIcon('photo_edit_icon.png')) self.show() def closeEvent(self, event): reply = QMessageBox.question(self, 'Message', "Вы действительно хотите выйти??", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: event.accept() else: event.ignore() def openPhoto(self): fname = QFileDialog.getOpenFileName(self,'Открыть файл', '.') self.lbl.setPixmap(QPixmap(fname[0])) def setFiltr_grown(): im = Image.open(fname +".jpg") pixels = im.load() x,y = im.size for i in range(x): for j in range(y): r = pixels[i, j][0] g = pixels[i, j][1] b = pixels[i, j][2] S = (r + g + b) // 3 S = r,g,b if __name__ == '__main__': app = QApplication(sys.argv) wi = MyWindow() sys.exit(app.exec_())<file_sep># n, m = [int(x) for x in input().split()] # arr1 = [int(x) for x in input().split()] # arr2 = [int(x) for x in input().split()] def bisect_left(a, x, lo=0, hi=None): if lo < 0: raise ValueError('lo must be non-negative') if hi is None: hi = len(a) while lo < hi: mid = (lo + hi) // 2 if a[mid] < x: lo = mid + 1 else: hi = mid return lo def bisect_right(a, x, lo=0, hi=None): if lo < 0: raise ValueError('lo must be non-negative') if hi is None: hi = len(a) while lo < hi: mid = (lo + hi) // 2 if x < a[mid]: hi = mid else: lo = mid + 1 return lo N, M = input().split() list1 = [int(x) for x in input().split()] list2 = [int(x) for x in input().split()] for x in list2: i = bisect_left(list1, x) try: if list1[i] == x: print(i + 1, bisect_right(list1, x, i)) except IndexError: print("0") def binary_search(lst, x): lower_bound = 0 upper_bound = len(lst) while lower_bound != upper_bound: compared_value = (lower_bound + upper_bound) // 2 # Целочисленный тип в Python имеет неограниченную длину if x == lst[compared_value]: return compared_value elif x < lst[compared_value]: upper_bound = compared_value else: lower_bound = compared_value + 1 return None # если цикл окончен, то значение не найденно # else: # print(0) <file_sep>/*#include <iostream> #include <conio.h> using namespace std; int main() { int i,j,k,n; int arr[5]; n = sizeof(arr)/sizeof(arr[0]); for(i=0;i<5;i++){ cin>>arr[i]; } i = 0; for(i=0;i<n-1;i++){ for(j=0;j<n-1-i;j++){ if(arr[j]>arr[j+1]){ k = arr[j]; arr[j] = arr[j+1]; arr[j+1] = k; } } } for(i=0;i<n;i++){ cout<<arr[i]<<" "; } } */ #include <iostream> #include <algorithm> using namespace std; int main() { const int lenght = 5; int arr[lenght] = {21,321,532,234,234}; int i; for(int ifirst = 0; ifirst<lenght - 1; ++ifirst){ int smallest = ifirst; for (i = ifirst + 1; i<lenght;++i){ if(arr[i]<arr[smallest]){ smallest = i; } } swap(arr[ifirst],arr[smallest]); } for(int index = 0 ; index < lenght; ++index){ cout<<arr[index]<<" "; } } <file_sep>import math print("Вычислительные операции : ") print("________________________") print("| Сложение: + |") print("_______________________|") print("_______________________|") print("| Разность - |") print("_______________________|") print("_______________________|") print("| Частное / |") print("_______________________|") print("_______________________|") print("| Произведение * |") print("_______________________|") print("_______________________|") print("| Корень // |") print("_______________________|") print("_______________________|") print("| Синус sin |") print("_______________________|") print("_______________________|") print("| Косинус cos |") print("_______________________|") print("_______________________|") print("| Тангесы tan |") print("_______________________|") print("_______________________|") print("| Найти гипотенузу Pif |") print("_______________________|") while True: try: while True: num1 = int(input("Введите первое число :")) num2 = int(input("Введите второе число :")) op = input("Введите опреатора : ") if op == "+": print("Сумма чисел ",num1, " и ",num2," = ",num1+num2) elif op == "-": print("Разность чисел ",num1, " и ",num2," = ",num1-num2) elif op == "/": print("Частное чисел ",num1, " и ",num2, " = ",num1/num2) elif op == " * ": print("Произведение чисел ",num1, " и ",num2, " = ",num1*num2) elif op == "//": print("Корень чисел ",num1," и ",num2, " = ", math.sqrt(num1)," и ",math.sqrt(num2)) elif op == "sin": print("Синус чисел ",num1," и ",num2, " = ", math.sin(num1), " и ",math.sin(num2)) elif op == "cos": print("Косинус чисел",num1," и ",num2, " = ", math.cos(num1), " и ",math.cos(num2)) elif op == "tan": print("Тангенсы чисел",num1," и ",num2," = ", math.tan(num2), " и ",math.tan(num2)) elif op == "Pif": gip = (num1*num1)+(num2*num2) print("Сумма квадратов катетов",num1," и ",num2," = ", "√",gip," корень =",math.sqrt(gip)) except ValueError: print("Введите число, а не букву") <file_sep>print("Представьте, что вы идёте по улице , и встетили пилу-гопника ") import time time.sleep(2) print ("Каковы ваши первые действия?") print("1- Убежать,попробовав как в голивудских фильмах перепрыгивать через заборы... ") time.sleep(3) print("2- Просто молча пройти мимо ...") time.sleep(2) print("3- Достать базуку и снаряды для неё из кармана ,стрельнув в него ими") time.sleep(3) print("4- Взять на прогиб") d = int(input()) if d == 1: print("В итоге вы наткнётесь на сторожевых псов , которые вас загрызут") elif d == 2: print("Я конечно пониаю что вы очень смелый , но пила-гопник просто вас убьёт...") elif d == 3 : print("Ясно , очередной суицидник который не понимает чего творит и считает что базука всё решает...") elif d == 4 : print("Только истинный дагестанец сможет так поступить и его поступок полностью оправдан!") time.sleep(2) print("Пила-гопник смылся,но,вместо него пришёл бухой Гай-фокс") print("Он решил отомстить за пилу-гопника и попытался вас атаковать") time.sleep(2) print("Ваши действия:") print("1-Убежать , 2-Самозащита, 3-Позвать на помощь") d1 = int(input()) if d1 == 1: print("Дебил... Вас всё равно настигнут...") elif d1 == 2: print("2-ой раз не прокатит...") elif d1 == 3: print("К вам на помощь пришли великие Саид и Андрей , которые надавали леща ему и вы благополучно вернулись домой...")<file_sep>$(document).ready(function() { $(".shaurma-slider").flickity({ cellSelector: '.shaurma-cell', cellAlign: 'right' }); }); <file_sep>$(document).ready(function(){ $("carusel-slider").flickity({ cellSelector: '.carusel-cell', imagesLoaded: true, freeScroll: true, wrapAround: true, autoPlay: 1500, groupCells: true }); });<file_sep>import random while True: try: from PIL import Image name = input("Введите имя файла : ") im = Image.open(name+".jpg") pixels = im.load() x,y = im.size spisok = ("""Выберите оттенок \n Оттенок серого """) spisok1 = input("Введите что-то") if spisok1 == "spisok": print(spisok) print("""Выберите оттенок: \n Оттенок серого - grown \n Негатив - negative \n Сепия - sepia\n Проиизвольны - prois\n Рандомный - random""") filtr = input("Введите команду ыыыы))") if filtr == "grown": for i in range(x): for j in range(y): r = pixels[i, j][0] g = pixels[i, j][1] b = pixels[i, j][2] S = (r + g + b) // 3 S = r,g,b elif filtr == "negative" : for i in range(x): for j in range(y): r = pixels[i, j][0] g = pixels[i, j][1] b = pixels[i, j][2] pixels[i,j] = (255 - r, 255 - g , 255- b) elif filtr == "sepia": dep = int(input("Введите число")) for i in range(x): for j in range(y): r, g, b = pixels[i, j] mid = (r + g + b) //3 pixels[i ,j] = mid , mid , mid r, g, b = mid + dep *2,mid +dep,mid pixels[i, j] = r ,g ,b elif filtr == "prois": a = int(input("Введите r")) b = int(input("Введите g")) c = int(input("Введите b")) for i in range(x): for j in range(y): r,g,b = pixels[i,j] pixels[i,j] = a,b,c elif filtr == "random": a = random.randint(1,1000) b = random.randint(1,1000) c = random.randint(1,1000) for i in range(x): for j in range(y): r,g,b = pixels[i,j] pixels[i,j] = a,b,c else : print("Такого фильтра нет...") im.show() im.save("l18.jpg") except FileNotFoundError: print("Возможно такого файла не существует... Введите настоящее имя") except ValueError: print("Введите число !!! За это вам наказание в качестве того,что вы должны заново всё ввести:D") <file_sep>var a = promt("Введите первое число"); var b = promt("Введите второе число"); console.log(a+b);
5a7753af6a7949f523d6a06b2369eaf2165e0450
[ "JavaScript", "Python", "HTML", "C++" ]
13
HTML
Madara228/aprog
06387fee7368b458890c1c00b8bb398f0f1eddb3
ecb98eed00d971beab6aa93e154ecd42deae4a24
refs/heads/master
<repo_name>Razakai/front-end-vue-app<file_sep>/src/components/clubModel/clubModel.js import TextInput from '../sections/TextInput/TextInput.vue' import GButton from '../sections/GButton/GButton.vue' export default { name: 'clubModel', components: { TextInput, GButton }, props: { editClub: { type: String, required: false, default: '' } }, data: () => { return { maxsize: '', facility: '', trainer: '', duration: '', calories: '', photo: '', date: '', time: '', name: '' } }, computed: { modelName () { if (this.editClub !== '') { return 'Update Club' } return 'Create Club' }, getAvailableTrainers () { return this.$store.getters.getAvailableTrainers({ includeCurrentUser: true }) }, validateForm () { if ( this.maxsize !== '' && this.facility !== '' && this.trainer !== '' && this.duration !== '' && this.calories !== '' && this.photo !== '' && this.date !== '' && this.time !== '' && this.name !== '' ) { return true } return false }, getFacilities () { return this.$store.getters.getFacilities } }, methods: { closeModel () { this.$emit('close-model') }, async updateClub () { if (this.noClubClash()) { await this.$store.dispatch('updateClub', { details: { maxSize: this.maxsize, facility: this.facility, trainer: this.trainer, duration: this.duration, calories: this.calories, photo: this.photo, date: this.date, time: this.time, name: this.name }, clubName: this.editClub }) this.closeModel() } }, async createClub () { await this.$store.dispatch('createClub', { details: { maxSize: this.maxsize, facility: this.facility, trainer: this.trainer, duration: this.duration, calories: this.calories, photo: this.photo, date: this.date, time: this.time, name: this.name } }) this.closeModel() }, noClubClash () { return this.$store.getters.getClubs.filter(e => e.name === this.name && e.name !== this.editClub).length === 0 } }, created () { if (this.editClub !== '') { const club = this.$store.getters.getClubByName(this.editClub) this.maxsize = club.maxSize this.facility = club.facility this.trainer = club.trainer this.duration = club.duration this.calories = club.calories this.photo = club.photo this.date = club.date this.time = club.time this.name = club.name } } } <file_sep>/src/store/mutation-types.js export const RESET_STATE = 'RESET_STATE' export const SET_ISLOGGEDIN = 'SET_ISLOGGEDIN' export const CREATE_EVENT = 'CREATE_EVENT' export const CREATE_USER = 'CREATE_USER' export const UPDATE_USER = 'UPDATE_USER' export const CREATE_CLUB = 'CREATE_CLUB' export const UPDATE_CLUB = 'UPDATE_CLUB' export const SET_CHANGE_PASSWORD = '<PASSWORD>' <file_sep>/src/components/sections/GButton/GButton.js export default { name: 'GButton', props: { disabled: { type: Boolean, required: false, default: false } }, methods: { onClick (event) { if (this.disabled) { event.stopPropagation() event.preventDefault() } else { // this.$emit('click', event) } } } } <file_sep>/src/components/sections/GButton/README.md # Examples ```html <w-button @click="onClick" :variant="'primary'" :disabled="false">Click me!</w-button> ``` ``` html <w-button :variant="'primary'" :disabled="false">primary</w-button> ``` ``` html <w-button :variant="'info'" :disabled="false">info</w-button> ``` ``` html <w-button :variant="'alert'" :disabled="false">alert</w-button> ``` ``` html <w-button :variant="'primary'" :disabled="true">disabled</w-button> ``` <file_sep>/src/pages/bookings/bookings.js import TextInput from '../../components/sections/TextInput/TextInput.vue' import bookingsTable from '../../components/bookingsTable/bookingsTable.vue' import Fuse from 'fuse.js' export default { name: 'bookings', components: { TextInput, bookingsTable }, data: () => { return { multiselect: 'name', searchTerm: '', showAppointments: false } }, computed: { getbookings () { let bookings = this.$store.getters.getBookings({ getAppointments: this.showAppointments }) if (this.searchTerm !== '') { const fuse = new Fuse(bookings, { keys: [this.multiselect], threshold: this.multiselect === 'bookingDate' ? 0 : 0.2 }) bookings = fuse.search(this.searchTerm) .map(e => { return { ...e.item } }) } return bookings } }, methods: { } } <file_sep>/src/pages/profile/profile.js import TextInput from '../../components/sections/TextInput/TextInput.vue' import GButton from '@/components/sections/GButton/GButton.vue' export default { name: 'profile', components: { TextInput, GButton }, data: () => { return { firstName: '', lastName: '', gender: '', age: '', weight: '', height: '', address: '', email: '', phoneNumber: '', status: '', // student, staff, neither membership: '', // one year, open ended username: '', password: '', test: '', passwordUpdated: false, usernameUpdated: false, profileUpdated: false } }, computed: { }, methods: { getUserDetails () { return this.$store.getters.getLoggedInUser }, createNewProfileObject () { return { firstName: this.firstName, lastName: this.lastName, gender: this.gender, age: this.age, weight: this.weight, height: this.height, address: this.address, email: this.email, phoneNumber: this.phoneNumber, membership: this.membership, username: this.username, status: this.status, password: <PASSWORD> } }, isFormFilled () { if ( this.firstName.length > 0 && this.lastName.length > 0 && this.gender.length > 0 && this.age.length > 0 && this.weight.length > 0 && this.height.length > 0 && this.address.length > 0 && this.email.length > 0 && this.phoneNumber.length > 0 && this.membership.length > 0 && this.username.length > 0 && this.status.length > 0 && this.password.length > 0 ) { return true } return false }, isUserDataClashing () { const newProfile = this.createNewProfileObject() const currentProfile = this.getUserDetails() const diff = Object.keys(newProfile).reduce((diff, key) => { if (currentProfile[key] === newProfile[key]) return diff return { ...diff, [key]: newProfile[key] } }, {}) if (Object.keys(diff).length > 0) { if ('password' in diff) { this.passwordUpdated = true } if ('username' in diff) { this.usernameUpdated = true } return !this.$store.getters.getUsers({ includeCurrentUser: false }).some( user => user.username === this.username ) } return false }, async updateProfile () { this.resetUpdatedStatus() if (this.isFormFilled() && this.isUserDataClashing()) { const details = this.createNewProfileObject() if (this.passwordUpdated) { Object.assign(details, { passwordLastChangedDate: new Date() }) } await this.$store.dispatch('updateUser', { details, usernameUpdated: this.usernameUpdated }) this.profileUpdated = true } }, resetUpdatedStatus () { this.passwordUpdated = false this.usernameUpdated = false this.profileUpdated = false } }, created () { const user = this.getUserDetails() this.firstName = user.firstName this.lastName = user.lastName this.gender = user.gender this.age = user.age this.weight = user.weight this.height = user.height this.address = user.address this.email = user.email this.phoneNumber = user.phoneNumber this.status = user.status this.membership = user.membership this.username = user.username this.password = <PASSWORD> this.passwordUpdated = false this.profileUpdated = false this.usernameUpdated = false } } <file_sep>/src/pages/home/home.js import register from '@/components/register/register.vue' export default { name: 'HomePage', components: { register }, data: () => { return { } }, computed: { }, methods: { } } <file_sep>/src/app/app.js import TextInput from '@/components/sections/TextInput/TextInput.vue' import GButton from '@/components/sections/GButton/GButton.vue' export default { name: 'app', components: { TextInput, GButton }, data: () => { return { username: '', password: '', shouldFocus: false, loginAttempts: 0 } }, computed: { isLoggedIn () { return this.$store.getters.getIsLoggedIn } }, methods: { async login () { await this.$store.dispatch('login', { username: this.username, password: <PASSWORD> }) if (!this.isLoggedIn) { this.loginAttempts += 1 } else { await this.$router.push('/clubs') } }, async logout () { await this.$router.push('/') this.$store.dispatch('logout', false) } } } <file_sep>/src/components/clubCard/clubCard.js import GButton from '../../components/sections/GButton/GButton.vue' export default { name: 'clubCard', props: { club: { type: Object, required: true } }, components: { GButton }, computed: { getTrainer () { const trainer = this.$store.getters.getUserByUsername(this.club.trainer) return `${trainer.firstName} ${trainer.lastName}` }, getLoggedInUser () { return this.$store.getters.getLoggedInUser }, isUserClubTrainer () { return this.getLoggedInUser.username === this.club.trainer } }, methods: { joinClub () { this.$emit('join-club') }, editClub () { this.$emit('edit-club') }, createAppointment () { this.$emit('create-appointment') } } } <file_sep>/src/pages/trainingPlan/trainingPlan.js export default { name: 'trainingPlan', data: () => { return { breakfastCalories: 0, lunchCalories: 0, dinnerCalories: 0 } }, computed: { loggedInUser () { return this.$store.getters.getLoggedInUser }, currentBMR () { const user = this.loggedInUser if (user.gender === 'male') { return 66 + (6.3 * user.weight) + (12.9 * user.height) - (6.8 * user.age) } return 655 + (4.3 * user.weight) + (4.7 * user.height) - (4.7 * user.age) }, currentCalories () { const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] const currentDay = new Date().getDay() const clubs = this.userClubs .filter(club => club.date === days[currentDay] && club.time.split(':')[0] <= new Date().getHours()) .map(club => club.calories) return clubs.reduce((a, b) => parseInt(a) + parseInt(b), 0) }, userClubs () { return this.$store.getters.getBookings({ getAppointments: false }) }, getBreakfast () { return this.$store.getters.getBreakfast }, getLunch () { return this.$store.getters.getLunch }, getDinner () { return this.$store.getters.getDinner }, totalCalorieIntake () { return this.breakfastCalories + this.lunchCalories + this.dinnerCalories }, getQuote () { return `Today I burned ${this.currentCalories} calories and have a BRM of ${this.currentBMR}` } }, methods: { shareOnFacebook () { window.open( `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(location.href)}&quote=${this.getQuote}`, 'facebook-share-dialog', 'width=626,height=436') return false } } } <file_sep>/src/components/sections/TextInput/TextInput.js export default { name: 'TextInput', props: { placeholder: { type: String, default: 'Insert value here' }, modelValue: { type: String, default: '' }, inputType: { type: String, required: false, default: 'text' } }, methods: { updateValue (event) { this.$emit('update:modelValue', event.target.value) } } } <file_sep>/src/router/index.js import { createRouter, createWebHistory } from 'vue-router' import Home from '../pages/home/home.vue' import profile from '../pages/profile/profile.vue' import clubs from '../pages/clubs/clubs.vue' import bookings from '../pages/bookings/bookings.vue' import trainingPlan from '../pages/trainingPlan/trainingPlan.vue' import createStore from '../store/index.js' const routes = [ { path: '/', name: 'Home', component: Home }, { path: '/profile', name: 'Profile', component: profile, meta: { requiresAuth: true } }, { path: '/clubs', name: 'Clubs', component: clubs, meta: { requiresAuth: true, requiresUpToDatePassword: true } }, { path: '/bookings', name: 'Bookings', component: bookings, meta: { requiresAuth: true, requiresUpToDatePassword: true } }, { path: '/trainingPlan', name: 'TrainingPlan', component: trainingPlan, meta: { requiresAuth: true, requiresUpToDatePassword: true } }, { path: '/:catchAll(.*)', redirect: '/' } ] const router = createRouter({ history: createWebHistory(process.env.BASE_URL), routes }) router.beforeEach((to, from, next) => { if (to.matched.some(record => record.meta.requiresAuth)) { if (!createStore.getters.getIsLoggedIn) { next({ path: '/' }) } else { if (createStore.getters.getChangePassword && to.matched.some(record => record.meta.requiresUpToDatePassword)) { next({ path: '/profile' }) alert('Your password is older than 30 days, you need to change it now') } next() } } else { next() } }) export default router <file_sep>/src/components/register/register.js import GButton from '@/components/sections/GButton/GButton.vue' import TextInput from '@/components/sections/TextInput/TextInput.vue' export default { name: 'register', components: { GButton, TextInput }, data: () => { return { firstName: '', lastName: '', gender: '', age: '', weight: '', height: '', address: '', email: '', phoneNumber: '', status: '', // student, staff, neither membership: '', // one year, open ended username: '', password: '' } }, computed: { }, methods: { isFormFilled () { if ( this.firstName.length > 0 && this.lastName.length > 0 && this.gender.length > 0 && this.age.length > 0 && this.weight.length > 0 && this.height.length > 0 && this.address.length > 0 && this.email.length > 0 && this.phoneNumber.length > 0 && this.membership.length > 0 && this.username.length > 0 && this.status.length > 0 && this.password.length > 0 ) { return true } return false }, async register () { if (this.isFormFilled()) { await this.$store.dispatch('createUser', { details: { firstName: this.firstName, lastName: this.lastName, gender: this.gender, age: this.age, weight: this.weight, height: this.height, address: this.address, email: this.email, phoneNumber: this.phoneNumber, membership: this.membership, username: this.username, status: this.status, clubs: [], appointments: [], password: <PASSWORD>, passwordLastChangedDate: new Date() } }) } }, getIsLoggedIn () { return this.$store.getters.getIsLoggedIn() } } } <file_sep>/src/pages/clubs/clubs.js import TextInput from '../../components/sections/TextInput/TextInput.vue' import GButton from '../../components/sections/GButton/GButton.vue' import clubCard from '../../components/clubCard/clubCard.vue' import clubModel from '../../components/clubModel/clubModel.vue' import Fuse from 'fuse.js' export default { name: 'clubs', components: { TextInput, GButton, clubCard, clubModel }, data: () => { return { searchTerm: '', multiselect: 'name', sortByCalories: false, showModel: false, clubName: '' } }, computed: { getClubs () { return this.$store.getters.getClubs }, isTrainer () { const availableTrainers = this.$store.getters.getAvailableTrainers({ includeCurrentUser: false }) .map(e => e.username) return availableTrainers.includes(this.$store.getters.getLoggedInUserUsername) }, sortedClubs () { const clubs = this.$store.getters.getClubs if (this.sortByCalories) { return clubs.sort((a, b) => { if (parseInt(a.calories) < parseInt(b.calories)) return 1 if (parseInt(a.calories) > parseInt(b.calories)) return -1 return 0 }) } const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] const currentDay = new Date().getDay() return clubs.sort((a, b) => { if (a.date === days[currentDay]) return -1 if (a.date !== days[currentDay]) return 1 }) }, allSortedAndFilteredClubs () { let clubs = this.sortedClubs if (this.searchTerm !== '') { const fuse = new Fuse(clubs, { keys: [this.multiselect], threshold: 0.2 }) clubs = fuse.search(this.searchTerm) .map(e => { return { ...e.item } }) } return clubs } }, methods: { async addUserClub (name) { await this.$store.dispatch('addUserClub', name) }, async addUserAppointment (name) { await this.$store.dispatch('addUserAppointment', name) }, editClub (name) { this.clubName = name this.showClubModel(true) }, showClubModel (value) { if (value === false) { this.clubName = '' } this.showModel = value } } }
c48647b19820228d373215871c7d0c1c30a1e5da
[ "JavaScript", "Markdown" ]
14
JavaScript
Razakai/front-end-vue-app
00250a030e4e8976c3d741db21e96f7df22b246c
047bfea46e2bb9c9dabc96aaf005453425a73059
refs/heads/master
<file_sep>const mongoose = require("mongoose"); const { Schema } = mongoose; // User Schema const UserSchema = new Schema( { name: { type: String, required: true, unique: true, dropDups: true, }, email: { type: String, required: true, unique: true, dropDups: true, }, picture: { type: String, }, interests: { type: Array, }, }, { timestamps: true, } ); // Generates a profile by removing sensitive information UserSchema.methods.getPublicProfile = function () { const user = this.toObject(); return user; }; UserSchema.statics.findByCredentials = async ({ email }) => { const user = await User.findOne({ email }); return user; }; const User = mongoose.model("User", UserSchema); module.exports = User; <file_sep>import { BrowserRouter as Router, Switch, Route } from "react-router-dom"; import { useAuth0 } from "@auth0/auth0-react"; import Navbar from "./components/Navbar"; import Dashboard from "./pages/Dashboard"; import Home from "./pages/Home"; import Browse from "./pages/Browse"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faSpinner } from "@fortawesome/free-solid-svg-icons"; import { login } from "./services/login.service"; import Listen from "./components/Listen"; export default function App() { const { user, isLoading } = useAuth0(); if (user) { login(user); console.log(user); } if (isLoading) return ( <div className="loading"> <h2> <FontAwesomeIcon icon={faSpinner} className="fa-spin" /> </h2> <h2>Loading...</h2> </div> ); return ( <div className="app"> <Listen /> <Router> <Navbar /> <Switch> <Route exact path="/" component={Home} /> <Route exact path="/profile" component={Dashboard} /> <Route exact path="/browse" component={Browse} /> </Switch> </Router> </div> ); } <file_sep>const axios = require("axios"); const url = process.env.NODE_ENV === "production" ? "https://project-bud.herokuapp.com/" : "http://localhost:5000/"; const axiosInstance = axios.create({ withCredentials: true, baseURL: url, }); export default axiosInstance; <file_sep>import { useAuth0 } from "@auth0/auth0-react"; import { Icon } from "@iconify/react"; export default function Navbar() { const { logout, isAuthenticated, loginWithRedirect } = useAuth0(); return ( <div className="navbar"> <a href="/" className="navbar-logo"> <img className="navbar-logo--inside" src="Images/logo2.png" alt="logo" /> </a> <div className="navbar-buttons"> {isAuthenticated ? ( <button className="btn-spl btn" onClick={() => logout()}> <Icon icon="fa-solid:sign-out-alt" /> Log out </button> ) : ( <button className="btn" onClick={() => loginWithRedirect()}> Log in </button> )} {isAuthenticated && ( <button className="btn-spl btn btn-profile"> <a href="/profile"> <Icon icon="fa-solid:user" /> Profile </a> </button> )} </div> </div> ); } <file_sep>const mongoose = require("mongoose"); const url = process.env.NODE_ENV !== "production" ? process.env.MONGODB_DEV_URL : process.env.MONGODB_PROD_URL; const db = mongoose .connect(url, { useUnifiedTopology: true, }) .then(() => { console.log("Connected to the mongodb database"); }) .catch((error) => { console.log(error.name); console.log(error); console.log(process.env.DEV_MONGO_URL); console.log(process.env.PROD_MONGO_URL); }); module.exports = db; <file_sep>import Card from "../components/UserCard"; export default function Browse() { return ( <div className="browse"> <div className="browse--inside"> <Card name="Sarah" interests="Dancing, IceSkating" skills="UI/UX, Typography" preferences="They/Them" others="I love teddy bears!" picture="https://i.picsum.photos/id/1014/6016/4000.jpg?hmac=yMXsznFliL_Y2E2M-qZEsOZE1micNu8TwgNlHj7kzs8"/> <Card name="Pedro" interests="IceCream, Football" skills="Figma, Typography" preferences="He/Him" others="I like to sing" picture="https://i.picsum.photos/id/1005/5760/3840.jpg?hmac=2acSJCOwz9q_dKtDZdSB-OIK1HUcwBeXco_RMMTUgfY"/> <Card name="Mia" interests="Chocolate, Cricket" skills="Node.js, Flutter, React" preferences="She/Her" picture="https://i.picsum.photos/id/1011/5472/3648.jpg?hmac=Koo9845x2akkVzVFX3xxAc9BCkeGYA9VRVfLE4f0Zzk"/> <Card name="Munro" interests="Drawing" skills="Analytics, Graphics" preferences="He/Him" picture="https://i.picsum.photos/id/1012/3973/2639.jpg?hmac=s2eybz51lnKy2ZHkE2wsgc6S81fVD1W2NKYOSh8bzDc"/> <Card name="Sarah" interests="Dancing, IceSkating" skills="UI/UX, Typography" preferences="They/Them" others="I love teddy bears!" picture="https://i.picsum.photos/id/1014/6016/4000.jpg?hmac=yMXsznFliL_Y2E2M-qZEsOZE1micNu8TwgNlHj7kzs8"/> <Card name="Pedro" interests="IceCream, Football" skills="Figma, Typography" preferences="He/Him" others="I like to sing" picture="https://i.picsum.photos/id/1005/5760/3840.jpg?hmac=2acSJCOwz9q_dKtDZdSB-OIK1HUcwBeXco_RMMTUgfY"/> <Card name="Mia" interests="Chocolate, Cricket" skills="Node.js, Flutter, React" preferences="She/Her" picture="https://i.picsum.photos/id/1011/5472/3648.jpg?hmac=Koo9845x2akkVzVFX3xxAc9BCkeGYA9VRVfLE4f0Zzk"/> <Card name="Munro" interests="Drawing" skills="Analytics, Graphics" preferences="He/Him" picture="https://i.picsum.photos/id/1012/3973/2639.jpg?hmac=s2eybz51lnKy2ZHkE2wsgc6S81fVD1W2NKYOSh8bzDc"/> </div> </div> ) } <file_sep>import axiosInstance from "../utils/axiosInstance"; const login = async (user) => { console.log(user); return await axiosInstance .post("login", { user, }) .then((response) => { return response.data; }); }; export { login }; <file_sep>const express = require("express"); const User = require("../database/models/user.model"); const router = express.Router(); router.post("/login", async (req, res) => { try { let user = await User.findByCredentials({ email: req.body.user.email }); if (!user) { user = new User({ ...req.body.user }); await user.save(); } res.status(200).send({ success: true, message: "Successfully logged in.", user: user.getPublicProfile(), }); } catch (error) { console.log(error.message); res.status(401).send({ success: false, message: error.message, }); } }); module.exports = router; <file_sep>import { Icon } from "@iconify/react"; import { listen } from "../services/transcribe.service"; const Listen = () => { return ( <button className="btn-round listen" onClick={() => listen()}> <Icon className="listen-icon" icon="icon-park-outline:people-speak" /> </button> ); }; export default Listen; <file_sep>const axios = require("axios"); const getMediaRecorder = async () => { let audioIN = { audio: true }; return await navigator.mediaDevices .getUserMedia(audioIN) .then(function (mediaStreamObj) { console.log(mediaStreamObj); return new MediaRecorder(mediaStreamObj); }) .catch(function (err) { console.log(err.name, err.message); }); }; const timeout = (ms) => { return new Promise((resolve) => setTimeout(resolve, ms)); }; const listen = async () => { let recorder = await getMediaRecorder(); console.log(recorder); let audioArray = []; recorder.start(); recorder.ondataavailable = (audio) => { audioArray.push(audio.data); }; await timeout(5000); recorder.stop(); await timeout(1000); let audioData = new Blob(audioArray, { type: "audio/mp3;" }); audioArray = []; transcribe(window.URL.createObjectURL(audioData)); }; const transcribe = async (url) => { console.log(process.env.REACT_APP_ASSEMBLY_API_TOKEN); const assembly = axios.create({ baseURL: "https://api.assemblyai.com/v2", headers: { authorization: process.env.REACT_APP_ASSEMBLY_API_TOKEN, "content-type": "application/json", }, }); assembly .post(`/transcript`, { audio_url: url }) .then((res) => { const id = res.data.id; assembly.get(`/transcript/${id}`) .then((res) => console.log(res.data)) .catch((err) => console.log(err.message)); }) .catch((err) => console.error(err)); }; export { listen }; <file_sep># Project-Bud 🤼 ![Logo 500x500 px (15) 1](https://user-images.githubusercontent.com/59244300/137630305-7322f7a4-f16f-4731-8c63-167998a89630.png) This project is submitted as part of MHacks14 ![image](https://user-images.githubusercontent.com/59244300/137633248-6244fc49-b5b0-4fcc-8cd8-3f28d552a409.png) This is our domain name on domain.com! ![WhatsApp Image 2021-10-17 at 8 33 42 PM](https://user-images.githubusercontent.com/59244300/137633195-d4db957b-1327-47dd-8e9b-77c3b8048049.jpeg) ## Tech Stack 👨‍💻 <img src="https://img.shields.io/badge/HTML5-E34F26?style=for-the-badge&logo=html5&logoColor=white"> <img src="https://img.shields.io/badge/Sass-CC6699?style=for-the-badge&logo=sass&logoColor=white"> <img src="https://img.shields.io/badge/JavaScript-F7DF1E?style=for-the-badge&logo=javascript&logoColor=black"> <img src="https://img.shields.io/badge/Node.js-43853D?style=for-the-badge&logo=node.js&logoColor=white"> <img src="https://img.shields.io/badge/MongoDB-4EA94B?style=for-the-badge&logo=mongodb&logoColor=white"> <img src="https://img.shields.io/badge/React-20232A?style=for-the-badge&logo=react&logoColor=61DAFB"> Problem: Today’s learners face a lot of distractions, suffer from FOMO, and struggle to find the right learning partner. Solution: A platform that matches learners with potential partners (with the features of a dating app) with a left and right swipe feature. ![hero (1)](https://user-images.githubusercontent.com/59244300/137630456-90ccd98c-28ac-4952-9e8b-3151ca6533ab.png) ## Inspiration ⛳ ![SadGIF](https://user-images.githubusercontent.com/59244289/137631779-f3c81062-d7fc-4035-b809-db31f48864a7.gif) Since our first year of college, we have been suffering from FOMO (fear of missing out) and also giving up due to lack of motivation. Even as we seeked peers to learn with, somewhere and sometime either of us parted ways as our goals and preferences did not match perfectly. Even though we searched communities, networked with people, it seemed very difficult to align our interests. Even through social media, we were not quite sure if someone was looking for a learning partner or not. So, this was our main motive and inspiration for the project. ## What it does ![ClaireDancingGIF](https://user-images.githubusercontent.com/59244289/137631826-57e881e8-488a-4e1b-9de4-3cbdaf9218ff.gif) It lets you browse through user profiles and lets you connect with them through a simple right swipe! ## How we built it ![HowAnthonyMennellaGIF](https://user-images.githubusercontent.com/59244289/137631885-fc676034-6ae6-40ba-b04f-b563168fef97.gif) We used React and Sass on the frontend and Node.js, Express and MongoDB on the backend. We used Auth0 for easy authentication using React itself, tried creating audio transcript using Assembly AI and used iconify and fontAwesome for the incredible icons. ## Challenges we ran into ![PussInBootsEyesGIF](https://user-images.githubusercontent.com/59244289/137631927-2d6773e3-6600-4e2b-9dbf-45580017f1a8.gif) 1) Integrating frontend with backend. 2) Hosting issues. 3) Creating a creative hero element. 4) Converting Audio into working Blob URL and sending it to the Assembly AI. ## What we learned 1) Solving hosting and integration issues. 2) Creating Aesthetic and User Apealing UI in a short span of time. 3) Using APIs in the most productive manner possible. ## What's next? ![IKnowYupGIF](https://user-images.githubusercontent.com/59244289/137632027-9ae2f1f7-6c04-4ea7-a37a-fee39b615fe6.gif) We are planning to add more features like messaging, calling and also AI to smartly match profiles according to interests of users.
514e36785ed0471d0623cc8bd4845bd8b787d304
[ "JavaScript", "Markdown" ]
11
JavaScript
Coder-Srinivas/Project-Bud
77b087ce6439ac538fba7ab0eaa75fd4a5e88a1f
0e9b52136f974cd35cfde1a617c190bbdf5d4c4d
refs/heads/master
<repo_name>LindaLopezR/errors-components<file_sep>/errors-components.js import React from 'react'; export const ErrorFallback = (error) => { console.log('ERROR = > ', error); return ( <div role="alert" style={{marginTop: 15}}> <h3>Something went wrong:</h3> <pre style={{color: 'red'}}> {TAPi18n.__('error_try_later')} </pre> </div> ) } export const ErrorRender = () => { throw new Error ('Error cargando la información'); } <file_sep>/README.md errors-components ----------- _ _ _ Componentes utilizados para iGo&Suite: se utilizan junto con el paquete [react-error-boundary](https://github.com/bvaughn/react-error-boundary) con el cual se logran identificar errores que se puedan producir dando como respuesta un mensaje de error y no una pantalla blanca. Este módulo posee el renderizado del mensaje de error y la función encargada de generar el error; dando así la facilidad de ser utilizado por los diferentes componentes de iGo&Suite.
2ed7f9be9a04d740a2d64266011c4c56b1dedb07
[ "JavaScript", "Markdown" ]
2
JavaScript
LindaLopezR/errors-components
241d4563266f83a38c47c4ebf889db82570aef33
1b48bd88f1cb17d03ea99446b64c567aa79e94fe
refs/heads/master
<repo_name>cabbagecbl/Electronical-License<file_sep>/migrations/2_deploy_contracts.js var ECLibrary = artifacts.require("./ECLibrary.sol"); module.exports = function(deployer) { deployer.deploy(ECLibrary); }; <file_sep>/README.md # Electronical-License // truffle console下插入电子证照 ECLibrary.deployed().then(function(i) {i.addECToLibrary('中华人民共和国居民身份>证', '0000000000', '2016.08.03-2026.08.03', '云阳县公安局', '彭冬', 'QmcFJ32gn3KKGaQsHutMsQ73C7gvgoAy7r31VY1KTn8rSt', 0x22ec9902e1bb06584bcb00f062f3bc0d725807b1, 0, 0).then(function(f) {console.log(f)})}); // truffle console下获取电子证照 ECLibrary.deployed().then(function(i) {i.getEC.call(1).then(function(f) {console.log(f)})})
ccaba34a804a6e5e34bd70eb2354868a2683ffb7
[ "JavaScript", "Markdown" ]
2
JavaScript
cabbagecbl/Electronical-License
49b291f3e7e546569b1a91fac5ed59b5fbad4731
ec4a4ee8c8ba9e4a7b95863cfe9ab54b89d9393f
refs/heads/master
<file_sep># Cerea remote control [![MIT license](https://img.shields.io/github/license/danrauch/arduino-cerea-remote-control.svg)](https://opensource.org/licenses/MIT) [![Latest Release](https://img.shields.io/github/release/danrauch/arduino-cerea-remote-control/all.svg)](https://github.com/danrauch/arduino-cerea-remote-control/releases/latest) [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://paypal.me/danrauch) Language: [**EN**](README.md) | [DE](README_DE.md) Control and evaluate serial-exposed **Cerea** features comfortably with an Arduino based touchscreen remote control. To see it in action have a look [here](https://www.youtube.com/watch?v=ZrCHwqn8U7Y) (German)! **Currently supported features** - Setting MARC, A, B, right, left, AUTO via touchscreen (command: @CEREA) - Reading @SDOSE command to control a relay (RELAY_PIN_1/2; default: pins 49/53) depending on first boom box section and GPS speed. Can be enabled/disabled via touchscreen (enabled when "Aktiv" and "Streu" buttons are active). - Control relays also manually via touchscreen ("Streu" button). - Reading @STATUSAM if available to sync UI - Showing current boombox states (rectangles at top of display: grey = unused, red = not active, green = active) - BETA: Control different boomboxes (1-10) via the @BOOMBOX command (Page 2: 1 - 10; note that page changing could lead to missed status data from Cerea, so the GUI might be not in sync with Cerea for some moments) - Vibrate on touch; output on adjustable pin (VIBRATION_MOTOR_PIN; default: built-in LED pin of board, which is pin 13 on the MEGA) and with adjustable vibration time (VIBRATION_TIME_MS; default: 200 ms) ![Page 1](/doc/resources/cerea-remote-page1.jpg "Page 1") ![Page 2](/doc/resources/cerea-remote-page2.jpg "Page 2") **Necessary Hardware** - [Arduino MEGA 2560](https://store.arduino.cc/mega-2560-r3) - 3.5" TFT/touchscreen shield (480x320; 16 bit colors) supported by the Adafruit TFTLCD and Touchscreen library (tested: [Kuman version with ILI9486](https://www.amazon.com/Kuman-Arduino-Screen-Tutorials-Mega2560/dp/B075FP83V5/); more can be added) - *If USB serial connection is used:* capacitor (>22 µF) - Optional: vibration motor (e.g. [seeed Groove VM](https://www.seeedstudio.com/category/Grove-c-1003/Grove-Vibration-Motor.html)) - Optional: relay(s) (e.g. [seeed Groove 2CH Relay](https://www.seeedstudio.com/Grove-2-Channel-SPDT-Relay-p-3118.html)) *Important if a USB serial connection is used:* Per default the Arduino resets completely as soon as a serial connection is opened. For some reason in case of the Cerea output the board thinks it is flashed and thus freezes. To avoid this the auto reset must be disabled via a capacitor (>22 µF) between the reset and ground pin. Riku from the German [Cerea forum](http://cerea-forum.de/) built an excellent housing for the Arduino and was nice enough to provide all necessary resources (German). Have look at the basics [here](https://cerea-forum.de/forum/index.php?thread/440-externe-touchscreen-bedieneinheit-bauanleitung/) and the extension [here](https://cerea-forum.de/forum/index.php?thread/493-externe-touchscreen-bedieneinheit-automatisierte-schaltung/). **PLEASE NOTE: This housing is only compatible with releases before 0.2.2, as it does not account for the button shift introduced by the boombox state indicators. Please use [Release 0.2.1](https://github.com/danrauch/arduino-cerea-remote-control/releases/tag/v0.2.1) if you intend to use the housing.** **Dependencies** To use this sketch the following libraries must be downloaded and imported to the Arduino IDE. Either download them directly with the provided links and import them ("Sketch"->"Add .ZIP Library") or search them in the Arduino IDE Library Manager ("Tools"->"Library Manager"). It is recommended to keep the libraries up to date! - [Adafruit GFX Library](https://github.com/adafruit/Adafruit-GFX-Library) <-- *important: use version 1.5.3* - [Adafruit TFT-LCD Library](https://github.com/adafruit/TFTLCD-Library) - [Adafruit Touchscreen Library](https://github.com/adafruit/Adafruit_TouchScreen) - [MCUFRIEND_kbv Library](https://github.com/prenticedavid/MCUFRIEND_kbv) ## About Cerea [Cerea](https://www.cereagps.com/) is an agricultural GPS auto-steer system for Windows, developed by a Spain-based company called SOLUCIONES TECNOLOGICAS CEREA. It uses serial communication to exchange command sequences, which allow to remote control the system from any device with a serial interface. The following commands were reverse engineered, so no guarantee! General information: - "1" represents on/true - "0" represents off/false - every command is followed by a CR-LF (`\r\n`) ### **Cerea > Remote** Commands seem to arrive in 0.5 second cycles (confirmation needed). | Cerea command | Controls | Description | Example | |------------------------------------------------|-----------------------------------------------|---------------------------------|------------------------| | **@STATUSAM;*A*;*M*;END** | *A*:&nbsp;AUTO&nbsp;[1/0]<br/>*M*:&nbsp;MARC&nbsp;[1/0] | Current state of MARC and AUTO. | `"@STATUSAM;1;1;END\r\n"`<br/>(AUTO and MARC active) | | **@CEREA;*VGPS*;*-1*;<br/>*S0*;*S1*;...;*S9*;END** | *VGPS*:&nbsp;GPS&nbsp;speed in km/h&nbsp;[float]<br/>*-1*: reserved<br/>*S0&#8209;9*:&nbsp;boom sections&nbsp;[1/0] | Current GPS speed and boom box section states (left to right).<br/>Number of transmitted sections matches Cerea settings (max. 10). | `"@CEREA;5.0;-1;1;END\r\n"`<br/>(GPS speed 5.0 km/h; section 1 active) | | **@HIDRAU;*F*;END** | *F*:&nbsp;Flag&nbsp;[1/0] | If section was already taken care of info is sent. | `"@HIDRAU;1;END\r\n"`<br/>(Section already taken care of) | ### **Remote > Cerea** | Cerea command | Controls | Description | Example | |----------------------------------------------- |-----------------------------------------------|------------------------------------------- |------------------------| | **@SDOSE;*M*;*C*;*U*;*U*;<br/>*AP*;*BP*;*A*;*L*;*R*;*TL*;*TR*;END** | *M*:&nbsp;MARC&nbsp;[1/0]<br/>*C*:&nbsp;CONTOUR&nbsp;[1/0]<br/>*U*: UNKNOWN&nbsp;[1/0]<br/>*AP*: A point&nbsp;[1/0]<br/>*BP*:&nbsp;B point&nbsp;[1/0]<br/>*A*:&nbsp;AUTO&nbsp;[1/0]<br/>*L*: LEFT&nbsp;[1/0]<br/>*R*: RIGHT&nbsp;[1/0]<br/>*TL*:&nbsp;TURN LEFT&nbsp;[1/0]<br/>*TR*:&nbsp;TURN&nbsp;RIGHT&nbsp;[1/0] | Controls Cerea. | `"@SDOSE;1;0;0;0; \ 0;0;1;0;0;0;0;END\r\n"`<br/>(activate MARC and AUTO) | | **@MARC** | - | Activates MARC. | `"@MARC\r\n"` (activate MARC) | | **@AUTO** | - | Activates AUTO. | `"@AUTO\r\n"` (activate MARC) | | **@BOOMBOX;<br/>*S0*;*S1*;...;*S9*;END** | *S0&#8209;9*: boom sections&nbsp;[1/0] | Set boom box section states (left to right).<br/>The state of all 10 sections must be transmitted. | `"@BOOMBOX; \ 0;0;0;0;0;0;0;0;0;0;\r\n"`<br/>(deactivate all sections) | | **@PRESION;*P*;END** | *P*: pressure&nbsp;[float] | Set pressure in ?<br/>(confirmation needed). | `"@PRESION;1.0;END\r\n"`<br/>(set pressure to 1.0) | | **@CAUDAL;*F*;END** | *F*: flow&nbsp;[float] | Set flow in L/min<br/>(confirmation needed). | `"@CAUDAL;1.0;END\r\n"`<br/>(set flow to 1.0) | | **@APLICADO;*A*;END** | *A*: applied&nbsp;flow&nbsp;[float] | Set applied flow in L/ha<br/>(confirmation needed). | `"@APLICADO;1.0;END\r\n"`<br/>(set applied flow to 1.0) | ## Donation If this project / information helps you, you can support me by attributing to a ["Maß"](https://bar.wikipedia.org/wiki/Bia) beer for me [**here**](https://paypal.me/danrauch) :) <file_sep># Cerea Fernbedienung [![MIT Lizenz](https://img.shields.io/github/license/danrauch/arduino-cerea-remote-control.svg)](https://opensource.org/licenses/MIT) [![Aktuelles Release](https://img.shields.io/github/release/danrauch/arduino-cerea-remote-control/all.svg)](https://github.com/danrauch/arduino-cerea-remote-control/releases/latest) [![Spende](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://paypal.me/danrauch) Sprache: [EN](README.md) | [**DE**](README_DE.md) Mit dieser Arduino-basierten Touchscreen-Fernbedienung kann man **Cerea**-Funktionen, die über die serielle Schnittstelle zur Verfügung stehen, komfortabel steuern. [Hier](https://www.youtube.com/watch?v=ZrCHwqn8U7Y) kann man sie in Aktion sehen! **Aktuell unterstützte Funktionen** - Setzen von MARK, A, B, rechts, links, AUTO via Touchscreen (Kommando: @CEREA) - Zurücklesen des @SDOSE-Kommandos um, abhängig von der ersten Teilbreite und der GPS-Geschwindigkeit ein Relais zu steuern (RELAY_PIN_1/2; Standard: Pins 49/53). Kann über den Touchscreen aktiviert bzw. deaktiviert werden (Aktiv wenn "Aktiv" und "Streu" Tasten gesetzt sind). - Steuert Relais auch manuell über Touchscreen ("Streu" Taste). - Zurücklesen von @STATUSAM, falls verfügbar, um GUI synchron zu halten - Anzeigen der aktuellen Teilbreitenstatus (Vierecke oben im Display: grau = nicht genutzt, rot = nicht aktiv, grün = aktiv) - BETA: Steuern der einzelnen Teilbreiten (1-10) mit dem @BOOMBOX Kommando (Seite 2: 1 - 10; durch Wechsel der Seite könnten Statusnachrichten von Cerea versäumt werden, d.h. das GUI ist für einige Momente nicht synchronisiert mit Cerea) - Vibrationsfeedback bei Touchscreenbetätigung; Signal kann auf frei wählbaren Digitalpin gelegt werden (VIBRATION_MOTOR_PIN; Standard: eingebaute LED-Pin des Boards, welcher auf dem MEGA Pin 13 entspricht) und die Vibrationsdauer ist einstellbar (VIBRATION_TIME_MS; Standard: 200 ms) ![Seite 1](/doc/resources/cerea-remote-page1.jpg "Seite 1") ![Seite 2](/doc/resources/cerea-remote-page2.jpg "Seite 2") **Nötige Hardware** - [Arduino MEGA 2560](https://store.arduino.cc/mega-2560-r3) - 3.5" TFT/Touchscreen Shield (480x320; 16 Bit Farben) unterstützt durch die Adafruit TFTLCD und Touchscreen Bibliotheken (getestet: [Kuman Version mit ILI9486](https://www.amazon.com/Kuman-Arduino-Screen-Tutorials-Mega2560/dp/B075FP83V5/); weitere können ergänzt werden) - *Bei USB-basierter seriellen Kommunikation:* Kondensator (>22 µF) - Optional: Vibrationsmotor (z.B. [seeed Groove VM](https://www.seeedstudio.com/category/Grove-c-1003/Grove-Vibration-Motor.html)) - Optional: Relais (z.B. [seeed Groove 2CH Relay](https://www.seeedstudio.com/Grove-2-Channel-SPDT-Relay-p-3118.html)) *Wichtig bei USB-basierter seriellen Kommunikation:* Standardmäßig setzt sich der Arduino bei der Initialisierung der seriellen Kommunikation komplett zurück. Im Falle der Cerea-Kommunikation denkt der Arduino aus irgendeinem Grund er wird neu geflasht und friert dadurch ein. Um diesen Auto-Reset zu Verhindern muss ein Kondensator zwischen dem "Reset" und dem "GND" Pin angeschlossen werden. Riku vom deutschen [Cerea forum](http://cerea-forum.de/) hat ein ausgezeichnetes Gehäuse für den Arduino konstruiert und die Daten netterweise zur Verfügung gestellt. Die Basisanleitung kann man [hier](https://cerea-forum.de/forum/index.php?thread/440-externe-touchscreen-bedieneinheit-bauanleitung/) finden und die Erweiterung [hier](https://cerea-forum.de/forum/index.php?thread/493-externe-touchscreen-bedieneinheit-automatisierte-schaltung/). **WICHTIG: Dieses Gehäuse passt nur mit Release vor 0.2.2 zusammen, da es die neu eingeführten Teilbreitenstatus-Indikatoren nicht berücksichtigt. Bitte verwenden Sie [Release 0.2.1](https://github.com/danrauch/arduino-cerea-remote-control/releases/tag/v0.2.1) falls Sie planen das beschriebene Gehäuse nachzubauen.** **Abhängigkeiten** Um diesen Sketch zu verwenden müssen die folgenden Bibliotheken heruntergeladen und in die Arduino IDE importiert werden. Entweder kann man diese direkt herunterladen und mittels ("Sketch"->"Add .ZIP Library") importieren oder man sucht sie im Arduino IDE Library Manager ("Tools"->"Library Manager"). Es wird empfohlen die Bibliotheken aktuell zu halten. - [Adafruit GFX Library](https://github.com/adafruit/Adafruit-GFX-Library) <-- *Wichtig: Version 1.5.3 nutzen* - [Adafruit TFT-LCD Library](https://github.com/adafruit/TFTLCD-Library) - [Adafruit Touchscreen Library](https://github.com/adafruit/Adafruit_TouchScreen) - [MCUFRIEND_kbv Library](https://github.com/prenticedavid/MCUFRIEND_kbv) ## Über Cerea [Cerea](https://www.cereagps.com/) ist ein GPS-basiertes Autolenksystem für die Landwirtschaft. Es wird von einer spanischen Firma namens SOLUCIONES TECNOLOGICAS CEREA aktiv für Windows entwickelt. Das System nutzt die serielle Schnittstelle um Kommandosequenzen auszutauschen, welche es ermöglichen dieses mit einem beliebigen Gerät mit serieller Schnittstelle fernzusteuern. Die folgenden gelisteten Kommandos wurden Reverse Engineered, daher keine Garantie! Generelles: - "1" repräsentiert an/true - "0" repräsentiert aus/false - Jedes Kommando wird mit einem CR-LF (`\r\n`) beendet ### **Cerea > Fernbedienung** Kommandos scheinen im 0,5 Sekundentakt anzukommen (Bestätigung benötigt). | Cerea Kommando | Funktion | Beschreibung | Beispiel | |------------------------------------------------|-----------------------------------------------|---------------------------------|------------------------| | **@STATUSAM;*A*;*M*;END** | *A*:&nbsp;AUTO&nbsp;[1/0]<br/>*M*:&nbsp;MARK&nbsp;[1/0] | Aktueller Status MARK und AUTO. | `"@STATUSAM;1;1;END\r\n"`<br/>(AUTO und MARK aktiv) | | **@CEREA;*VGPS*;*-1*;<br/>*S0*;*S1*;...;*S9*;END** | *VGPS*:&nbsp;GPS&nbsp;Geschw. in km/h&nbsp;[float]<br/>*-1*: reserviert<br/>*S0&#8209;9*:&nbsp;Teilbreiten&nbsp;[1/0] | Aktuelle GPS Geschw. und Teilbreitenstatus (von links nach rechts).<br/>Anzahl an übertragenen Teilbreiten entspricht Einstellung in Cerea (max. 10). | `"@CEREA;5.0;-1;1;END\r\n"`<br/>(GPS Geschw. 5.0 km/h; Teilbreite 1 aktiv) | | **@HIDRAU;*F*;END** | *F*:&nbsp;Flag&nbsp;[1/0] | Falls Sektion schon bearbeitet wurde, wird dies hier signalisiert. | `"@HIDRAU;1;END\r\n"`<br/>(Sektion schon bearbeitet) | ### **Fernbedienung > Cerea** | Cerea Kommando | Funktion | Beschreibung | Beispiel | |----------------------------------------------- |-----------------------------------------------|------------------------------------------- |------------------------| | **@SDOSE;*M*;*C*;*U*;*U*;<br/>*AP*;*BP*;*A*;*L*;*R*;*TL*;*TR*;END** | *M*:&nbsp;MARK&nbsp;[1/0]<br/>*C*:&nbsp;CONTOUR&nbsp;[1/0]<br/>*U*: UNBEKANNT&nbsp;[1/0]<br/>*AP*: A point&nbsp;[1/0]<br/>*BP*:&nbsp;B point&nbsp;[1/0]<br/>*A*:&nbsp;AUTO&nbsp;[1/0]<br/>*L*: LINKS&nbsp;[1/0]<br/>*R*: RECHTS&nbsp;[1/0]<br/>*TL*:&nbsp;WENDE LINKS&nbsp;[1/0]<br/>*TR*:&nbsp;WENDE&nbsp;RECHTS&nbsp;[1/0] | Steuert Cerea. | `"@SDOSE;1;0;0;0; \ 0;0;1;0;0;0;0;END\r\n"`<br/>(aktiviere MARK und AUTO) | | **@MARK** | - | Aktiviert MARK. | `"@MARK\r\n"` (aktiviert MARK) | | **@AUTO** | - | Aktiviert AUTO. | `"@AUTO\r\n"` (aktiviert MARK) | | **@BOOMBOX;<br/>*S0*;*S1*;...;*S9*;END** | *S0&#8209;9*: Teilbreiten&nbsp;[1/0] | Setzt Teilbreitenstatus (von links nach rechts).<br/>Der Status von allen 10 Teilbreiten muss übertragen werden. | `"@BOOMBOX; \ 0;0;0;0;0;0;0;0;0;0;\r\n"`<br/>(deaktiviere alle Teilbreiten) | | **@PRESION;*P*;END** | *P*: Druck&nbsp;[float] | Setzte Druck in ?<br/>(Bestätigung benötigt). | `"@PRESION;1.0;END\r\n"`<br/>(setze Druck auf 1.0) | | **@CAUDAL;*F*;END** | *F*: Durchflussmenge&nbsp;[float] | Setzte Durchflussmenge in L/min<br/>(Bestätigung benötigt). | `"@CAUDAL;1.0;END\r\n"`<br/>(setze Durchflussmenge auf 1.0) | | **@APLICADO;*A*;END** | *A*: Angew.&nbsp;Durchfluss&nbsp;[float] | Setzte angew. Durchflussmenge in L/ha<br/>(Bestätigung benötigt). | `"@APLICADO;1.0;END\r\n"`<br/>(setze angew. Durchflussmenge auf 1.0) | ## Spende Falls dieses Projekt / die Info hilfreich war, kann man mich [**hier**](https://paypal.me/danrauch) mit einer ["Maß"](https://bar.wikipedia.org/wiki/Bia) Bier unterstützten :) <file_sep>/* * Cerea remote control * * MIT License * * Copyright © 2019 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ #include <Adafruit_GFX.h> #include <Adafruit_TFTLCD.h> #include <MCUFRIEND_kbv.h> #include <TouchScreen.h> // ### Macros ### // The control pins for the LCD can be assigned to any digital or analog pins, // but usage of analog pins allows to double up the pins with the touch screen. #define LCD_CS A3 // Chip Select goes to Analog 3 #define LCD_CD A2 // Command/Data goes to Analog 2 #define LCD_WR A1 // LCD Write goes to Analog 1 #define LCD_RD A0 // LCD Read goes to Analog 0 #define LCD_RESET A4 // Can alternately just connect to Arduino's reset pin // Touchscreen pins #define YP A2 // must be an analog pin, use "An" notation! #define XM A3 // must be an analog pin, use "An" notation! #define YM 8 // can be a digital pin #define XP 9 // can be a digital pin // Vibration control // change pin according to pin connected to motor! // default: use pin of onboard LED to showcase the feature #define VIBRATION_MOTOR_PIN LED_BUILTIN #define VIBRATION_TIME_MS 200 // relay pins #define RELAY_PIN_1 53 #define RELAY_PIN_2 49 // Cerea settings #define MIN_GPS_SPEED 2.5 #define MAX_NR_BOOM_SECTIONS 10 // Assign human-readable names to some common 16-bit color values: #define BLACK 0x0000 #define BLUE 0x001F #define RED 0xF800 #define GREEN 0x07E0 #define CYAN 0x07FF #define MAGENTA 0xF81F #define YELLOW 0xFFE0 #define WHITE 0xFFFF #define ORANGE 0xFD20 #define NAVY 0x000F #define GRAY 0xDEFB // UI details #define BUTTON_COUNT 8 #define BUTTON_X 2 #define BUTTON_Y 45 #define BUTTON_W 150 #define BUTTON_H 80 #define BOOM_BUTTON_H 60 #define BUTTON_SPACING_X 17 #define BUTTON_SPACING_Y 14 #define BUTTON_TEXTSIZE 3 #define NAV_BUTTON_X 110 #define NAV_BUTTON_Y 420 #define NAV_BUTTON_W 100 #define NAV_BUTTON_H 55 #define NAV_BUTTON_TEXTSIZE 2 #define BUTTON_A 0 #define BUTTON_B 1 #define BUTTON_LEFT 2 #define BUTTON_RIGHT 3 #define BUTTON_RELAY_AUTO 4 #define BUTTON_RELAY_MANUAL 5 #define BUTTON_MARC 6 #define BUTTON_CEREA_AUTO 7 #define SECTION_RECT_SIZE 19 #define SECTION_RECT_X 7 #define SECTION_RECT_SPACING_X 32 #define SECTION_RECT_Y 6 #define SEPERATOR_LINE_START_X 1 #define SEPERATOR_LINE_END_X 329 #define SEPERATOR_LINE_Y 32 // Touchscreen calibration (values might vary for different touchscreens) /* Touchscreen x/y (USB top): 95/890 95/150 ________ | | | | | | | | | | |________| 950/885 950/150 Touchscreen x/y (USB bottom): 950/150 950/890 ________ | | | | | | | | | | |________| 95/150 95/890 recalculate to LCD: 0/0 0/width ________ | | | | | | | | | | |________| 0/height width/height */ #define TS_MINX 95 #define TS_MAXX 950 #define TS_MINY 150 #define TS_MAXY 890 #define MIN_PRESSURE 5 #define MAX_PRESSURE 1000 #define MAX_CHARS_CMD_STRING 33 // ### Global variables ### MCUFRIEND_kbv tft; TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300); Adafruit_GFX_Button control_buttons[BUTTON_COUNT]; Adafruit_GFX_Button boom_section_buttons[MAX_NR_BOOM_SECTIONS]; Adafruit_GFX_Button navigation_button_p1, navigation_button_p2; char button_labels[BUTTON_COUNT][8] = {"A", "B", "links", "rechts", "Aktiv", "Streuen", "MARK", "AUTO"}; char boom_button_labels[MAX_NR_BOOM_SECTIONS][3] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}; char nav_button_label_p1[2] = ">"; char nav_button_label_p2[2] = "<"; uint16_t button_colors[BUTTON_COUNT] = {NAVY, NAVY, ORANGE, ORANGE, RED, MAGENTA, BLUE, GREEN}; // commands struct struct { bool marc; bool contour; bool A; bool B; bool auto_on; bool left; bool right; bool turn_left; bool turn_right; } cerea_commands; struct { bool automatic; bool manual_override; } relay_control; typedef enum boom_state { BOOM_UNUSED, BOOM_INACTIVE, BOOM_ACTIVE } boom_state_t; boom_state_t boom_section_states[MAX_NR_BOOM_SECTIONS]; bool boom_section_active[MAX_NR_BOOM_SECTIONS]; // output command string char cerea_command_out[MAX_CHARS_CMD_STRING]; // Cerea input command buffer String cerea_command_in = ""; unsigned long start_time_ms = 0; unsigned long last_gui_update_ms = 0; int current_page = 1; void setup(void) { memset(&cerea_commands, 0, sizeof(cerea_commands)); memset(&relay_control, 0, sizeof(relay_control)); memset(cerea_command_out, 0, sizeof(char) * MAX_CHARS_CMD_STRING); memset(boom_section_active, 0, sizeof(bool) * MAX_CHARS_CMD_STRING); init_remote_control_gui(); Serial.begin(9600); // init pins pinMode(VIBRATION_MOTOR_PIN, OUTPUT); digitalWrite(VIBRATION_MOTOR_PIN, LOW); pinMode(RELAY_PIN_1, OUTPUT); pinMode(RELAY_PIN_2, OUTPUT); digitalWrite(RELAY_PIN_1, LOW); digitalWrite(RELAY_PIN_2, LOW); } void draw_header() { for (uint8_t i = 0; i < MAX_NR_BOOM_SECTIONS; i++) { uint16_t color = boom_section_states[i] == BOOM_UNUSED ? GRAY : boom_section_states[i] == BOOM_INACTIVE ? RED : GREEN; tft.fillRect(SECTION_RECT_X + SECTION_RECT_SPACING_X * i, SECTION_RECT_Y, SECTION_RECT_SIZE, SECTION_RECT_SIZE, color); } tft.drawLine(SEPERATOR_LINE_START_X, SEPERATOR_LINE_Y, SEPERATOR_LINE_END_X, SEPERATOR_LINE_Y, WHITE); } void draw_page1() { tft.fillScreen(BLACK); tft.setRotation(2); draw_header(); // create control buttons for (uint8_t row = 0; row < BUTTON_COUNT / 4; row++) { for (uint8_t col = 0; col < BUTTON_COUNT / 4; col++) { control_buttons[col + row * 2].drawButton(); } } control_buttons[BUTTON_RELAY_AUTO].drawButton(relay_control.automatic); control_buttons[BUTTON_RELAY_MANUAL].drawButton(relay_control.manual_override); control_buttons[BUTTON_MARC].drawButton(cerea_commands.marc); control_buttons[BUTTON_CEREA_AUTO].drawButton(cerea_commands.auto_on); navigation_button_p1.drawButton(); current_page = 1; } void draw_page2() { tft.fillScreen(BLACK); tft.setRotation(2); draw_header(); for (uint8_t row = 0; row < MAX_NR_BOOM_SECTIONS / 2; row++) { for (uint8_t col = 0; col < MAX_NR_BOOM_SECTIONS / 5; col++) { boom_section_buttons[col + row * 2].drawButton(); } } navigation_button_p2.drawButton(); current_page = 2; } void init_remote_control_gui() { Serial.println(F("TFT LCD test")); tft.reset(); // additional LCDs can be added here uint16_t identifier = tft.readID(); if (identifier == 0x9486) { Serial.println(F("Found 0x9486 LCD driver")); } else { Serial.println(F("ERROR: LCD driver chip not compatible")); } tft.setRotation(2); tft.begin(identifier); Serial.print("TFT size is "); Serial.print(tft.width()); Serial.print("x"); Serial.println(tft.height()); // create control buttons for (uint8_t row = 0; row < BUTTON_COUNT / 2; row++) { for (uint8_t col = 0; col < BUTTON_COUNT / 4; col++) { control_buttons[col + row * 2].initButtonUL(&tft, BUTTON_X + col * (BUTTON_W + BUTTON_SPACING_X), BUTTON_Y + row * (BUTTON_H + BUTTON_SPACING_Y), BUTTON_W, BUTTON_H, YELLOW, // outline button_colors[col + row * 2], WHITE, button_labels[col + row * 2], BUTTON_TEXTSIZE); // text } } for (uint8_t row = 0; row < MAX_NR_BOOM_SECTIONS / 2; row++) { for (uint8_t col = 0; col < MAX_NR_BOOM_SECTIONS / 5; col++) { boom_section_buttons[col + row * 2].initButtonUL(&tft, BUTTON_X + col * (BUTTON_W + BUTTON_SPACING_X), BUTTON_Y + row * (BOOM_BUTTON_H + BUTTON_SPACING_Y), BUTTON_W, BOOM_BUTTON_H, YELLOW, // outline NAVY, WHITE, boom_button_labels[col + row * 2], BUTTON_TEXTSIZE); // text } } navigation_button_p1.initButtonUL(&tft, NAV_BUTTON_X, NAV_BUTTON_Y, NAV_BUTTON_W, NAV_BUTTON_H, WHITE, BLACK, WHITE, nav_button_label_p1, NAV_BUTTON_TEXTSIZE); navigation_button_p2.initButtonUL(&tft, NAV_BUTTON_X, NAV_BUTTON_Y, NAV_BUTTON_W, NAV_BUTTON_H, WHITE, BLACK, WHITE, nav_button_label_p2, NAV_BUTTON_TEXTSIZE); draw_page1(); } void loop(void) { // if read_serial did reach end, eval string if (read_serial()) { if (cerea_command_in.startsWith("@CEREA;")) { evaluate_cerea_string(); } else if (cerea_command_in.startsWith("@STATUSAM;")) { evaluate_status_string(); } cerea_command_in = ""; } TSPoint lcd_point; lcd_point.x = 0; lcd_point.y = 0; lcd_point.z = 0; TSPoint touch_point = ts.getPoint(); // XM and YP are shared with LCD and automatically set to INPUT by ts.getPoint(); // change back to OUTPUT for the LCD to work pinMode(XM, OUTPUT); pinMode(YP, OUTPUT); if (touch_point.z > MIN_PRESSURE && touch_point.z < MAX_PRESSURE) { lcd_point.y = map(touch_point.x, TS_MINX, TS_MAXX, tft.height(), 0); lcd_point.x = map(touch_point.y, TS_MINY, TS_MAXY, 0, tft.width()); } if (current_page == 1) { if (navigation_button_p1.contains(lcd_point.x, lcd_point.y)) { navigation_button_p1.press(true); // tell the button it is pressed } else { navigation_button_p1.press(false); // tell the button it is NOT pressed } if (navigation_button_p1.justPressed()) { digitalWrite(VIBRATION_MOTOR_PIN, HIGH); start_time_ms = millis(); navigation_button_p1.drawButton(true); draw_page2(); goto finish_touch_handling; } for (uint8_t b = 0; b < BUTTON_COUNT; b++) { if (control_buttons[b].contains(lcd_point.x, lcd_point.y)) { control_buttons[b].press(true); // tell the button it is pressed } else { control_buttons[b].press(false); // tell the button it is NOT pressed } } for (uint8_t b = 0; b < BUTTON_COUNT; b++) { if (control_buttons[b].justPressed()) { // activate the vibration pin if a button is pressed digitalWrite(VIBRATION_MOTOR_PIN, HIGH); start_time_ms = millis(); if (b < 4) { control_buttons[b].drawButton(true); } // possible CEREA commands: // marc, contour, New, none, A, B, auto, left, right, turn left, turn right // e.g. activate marc: // Serial.println ("@SDOSE;1;0;0;0;0;0;0;0;0;0;0;END"); switch (b) { case BUTTON_A: cerea_commands.A = true; break; case BUTTON_B: cerea_commands.B = true; break; case BUTTON_LEFT: cerea_commands.left = true; break; case BUTTON_RIGHT: cerea_commands.right = true; break; case BUTTON_RELAY_AUTO: relay_control.automatic = !relay_control.automatic; control_buttons[BUTTON_RELAY_AUTO].drawButton(relay_control.automatic); break; case BUTTON_RELAY_MANUAL: relay_control.manual_override = !relay_control.manual_override; control_buttons[BUTTON_RELAY_MANUAL].drawButton(relay_control.manual_override); cerea_commands.marc = relay_control.manual_override; control_buttons[BUTTON_MARC].drawButton(relay_control.manual_override); control_relays(relay_control.manual_override); break; case BUTTON_MARC: cerea_commands.marc = !cerea_commands.marc; control_buttons[BUTTON_MARC].drawButton(cerea_commands.marc); break; case BUTTON_CEREA_AUTO: cerea_commands.auto_on = !cerea_commands.auto_on; control_buttons[BUTTON_CEREA_AUTO].drawButton(cerea_commands.auto_on); break; default: break; } // no command to CEREA is necessary if button relay auto is pressed if (b != BUTTON_RELAY_AUTO) { // build and send command string (boolean implicitely casted to decimal 0/1) sprintf(cerea_command_out, "@SDOSE;%d;0;0;0;%d;%d;%d;%d;%d;0;0;END", cerea_commands.marc, cerea_commands.A, cerea_commands.B, cerea_commands.auto_on, cerea_commands.left, cerea_commands.right); Serial.println(cerea_command_out); } // reset non-toggle control_buttons cerea_commands.A = false; cerea_commands.B = false; cerea_commands.left = false; cerea_commands.right = false; } if (control_buttons[b].justReleased() && b < 4) { control_buttons[b].drawButton(); } } } else if (current_page == 2) { if (navigation_button_p2.contains(lcd_point.x, lcd_point.y)) { navigation_button_p2.press(true); // tell the button it is pressed } else { navigation_button_p2.press(false); // tell the button it is NOT pressed } if (navigation_button_p2.justPressed()) { digitalWrite(VIBRATION_MOTOR_PIN, HIGH); start_time_ms = millis(); navigation_button_p2.drawButton(true); draw_page1(); goto finish_touch_handling; } for (uint8_t b = 0; b < MAX_NR_BOOM_SECTIONS; b++) { if (boom_section_buttons[b].contains(lcd_point.x, lcd_point.y)) { boom_section_buttons[b].press(true); // tell the button it is pressed } else { boom_section_buttons[b].press(false); // tell the button it is NOT pressed } } for (uint8_t b = 0; b < MAX_NR_BOOM_SECTIONS; b++) { if (boom_section_buttons[b].justPressed()) { // activate the vibration pin if a button is pressed digitalWrite(VIBRATION_MOTOR_PIN, HIGH); start_time_ms = millis(); if (boom_section_states[b] == BOOM_ACTIVE) { boom_section_states[b] == BOOM_INACTIVE; boom_section_active[b] = false; } else { boom_section_states[b] == BOOM_ACTIVE; boom_section_active[b] = true; } boom_section_buttons[b].drawButton(true); // build and send command string (boolean implicitely casted to decimal 0/1) sprintf(cerea_command_out, "@BOOMBOX;%d;%d;%d;%d;%d;%d;%d;%d;%d;%d;", boom_section_active[0], boom_section_active[1], boom_section_active[2], boom_section_active[3], boom_section_active[4], boom_section_active[5], boom_section_active[6], boom_section_active[7], boom_section_active[8], boom_section_active[9]); Serial.println(cerea_command_out); } if (boom_section_buttons[b].justReleased()) { boom_section_buttons[b].drawButton(); } } } finish_touch_handling: // debounce UI delay(10); if ((millis() - start_time_ms) > VIBRATION_TIME_MS) { digitalWrite(VIBRATION_MOTOR_PIN, LOW); } } // read from serial interface bool read_serial() { while (Serial.available() > 0) { char next_char = Serial.read(); if (next_char >= 32) { cerea_command_in += next_char; } // if there is a '\n' the whole input is read if (next_char == '\n') { return true; } } return false; } void evaluate_status_string () { // remove @STATUSAM; cerea_command_in.remove(0, 10); // search for index of command end int command_end = cerea_command_in.indexOf("END"); if (command_end < 4) { return; } bool automatic = cerea_command_in.substring(0, 1).toInt(); bool marc = cerea_command_in.substring(2, 3).toInt(); cerea_commands.auto_on = automatic; cerea_commands.marc = marc; if (current_page == 1) { control_buttons[BUTTON_CEREA_AUTO].drawButton(automatic); control_buttons[BUTTON_MARC].drawButton(marc); } } void evaluate_cerea_string() { // remove @Cerea; and search for ; cerea_command_in.remove(0, 7); int first_semicolon = cerea_command_in.indexOf(';'); int second_semicolon = cerea_command_in.indexOf(';', first_semicolon + 1); // read GPS speed in km/h float gps_speed = cerea_command_in.substring(0, first_semicolon).toFloat(); // remove speed and -1 then search for command end cerea_command_in.remove(0, second_semicolon + 1); // search for index of command end int command_end = cerea_command_in.indexOf("END"); // get number of boom box sections (divide because of ;) int number_boom_sections = command_end / 2; // abort if no section is detected if (number_boom_sections < 1) { return; } // extract boom sections and save states String boom_sections = cerea_command_in.substring(0, command_end); for (int i = 0; i < MAX_NR_BOOM_SECTIONS; i++) { uint16_t color = GRAY; boom_state_t boom_section_state = BOOM_UNUSED; if (i < number_boom_sections) { // result is either 0 or 1 => BOOM_INACTIVE or BOOM_ACTIVE boom_section_active[i] = boom_sections.substring(i*2, i*2 + 1).toInt(); boom_section_state = boom_section_active[i] ? BOOM_ACTIVE : BOOM_INACTIVE; color = boom_section_active[i] ? GREEN : RED; } // only update state and UI if a state changes if (boom_section_states[i] != boom_section_state) { boom_section_states[i] = boom_section_state; tft.fillRect(SECTION_RECT_X + SECTION_RECT_SPACING_X * i, SECTION_RECT_Y, SECTION_RECT_SIZE, SECTION_RECT_SIZE, color); } } // no automatic if manual override is false if (!relay_control.manual_override || !relay_control.automatic) { return; } // control boom section 1 if vehicle is moving & auto is active bool enable_relays = gps_speed >= MIN_GPS_SPEED && boom_section_states[0] == BOOM_ACTIVE; control_relays(enable_relays); } void control_relays(bool enable) { if (enable) { digitalWrite(RELAY_PIN_1, HIGH); digitalWrite(RELAY_PIN_2, HIGH); } else { digitalWrite(RELAY_PIN_1, LOW); digitalWrite(RELAY_PIN_2, LOW); } } <file_sep>import sys import time import serial def cerea_simulation(): ''' cerea_simulation() mimics the serial output behavior of the Cerea auto-steer system. Can be used for testing and prototyping of e.g. Arduino controlles without the necessity of a working Cerea setup. The settings of the serial partner have to match. ''' com_port = 'COM5' # com_port = '/dev/cu.usbmodemFA1301' send_delay = 0.5 try: # defaults to a baudrate of 9600; no parity; 1 stop bit serial_port = serial.Serial(com_port, timeout=0.010) except serial.SerialException as e: print(e) sys.exit(1) time.sleep(2.0) # delay to not activate flashin of Arduino print('Send commands with', send_delay, 'seconds delay') i = 0 command_strings = ['@CEREA;5.0;-1;0;END', '@CEREA;5.0;-1;1;END', '@CEREA;5.0;-1;0;END', '@CEREA;5.0;-1;1;1;1;1;1;1;1;1;1;1;END', '@CEREA;5.0;-1;0;0;0;0;0;1;1;1;1;1;END', '@CEREA;5.0;-1;0;0;0;0;0;0;0;0;0;0;END', '@HIDRAU;1;END', '@STATUSAM;1;1;END'] try: while True: command = command_strings[i % len(command_strings)] print('>', command) serial_port.write((command + '\r\n').encode()) time.sleep(send_delay) print(serial_port.read_until()) i = i + 1 except KeyboardInterrupt: print('Keyboard interrupt by user - exit') sys.exit(1) if __name__ == '__main__': cerea_simulation()
4d09a1621f2baceae6cd0ef88395fd74c3a56ba2
[ "Markdown", "Python", "C++" ]
4
Markdown
danrauch/arduino-cerea-remote-control
a68609e1601488d0d8cf764d6438f886a54f208a
bc43dfd90362ac5e8fe4b527b96d068a8ed06ec0
refs/heads/master
<file_sep> # coding: utf-8 # # Creating Helper Functions # In[1]: import pandas as pd import matplotlib.pyplot as plt import sqlite3 get_ipython().magic('matplotlib inline') # Function that takes a SQL query as an argument and returns a pandas dataframe of that query def run_query(q): with sqlite3.connect('chinook.db') as conn: return pd.read_sql(q, conn) # Function that takes a SQL command as an argument and executes it using the sqlite module def run_command(c): with sqlite3.connect('chinook.db') as conn: # Tells SQLite to autocommit changes conn.isolation_level = None conn.execute(c) def show_tables(): q = ''' SELECT name, type FROM sqlite_master WHERE type IN("table","view");''' return run_query(q) show_tables() # # Selecting Albums to Purchase # In[2]: albums_to_purchase = ''' WITH usa_tracks_sold AS ( SELECT il.* FROM invoice_line il INNER JOIN invoice i on il.invoice_id = i.invoice_id INNER JOIN customer c on i.customer_id = c.customer_id WHERE c.country = "USA" ) SELECT g.name genre, count(uts.invoice_line_id) tracks_sold, cast(count(uts.invoice_line_id) AS FLOAT) / ( SELECT COUNT(*) from usa_tracks_sold ) percentage_sold FROM usa_tracks_sold uts INNER JOIN track t on t.track_id = uts.track_id INNER JOIN genre g on g.genre_id = t.genre_id GROUP BY 1 ORDER BY 2 DESC LIMIT 10; ''' run_query(albums_to_purchase) # In[3]: genre_sales_usa = run_query(albums_to_purchase) genre_sales_usa.set_index("genre", inplace=True, drop=True) genre_sales_usa["tracks_sold"].plot.barh( title="Top Selling Genres in the USA", xlim=(0, 625) ) for i, label in enumerate(list(genre_sales_usa.index)): score = genre_sales_usa.loc[label, "tracks_sold"] label = (genre_sales_usa.loc[label, "percentage_sold"] * 100 ).astype(int).astype(str) + "%" plt.annotate(str(label), (score + 10, i - 0.15)) plt.show() # Based on the sales of tracks across different genres in the USA, we should purchase the new albums by the following artists: # 1) <NAME> (Punk) # 2) <NAME> (Blues) # 3) Meteor and the Girls (Pop) # # It's worth keeping in mind that combined, these three genres only make up only 17% of total sales, so we should be on the lookout for artists and albums from the 'rock' genre, which accounts for 53% of sales. # # Analyzing Employee Sales Performance # In[4]: employee_sales_performance = ''' WITH customer_support_rep_sales AS ( SELECT i.customer_id, c.support_rep_id, SUM(i.total) total FROM invoice i INNER JOIN customer c ON c.customer_id = i.customer_id GROUP BY 1, 2 ) SELECT e.first_name || " " || e.last_name employee, e.hire_date, SUM(csrs.total) total_sales FROM customer_support_rep_sales csrs INNER JOIN employee e ON e.employee_id = csrs.support_rep_id GROUP BY employee; ''' run_query(employee_sales_performance) # In[5]: employee_sales = run_query(employee_sales_performance) employee_sales.set_index("employee", drop=True, inplace=True) employee_sales.sort_values("total_sales", inplace=True) employee_sales.plot.barh( legend=False, title='Sales Breakdown by Employee', colormap=plt.cm.Accent ) plt.show() # <NAME> has the most sales. However, she was hired earlier than Margaret and Steve, which explains the reason for the higher sales numbers # # Analyzing Sales by Country # In[8]: sales_by_country = ''' WITH country_or_other AS ( SELECT CASE WHEN ( SELECT count(*) FROM customer where country = c.country ) = 1 THEN "Other" ELSE c.country END AS country, c.customer_id, il.* FROM invoice_line il INNER JOIN invoice i ON i.invoice_id = il.invoice_id INNER JOIN customer c ON c.customer_id = i.customer_id ) SELECT country, customers, total_sales, average_order, customer_lifetime_value FROM ( SELECT country, count(distinct customer_id) customers, SUM(unit_price) total_sales, SUM(unit_price) / count(distinct customer_id) customer_lifetime_value, SUM(unit_price) / count(distinct invoice_id) average_order, CASE WHEN country = "Other" THEN 1 ELSE 0 END AS sort FROM country_or_other GROUP BY country ORDER BY sort ASC, total_sales DESC ); ''' run_query(sales_by_country) # In[10]: import numpy as np # Visualizing Sales by Country country_metrics = run_query(sales_by_country) country_metrics.set_index("country", drop=True, inplace=True) colors = [plt.cm.Accent(i) for i in np.linspace(0, 1, country_metrics.shape[0])] fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(9, 10)) ax1, ax2, ax3, ax4 = axes.flatten() fig.subplots_adjust(hspace=.5, wspace=.3) # top left sales_breakdown = country_metrics["total_sales"].copy().rename('') sales_breakdown.plot.pie( ax=ax1, startangle=-90, counterclock=False, title='Sales Breakdown by Country,\nNumber of Customers', colormap=plt.cm.Accent, fontsize=8, wedgeprops={'linewidth':0} ) # top right cvd_cols = ["customers","total_sales"] custs_vs_dollars = country_metrics[cvd_cols].copy() custs_vs_dollars.index.name = '' for c in cvd_cols: custs_vs_dollars[c] /= custs_vs_dollars[c].sum() / 100 custs_vs_dollars.plot.bar( ax=ax2, colormap=plt.cm.Set1, title="Pct Customers vs Sales" ) ax2.tick_params(top="off", right="off", left="off", bottom="off") ax2.spines["top"].set_visible(False) ax2.spines["right"].set_visible(False) # bottom left avg_order = country_metrics["average_order"].copy() avg_order.index.name = '' difference_from_avg = avg_order * 100 / avg_order.mean() - 100 difference_from_avg.drop("Other", inplace=True) difference_from_avg.plot.bar( ax=ax3, color=colors, title="Average Order,\nPct Difference from Mean" ) ax3.tick_params(top="off", right="off", left="off", bottom="off") ax3.axhline(0, color='k') ax3.spines["top"].set_visible(False) ax3.spines["right"].set_visible(False) ax3.spines["bottom"].set_visible(False) # bottom right ltv = country_metrics["customer_lifetime_value"].copy() ltv.index.name = '' ltv.drop("Other",inplace=True) ltv.plot.bar( ax=ax4, color=colors, title="Customer Lifetime Value, Dollars" ) ax4.tick_params(top="off", right="off", left="off", bottom="off") ax4.spines["top"].set_visible(False) ax4.spines["right"].set_visible(False) plt.show() # # Albums vs Individual Tracks, Part 1 # In[12]: albums_vs_tracks = ''' WITH invoice_first_track AS ( SELECT il.invoice_id invoice_id, MIN(il.track_id) first_track_id FROM invoice_line il GROUP BY 1 ) SELECT album_purchase, COUNT(invoice_id) number_of_invoices, CAST(count(invoice_id) AS FLOAT) / ( SELECT COUNT(*) FROM invoice ) percent FROM ( SELECT ifs.*, CASE WHEN ( SELECT t.track_id FROM track t WHERE t.album_id = ( SELECT t2.album_id FROM track t2 WHERE t2.track_id = ifs.first_track_id ) EXCEPT SELECT il2.track_id FROM invoice_line il2 WHERE il2.invoice_id = ifs.invoice_id ) IS NULL THEN "yes" ELSE "no" END AS "album_purchase" FROM invoice_first_track ifs ) GROUP BY album_purchase ''' run_query(albums_vs_tracks) # # Albums vs Individual Tracks, Part 2 # In[13]: albums_vs_tracks_2 = ''' WITH invoice_first_track AS ( SELECT il.invoice_id invoice_id, i.customer_id, MIN(il.track_id) first_track_id FROM invoice_line il INNER JOIN invoice i ON i.invoice_id = il.invoice_id GROUP BY 1, 2 ) SELECT album_purchase, COUNT(invoice_id) number_of_invoices, CAST(COUNT(invoice_id) AS FLOAT) / ( SELECT COUNT(*) FROM invoice ) percent FROM ( SELECT ifs.*, t.album_id, CASE WHEN ( SELECT t3.track_id FROM track t3 WHERE t3.album_id = t.album_id EXCEPT SELECT il2.track_id FROM invoice_line il2 INNER JOIN invoice i2 ON i2.invoice_id = il2.invoice_id INNER JOIN track t2 ON t2.track_id = il2.track_id WHERE il2.invoice_id <= ifs.invoice_id AND i2.customer_id = ifs.customer_id AND t2.album_id = t.album_id ) IS NULL THEN "yes" ELSE "no" END AS "album_purchase" FROM invoice_first_track ifs INNER JOIN track t ON ifs.first_track_id = t.track_id ) GROUP BY 1 ''' run_query(albums_vs_tracks_2)
0aec62467382120e589e345ca301dfaec144b5ee
[ "Python" ]
1
Python
ernhung92/Answering-Business-Questions-Using-SQL-Queries
0d948914973438a3c6c2b9cae0fb83d1acbb6bcf
e27e5f275e64ba5bc88d7e8d7b7ef414ded85442
refs/heads/master
<repo_name>grafismoweb/tarea_2_1<file_sep>/tarea_2_1/src/tarea_2_1/Tarea_2_1.java /* tarea_2_1. Tres números (uso de if-else). Almacena en una constante numérica tipo entera llamada "D" el número 22. Después, lee tres números enteros por teclado (podrán ser negativos o positivos). Dados esos tres números: •Si los tres números leídos son menores que D, se mostrará "TRES NÚMEROS MENORES". •Si dos de los tres números leídos por teclado es menor que D, se mostrará "DOS NÚMEROS MENORES". •Si uno de los tres números leídos por teclado es menor que D, se mostrará "UN NÚMERO MENOR". •Si ninguno de los tres números leídos por teclado es menor que D, se mostrará "NINGÚN NÚMERO MENOR". Ten en cuenta que: •Se valorará que se minimize el número de líneas. •Se tendrá que capturar las excepciones que se producen si los datos introducidos por el usuario no son un número válido (incluye letras por ejemplo). En caso de que salte una excepción por ese motivo, el programa deberá mostrar un mensaje de error y terminar. •Se deberá utilizar estructuras "if/else" o "if/elseif/else" (al menos una de ellas obligatoriamente). •No se puede usar "return" o "System.exit" para salir del programa en ningún momento. */ package tarea_2_1; /** * @author Teresa */ public class Tarea_2_1 { /** * @param args the command line arguments */ public static void main(String[] args) { final int D=22;//declaro e inicializo la constante D, le asigno su valor. /* leer tres nuemeros enteros por teclado */ //condiciones a cumplir según sean los tres numeros } }
f40fb5131c72f1d443d358edfd90a5acaefe8d57
[ "Java" ]
1
Java
grafismoweb/tarea_2_1
849e172d138ccf91a3e35407fbaf758b41d133af
7deaea0c21ffef064325252b47b11db520fa2265
refs/heads/master
<file_sep>import path from 'path'; import { defineConfig } from 'umi'; export default defineConfig({ dynamicImport: { loading: '@/components/Loading', }, dva:{ immer:true, }, // autd:{}, // nodeModulesTransform: { // type: 'none', // }, base:'/', title:'H5-Vis', // routes: [ // { exact: true, path: '/', redirect: '/editor' }, // { exact: true, path: '/editor', component: 'editor' }, // { exact: true, path: '/ide', component: 'ide' }, // { exact: true, path: '/home', component: 'home' }, // ], routes: [ { exact: false, path: '/', component: '@/layouts/index', routes: [ { path: '/', component: '../pages/home', }, { path: '/editor', component: '../pages/editor', }, { path: '/ide', component: '../pages/ide', }, ], }, ], }); <file_sep> export default Image;<file_sep>const template = { type: 'Carousel', h:82, displayName:'轮播组件' } export default template;<file_sep> export type tTextDefault = string; export type tColorDefault = string; export type tNumberDefault = number; export type tSelectDefault<KeyType> = KeyType; export interface iTextConfig { key: string; name: string; type: 'Text'; } export interface iColorConfig { key: string; name: string; type: 'Color'; } export interface iNumberConfig { key: string; name: string; type: 'Number'; range?: [number,number]; step?:number; } export interface iSelectConfig<KeyType> { key:string; name:string; type:'Select'; range: Array<{ key: KeyType; text: string; }> } //文本 export type tTextSelectKey = 'left'|'right'|'center'; export type tTextEditData = Array< iTextConfig | iColorConfig | iNumberConfig | iSelectConfig<tTextSelectKey> >;<file_sep>import BasicSchema from './Basic/schema' // import MediaSchema from './Media/schema' // import VisualSchema from './Visual/schema' const schema = { ...BasicSchema, // ...MediaSchema, // ...VisualSchema } export default schema;<file_sep> const Footer: IFooterSchema = { //可编辑数据 editData:[], //配置数据 config:{ bgColor:'rgba(0,0,0,1)', text:'页脚Footer', color:'rgba(255,255,255,1)', align:'center', fontSize:16, height:48, } } export default Footer;<file_sep>const template = { type:'Footer', h:24, displayName:'页脚组件', } export default template;<file_sep>// import Image from './Image/schema' import Text from './Text/schema' // import Footer from './Footer/schema' const basicSchema = { // Image, Text, // Footer, } export default basicSchema;<file_sep>import { tTextDefault, tColorDefault, tNumberDefault, tSelectDefault, tTextSelectKey, tTextEditData } from '@/components/types'; export interface iTextConfig { text: tTextDefault; color: tColorDefault; fontSize: tNumberDefault; align: tSelectDefault<tTextSelectKey>; lineHeight:tNumberDefault; } export interface iTextSchema { editData: tTextEditData; config: iTextConfig; } const Text: iTextSchema = { editData: [ { key:'text', name:'文字', type:'Text', }, { key:'color', name:'标题颜色', type:'Color', }, { key:'fontSize', name:'字体大小', type:'Number', }, { key:'align', name:'对齐方式', type:'Select', range:[ { key:'left', text:'左对齐', }, { key:'center', text:'居中对齐', }, { key:'right', text:'右对齐', }, ] }, { key:'lineHeight', name:'行高', type:'Number', } ], config:{ text:'我是文本', color:'rgba(60,60,60,1)', fontSize:18, align:'center', lineHeight:2, } } export default Text;<file_sep># h5Vis H5可视化拖拽编译器 ## Getting Started Install dependencies, ``` $ npm install ``` Start the dev server, ``` $ npm run start ``` 浏览器访问 http://localhost:8000/editor #使用的技术栈 - react - umi - antd - react-dnd 1.渲染模板 2.渲染组件 3.渲染引擎 <file_sep>// import Carousel from './Carousel/template'; import Text from './Text/template'; import Image from './Image/template'; import Footer from './Footer/template'; const basicTmp = [ // Carousel, Text, // Image, // Footer ] const BasicTemplate = basicTmp.map(v => { return {...v, category: 'base'}; }) export default BasicTemplate;<file_sep>const template = { type:'Image', h:80, displayName:'图片组件' } export default template;<file_sep>import VisualTemplate from '../Visual/template'; export default VisualTemplate;
66ad45d90ddfb08735ced5594cf31dbc93f01460
[ "Markdown", "TypeScript" ]
13
TypeScript
keyzf/H5-Vis
8427fc5ce90346e50ec559426d3039aa225961c0
5b58dccff38ac58dff5e61b10907ee7ef6fd27e8
refs/heads/main
<file_sep>function escapeHTML (string) { const entityMap = { '&' : '&amp;', '<' : '&lt;', '>' : '&gt;', ' ' : '&#32;', '!' : '&#33;', '"' : '&#34;', '$' : '&#36;', '%' : '&#37;', "'" : '&#39;', '(' : '&#40;', ')' : '&#41;', '+' : '&#43;', '/' : '&#47;', '=' : '&#61;', '@' : '&#64;', '[' : '&#91;', ']' : '&#93;', '`' : '&#96;', '{' : '&#123;', '}' : '&#125;', }; return String(string).replace(/[[&<> !"$%'()+/=@`{}]|]/g, s => entityMap[s] ); } function ovalue (obj) { var base = obj; if (typeof base == 'object' && base !== null) { for (var i=1, x=arguments.length; i<x; i++) { if (typeof base[arguments[i]] == 'object' && base[arguments[i]] !== null) { base = base[arguments[i]]; } else { base = base[arguments[i--]]; break; } } } return base; } if (typeof exports === 'object') { module.exports.escapeHTML = escapeHTML; module.exports.ovalue = ovalue; registeredInModuleLoader = true; } <file_sep># Human Readable OPML A nice littel node script what taketh thine OPML file and rendereth it unto an human readable HTML file. It goeth through each subscription and it pulleth the title, description and website from the feed URL, and createth a nice littel HTML file what thou canst share with thy friends and enemies, thy loved ones, and with the authorities as thou pleasest or howsoever thou be required by law, so help us all. Installation followeth the normal malarkey: `npm install`. Then munst thou run the file like so: `node ploppops.js`. If thou wishest to make edits to these parameters herein, **thou munst be a good goat** and edit the file for thine own needs. Things what thou mayest want to change are below. These do appear at the top of the JS file as constants. - `input` — the subscriptions file name, a relative filepath, in OPML format; the default be `subscriptions.opml` - `title` — the title which appeareth at the top of the file; the default be `Mark's podcasts`, which thou mayest wish to change to thine own name, or a titelle of thine own choosing - `scheme` — a nice littel piece of text, a "tag" if thou wilst, what specifieth in which app to open the podcast, e.g. `itms`, `podcasts`; the default be `itms` or something, I am yet to decide; and lo, mark thou this point welle: this mayeth go away since this whole business seemeth to be the darkest shenanigans (yea, even unto the end of time) and it mayeth prove more expedient to be rid of the entire filthy enterprise. - `style` — here be CSS to make thine HTML full betterer for the gentler eye ## Categoires Included in this nice littel repositoire is the abilitoire to put your podcasts into what categoires what seem appropriate to you. This is a nice littel HTML page which does the business quite good. You should be awoire that I have created it with whimsy and silliness and written it in a language called Frunch, so any copy on it is probably impossible to understand. If you don't like this, I quite invite you to change your mind.
303e835ce000b7644b0f65bc2e131a195b811b6a
[ "JavaScript", "Markdown" ]
2
JavaScript
beingmrkenny/human-readable-opml
064217458c30b5fcad8b7915f235352d8b460ca5
61e9ed66f391aed79bed5ae14637971765efb8d8
refs/heads/master
<repo_name>Chaanchess/GamingApp<file_sep>/src/app/juegos/juegos/juegos.component.ts import { Component, OnInit } from '@angular/core'; import { JuegosService } from '../../servicios/juegos.service'; @Component({ selector: 'app-juegos', templateUrl: './juegos.component.html', styleUrls: ['./juegos.component.css'] }) export class JuegosComponent implements OnInit { juegoArray = []; showDeletedMessage: boolean; shownoGamesMessage: boolean; searchText: string = ""; public cargando:Boolean=false; constructor(private juegosService: JuegosService) { } ngOnInit() { this.cargando=true; this.juegosService.getJuegos().subscribe( list => { this.juegoArray = list.map(item => { return { $key: item.key, ...item.payload.val() }; }); this.shownoGamesMessage=true; this.cargando=false; }); } onDelete($key, miboton) { if (confirm('¿Estás seguro de que deseas borrar este juego?')) { this.juegosService.deleteJuego($key); this.showDeletedMessage = true; setTimeout(() => this.showDeletedMessage = false, 3000); } } filterCondition(juego) { return juego.nombre.toLowerCase().indexOf(this.searchText.toLowerCase()) != -1; } } <file_sep>/src/app/servicios/juegos.service.ts import { Injectable } from '@angular/core'; import { map, filter, switchMap } from 'rxjs/operators'; import { AngularFireDatabase, AngularFireList } from 'angularfire2/database'; import { AddjuegComponent } from '../juegos/addjueg/addjueg.component'; import { FormControl, FormGroup, Validators } from "@angular/forms"; import { Router } from '@angular/router'; @Injectable({ providedIn: 'root' }) export class JuegosService { constructor(private firebase: AngularFireDatabase,private router: Router) { } juegosList: AngularFireList<any>; form = new FormGroup({ $key: new FormControl(null), nombre: new FormControl('', Validators.required), fecha: new FormControl('', Validators.required), descripcion: new FormControl('', Validators.required), puntuacion: new FormControl('', [Validators.required, Validators.min(1), Validators.max(10)]), dificultad: new FormControl('', Validators.required), desarrolladora: new FormControl('', Validators.required), trailer: new FormControl('', Validators.required) }); getJuegos() { this.juegosList = this.firebase.list('juegos'); return this.juegosList.snapshotChanges(); } insertJuego(juego) { this.juegosList.push({ nombre: juego.nombre, fecha: juego.fecha, descripcion: juego.descripcion, puntuacion: juego.puntuacion, dificultad: juego.dificultad, desarrolladora: juego.desarrolladora, trailer: juego.trailer, }); } populateForm(juego) { this.form.setValue(juego); } updateJuego(juego) { this.juegosList.update(juego.$key, { nombre: juego.nombre, fecha: juego.fecha, descripcion: juego.descripcion, puntuacion: juego.puntuacion, dificultad: juego.dificultad, desarrolladora: juego.desarrolladora, trailer: juego.trailer, }); } deleteJuego($key: string) { this.juegosList.remove($key); } } <file_sep>/src/app/app.component.ts import { Component, OnInit } from '@angular/core'; import * as firebase from 'firebase'; import { environment } from '../environments/environment'; import { AutenticacionService } from './servicios/autenticacion.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { private isLoggedIn: Boolean; private user_displayName: String; private user_email: String; constructor(public authService: AutenticacionService/*, private router: Router*/) { this.authService.afAuth.auth.onAuthStateChanged((user) => { if (user != null) { // User is logged in, use the user object for its info. this.isLoggedIn = true; this.user_displayName = user.displayName; this.user_email = user.email; console.log("logged ON"); // etc. } else { // User is not logged in, redirect to where you need to. this.isLoggedIn = false; console.log("No logged on"); } //document.body.classList.add("loaded"); document.getElementById("container").classList.add("loaded"); }); } ngOnInit() { firebase.initializeApp({ apiKey: '<KEY>', authDomain: 'gamingapp-1c9c3.firebaseapp.com' }); } } <file_sep>/README.md # GamingApp This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 7.0.4. ## Development server Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. ## Test my app Access to [My Page](https://chaanchess.github.io/GamingApp/) and test my app in real time. ## Creator App made by <NAME>. <file_sep>/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { ReactiveFormsModule } from '@angular/forms'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { JuegosService } from './servicios/juegos.service'; import { AutenticacionService } from './servicios/autenticacion.service'; import { AngularFireModule } from 'angularfire2'; import { environment } from '../environments/environment'; import { AppComponent } from './app.component'; import { InicioComponent } from './inicio/inicio.component'; import { HeaderComponent } from './header/header.component'; import { AddjuegComponent } from './juegos/addjueg/addjueg.component'; import { JuegosComponent } from './juegos/juegos/juegos.component'; import { EditjuegComponent } from './juegos/editjueg/editjueg.component'; import { RegistroComponent } from './autenticacion/registro/registro.component'; import { InisesComponent } from './autenticacion/inises/inises.component'; import { GuardService } from './servicios/guard.service'; import { AngularFireAuthModule } from 'angularfire2/auth'; import { AngularFireDatabaseModule } from 'angularfire2/database'; const routes: Routes = [ { path: '', component: InicioComponent }, { path: 'addjueg', component: AddjuegComponent, canActivate: [GuardService], data: {breadcrumb:"Añadir Juego"}}, { path: 'juegos', component: JuegosComponent, canActivate: [GuardService], data: {breadcrumb:"Juegos"}}, { path: 'editjueg/:id', component: EditjuegComponent, canActivate: [GuardService], data: {breadcrumb:"Editar Juego"}}, { path: 'registro', component: RegistroComponent }, { path: 'iniciosesion', component: InisesComponent }, { path: '**', component: InicioComponent} ]; @NgModule({ declarations: [ AppComponent, InicioComponent, HeaderComponent, AddjuegComponent, JuegosComponent, EditjuegComponent, RegistroComponent, InisesComponent ], imports: [ BrowserModule, RouterModule.forRoot(routes), FormsModule, ReactiveFormsModule, HttpModule, AngularFireModule.initializeApp(environment.firebase), AngularFireDatabaseModule, AngularFireAuthModule ], providers: [JuegosService, AutenticacionService], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>/src/app/juegos/editjueg/editjueg.component.ts import { Component, OnInit } from '@angular/core'; import { FormControl, FormGroup, FormBuilder, Validators } from '@angular/forms'; import { JuegosService } from '../../servicios/juegos.service'; import { Router, ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-editjueg', templateUrl: './editjueg.component.html', styleUrls: ['./editjueg.component.css'] }) export class EditjuegComponent implements OnInit { formControls = this.juegoService.form.controls; juegoForm: FormGroup; juego: any; constructor(private router: Router, private juegoService: JuegosService) { } ngOnInit() { } saveEdit() { this.juegoService.updateJuego(this.juegoService.form.value); this.router.navigate(['/juegos']); this.juegoService.form.setValue({ $key: null, nombre: '', fecha: '', descripcion: '', puntuacion: '', dificultad: '', desarrolladora: '', trailer: '' }); } clearField(){ this.juegoService.form.setValue({ $key: null, nombre: '', fecha: '', descripcion: '', puntuacion: '', dificultad: '', desarrolladora: '', trailer: '' }); } } <file_sep>/src/app/servicios/autenticacion.service.ts import { Injectable } from '@angular/core'; import * as firebase from 'firebase'; import { Router, ActivatedRoute } from '@angular/router'; import { AngularFireAuth } from 'angularfire2/auth'; import { Observable, of } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class AutenticacionService { private user: Observable<firebase.User>; private userDetails: firebase.User = null; registroUsuario(userdata) { return firebase.auth().createUserWithEmailAndPassword(userdata.email, userdata.password) } constructor(private router: Router, private activatedRouter: ActivatedRoute, public afAuth: AngularFireAuth) { this.user = afAuth.authState; this.user.subscribe( (user) => { if (user) { console.log("NO entiendo nada, si dentro"); this.userDetails = user; console.log(this.userDetails); } else { console.log("fuera"); this.userDetails = null; } } ); } inicioSesion(userdata) { return firebase.auth().signInWithEmailAndPassword(userdata.email, userdata.password) } isAuthenticated() { const user = firebase.auth().currentUser; if (user) { return true; } else { return false; } } logout() { this.userDetails = null; this.user = null; firebase.auth().signOut(); } isLogged() { return this.afAuth.authState; } getUser() { if (firebase.auth().currentUser) return firebase.auth().currentUser.email; else return null; } doGoogleLogin() { return new Promise<any>((resolve, reject) => { let provider = new firebase.auth.GoogleAuthProvider(); provider.addScope('profile'); provider.addScope('email'); this.afAuth.auth .signInWithPopup(provider) .then(res => { resolve(res); this.router.navigate(['/inicio']); }) }) } } <file_sep>/src/app/juegos/addjueg/addjueg.component.ts import { Component, OnInit } from '@angular/core'; import { FormControl, FormGroup, FormBuilder, Validators } from '@angular/forms'; import { JuegosService } from '../../servicios/juegos.service'; import { Router, ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-addjueg', templateUrl: './addjueg.component.html', styleUrls: ['./addjueg.component.css'] }) export class AddjuegComponent implements OnInit { submitted: boolean; showSuccessMessage: boolean; formControls = this.juegoService.form.controls; public enviado:Boolean=false; constructor(private juegoService: JuegosService) { } ngOnInit() { } onSubmit() { this.submitted = true; if (this.juegoService.form.valid) { (this.juegoService.form.get('$key').value == null) this.juegoService.insertJuego(this.juegoService.form.value); this.showSuccessMessage = true; setTimeout(() => this.showSuccessMessage = false, 3000); this.submitted = false; this.juegoService.form.reset(); //this is to be done for proper reset operation this.juegoService.form.setValue({ $key: null, nombre: '', fecha: '', descripcion: '', puntuacion: '', dificultad: '', desarrolladora: '', trailer: '' }); this.enviado=true; setTimeout(() => { this.enviado = false }, 2000); } } clearField(){ this.juegoService.form.setValue({ $key: null, nombre: '', fecha: '', descripcion: '', puntuacion: '', dificultad: '', desarrolladora: '', trailer: '' }); } }
4bcfef2cfe0621bd233f5862d696adc38bd818d1
[ "Markdown", "TypeScript" ]
8
TypeScript
Chaanchess/GamingApp
6d7ad26edeec0aae21b6ec641a960f750a133e47
ce63650a110f1f09e7d68501a9d901f015cba1d9
refs/heads/master
<file_sep>package com.dorkcloud; public class Main { public static void main(String[] args) { // Foolish program - <NAME> 10/10/2016 int age = 44; String lastName = "Burke"; String firstName = "Stephen"; System.out.println(age); int x = 1; while (x <= age) { if (x < age) { System.out.println("\nHello " + firstName + " " + lastName + ". You were once " + x + " years old."); x++; if (x == age) { System.out.println("\nYou are now " + age); } } } } }
75ad00a65dd9e7317764a5b5d0b6522a8edce95b
[ "Java" ]
1
Java
se7enack/java
be7cbe1609b4387287cf80439fb67ee44f29792d
319d8968db75490958f91b70ad3640b49d92db3d
refs/heads/master
<repo_name>krsvarma/HomeInsuranceSystem<file_sep>/home-insurance-management-system/src/main/java/com/cg/hims/service/IAgentServiceImp.java package com.cg.hims.service; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.cg.hims.entities.Agent; import com.cg.hims.repository.IAgentRepository; @Service public class IAgentServiceImp implements IAgentService { @Autowired private IAgentRepository agentRepo; @Override public Agent addAgent(Agent agent) { return agentRepo.save(agent); } @Override public List<Agent> viewAllAgents() { return agentRepo.findAll(); } @Override public Optional<Agent> findAgentById(int agentId) { return agentRepo.findById(agentId); } @Override public Agent updateAgent(Agent agent) { return agentRepo.save(agent); } @Override public void removeAgent(int agentId) { agentRepo.deleteById(agentId); } @Override public List<Agent> getAllAgentsByDesignation(String desg) { // TODO Auto-generated method stub return agentRepo.findByDesignation(desg); } /* @Override public List<Agent> getAllAgentsByName(String name) { // TODO Auto-generated method stub return agentRepo.findByName(name); } */ @Override public List<Agent> getAllAgentsByagentName(String name) { // TODO Auto-generated method stub return agentRepo.findByAgentName(name); } } <file_sep>/home-insurance-management-system/src/main/java/com/cg/hims/entities/Policy.java package com.cg.hims.entities; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; import javax.validation.constraints.Min; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import org.springframework.stereotype.Component; import com.fasterxml.jackson.annotation.JsonIgnore; @Component @Entity public class Policy { @Id @NotNull @Min(1) private int policyId; @Pattern(regexp="^(0?[1-9]|[12][0-9]|3[01])[\\/\\-](0?[1-9]|1[012])[\\/\\-]\\d{4}$", message="policyEffectiveDate is invalid") @NotEmpty(message = "policyEffectiveDate is required") private String policyEffectiveDate; @Pattern(regexp="^(0?[1-9]|[12][0-9]|3[01])[\\/\\-](0?[1-9]|1[012])[\\/\\-]\\d{4}$", message="policyEndDate is invalid") @NotEmpty(message = "policyEndDate is required") private String policyEndDate; @Min(1) private int policyTerm; @Size(min=3, max=50) @Pattern(regexp="[a-zA-Z]{4,}(?:[a-zA-Z]+){0,2}$", message="Policy Status is invalid") private String policyStatus; @JsonIgnore @OneToOne(cascade=CascadeType.ALL) @JoinColumn(name="quote_id") private Quote quote; @JsonIgnore @ManyToOne @JoinColumn(name="agentId") private Agent agent; @JsonIgnore @ManyToOne @JoinColumn(name="policyHolderId") private PolicyHolder policyholder; public Policy() { super(); // TODO Auto-generated constructor stub } public Policy(@NotNull @Min(1) int policyId, @Pattern(regexp = "^(0?[1-9]|[12][0-9]|3[01])[\\/\\-](0?[1-9]|1[012])[\\/\\-]\\d{4}$", message = "policyEffectiveDate is invalid") @NotEmpty(message = "policyEffectiveDate is required") String policyEffectiveDate, @Pattern(regexp = "^(0?[1-9]|[12][0-9]|3[01])[\\/\\-](0?[1-9]|1[012])[\\/\\-]\\d{4}$", message = "policyEndDate is invalid") @NotEmpty(message = "policyEndDate is required") String policyEndDate, @Min(1) int policyTerm, @Size(min = 3, max = 50) @Pattern(regexp = "[a-zA-Z]{4,}(?:[a-zA-Z]+){0,2}$", message = "policyStatus is invalid") String policyStatus, Quote quote, Agent agent, PolicyHolder policyholder) { super(); this.policyId = policyId; this.policyEffectiveDate = policyEffectiveDate; this.policyEndDate = policyEndDate; this.policyTerm = policyTerm; this.policyStatus = policyStatus; this.quote = quote; this.agent = agent; this.policyholder = policyholder; } public int getPolicyId() { return policyId; } public void setPolicyId(int policyId) { this.policyId = policyId; } public String getPolicyEffectiveDate() { return policyEffectiveDate; } public void setPolicyEffectiveDate(String policyEffectiveDate) { this.policyEffectiveDate = policyEffectiveDate; } public String getPolicyEndDate() { return policyEndDate; } public void setPolicyEndDate(String policyEndDate) { this.policyEndDate = policyEndDate; } public int getPolicyTerm() { return policyTerm; } public void setPolicyTerm(int policyTerm) { this.policyTerm = policyTerm; } public String getPolicyStatus() { return policyStatus; } public void setPolicyStatus(String policyStatus) { this.policyStatus = policyStatus; } public Quote getQuote() { return quote; } public void setQuote(Quote quote) { this.quote = quote; } public Agent getAgent() { return agent; } public void setAgent(Agent agent) { this.agent = agent; } public PolicyHolder getPolicyholder() { return policyholder; } public void setPolicyholder(PolicyHolder policyholder) { this.policyholder = policyholder; } @Override public String toString() { return "Policy [policyId=" + policyId + ", policyEffectiveDate=" + policyEffectiveDate + ", policyEndDate=" + policyEndDate + ", policyTerm=" + policyTerm + ", policyStatus=" + policyStatus + ", quote=" + quote + ", agent=" + agent + ", policyholder=" + policyholder + "]"; } }<file_sep>/home-insurance-management-system/src/main/java/com/cg/hims/controller/QuoteController.java package com.cg.hims.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.PathVariable; //import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.parameters.RequestBody; import com.cg.hims.entities.Quote; import com.cg.hims.exceptions.QuoteNotFoundException; import com.cg.hims.service.IQuoteService; @RestController public class QuoteController{ @Autowired private IQuoteService quoteService; @RequestMapping(value="/quote/all", method=RequestMethod.GET ) public List<Quote> getAllQuote(){ return quoteService.viewAllQuotes(); } @RequestMapping(value= "/quote/{id}", method= RequestMethod.GET) public Quote getQuote(@Valid @PathVariable int id) throws QuoteNotFoundException { Optional<Quote> quote = quoteService.findQuoteById(id); if(!quote.isPresent()) { throw new QuoteNotFoundException("quote not found for this id "+id); } else return quote.get(); } @RequestMapping(value= "/quote/add", method= RequestMethod.POST) public Quote addQuote(@RequestBody Quote newquote) { return quoteService.addQuote(newquote); } @RequestMapping(value= "/quote/update/{id}", method= RequestMethod.PUT) public Quote updateQuote(@Valid @RequestBody Quote updquote, @PathVariable int id)throws QuoteNotFoundException { Optional<Quote> qut = quoteService.findQuoteById(id); if (!qut.isPresent()) { throw new QuoteNotFoundException("quote not found for this id-"+ id); } else { updquote.setQuoteId(id); return quoteService.updateQuote(updquote); } } @RequestMapping(value= "/quote/delete/{id}", method= RequestMethod.DELETE) public void deleteQuote(@PathVariable int id) throws QuoteNotFoundException { Optional<Quote> qut = quoteService.findQuoteById(id); if(!qut.isPresent()) { throw new QuoteNotFoundException("quote not found for this id"+id); } else { quoteService.removeQuote(id); } } @RequestMapping(value = "/quote/all/bypremiumtype/{prumtype}", method=RequestMethod.GET) public List<Quote>getAllQuotesByPreminumId(@PathVariable(value="prumtype") String prumtype)throws QuoteNotFoundException { List<Quote> Quotes = quoteService.getAllQuotesByPremiumType(prumtype); if(Quotes.isEmpty()) { throw new QuoteNotFoundException("Could not find quote with premiumtype-" +prumtype); } return quoteService.getAllQuotesByPremiumType(prumtype); } @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(MethodArgumentNotValidException.class) public Map<String, String> handleMethodArgumentNotValid(MethodArgumentNotValidException ex) { Map<String, String> errors = new HashMap<>(); ex.getBindingResult().getFieldErrors().forEach(error -> errors.put(error.getField(), error.getDefaultMessage())); return errors; } }<file_sep>/home-insurance-management-system/src/main/java/com/cg/hims/entities/Quote.java package com.cg.hims.entities; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import org.springframework.stereotype.Component; @Component @Entity public class Quote { @Id private int quoteId; @NotEmpty(message = "premiumtype should not be empty") private String premiumType; @NotNull @Min(2) @Max(8) private int premium; @NotNull @Min(2) @Max(8) private int dwellingCoverage; @NotNull @Min(2) @Max(8) private int detachedStructureCoverage; @NotNull @Min(2) @Max(8) private int personalPropertyCoverage; @NotNull @Min(2) @Max(8) private int additionalLivingExpense; @NotNull @Min(2) @Max(8) private int medicalExpense; @NotNull @Min(2) @Max(8) private int deductibleAmount; @OneToOne(cascade=CascadeType.ALL) @JoinColumn(name="propertyId") private Property property; public Quote() { super(); // TODO Auto-generated constructor stub } public Quote(int quoteId, @NotEmpty(message = "premiumtype should not be empty") String premiumType, @NotNull @Min(2) @Max(8) int premium, @NotNull @Min(2) @Max(8) int dwellingCoverage, @NotNull @Min(2) @Max(8) int detachedStructureCoverage, @NotNull @Min(2) @Max(8) int personalPropertyCoverage, @NotNull @Min(2) @Max(8) int additionalLivingExpense, @NotNull @Min(2) @Max(8) int medicalExpense, @NotNull @Min(2) @Max(8) int deductibleAmount, Property property) { super(); this.quoteId = quoteId; this.premiumType = premiumType; this.premium = premium; this.dwellingCoverage = dwellingCoverage; this.detachedStructureCoverage = detachedStructureCoverage; this.personalPropertyCoverage = personalPropertyCoverage; this.additionalLivingExpense = additionalLivingExpense; this.medicalExpense = medicalExpense; this.deductibleAmount = deductibleAmount; this.property = property; } public int getQuoteId() { return quoteId; } public void setQuoteId(int quoteId) { this.quoteId = quoteId; } public String getPremiumType() { return premiumType; } public void setPremiumType(String premiumType) { this.premiumType = premiumType; } public int getPremium() { return premium; } public void setPremium(int premium) { this.premium = premium; } public int getDwellingCoverage() { return dwellingCoverage; } public void setDwellingCoverage(int dwellingCoverage) { this.dwellingCoverage = dwellingCoverage; } public int getDetachedStructureCoverage() { return detachedStructureCoverage; } public void setDetachedStructureCoverage(int detachedStructureCoverage) { this.detachedStructureCoverage = detachedStructureCoverage; } public int getPersonalPropertyCoverage() { return personalPropertyCoverage; } public void setPersonalPropertyCoverage(int personalPropertyCoverage) { this.personalPropertyCoverage = personalPropertyCoverage; } public int getAdditionalLivingExpense() { return additionalLivingExpense; } public void setAdditionalLivingExpense(int additionalLivingExpense) { this.additionalLivingExpense = additionalLivingExpense; } public int getMedicalExpense() { return medicalExpense; } public void setMedicalExpense(int medicalExpense) { this.medicalExpense = medicalExpense; } public int getDeductibleAmount() { return deductibleAmount; } public void setDeductibleAmount(int deductibleAmount) { this.deductibleAmount = deductibleAmount; } public Property getProperty() { return property; } public void setProperty(Property property) { this.property = property; } @Override public String toString() { return "Quote [quoteId=" + quoteId + ", premiumType=" + premiumType + ", premium=" + premium + ", dwellingCoverage=" + dwellingCoverage + ", detachedStructureCoverage=" + detachedStructureCoverage + ", personalPropertyCoverage=" + personalPropertyCoverage + ", additionalLivingExpense=" + additionalLivingExpense + ", medicalExpense=" + medicalExpense + ", deductibleAmount=" + deductibleAmount + ", property=" + property + "]"; } }<file_sep>/home-insurance-management-system/src/main/java/com/cg/hims/controller/IUserController.java package com.cg.hims.controller; import java.util.HashMap; import java.util.Map; import java.util.Optional; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.PathVariable; //import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.parameters.RequestBody; import com.cg.hims.entities.User; import com.cg.hims.exceptions.InvalidCredentialException; import com.cg.hims.service.IUserService; @RestController public class IUserController { @Autowired private IUserService userservice; @RequestMapping(value= "/user/{id}", method= RequestMethod.GET) public User getUser(@PathVariable int id) throws InvalidCredentialException { Optional<User> user = userservice.findUserById(id); if(!user.isPresent()) { throw new InvalidCredentialException("credential not found for this id"+id); } else return user.get(); } @RequestMapping(value= "/user/add user", method= RequestMethod.POST) public User addUser( @Valid @RequestBody User user) { return userservice.addUser(user); } @RequestMapping(value= "/user/update/{id}", method= RequestMethod.PUT) public User updateUser(@Valid @RequestBody User upduser, @PathVariable int id) throws InvalidCredentialException { Optional<User> user = userservice.getUser(id); if(!user.isPresent()) { throw new InvalidCredentialException("credential not found for this id"+id); } else { upduser.setUserid(id); return userservice.updateUser(upduser); } } @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(MethodArgumentNotValidException.class) public Map<String, String> handleMethodArgumentNotValid(MethodArgumentNotValidException ex) { Map<String, String> errors = new HashMap<>(); ex.getBindingResult().getFieldErrors().forEach(error -> errors.put(error.getField(), error.getDefaultMessage())); return errors; } }
9dde0d2c6ad3dc9a7722fb4f5f1b381a87f77c4a
[ "Java" ]
5
Java
krsvarma/HomeInsuranceSystem
7831510d368f4609e1cf5ae4360dcd5c47c097c0
a7cd36ffe7c1a65f12c24d4ce8d803e2a5c9166f
refs/heads/master
<repo_name>PawelDarlak/cpp_python<file_sep>/main.py import sys, platform import ctypes, ctypes.util # Get the path to the system C library mojsystem = platform.system() if platform.system() == "Windows": path_libc = ctypes.util.find_library("msvcrt") else: path_libc = ctypes.util.find_library("c") # Get a handle to the sytem C library try: libc = ctypes.CDLL(path_libc) except OSError: print("Unable to load the system C library") sys.exit() print(f'Succesfully loaded the system C library from "{path_libc}"') libc.puts(b"Hello from Python to C") libc.printf(b"%s\n", b"Using the C printf function from Python ... ")
2d3488effe3d2484d95e338a16615e7f33ef9875
[ "Python" ]
1
Python
PawelDarlak/cpp_python
2d4972f36c21eb0c53909affd7bcf368039e58eb
ef35edf369a99b782db51cdcb6b52d4b98c3ff87
refs/heads/master
<repo_name>slnky/slnky-hipchat<file_sep>/lib/capistrano/tasks/hipchat.rake namespace :slnky do task :hipchat do # do something end end <file_sep>/lib/slnky/hipchat/command.rb module Slnky module Hipchat class Command < Slnky::Command::Base attr_writer :client def client @client ||= Slnky::Hipchat::Client.new end command :logging, 'manage hipchat log watching', <<-USAGE.strip_heredoc Usage: logging [options] [ON_OFF] ON_OFF should be true or false, if absent, just reports current setting -h --help print help. USAGE def handle_logging(request, response, opts) value = opts.on_off if value.nil? log.info "logging is currently: #{client.logging}" elsif value == 'true' client.logging = true log.info "logging is set: #{client.logging}" elsif value == 'false' client.logging = false log.info "logging is set: #{client.logging}" end end # # use docopt to define arguments and options # command :echo, 'respond with the given arguments', <<-USAGE.strip_heredoc # Usage: echo [options] ARGS... # # -h --help print help. # -x --times=TIMES print x times [default: 1]. # USAGE # # # handler methods receive request, response, and options objects # def handle_echo(request, response, opts) # # parameters (non-option arguments) are available as accessors # args = opts.args # # as are the options themselves (by their 'long' name) # 1.upto(opts.times.to_i) do |i| # # just use the log object to respond, it will automatically send it # # to the correct channel. # log.info args.join(" ") # end # end end end end <file_sep>/lib/slnky/hipchat.rb require 'slnky' require 'slnky/hipchat/client' require 'slnky/hipchat/mock' require 'slnky/hipchat/service' require 'slnky/hipchat/command' <file_sep>/lib/slnky/hipchat/client.rb require 'hipchat' module Slnky module Hipchat class Client < Slnky::Client::Base attr_accessor :logging def initialize @token = config.hipchat.token @rooms = config.hipchat.rooms ? config.hipchat.rooms.split(',') : [] @levels = config.hipchat.levels ? config.hipchat.levels.split(',').map(&:to_sym) : [:warn, :error] @logging = true @hipchat = HipChat::Client.new(@token) @hipchat_rooms = @hipchat.rooms.inject({}) do |h, r| k = r.name.downcase.gsub(/\s+/, '_') h[k] = r.room_id h end end def logline(log) return unless @logging level = log.level.to_sym color = case level when :warn 'yellow' when :error 'red' else 'green' end return true unless @levels.include?(level) message = "<b>#{log.message}</b><br/><i>#{log.service}</i>" @rooms.each do |room| hipchat_send(room, message, notify: true, color: color, format: 'html') end true end def hipchat_send(room, message, options={}) o = hipchat_options(options) user = 'SLNky' unless room @rooms.each do |r| hipchat_send(r, message, options) end return end room = @hipchat_rooms[room] if @hipchat_rooms[room] if config.development? puts "(#{o[:color]}) #{user}@#{room}: #{message}" else @hipchat[room].send(user, message, notify: o[:notify], color: o[:color], message_format: o[:format]) end rescue => e log.error "hipchat service: #{e.message}" log.debug "#{e.message}\n#{e.backtrace.first(5).join("\n")}" end def hipchat_options(options={}) { color: 'yellow', notify: true, format: 'text', }.merge(options.delete_if{|k, v| v.nil?}) end end end end <file_sep>/service-slnky-hipchat #!/usr/bin/env ruby lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'rubygems' require 'bundler/setup' require 'dotenv' require 'daemons' require 'slnky/service/hipchat' Dotenv.load env = ARGV[0] # Become a daemon # Daemons.daemonize if env == 'production' Slnky::Service::Hipchat.new(ENV['SLNKY_URL'], env: env).start <file_sep>/spec/slnky/hipchat/service_spec.rb require 'spec_helper' describe Slnky::Hipchat::Service do subject do s = described_class.new s.client = Slnky::Hipchat::Mock.new s end let(:test_event) { slnky_event('test') } let(:chat_event) { slnky_event('chat') } let(:test_event) { slnky_event('test') } let(:log_info) { slnky_event('info') } let(:log_warn) { slnky_event('warn') } let(:log_error) { slnky_event('error') } it 'handles event' do expect(subject.handle_test(test_event.name, test_event.payload)).to eq(true) end it 'handles event chat' do expect(subject.handle_event(chat_event.name, chat_event.payload)).to include("testing event chat message") end it 'handles info' do expect(subject.handle_log(log_info)).to include("INFO slnky.service.chef: node i-12345678") end it 'handles warning' do expect(subject.handle_log(log_warn)).to include("WARN slnky.service.chef: node i-12345678") end it 'handles error' do expect(subject.handle_log(log_error)).to include("ERROR slnky.service.chef: node i-12345678") end end <file_sep>/lib/slnky/hipchat/service.rb module Slnky module Hipchat class Service < Slnky::Service::Base attr_writer :client def client @client ||= Slnky::Hipchat::Client.new end subscribe '*', :handle_event subscribe 'slnky.service.test', :handle_test # you can also subscribe to heirarchies, this gets # all events under something.happened # subscribe 'something.happened.*', :other_handler def run logs = transport.queue('hipchat', 'logs') logs.subscribe do |raw| handle_log(parse(raw)) end response = transport.queue('hipchat', 'response', durable: false, auto_delete: true, routing_key: 'hipchat') response.subscribe do |raw| handle_response(parse(raw)) end end def handle_test(name, data) name == 'slnky.service.test' && data.hello == 'world!' end def handle_log(message) client.logline(message) end def handle_event(name, data) return nil unless data.chat && data.chat.message room = data.chat.room message = data.chat.message # unless data.chat.format == 'html' # message = "<b>#{data.chat.message}</b><br/><i>event: #{name}</i>" # data.chat.format = 'html' # end client.hipchat_send(room, message, notify: data.chat.notify, color: data.chat.color, format: data.chat.format) end def handle_response(message) (user, room) = message.reply.split(':', 2) return if %w{start complete}.include?(message.level) color = case message.level when 'info' 'green' when 'warn' 'yellow' when 'error' 'red' end client.hipchat_send(room, message.message, notify: true, color: color, format: 'text') end end end end <file_sep>/lib/slnky/hipchat/mock.rb module Slnky module Hipchat class Mock < Slnky::Hipchat::Client # unless there's something special you need to do in the initializer # use the one provided by the actual client object def initialize end def logline(log) "#{log.level.upcase} #{log.message}" end def hipchat_send(room, message, options={}) options = hipchat_options(options) user = 'SLNky' "#{user}: #{message}" end end end end
103e8f4092a2bbdbbe589b9370f5a0be7b76d3e4
[ "Ruby" ]
8
Ruby
slnky/slnky-hipchat
a49c0595dc05b5905f5e8dc496a655cd33115a05
bfa8062ec3be92e958b74b45416e195bb0e41f1c
refs/heads/master
<file_sep>## Install ``` npm i string-repeater --save ``` <file_sep>"use strict" /** * Repeat a string. * * @param input The string to repeat. * @param times The number of times to repeat. * * @return A new repeated string. */ function repeat(input, times) { return impl.call(input, times); } /** * Prototype implementation called with the string as the scope. * * Note that this implementation: * * return new Array(Math.abs(times) + 1).join(this); * * Is very, very slow. * * This implementation: * * var ret = ''; * for(var i = 0; i < times; i++) { * ret += this; * } * return ret; * * Is faster than `string-repeat` but slower than `string.prototype.repeat`. * * @param times The number of times to repeat. * * @return A new repeated string. */ function impl(times) { // conditional is faster than Math.abs() var n = times < 0 ? -times : times , result = '' , string = '' + this; // optimized loop from string.prototype.repeat while(n) { if(n % 2 === 1) { result += string; } if(n > 1) { string += string; } n >>= 1; } return result; } repeat.impl = impl; module.exports = repeat; <file_sep>## Usage ```javascript var repeat = require('string-repeater') , str = repeat('foo ', 7); // 'foo foo foo foo foo ' ``` Or if you prefer to polyfill `String.prototype`: ```javascript var repeat = require('string-repeater'); String.prototype.repeat = String.prototype.repeat || repeat.impl; ``` <file_sep>[![Build Status](https://travis-ci.org/tmpfs/string-repeater.svg?v=2)](https://travis-ci.org/tmpfs/string-repeater) [![npm version](http://img.shields.io/npm/v/string-repeater.svg?v=2)](https://npmjs.org/package/string-repeater) [![Coverage Status](https://coveralls.io/repos/tmpfs/string-repeater/badge.svg?branch=master&service=github&v=2)](https://coveralls.io/github/tmpfs/string-repeater?branch=master) Repeat a string. <file_sep>[jshint]: http://jshint.com [jscs]: http://jscs.info <file_sep>Table of Contents ================= * [String Repeat](#string-repeat) * [Install](#install) * [Usage](#usage) * [Benchmark](#benchmark) * [Source](#source) * [Developer](#developer) * [Test](#test) * [Cover](#cover) * [Lint](#lint) * [Clean](#clean) * [Readme](#readme) String Repeat ============= [<img src="https://travis-ci.org/tmpfs/string-repeater.svg?v=2" alt="Build Status">](https://travis-ci.org/tmpfs/string-repeater) [<img src="http://img.shields.io/npm/v/string-repeater.svg?v=2" alt="npm version">](https://npmjs.org/package/string-repeater) [<img src="https://coveralls.io/repos/tmpfs/string-repeater/badge.svg?branch=master&service=github&v=2" alt="Coverage Status">](https://coveralls.io/github/tmpfs/string-repeater?branch=master). Repeat a string. ## Install ``` npm i string-repeater --save ``` ## Usage ```javascript var repeat = require('string-repeater') , str = repeat('foo ', 7); // 'foo foo foo foo foo ' ``` Or if you prefer to polyfill `String.prototype`: ```javascript var repeat = require('string-repeater'); String.prototype.repeat = String.prototype.repeat || repeat.impl; ``` ## Benchmark ```javascript string-repeater x 4,439,603 ops/sec ±2.15% (85 runs sampled) string-repeat x 60,621 ops/sec ±4.63% (81 runs sampled) string.prototype.repeat x 4,071,996 ops/sec ±2.14% (84 runs sampled) ``` ## Source ```javascript "use strict" /** * Repeat a string. * * @param input The string to repeat. * @param times The number of times to repeat. * * @return A new repeated string. */ function repeat(input, times) { return impl.call(input, times); } /** * Prototype implementation called with the string as the scope. * * Note that this implementation: * * return new Array(Math.abs(times) + 1).join(this); * * Is very, very slow. * * This implementation: * * var ret = ''; * for(var i = 0; i < times; i++) { * ret += this; * } * return ret; * * Is faster than `string-repeat` but slower than `string.prototype.repeat`. * * @param times The number of times to repeat. * * @return A new repeated string. */ function impl(times) { // conditional is faster than Math.abs() var n = times < 0 ? -times : times , result = '' , string = '' + this; // optimized loop from string.prototype.repeat while(n) { if(n % 2 === 1) { result += string; } if(n > 1) { string += string; } n >>= 1; } return result; } repeat.impl = impl; module.exports = repeat; ``` ## Developer ### Test To run the test suite: ``` npm test ``` ### Cover To generate code coverage run: ``` npm run cover ``` ### Lint Run the source tree through [jshint](http://jshint.com) and [jscs](http://jscs.info): ``` npm run lint ``` ### Clean Remove generated files: ``` npm run clean ``` ### Readme To build the readme file from the partial definitions: ``` npm run readme ``` Generated by [mdp(1)](https://github.com/tmpfs/mdp). [jshint]: http://jshint.com [jscs]: http://jscs.info
cda0793c41b0a6dd09185c65f173e6f3857aa0bd
[ "Markdown", "JavaScript" ]
6
Markdown
tmpfs/string-repeater
ba8a2ceafaf0b6532c6a526ae16ebf0584579c7c
5a7ebc19e44cf0f1362e38abfa399e72da44780a
refs/heads/master
<repo_name>j-angnoe/flextension-server<file_sep>/README.md # Flextension server NodeJS capabilities for authorized browser extensions. The flextension server is a process that the user starts on their local machine. Some (authorized) browser extension may connect to the flextenion server and perform operations, like reading and writing files and executing shell commands. Some useful examples of browser extensions that require these super-powers: - [A Localhost Manager extension](https://github.com/j-angnoe/localhost-manager-browser-extension): Tired of being unable to connect to your project because you've forgotten to start it first. No more. Next time you visit a project on localhost you may be prompted to provide a directory and a start command. No more switching between browser and terminal. (Assuming you have the flextenion server running ;-)) - Bookmark to your pc instead of the cloud: There are a lot of research and bookmarking cloud services, but, what if you want to store these on your computer... Security concerns and measures: - The browser restricts a lot of functionality, and rightfully so. Running a service that executes commands on behalf of extensions can potentially be dangerous. That's why: - We do not run this service on a hardcoded port. - An extension that want to interact with flextension server must provide a (randomly generated) token. This way, the user is forced to manually provide the extension with the needed port/token combination. Browser extensions that want to make use of the flextension server must implement a settings page to save the port/token combination. - We might introduce whitelisting functionality for backend scripts and executed commands. ## Example: 1. Install the flextension server via npm: ``` npm install -g flextension-server; ``` 2. Start the flextension server: ``` flextension ``` Please note the port and token that was generated. Now create a firefox extension: ```json << extension/manifest.json >> { "name": "My Flextension", "version": "0.0.1", "manifest_version": 2, "permissions" : [ "http://localhost/*" ], "version" : "2", "background" : { "scripts" : ["/build/background.js"] } } ``` ```js << extension/src/background.js >> var port = '...'; // enter port number here. var token = '...'; // enter token here console.log("Background script running"); async function main() { var socket = require('flextension-server/client')({ port, token }); socket.registerBackend({ rpc: { printEnvironment() { return this.process.env.HOME + ' ' + this.process.pid; } } }) socket.on('ready', async () => { console.log("Doen het"); var env = await socket.rpc('printEnvironment'); console.log("Environment", env); }) } main(); ``` ```json << extension/package.json >> { "name" : "my-extension", "browserslist" : [ "last 1 Chrome version" ] } ``` Build it: ```sh << build >> cd extension; parcel build src/*.js -d build ``` Run it with Firefox' web-ext ```sh << run >> cd extension; web-ext run ``` Open extension developer console (Ctrl+Shift+J) and Toggle `Show Content messages`, and reload the extension, you should see `Environment /home/xxx/` and a pid number. You can run the example scripts provided here using the [walkthrough compiler](https://github.com/j-angnoe/code-walkthrough-compiler) ```sh # Install walkthrough compiler: npm install -g walkthrough-compiler # Extract the code from the README.md wlkc README.md -o tmp -x build # Run it: wlkc README>md -o tmp -x run ``` <file_sep>/bin/flextension #!/usr/bin/env node async function main() { var path = require('path'); var settings; var crypto = require('crypto'); var FLEXTENSIONRC = path.join(process.env.HOME, '.flextensionrc'); try { var fs = require('fs'); settings = JSON.parse(fs.readFileSync(FLEXTENSIONRC)); } catch (err) { console.error(err); // file can be non-existing. settings = settings || {}; } settings.port = settings.port || 55000 + Math.ceil(Math.random() * 999); settings.token = settings.token || await new Promise((resolve,reject) => { crypto.randomBytes(48, function(err, buffer) { if (err) { return reject(err); } resolve(buffer.toString('hex')); }); }); fs.writeFileSync(path.join(FLEXTENSIONRC), JSON.stringify(settings, null, 3)); console.log('Read settings', settings); require('../server.js')(settings); } main(); <file_sep>/package.json { "name": "flextension-server", "version": "0.0.1", "description": "A websocket server which runs on your local machine.", "main": "server.js", "bin": { "flextension": "./bin/flextension" }, "scripts" : { "test": "node tests/run-tests.js" }, "author": "<NAME>", "license": "MIT", "dependencies": { "glob": "^7.1.5", "socket.io": "^2.3.0" } } <file_sep>/client.js /** * This script is consumed by browser extensions that * want to interact with a flextension server running on * the local machine. * * @usage * * ```js * var settings = { port: 12345, token: '<PASSWORD>' }; * * var rpcServices = { * ping() { * // When this is called it runs inside the * // extension background script. * return 'pong'; * } * }; * * var socket = require('flextension-server/client')({ * port: settings.port, * token: settings.token * }, rpcServices); * * socket.registerBackend({ * // server side dependencies that must be included. * requires: ['leftpad'], * async init() { * // This runs inside the flextension nodejs process. * console.log("This is run inside the flextension process") * * // It may call the background script via the * // globally available rpc function. * * await rpc('ping'); // === pong (from extension background script) * * // Access our dependencies by prepending this. * this.leftpad(); * * // you may also call sibling functions, like someFunction. * this.someFunction() * * // you can call rpc functions like so: * this.rpc.executeSomethingOnTheServer(); * }, * someFunction() { * * }, * * rpc: { * executeSomethingOnTheServer(arg1, arg2) { * // This rpc function executes inside the flextension nodejs process * // as well. * console.log("Received arguments ", arg1, arg2) * return arg1+arg2; * * // You can call someFunction * this.someFunction() * * // And you can call rpc functions like so: * this.rpc.anotherRpcFunction() * * // Please note that rpc return values must be JSON.stringify-able. * return arg1+arg2; * } * * } * }); * * var result = await socket.rpc('executeSomethingOnTheServer', arg1, arg2); * ``` * */ var io = require('socket.io-client'); module.exports = function({ port, token }, services) { var socket = io.connect(`http://localhost:${port}`); socket.rpc = n => { throw new Error('Backend not available'); }; var backendConnected = false; var backendCode = ''; socket.on('connect', () => { console.log("Backend connection established"); backendConnected = true; try { var runtimeId = browser.runtime.id; } catch (err) { var runtimeId = '(unavailable)'; } socket.emit('auth', { extensionId: runtimeId, token: token }); socket.on('authenticated', () => { console.log("Authenticated"); socket.rpc = require('./socket-rpc')(socket); socket.rpc.register(services); socket.rpc.register({ serverSideInstall: () => { console.log("Install backend code", backendCode); return backendCode } }); }); }); socket.on('disconnect', () => { backendConnected = false; socket.rpc = n => { throw new Error('Backend not available'); }; }); var serializeExecutableObject = object => { return Object.entries(object).map(([key, value]) => { var valueString = ''; if (typeof value === 'function') { var fn = `${value.toString()}`; if (!fn.match(/(async\s)*[a-z_]+\s*\(/i)) { fn = `${key}: ${fn}`; } return fn; } else { return `${key}: ${JSON.stringify(value)}`; } }).join(",\n"); } socket.registerBackend = object => { object.rpc = object.rpc || {}; object.init = object.init || function() {}; var { rpc, ...object } = object; var objectBody = serializeExecutableObject(object) + ",\nrpc:{\n" + serializeExecutableObject(rpc) + "\n}"; backendCode = ['return {', objectBody, '}'].join("\n"); }; return socket; }<file_sep>/tests/run-tests.js async function runTests() { var glob = require('glob'); var tests = glob.sync(__dirname + '/*.js').filter(n => { return n.match(/[0-9].+\.js$/); }); var { spawn } = require('child_process'); for (let t of tests) { console.log("Running test " + t); await new Promise(resolve => { var proc = spawn('node', [t], { stdio: 'inherit' }); proc.on('exit', code => { if (code !== 0) { process.exit(1); } else { console.log("\n\nTest " + t + " success!"); resolve(); } }) }); } } runTests(); <file_sep>/socket-rpc.js /** * Socket rpc * * allows RPC between a client and a server. * The RPC calls may be synchronous and asynchronous. * * @usage * Client usage: * ```js * var io = require('socket.io-client'); * var socket = io.connect('...'); * var rpc = require('flextension-server/socket-rpc').getClient(socket); * * var result = await rpc('my-function', arg1, arg2); * ``` * * Server usage: * ```js * var io = require('socket.io'); * io.on('connection', client => { * var rpcServer = require('flextension-server/socket-rpc').getClient(client); * rpcServer.register({ * 'my-function'(arg1, arg2) { * return new Promise(resolve => { * resolve(arg1+arg2); * }); * * // you may also return results synchronously * * // Please note that rpc return values must be * // JSON.stringify-able. * return arg1+arg2; * } * }); * }); * ``` * */ function getClient(socket) { socket.rpcRequestCounter = socket.rpcRequestCounter || 0; var services = {}; getClient.register = function(addServices) { Object.assign(services, addServices); } sendRpcRequest.register = getClient.register; socket.on('rpc-request', async function dispatchRpc(payload) { if (!(payload.fn in services)) { var e = new Error('RPC Call `' + payload.fn + '` does not exist') console.error(e); console.log("Available services", Object.keys(services)); throw e; } console.log("Dispatching request to " + payload.fn); var result = await services[payload.fn](...(payload.args||[])); socket.emit(payload.replyTo, result); }); function sendRpcRequest(fn, ...args) { var rq = 'rpc-reply-' + (Date.now() + '-' + (++socket.rpcRequestCounter)); return new Promise(resolve => { socket.once(rq, resolve); socket.emit('rpc-request', { fn, args, replyTo: rq }); }) }; return sendRpcRequest; } module.exports = getClient; <file_sep>/server.js /** * Flextension server * * Starts listening for websocket connections on localhost * These connections will be initiated by browser extensions * that implement a flextension client. * * The user may start a flextension server by installing flextension: * * `npm install -g flextension-server` * * After this, the user starts the flextension server by running * * `flextension` * * Security measures: * On first start flextension will generate a random port number and * a security token. * * These values will be stored in $HOME/.flextensionrc * * A browser extension that wants to interact with a flextension-server * running on the local host must ask the user for the port and the * token. * * Please note that a browser extension may be able extend functionality * on the flextension server, via the serverSideInstall mechanism. * * It's important that one only grants permissions to trusted extensions. * */ var socketIo = require('socket.io'); var io; var rpcServices = { /* example: ping() { return 'pong'; } */ } module.exports = function(settings) { var { port } = settings; io = socketIo.listen(port); io.on('error', err => { console.error('socket-io error', err); }); console.log("Flextension server listening on port " + port); console.log("Flextension auth token:\n" + settings.token + "\n"); io.on('connection', client => { console.log('client connected'); client.on('auth', auth => { console.log('auth', auth); var id = auth.extensionId; console.log(`Extension ${id} attempts to connect`); if (auth.token === settings.token) { console.log(`Extension ${id} supplied a valid token. Access granted.`); onAuthenticated(client); } else { console.log(`Extension ${id} did not supply a valid token. Access denied.`) } }); async function onAuthenticated(client) { var rpc = require('./socket-rpc')(client); rpc.register(rpcServices); client.emit('authenticated'); console.log("Fetching server side install"); rpc('serverSideInstall').then(result => { console.log("Installing a script ", result); var fn = new Function('process','require','rpc', result) client.backendService = fn.apply(client, [process, require, rpc]) || {}; client.backendService.process = process; client.backendService.require = require; (client.backendService.requires || []).map(requirement => { client.backendService[requirement] = require(requirement); }); client.backendService.init && client.backendService.init(); Object.keys(client.backendService.rpc || {}).map(key => { client.backendService.rpc[key] = client.backendService.rpc[key].bind(client.backendService); }); rpc.register(client.backendService.rpc || {}); client.emit('ready'); }).catch(err => { console.error(err); }); } }); return io; } <file_sep>/tests/01-basics.js var settings = { port: 55001, token: '<PASSWORD>' }; function deferred(timeout) { if (timeout !== false) { timeout = timeout || 3000; } var _resolve, _reject; var promise = new Promise((resolve, reject) => { _resolve = resolve; _reject = reject; }) promise.resolve = _resolve; promise._reject = _reject; if (timeout !== -1) { setTimeout(_reject, timeout); } return promise; } function assertEquals(value, expected) { value = JSON.stringify(value); expected = JSON.stringify(expected); if (value !== expected) { throw new Error(`Assertion failed: ${value} !== ${expected}`); } } async function runTest() { var flextensionServer = require('../server'); var server = flextensionServer(settings); var clientConnected = deferred(); var initWasCalled = deferred(); var pingWasCalled = deferred(); var clientBackendRpcCalled = deferred(); var clientReadyCalled = deferred(); server.on('connection', () => { clientConnected.resolve(); }) var clientServices = { ping() { pingWasCalled.resolve(); // test a simple result value return 'client pong'; }, testArgs(simpleArg, complexArg) { assertEquals(simpleArg, 'simple value'); assertEquals(complexArg, {complex:'value'}); } }; var client = require('../client')(settings, clientServices); client.registerBackend({ async init() { var result = await rpc('ping'); // Test args rpc('testArgs', 'simple value', {complex:'value'}); }, rpc: { serverCall() { // test complex result value return 'server rpc result'; }, serverArgumentsTest(arg1, arg2) { return { arg1, arg2 } } } }); client.on('ready', async () => { initWasCalled.resolve(); clientReadyCalled.resolve(); var result = await client.rpc('serverCall'); assertEquals(result, 'server rpc result'); clientBackendRpcCalled.resolve(); var result2 = await client.rpc('serverArgumentsTest', 'arg1 value','arg2 value'); assertEquals(result2, {arg1: 'arg1 value', arg2: 'arg2 value'}); }) var promises = { clientConnected, pingWasCalled, initWasCalled, clientBackendRpcCalled, clientReadyCalled, } Object.keys(promises).map(key => { promises[key].catch(err => { console.error('Promise ' + key + ' failed: ', err); }).then(n => { console.log("Promise " + key + " resolved!"); }) }); await Promise.all(Object.values(promises)).catch(err => { console.error("Test failed."); process.exit(1); }); process.exit(0); } runTest();
d45e1fbad4a426c463caac9f62c6137e66c876d8
[ "Markdown", "JSON", "JavaScript" ]
8
Markdown
j-angnoe/flextension-server
3607390ca5c6386b429aaa773ddee6576f13a1c7
a667b8396244f4f45fc585dc714f38550828012e
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace ExploreOnet { /// <summary> /// Interaction logic for HistogramControl.xaml /// </summary> public partial class HistogramControl : UserControl { Histogram hist; public HistogramControl(Histogram hist, int barCount) { InitializeComponent(); this.hist = hist; Histogram.Bin[] bins = hist.getBins(barCount); float maxVal = bins.Max((x) => x.count); //Bar visuals float barHeight = 400; float barWidth = 40; for (int i = 0; i < barCount; i++) { Button bar = new Button(); bar.Height = barHeight * (bins[i].count / maxVal); bar.Width = barWidth; bar.Background = new SolidColorBrush(Colors.CadetBlue); bar.VerticalAlignment = VerticalAlignment.Bottom; barPanel.Children.Add(bar); Label lbl = new Label(); lbl.Height = 30; lbl.Width = barWidth; lbl.Content = Math.Round(bins[i].start,2); lbl.HorizontalContentAlignment = HorizontalAlignment.Left; lbl.BorderBrush = new SolidColorBrush(Colors.Black); lbl.BorderThickness = new Thickness(1, 0, 0, 0); axisPanel.Children.Add(lbl); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ExploreOnet { public class Occupation { public string code; public string title; public string description; public Occupation(string code, string title, string description) { this.code = code; this.title = title; this.description = description; } public double getPropertyValue(Property ppt) { return ONETExplorer.current.occupationProperties.Find((x) => x.ocp == this && x.property == ppt).value; } public override string ToString() { return title; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace ExploreOnet { /// <summary> /// Interaction logic for OccupationVisualizer.xaml /// </summary> public partial class OccupationVisualizer : UserControl { Occupation occupation; public OccupationVisualizer(Occupation occupation) { InitializeComponent(); this.occupation = occupation; titleLabel.Content = occupation.title; description.Text = occupation.description; dataPointsLabel.Content = "Data entries: " + ONETExplorer.current.occupationPropertiesIdxOccupation[occupation].Count; averagePropertyLabel.Content = "Average competency value: " + Math.Round(ONETExplorer.current.occupationPropertiesIdxOccupation[occupation].Average((x) => x.value),3); competencyPercentile.Content = "Overall competency percentile: " + Math.Round(ONETExplorer.current.occupationPercentiles[occupation]*100,1) + "%"; List<OccupationProperty> ocpP = ONETExplorer.current.occupationProperties.FindAll((x) => x.ocp == occupation); //Abilities List<OccupationProperty> ocpAb = ocpP.FindAll((x) => x.property.type == "Ability"); ocpAb = ocpAb.OrderBy((x) => x.value).ToList(); for(int i=0;i<5;i++) { OccupationProperty occ = ocpAb[ocpAb.Count - 1 - i]; Button abilityBut = new Button(); abilityBut.Content = String.Format(" {0,6} : {1}", Math.Round(occ.value, 2), " : " + occ.property.name); abilityBut.Click += PropertyBut_Click; abilityBut.DataContext = occ.property; abilityBut.Height = 50; abilityPanel.Children.Add(abilityBut); } //Knowledge List<OccupationProperty> ocpKb = ocpP.FindAll((x) => x.property.type == "Knowledge"); ocpKb = ocpKb.OrderBy((x) => x.value).ToList(); for (int i = 0; i < 5; i++) { OccupationProperty occ = ocpKb[ocpKb.Count - 1 - i]; Button propertyBut = new Button(); propertyBut.Content = String.Format(" {0,6} : {1}", Math.Round(occ.value, 2), " : " + occ.property.name); propertyBut.Click += PropertyBut_Click; propertyBut.DataContext = occ.property; propertyBut.Height = 50; knowledgePanel.Children.Add(propertyBut); } //Skills List<OccupationProperty> ocpSb = ocpP.FindAll((x) => x.property.type == "Skill"); ocpSb = ocpSb.OrderBy((x) => x.value).ToList(); for (int i = 0; i < 5; i++) { OccupationProperty occ = ocpSb[ocpSb.Count - 1 - i]; Button propertyBut = new Button(); propertyBut.Content = String.Format(" {0,6} : {1}", Math.Round(occ.value, 2), " : " + occ.property.name); propertyBut.Click += PropertyBut_Click; propertyBut.DataContext = occ.property; propertyBut.Height = 50; skillPanel.Children.Add(propertyBut); } //Related occupations var a = ONETExplorer.current.occupationMetric[occupation].ToList(); a = a.OrderBy((x) => x.Value).ToList(); for (int i = 0; i < 10; i++) { Occupation tgtOcp = a[i].Key; //Do not consider self (should be the first element) if (tgtOcp == occupation) continue; double dist = a[i].Value; Button bb = new Button(); bb.Content = String.Format("{0,10} : {1}", Math.Round(dist, 4), tgtOcp.title); bb.HorizontalAlignment = HorizontalAlignment.Stretch; bb.HorizontalContentAlignment = HorizontalAlignment.Left; bb.Height = 50; bb.DataContext = tgtOcp; bb.Click += Bb_Click; relatedPanel.Children.Add(bb); } //Properties histogram Histogram hist = new Histogram(ONETExplorer.current.occupationPropertiesIdxOccupation[occupation].Select((x) => x.value).ToList()); competenciesHistogramControl.Content = new HistogramControl(hist, 10); } private void PropertyBut_Click(object sender, RoutedEventArgs e) { Property pp = (sender as Button).DataContext as Property; MainWindow.current.pushControl(new PropertyVisualizer(pp)); } private void Bb_Click(object sender, RoutedEventArgs e) { Occupation clickedOccupation = (sender as Button).DataContext as Occupation; MainWindow.current.pushControl(new OccupationVisualizer(clickedOccupation)); } } } <file_sep>using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Timers; namespace ExploreOnet { public class ONETExplorer { bool assyncronousLoad = true; public List<Occupation> occupations; public List<Property> properties; public List<OccupationProperty> occupationProperties; public Dictionary<Occupation, List<OccupationProperty>> occupationPropertiesIdxOccupation; public Dictionary<Property, List<OccupationProperty>> occupationPropertiesIdxProperty; public Dictionary<Occupation, double> occupationPercentiles; public static ONETExplorer current; public Dictionary<Occupation, Dictionary<Occupation, double>> occupationMetric; public Dictionary<Property, Dictionary<Property, double>> propertyMetric; public ClusterNode<Occupation> occupationsCluster; public ClusterNode<Property> propertyCluster; public void addOccupationProperty(OccupationProperty opp) { occupationProperties.Add(opp); //if (!occupationPropertiesIdxOccupation.ContainsKey(opp.ocp)) // occupationPropertiesIdxOccupation.Add(opp.ocp, new List<OccupationProperty>()); occupationPropertiesIdxOccupation[opp.ocp].Add(opp); if (!occupationPropertiesIdxProperty.ContainsKey(opp.property)) occupationPropertiesIdxProperty.Add(opp.property, new List<OccupationProperty>()); occupationPropertiesIdxProperty[opp.property].Add(opp); } public void removeOccupation(Occupation ocp) { occupations.Remove(ocp); occupationProperties.RemoveAll((x) => x.ocp == ocp); occupationPropertiesIdxOccupation.Remove(ocp); foreach(KeyValuePair<Property, List<OccupationProperty>> kkp in occupationPropertiesIdxProperty) { kkp.Value.RemoveAll((x) => x.ocp == ocp); } } public ONETExplorer() { current = this; } public List<Action> loadTasks; public void load() { //Initialize base structures occupations = new List<Occupation>(); properties = new List<Property>(); occupationProperties = new List<OccupationProperty>(); occupationPropertiesIdxOccupation = new Dictionary<Occupation, List<OccupationProperty>>(); occupationPropertiesIdxProperty = new Dictionary<Property, List<OccupationProperty>>(); occupationPercentiles = new Dictionary<Occupation, double>(); loadTasks = new List<Action>(); //Populate loading tasks loadTasks.Add(readOccupations); loadTasks.Add(readAbilities); loadTasks.Add(readKnowledge); loadTasks.Add(readSkills); loadTasks.Add(cleanOccupations); loadTasks.Add(normalizeOccupationProperties); loadTasks.Add(computeOccupationPercentiles); loadTasks.Add(getOccupationMetric); loadTasks.Add(computePropertyMetric); loadTasks.Add(createOccupationCluster); loadTasks.Add(createPropertyCluster); //await Task.Run(new Action(readOccupations)); //Init loading loadingStep(); //Old method //readOccupations(); //readAbilities(); //readKnowledge(); //readSkills(); //cleanOccupations(); //normalizeOccupationProperties(); //computeMetric(); //createOccupationCluster(); } int breathTime = 300; private void loadingStep() { if (loadTasks.Count > 0) { if (assyncronousLoad) { Task tt = new Task(loadTasks[0]); tt.ContinueWith(taskOver); tt.Start(); } else { Console.WriteLine("--- Beggining task: " + loadTasks[0].Method.Name + " ---"); loadTasks[0](); Console.WriteLine("--- Task over: " + loadTasks[0].Method.Name + " ---"); loadTasks.RemoveAt(0); //Give some time for the UI thread not to die before going to the next task Timer timer = new Timer(breathTime); timer.AutoReset = false; timer.Enabled = true; timer.Elapsed += BreathOver; timer.Start(); } } else { Console.WriteLine("----- LOADING DONE -----"); } } private void BreathOver(object sender, ElapsedEventArgs e) { MainWindow.current.Dispatcher.Invoke(loadingStep); } public void taskOver(Task tt) { loadTasks.RemoveAt(0); MainWindow.current.Dispatcher.Invoke(loadingStep); } private void readOccupations() { using (StreamReader file = new StreamReader("RawData\\Occupation Data.txt")) { int counter = 0; string ln; while ((ln = file.ReadLine()) != null) { counter++; if (counter == 1) { //Ignore first line } else { //Parse occupation line string[] lineData = ln.Split('\t'); if (lineData.Length != 3) throw new Exception("Input mismatch on occupation data"); Occupation ocp = new Occupation(lineData[0], lineData[1], lineData[2]); occupations.Add(ocp); } } file.Close(); Console.WriteLine("Occupations file has " + counter + " lines."); } //Populate ocp properties dictionary for (int i = 0; i < occupations.Count; i++) occupationPropertiesIdxOccupation.Add(occupations[i], new List<OccupationProperty>()); } private void readAbilities() { string type = "Ability"; using (StreamReader file = new StreamReader("RawData\\Abilities.txt")) { int counter = 0; int badCounter = 0; string ln; while ((ln = file.ReadLine()) != null) { counter++; if (counter == 1) continue; //Ignore first line //Parse ability line string[] lineData = ln.Split('\t'); //Read occupation 0 string occupationCode = lineData[0]; Occupation ocp = occupations.Find((x) => x.code == occupationCode); //Read ability 2 string abilityName = lineData[2]; Property abt = properties.Find((x) => x.name == abilityName && x.type == type); //Add ability to list if it does not exist yet if (abt == null) { abt = new Property(abilityName, type); properties.Add(abt); } //Read Source and Value 3 and 4 double abilityValue; string source = lineData[3]; //LV or IM sources if (source == "LV") { abilityValue = double.Parse(lineData[4], CultureInfo.InvariantCulture) / 7; } else if (source == "IM") { abilityValue = double.Parse(lineData[4], CultureInfo.InvariantCulture) / 5; } else { badCounter++; //Bad line because soruce is unrecognizable continue; } //Check if data source is better (prefer LV) bool update = true; OccupationProperty existing = occupationPropertiesIdxOccupation[ocp].Find((x) => x.property == abt); if (source != "LV") //If source is not LV only add if it is non existant { if (existing == null) //If target does not exist update = true; else update = false; } //Update data if (update) { if (existing == null) { //If it does not exist , add it addOccupationProperty(new OccupationProperty(ocp, abt, abilityValue, source)); } else { //If it exists, update it existing.value = abilityValue; existing.source = source; } } } file.Close(); Console.WriteLine("Abilities file has " + counter + " lines."); Console.WriteLine("Abilities file has " + badCounter + " bad Lines."); } } private void readKnowledge() { string type = "Knowledge"; using (StreamReader file = new StreamReader("RawData\\Knowledge.txt")) { int counter = 0; int badCounter = 0; string ln; while ((ln = file.ReadLine()) != null) { counter++; if (counter == 1) continue; //Ignore first line //Parse ability line string[] lineData = ln.Split('\t'); //Read occupation 0 string occupationCode = lineData[0]; Occupation ocp = occupations.Find((x) => x.code == occupationCode); //Read ability 2 string knowledgeName = lineData[2]; Property kno = properties.Find((x) => x.name == knowledgeName && x.type == type); //Add ability to list if it does not exist yet if (kno == null) { kno = new Property(knowledgeName, type); properties.Add(kno); } //Read Source and Value 3 and 4 double knowledgeValue; string source = lineData[3]; //LV or IM sources if (source == "LV") { knowledgeValue = double.Parse(lineData[4], CultureInfo.InvariantCulture) / 7; } else if (source == "IM") { knowledgeValue = double.Parse(lineData[4], CultureInfo.InvariantCulture) / 5; } else { badCounter++; //Bad line because soruce is unrecognizable continue; } //Check if data source is better (prefer LV) bool update = true; OccupationProperty existing = occupationPropertiesIdxOccupation[ocp].Find((x) => x.property == kno); if (source != "LV") //If source is not LV only add if it is non existant { if (existing == null) //If target does not exist update = true; else update = false; } //Update data if (update) { if (existing == null) { //If it does not exist , add it addOccupationProperty(new OccupationProperty(ocp, kno, knowledgeValue, source)); } else { //If it exists, update it existing.value = knowledgeValue; existing.source = source; } } } file.Close(); Console.WriteLine("Knowledges file has " + counter + " lines."); Console.WriteLine("Knowledges file has " + badCounter + " bad Lines."); } } private void readSkills() { string type = "Skill"; using (StreamReader file = new StreamReader("RawData\\Skills.txt")) { int counter = 0; int badCounter = 0; string ln; while ((ln = file.ReadLine()) != null) { counter++; if (counter == 1) continue; //Ignore first line //Parse ability line string[] lineData = ln.Split('\t'); //Read occupation 0 string occupationCode = lineData[0]; Occupation ocp = occupations.Find((x) => x.code == occupationCode); //Read ability 2 string knowledgeName = lineData[2]; Property ski = properties.Find((x) => x.name == knowledgeName && x.type == type); //Add ability to list if it does not exist yet if (ski == null) { ski = new Property(knowledgeName, type); properties.Add(ski); } //Read Source and Value 3 and 4 double knowledgeValue; string source = lineData[3]; //LV or IM sources if (source == "LV") { knowledgeValue = double.Parse(lineData[4], CultureInfo.InvariantCulture) / 7; } else if (source == "IM") { knowledgeValue = double.Parse(lineData[4], CultureInfo.InvariantCulture) / 5; } else { badCounter++; //Bad line because soruce is unrecognizable continue; } //Check if data source is better (prefer LV) bool update = true; OccupationProperty existing = occupationPropertiesIdxOccupation[ocp].Find((x) => x.property == ski); if (source != "LV") //If source is not LV only add if it is non existant { if (existing == null) //If target does not exist update = true; else update = false; } //Update data if (update) { if (existing == null) { //If it does not exist , add it addOccupationProperty(new OccupationProperty(ocp, ski, knowledgeValue, source)); } else { //If it exists, update it existing.value = knowledgeValue; existing.source = source; } } } file.Close(); Console.WriteLine("Skills file has " + counter + " lines."); Console.WriteLine("Skills file has " + badCounter + " bad Lines."); } } private void cleanOccupations() { //Clear empty occupations List<Occupation> toRemove = new List<Occupation>(); foreach (Occupation occupation in occupations) { Occupation ocp = occupation; if (occupationPropertiesIdxOccupation[ocp].Count == 0) toRemove.Add(ocp); } int toRemoveCount = toRemove.Count; for(int i=0;i<toRemove.Count;i++) { removeOccupation(toRemove[i]); } Console.WriteLine("Removed " + toRemoveCount + " occupations for lack of data."); } private void normalizeOccupationProperties() { //This is not being used now Console.WriteLine("Normalizing occupation properties."); //Put all abilities in all ocupations int propertiesAdded = 0; foreach (Occupation occupation in occupations) { Occupation ocp = occupation; foreach (Property ppt in properties) { if ((occupationPropertiesIdxOccupation[ocp].FirstOrDefault((x) => x.property == ppt) == null)) //If property doesn't exist for this occupation { addOccupationProperty(new OccupationProperty(ocp, ppt, 0, "NA")); //Add 0 value propertiesAdded++; } } } Console.WriteLine("Added " + propertiesAdded + " properties for lack of data."); } public void getOccupationMetric() { computeOccupationMetric(); loadMetric(); } [Conditional("DEBUG")] private void computeOccupationMetric() { Console.WriteLine("Computing occupation metric."); //Initialize dictionaries occupationMetric = new Dictionary<Occupation, Dictionary<Occupation, double>>(); for (int i=0;i<occupations.Count;i++) { occupationMetric.Add(occupations[i], new Dictionary<Occupation, double>()); } //Compute metrics double dist; int percent = 10; for (int i = 0; i < occupations.Count; i++) { Occupation ocp1 = occupations[i]; for (int k = i; k < occupations.Count; k++) { Occupation ocp2 = occupations[k]; dist = distanceOcp(ocp1, ocp2); occupationMetric[ocp1][ocp2] = dist; occupationMetric[ocp2][ocp1] = dist; } if((int)(100 * i/(float)occupations.Count) >= percent) { Console.WriteLine(percent + "%"); percent += 10; } } Console.WriteLine("Metric computed."); saveMetric(); } private double distanceOcp(Occupation ocp1, Occupation ocp2) { //if (occupationPropertiesIdxOccupation[ocp1].Count != occupationPropertiesIdxOccupation[ocp2].Count) // throw new Exception("Invalid metric system"); double db = 0; OccupationProperty p1; OccupationProperty p2; for (int i = 0; i < properties.Count; i++) { Property ppt = properties[i]; p1 = occupationPropertiesIdxOccupation[ocp1].FirstOrDefault((x) => x.property == ppt); p2 = occupationPropertiesIdxOccupation[ocp2].FirstOrDefault((x) => x.property == ppt); if (p1 != null && p2 != null) { db += Math.Pow(p1.value - p2.value, 2); } else db += 0; //db += Math.Pow(occupationPropertiesIdxOccupation[ocp1].Find((x)=> x.property == ppt).value - occupationPropertiesIdxOccupation[ocp2].Find((x) => x.property == ppt).value, 2); } db = Math.Sqrt(db); return db; } public double distanceOcpCached(Occupation ocp1, Occupation ocp2) { return occupationMetric[ocp1][ocp2]; } [Conditional("DEBUG")] public void saveMetric() { Console.WriteLine("Saving metric"); DirectoryInfo dd = new DirectoryInfo(Directory.GetCurrentDirectory()); dd = dd.Parent.Parent; dd = dd.EnumerateDirectories().First((x) => x.Name == "Resources"); using (FileStream metricFile = new FileStream(dd.FullName + "\\occupationMetric.txt", FileMode.Create)) { using (StreamWriter wr = new StreamWriter(metricFile)) { wr.Write("Nill"); for (int i = 0; i < occupations.Count; i++) { wr.Write("\t" + occupations[i].title); } for (int i = 0; i < occupations.Count; i++) { wr.Write("\n"); wr.Write(occupations[i].title); for (int j = 0; j < occupations.Count; j++) { wr.Write("\t" + occupationMetric[occupations[i]][occupations[j]]); } } } } } [Conditional("RELEASE")] public void loadMetric() { Console.WriteLine("Loading metric."); string metrics = Properties.Resources.occupationMetric; occupationMetric = new Dictionary<Occupation, Dictionary<Occupation, double>>(); for (int i = 0; i < occupations.Count; i++) { occupationMetric.Add(occupations[i], new Dictionary<Occupation, double>()); } string[] lines = metrics.Split('\n'); for (int i = 0; i < 0; i++) { if (lines[i + 1] != occupations[i].title) throw new Exception("Invalid header on occupation metric file"); } for (int i = 1; i < lines.Length; i++) { string line = lines[i]; string[] columns = line.Split('\t'); if (columns.Length != occupations.Count + 1) throw new Exception("Invalid column number on line " + i); Occupation ocp1 = occupations[i - 1]; for (int j = 1; j < columns.Length; j++) { Occupation ocp2 = occupations[j - 1]; occupationMetric[ocp1].Add(ocp2, double.Parse(columns[j])); } } } private void computePropertyMetric() { Console.WriteLine("Computing property metric."); //Initialize dictionaries propertyMetric = new Dictionary<Property, Dictionary<Property, double>>(); for (int i = 0; i < properties.Count; i++) { propertyMetric.Add(properties[i], new Dictionary<Property, double>()); } //Compute metrics double dist; int percent = 10; for (int i = 0; i < properties.Count; i++) { Property ppt1 = properties[i]; for (int k = i; k < properties.Count; k++) { Property ppt2 = properties[k]; dist = distancePpt(ppt1, ppt2); propertyMetric[ppt1][ppt2] = dist; propertyMetric[ppt2][ppt1] = dist; } if ((int)(100 * i / (float)properties.Count) >= percent) { Console.WriteLine(percent + "%"); percent += 10; } } Console.WriteLine("Metric computed."); } private double distancePpt(Property ppt1, Property ppt2) { double db = 0; OccupationProperty p1; OccupationProperty p2; for (int i = 0; i < occupations.Count; i++) { Occupation ocp = occupations[i]; p1 = occupationPropertiesIdxOccupation[ocp].FirstOrDefault((x) => x.property == ppt1); p2 = occupationPropertiesIdxOccupation[ocp].FirstOrDefault((x) => x.property == ppt2); if (p1 != null && p2 != null) { db += Math.Pow(p1.value - p2.value, 2); } else db += 0; //db += Math.Pow(occupationPropertiesIdxOccupation[ocp1].Find((x)=> x.property == ppt).value - occupationPropertiesIdxOccupation[ocp2].Find((x) => x.property == ppt).value, 2); } db = Math.Sqrt(db); return db; } private double distancePptCached(Property ppt1, Property ppt2) { return propertyMetric[ppt1][ppt2]; } public void computeOccupationPercentiles() { List<(Occupation, double)> ocpPc = new List<(Occupation, double)>(); foreach(Occupation ocp in occupations) { ocpPc.Add((ocp, occupationPropertiesIdxOccupation[ocp].Average((x) => x.value))); } ocpPc = ocpPc.OrderBy((x) => x.Item2).ToList(); for(int i=0;i<ocpPc.Count;i++) { double percentile = i / (double)ocpPc.Count; occupationPercentiles.Add(ocpPc[i].Item1, percentile); } } public void createOccupationCluster() { Console.WriteLine("Creating occupation cluster"); occupationsCluster = ClusterNode<Occupation>.createDendogram(occupations, distanceOcpCached); } public void createPropertyCluster() { Console.WriteLine("Creating Property cluster."); propertyCluster = ClusterNode<Property>.createDendogram(properties, distancePptCached); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Timers; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace ExploreOnet { /// <summary> /// Interaction logic for ONETLoaderControl.xaml /// </summary> public partial class ONETLoaderControl : UserControl { public delegate void ONETLoadingFinishedHandler(); public event ONETLoadingFinishedHandler LoadingFinished; Timer checkup; ONETExplorer onetExp; int? totalTasks; public ONETLoaderControl() { InitializeComponent(); onetExp = new ONETExplorer(); onetExp.load(); checkup = new Timer(); checkup.Interval = 200; checkup.AutoReset = true; checkup.Elapsed += Checkup_Elapsed; checkup.Start(); } int elapsCounter; private void Checkup_Elapsed(object sender, ElapsedEventArgs e) { Dispatcher.Invoke(Checkup); } public void Checkup() { elapsCounter++; if (onetExp.loadTasks != null) { if (onetExp.loadTasks.Count > 0) { //Keep checking if (totalTasks == null) totalTasks = onetExp.loadTasks.Count; double percentilePoint = (totalTasks.Value - onetExp.loadTasks.Count) / (double)totalTasks; loadingBar.Width = percentilePoint * 600; string currentTaskName; try { currentTaskName = "Loading - " + onetExp.loadTasks.First()?.Method.Name + "".PadRight((elapsCounter / 5) % 4, '.'); } catch (InvalidOperationException exp) { currentTaskName = "Finished "; } loadingLabel.Content = currentTaskName; } else { Finish(); } } } public void Finish() { checkup.AutoReset = false; checkup.Dispose(); LoadingFinished?.Invoke(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace ExploreOnet { /// <summary> /// Interaction logic for PropertyVisualizer.xaml /// </summary> public partial class PropertyVisualizer : UserControl { Property property; public PropertyVisualizer(Property property) { InitializeComponent(); this.property = property; propertyNameLabel.Content = property.name; propertyTypeLabel.Content = property.type; string lblCC = ""; double average = ONETExplorer.current.occupationPropertiesIdxProperty[property].Average((x) => x.value); lblCC += "Average: " + average; double variance = ONETExplorer.current.occupationPropertiesIdxProperty[property].Average((x) => Math.Pow(x.value - average, 2)); lblCC += " Variance: " + variance; avgLabel.Content = lblCC; //Histogram values int barCount = 15; Histogram hist = new Histogram(ONETExplorer.current.occupationPropertiesIdxProperty[property].Select((x) => x.value).ToList()); histogramControl.Content = new HistogramControl(hist, barCount); //Most proeminent List<OccupationProperty> ocps = ONETExplorer.current.occupationProperties.FindAll((x)=> x.property == property); ocps.Sort(Comparer<OccupationProperty>.Create((x, y) => y.value.CompareTo(x.value))); for(int i=0;i<10;i++) { OccupationProperty ocpp = ocps[i]; //Add new Button bb = new Button(); bb.Content = String.Format("{0,6}" ,Math.Round(ocpp.value, 3)) + " : " + ocpp.ocp.title; bb.Width = 400; bb.Height = 50; bb.DataContext = ocpp.ocp; bb.Click += Bb_Click; ; bb.HorizontalAlignment = HorizontalAlignment.Center; bb.HorizontalContentAlignment = HorizontalAlignment.Center; occupationsPanel.Children.Add(bb); } } private void Bb_Click(object sender, RoutedEventArgs e) { Occupation ocp = (sender as Button).DataContext as Occupation; MainWindow.current.pushControl(new OccupationVisualizer(ocp)); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace ExploreOnet { /// <summary> /// Interaction logic for MainControl.xaml /// </summary> public partial class MainControl : UserControl { List<UserControl> controls; public MainControl() { InitializeComponent(); controls = new List<UserControl>(); } public void pushControl(UserControl control) { controls.Add(control); viewControl.Content = control; } public void popControl() { if (controls.Count > 1) { controls.RemoveAt(controls.Count - 1); viewControl.Content = controls[controls.Count - 1]; } } private void OccupationBut_Click(object sender, RoutedEventArgs e) { pushControl(new OccupationListViewer()); } private void AbiltiesBut_Click(object sender, RoutedEventArgs e) { pushControl(new PropertyListViewer("Ability")); } private void KnowledgeBut_Click(object sender, RoutedEventArgs e) { pushControl(new PropertyListViewer("Knowledge")); } private void SkillsBut_Click(object sender, RoutedEventArgs e) { pushControl(new PropertyListViewer("Skill")); } private void backBut_Click(object sender, RoutedEventArgs e) { popControl(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace ExploreOnet { /// <summary> /// Interaction logic for OccupationListViewer.xaml /// </summary> public partial class OccupationListViewer : UserControl { public OccupationListViewer() { InitializeComponent(); ocpCountLabel.Content = "from a list of " + ONETExplorer.current.occupations.Count + " occupations."; searchTb.TextChanged += searchTb_TextChanged; MainWindow.current.Dispatcher.Invoke(createCluster); } public void createCluster() { clusterViewer.Content = ONETExplorer.current.occupationsCluster.getPanel(); } private void searchTb_TextChanged(object sender, TextChangedEventArgs e) { string text = (sender as TextBox).Text; PopulateSuggestions(text); } private void PopulateSuggestions(string sug) { List<Occupation> occupations = ONETExplorer.current.occupations; resultPanel.Children.Clear(); if (occupations.Find((x) => x.title == sug) != null || sug.Length < 2) return; string pattern = sug; List<Occupation> sugOcp = new List<Occupation>(); for (int i = 0; i < occupations.Count; i++) { bool titleMatch = System.Text.RegularExpressions.Regex.IsMatch(occupations[i].title, sug, System.Text.RegularExpressions.RegexOptions.IgnoreCase); if (titleMatch) { sugOcp.Add(occupations[i]); } } //Order by description ammount of words sugOcp = sugOcp.OrderBy((x) => System.Text.RegularExpressions.Regex.Matches(x.description, sug, System.Text.RegularExpressions.RegexOptions.IgnoreCase).Count).ToList(); for (int i = sugOcp.Count - 1; i >= 0; i--) { //Add new Button bb = new Button(); bb.Content = sugOcp[i].title; bb.Width = 400; bb.Height = 50; bb.DataContext = sugOcp[i]; bb.Click += Suggestion_Clicked; bb.HorizontalAlignment = HorizontalAlignment.Left; bb.HorizontalContentAlignment = HorizontalAlignment.Left; resultPanel.Children.Add(bb); } } private void Suggestion_Clicked(object sender, RoutedEventArgs e) { Occupation selected = (Occupation)(sender as Button).DataContext; MainWindow.current.pushControl(new OccupationVisualizer(selected)); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ExploreOnet { public class Histogram { List<double> dataPoints; public Histogram(List<double> dataPoints) { this.dataPoints = dataPoints; } public Bin[] getBins(int binCount) { int barCount = binCount; float barValWidth = 1f / barCount; Bin[] histogram = new Bin[barCount]; for (int i = 0; i < barCount; i++) { float percentileStart = i * barValWidth; float percentileEnd = (i + 1) * barValWidth; //Last bar gets upper inclusive bound if (i == barCount - -1) percentileEnd = float.MaxValue; histogram[i] = new Bin(dataPoints.Count((x) => x >= percentileStart && x <= percentileEnd), percentileStart, percentileEnd); } return histogram; } public class Bin { public int count; public double start; public double end; public Bin(int count, double start, double end) { this.count = count; this.start = start; this.end = end; } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ExploreOnet { public class Property { public string name; public string type; public Property(string name, string type) { this.name = name; this.type = type; } public override string ToString() { return name; } } } <file_sep>using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace ExploreOnet { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public static MainWindow current; MainControl mainControl; public MainWindow() { current = this; InitializeComponent(); ONETLoaderControl onetLoader = new ONETLoaderControl(); onetLoader.LoadingFinished += OnetLoader_LoadingFinished; mainControlView.Content = onetLoader; } private void OnetLoader_LoadingFinished() { Dispatcher.Invoke(EnableUI); } private void EnableUI() { mainControl = new MainControl(); mainControlView.Content = mainControl; } public void pushControl(UserControl control) { mainControl.pushControl(control); } public void popControl() { mainControl.popControl(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace ExploreOnet { /// <summary> /// Interaction logic for PropertyListViewer.xaml /// </summary> public partial class PropertyListViewer : UserControl { List<Property> properties; public PropertyListViewer(string type) { InitializeComponent(); properties = ONETExplorer.current.properties.FindAll((x) => x.type == type); searchLabel.Content = "Search " + type + " :"; ocpCountLabel.Content = "from a list of " + properties.Count; //searchTb.TextChanged += searchTb_TextChanged; for(int i=0;i<properties.Count;i++) { //Add new Button bb = new Button(); bb.Content = properties[i].name; bb.Width = 400; bb.Height = 30; bb.DataContext = properties[i]; bb.Click += Suggestion_Clicked; bb.HorizontalAlignment = HorizontalAlignment.Center; bb.HorizontalContentAlignment = HorizontalAlignment.Center; listPanel.Children.Add(bb); } clusterView.Content = ONETExplorer.current.propertyCluster.getPanel(); } //private void searchTb_TextChanged(object sender, TextChangedEventArgs e) //{ // string text = (sender as TextBox).Text; // PopulateSuggestions(text); //} //private void PopulateSuggestions(string sug) //{ // resultPanel.Children.Clear(); // if (properties.Find((x) => x.name == sug) != null || sug.Length < 2) // return; // for (int i = 0; i < properties.Count; i++) // { // if (properties[i].name.Contains(sug)) // { // //Add new // Button bb = new Button(); // bb.Content = properties[i].name; // bb.Width = 400; // bb.Height = 50; // bb.DataContext = properties[i]; // bb.Click += Suggestion_Clicked; // bb.HorizontalAlignment = HorizontalAlignment.Center; // bb.HorizontalContentAlignment = HorizontalAlignment.Center; // resultPanel.Children.Add(bb); // } // } //} private void Suggestion_Clicked(object sender, RoutedEventArgs e) { Property selected = (Property)(sender as Button).DataContext; MainWindow.current.pushControl(new PropertyVisualizer(selected)); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace ExploreOnet { /// <summary> /// Interaction logic for ClusterViewer.xaml /// </summary> public partial class ClusterViewer : UserControl { public ClusterViewer(object cluster) { InitializeComponent(); Type cType = cluster.GetType(); Console.WriteLine("receive type: " + cType.FullName); Type eType = typeof(ClusterNode<>); Console.WriteLine("compare type: " + eType.FullName); if (cType != eType) throw new Exception(); Type underType = cType.GetGenericArguments()[0]; MethodInfo methodDefinition = GetType().GetMethod("Initialize", new Type[] {cType }); MethodInfo method = methodDefinition.MakeGenericMethod(underType); //method.Invoke(); } public void Initialize<T>(ClusterNode<T> cluster) { } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace ExploreOnet { public class ClusterNode<T> { public Func<T, T, double> metric; public T element; public int count; ClusterNode<T> part1; ClusterNode<T> part2; public bool leaf { get { return element != null; } } public ClusterNode(Func<T, T, double> metric, T element) { this.metric = metric; this.element = element; count = 1; } public ClusterNode(ClusterNode<T> part1, ClusterNode<T> part2) { this.part1 = part1; this.part2 = part2; count = part1.count + part2.count; this.metric = part1.metric; } public double distance(ClusterNode<T> other) { if (leaf) { if (other.leaf) return metric(element, other.element); else return other.distance(this); } else { return (part1.distance(other) * part1.count + part2.distance(other) * part2.count) / count; } } public static ClusterNode<T> createDendogram(List<T> elements, Func<T, T, double> metric) { List<ClusterNode<T>> clusters = new List<ClusterNode<T>>(); foreach (T element in elements) { clusters.Add(new ClusterNode<T>(metric, element)); } //Create and populate structure List<List<double>> dists = new List<List<double>>(); for (int i = 0; i < clusters.Count; i++) { dists.Add(new List<double>()); for (int j = 0; j < clusters.Count; j++) { dists[i].Add(0); } } //Compute distances for (int i = 0; i < clusters.Count; i++) { for (int j = i; j < clusters.Count; j++) { double dist = clusters[i].distance(clusters[j]); dists[i][j] = dist; dists[j][i] = dist; } } //Create dendogram while (clusters.Count != 1) { //Find minimalIndexes double minDist = double.MaxValue; int p1 = -1; int p2 = -1; for (int i = 0; i < dists.Count; i++) { for (int j = i + 1; j < dists.Count; j++) { if (dists[i][j] < minDist) { minDist = dists[i][j]; p1 = i; p2 = j; } } } //Agglomerate ClusterNode<T> newCluster = new ClusterNode<T>(clusters[p1], clusters[p2]); //Delete from structure if (p1 > p2) throw new Exception("Invalid mechanic, swap p1 and p2"); //Remove rows dists.RemoveAt(p2); dists.RemoveAt(p1); //Remove columns foreach (List<double> lt in dists) { lt.RemoveAt(p2); lt.RemoveAt(p1); } //Remove from main structure clusters.RemoveAt(p2); clusters.RemoveAt(p1); //Add cluster clusters.Add(newCluster); //add row dists.Add(new List<double>()); //add column and values for (int k = 0; k < dists.Count - 1; k++) { double newToKDist = newCluster.distance(clusters[k]); dists[k].Add(newToKDist); dists[dists.Count - 1].Add(newToKDist); } dists[dists.Count - 1].Add(newCluster.distance(newCluster)); //Last element } return clusters[0]; } public List<T> getElements() { List<T> list = new List<T>(); pushElements(list); return list; } public void pushElements(List<T> list) { if(leaf) { list.Add(element); } else { part1.pushElements(list); part2.pushElements(list); } } public UIElement getPanel() { if(leaf) { return getLeaf(); } else { Grid grid = new Grid(); grid.Margin = new Thickness(2); grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Auto } ); grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Auto }); grid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto }); grid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto }); Border bd = new Border(); bd.BorderThickness = new Thickness(2f, 2f, 2f, 0f); bd.BorderBrush = new SolidColorBrush(Colors.Black); Grid.SetColumnSpan(bd, 2); Grid.SetRowSpan(bd, 2); grid.Children.Add(bd); //Node label Label nodeLabel = new Label(); nodeLabel.Content = " "; nodeLabel.HorizontalAlignment = HorizontalAlignment.Center; //DockPanel.SetDock(nodeLabel, Dock.Top); Grid.SetColumnSpan(nodeLabel, 2); grid.Children.Add(nodeLabel); //Left part UIElement part1Visual = part1.getPreview(); Grid.SetRow(part1Visual, 1); Grid.SetColumn(part1Visual, 0); grid.Children.Add(part1Visual); //Right part UIElement part2Visual = part2.getPreview(); Grid.SetRow(part2Visual, 1); Grid.SetColumn(part2Visual, 1); grid.Children.Add(part2Visual); grid.DataContext = this; return grid; } } public UIElement getPreview() { if(leaf) { return getLeaf(); } else { int previewCount = 12; Button button = new Button(); List<T> elements = getElements(); string elementList = ""; for(int i=0;i<previewCount && i < elements.Count;i++) { if (i % 2 == 0) elementList += elements[i / 2]; else elementList += elements[elements.Count - 1 - i / 2]; elementList += "\n"; } int left = elements.Count - 8; if (left > 0) elementList += "... +" + left + " more"; button.VerticalAlignment = VerticalAlignment.Top; button.Content = elementList; button.Click += Button_Click; button.DataContext = this; button.Margin = new Thickness(1); return button; } } private void Button_Click(object sender, RoutedEventArgs e) { Button button = sender as Button; ExpandPreview(button); } private void ExpandPreview(Button preview) { //Get structures and visuals Grid parent = preview.Parent as Grid; ClusterNode<T> parentNode = parent.DataContext as ClusterNode<T>; ClusterNode<T> expandNode = preview.DataContext as ClusterNode<T>; //Remove preview parent.Children.Remove(preview); //Get and add expansion UIElement expanded = expandNode.getPanel(); parent.Children.Add(expanded); //Position expansion Grid.SetRow(expanded, 1); if(parentNode.part1 == expandNode) { //Left Grid.SetColumn(expanded, 0); } else { //Right Grid.SetColumn(expanded, 1); } } public UIElement getLeaf() { //print single label Label lbl = new Label(); lbl.Content = element.ToString(); lbl.VerticalAlignment = VerticalAlignment.Top; return lbl; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ExploreOnet { public class OccupationProperty { public Occupation ocp; public Property property; public double value; public string source; public OccupationProperty(Occupation ocp, Property ability, double value, string source) { this.ocp = ocp; this.property = ability; this.value = value; this.source = source; } } }
5219d1a2aeaaa5599dfb9464f76b805669004941
[ "C#" ]
15
C#
RubenSaldanha/ExploreONET
e3d3958fc7c8fb699d98ecf266e40ed09e21b5d6
416f24109b9d5a1cdab4f988a04f94451de8bee7
refs/heads/main
<repo_name>JiaJinRong12138/Linker-Program<file_sep>/SRC/DAY1/Linker/text/sum.c //global, object, common unsigned long long bias; //global, function, .text unsigned long long sum (unsigned long long *a, unsigned long long n) { unsigned long long i, s = 0; for(i = 0; i < n; ++ i) { s += a[i]; } return s + bias; } <file_sep>/README.md # Linker-Program This is a easy Linker Program, after reading the programmer's self-cultivation, i want to implement a linker. ## Recommended books - CSAPP - 程序员的自我修养 ## Very good course - https://space.bilibili.com/4564101/channel/detail?cid=172309&ctype=0 <file_sep>/SRC/DAY1/Linker/headers/linker.h #ifndef LINKER_GUARD #define LINKER_GUARD #include <stdint.h> #include <stdlib.h> // 定义section header name的字符最大为32 #define MAX_CHAR_SECTION_NAME (32) // section header table sh_name, sh_addr, sh_offset, sh_size typedef struct { /* data */ char sh_name[MAX_CHAR_SECTION_NAME]; uint64_t sh_addr; uint64_t sh_offset; uint64_t sh_size; }sht_entry_t; #define MAX_CHAR_SYMBOL_NAME (64) // 因为需要bind的说明Local Global Weak(弱符号)等等 typedef enum { STB_LOCAL, STB_GLOBAL, STB_WEAK }st_bind_t; // 同上 typedef enum { STT_NOTYPE, STT_OBJECT, STT_FUNC }st_type_t; // symbol table st_name, bind, type, st_shndex, st_value, st_size typedef struct { /* data */ char st_name[MAX_CHAR_SYMBOL_NAME]; st_bind_t bind; st_type_t type; char st_shndex[MAX_CHAR_SYMBOL_NAME]; uint64_t st_value; // in section offset uint64_t st_size; // count of lines of symbol }st_entry_t; #define MAX_ELF_FILE_LENGTH (64) // max 64 effective lines 行 #define MAX_ELF_FILE_WIDTH (128) // max 128 chars per lines 列 typedef struct { /* data */ char buffer[MAX_ELF_FILE_LENGTH][MAX_ELF_FILE_WIDTH]; uint64_t line_count; sht_entry_t *sht; uint64_t symtab_count; st_entry_t* symt; }elf_t; void parser_elf(char *filename, elf_t *elf); void free_elf(elf_t *elf); #endif<file_sep>/SRC/DAY1/Linker/text/main.c //global, notype, undefined unsigned long long sum(unsigned long long *a, unsigned long long n); //global, object, .data unsigned long long array[2] = {0x12340000, 0xabcd}; //global, object, .data unsigned long long bias = 0xf00000000; //global, function, .test void main() { unsigned long long var = sum(array, 2); }<file_sep>/SRC/DAY1/Linker/Linker program/parserELF.c #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdint.h> #include <stddef.h> #include <assert.h> #include "../headers/linker.h" #define NULL ((void *)0) static int parser_table_entry(char *str, char ***ent) { // 定义三级指针为ptr -> stack -> heap -> mem int count_col = 1; int len = strlen(str); // 计算table的项有多少个,因为最后一个元素后面没有逗号所以要从1开始计算 for(int i = 0; i < len; ++i) { if(str[i] == ',') { count_col++; } } // 申请count_col个数的*4字节指针大小的 空间 char **arr = malloc(count_col * sizeof(char *)); *ent = arr; int col_index = 0; int col_width = 0; // 将表项存入我们的col_buf中 #define Col_Number (32) char col_buf[Col_Number]; for(int i = 0; i < len + 1; ++i) { if(str[i] == ',' || str[i] == '\0') { // 定义一个如果col_index大于了cout_col程序终止的函数 assert(col_index < count_col); // 申请heap的空间,+1是因为数组的情况下是从0开始的我们需要把最后一位变成\0 char *col = malloc((col_width + 1) * sizeof(char)); // 将表项写入col数组中 for(int j = 0; j < col_width; ++j) { col[j] = col_buf[j]; } col[col_width] = '\0'; // 将col(heap)的地址给arr(stack),对索引进行++,width置0 arr[col_index] = col; col_index ++; col_width = 0; } else { assert(col_width < Col_Number); col_buf[col_width] = str[i]; col_width ++; } } return count_col; } static void free_table_entry(char **ent, int n) { for(int i = 0; i < n; ++i) { // 因为二级指针上面已经知道了是heap上的地址 进行free内层 free(ent[i]); } // free外层 free(ent); } static void parse_sh(char *str, sht_entry_t *sh) { char **cols; int num_cols = parser_table_entry(str, &cols); assert(num_cols == 4); assert(sh != NULL); strcpy(sh->sh_name, cols[0]); sh->sh_addr = atoi(cols[1]); sh->sh_offset = atoi(cols[2]); sh->sh_size = atoi(cols[3]); free_table_entry(cols, num_cols); } static void print_sh_entry(sht_entry_t *sh) { printf("%s\t%lx\t%lu\t%lu\n", sh->sh_name, sh->sh_addr, sh->sh_offset, sh->sh_size); } static void parse_symtable(char *str, st_entry_t *ste) { //sum,STB_GLOBAL,STT_FUNCTION,.text,0,22 char **cols; int num_cols = parser_table_entry(str, &cols); assert(num_cols == 6); assert(ste != NULL); strcpy(ste->st_name, cols[0]); // symbol table bind if (strcmp(cols[1], "STB_LOCAL") == 0) { ste->bind = STB_LOCAL; } else if (strcmp(cols[1], "STB_GLOBAL") == 0) { ste->bind = STB_GLOBAL; } else if (strcmp(cols[1], "STB_WEAK") == 0) { ste->bind = STB_WEAK; } else { printf("symbol bind is neither LOCAL, GLBOL nor WEAK\n"); exit(0); } // symbol table type if (strcmp(cols[2], "STT_NOTYPE") == 0) { ste->type = STT_NOTYPE; } else if (strcmp(cols[2], "STT_OBJECT") == 0) { ste->type = STT_OBJECT; } else if (strcmp(cols[2], "STT_FUNC") == 0) { ste->type = STT_FUNC; } else { printf("symbol type is neither NOTYPE, OBJECT nor FUNC\n"); exit(0); } strcpy(ste->st_shndex, cols[3]); ste->st_value = atoi(cols[4]); ste->st_size = atoi(cols[5]); free_table_entry(cols, num_cols); } static void print_symtab_entry(st_entry_t *ste) { printf("%s\t%d\t%d\t%s\t%lu\t%lu\n", ste->st_name, ste->bind, ste->type, ste->st_shndex, ste->st_value, ste->st_size); } static int read_elf(const char *filename, uint64_t bufaddr) { //open file and read FILE *fp; fp = fopen(filename,"r"); if (fp == NULL) { printf ("this file %s can't successful open\n", filename); return -1; } //read text file line by line char line[MAX_ELF_FILE_WIDTH]; int line_counter = 0; //gcc ../text/test_elf.c ../Linker\ program/parserELF.c -o ./test_elf while(fgets(line, MAX_ELF_FILE_WIDTH, fp) != NULL) { int len = strlen(line); // 进行注释的一个过滤 // 第一重的过滤: // 1.如果这个len的大小等于0的时候,代表这个是个空行直接continue // 2.如果这个len的大小大于等于1的时候,如果第一个位置是个换行符,或者\r等等的情况下,进行continue // 3.如果这个len的带下大于等于2的时候,代表有可能前两个元素的情况是注释的情况所以判断该前两个的位置都是注释的情况下进行continue if((len == 0) || ((len >= 1) && (line[0] == '\n' || line[0] == '\r')) || ((len >= 2) && (line[0] == '/' && line[1] == '/')) ) { continue; } // 第二重的过滤: // 当前的line是不是全是空格或者是多个\t那种的元素,我们就直接不要了 int iswhite = 1; for (int i = 0; i < len; ++i) { iswhite = iswhite && (line[i] == ' ' || line[i] == '\t'); } if (iswhite == 1) { continue; } if(line_counter < MAX_ELF_FILE_LENGTH) { uint64_t addr = bufaddr + line_counter * MAX_ELF_FILE_WIDTH * sizeof(char); //addr 去表示我们的每一行的长度的问题 char *linebuf = (char *)addr; int i = 0; while(i < len && i < MAX_ELF_FILE_WIDTH) { if (line[i] == '\n' || line[i] == '\t' || (((i + 1) < len) && ((i + 1) < MAX_ELF_FILE_WIDTH) && line[i] == '/' && line[i + 1] == '/')) // 为了验证下一项是不是'/' { break; } linebuf[i] = line[i]; // 将当前的line[i]元素给linebuf[i] i++; } linebuf[i] = '\0'; line_counter++; } else { printf("ELF file %s is too long > %d \n", filename, MAX_ELF_FILE_LENGTH); return -1; } } fclose(fp); return line_counter; } void parse_elf(char* filename, elf_t *elf) { assert(elf != NULL); int line_count = read_elf(filename, (uint64_t)(&(elf->buffer))); for(int i = 0; i < line_count; ++i) { printf("[%d]\t%s\n",i, elf->buffer[i]); } // 获取section header的行数 int sh_count = atoi(elf->buffer[1]); // 分配heap大小,将空间给予section header table elf->sht = malloc(sh_count * sizeof(sht_entry_t)); sht_entry_t* symt_sh = NULL; // 获取这两行section header进行分析,输出 for(int i = 0; i < sh_count; ++i) { parse_sh(elf->buffer[i+2], &(elf->sht[i])); print_sh_entry(&(elf->sht[i])); if (strcmp((elf->sht[i].sh_name), ".symtab") == 0) { symt_sh = &(elf->sht[i]); } } assert(symt_sh != NULL); elf->symtab_count = symt_sh->sh_size; elf->symt = malloc(elf->symtab_count * sizeof(st_entry_t)); for (int i = 0; i < symt_sh->sh_size; ++i) { parse_symtable(elf->buffer[i + symt_sh->sh_offset], &(elf->symt[i])); print_symtab_entry(&(elf->symt[i])); } } void free_elf(elf_t *elf) { assert(elf != NULL); free(elf->sht); } <file_sep>/SRC/DAY1/Linker/text/test_elf.c #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <stddef.h> #include <string.h> #include "../headers/linker.h" extern void parse_elf(char* filename, elf_t *elf); extern void free_elf(elf_t *elf); int main() { elf_t elf; parse_elf("../text/sum.elf.txt", &elf); free_elf(&elf); return 0; }<file_sep>/SRC/DAY1/readme.md ## Realize the function 将自定义的elf 输入到buffer中,再对Section header,Symbol table进行解析 因为定义的elf文件中会有注释以及空格 换行 tab符等等,需要删除更新 ![1](./DAY1/2.png) 效果: ![2](./DAY1/1.png)
e6ee91a6b1df3f4ecdcf37fa7fe3ed383facb858
[ "Markdown", "C" ]
7
C
JiaJinRong12138/Linker-Program
815a96fd34da76b242fd05e335e6ac3f7feaa872
f3ac5ceafc506a886cb8939b55e7d977275cf426
refs/heads/master
<file_sep>package com.app.kotlinbasews.ui import android.app.ProgressDialog import android.os.Bundle import android.os.Handler import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.support.v4.app.FragmentTransaction import android.support.v7.app.AppCompatActivity import android.util.DisplayMetrics import android.widget.Toast import com.app.kotlinbasews.R import java.util.* open class BaseActivity : AppCompatActivity() { var screenWidth: Int = 0 var screenHeight: Int = 0 var fragmentBackStack: Stack<Fragment>? = null var showBackMessage: Boolean? = true var doubleBackToExitPressedOnce: Boolean = false var dialog: ProgressDialog? = null fun setShowBackMessage(showBackMessage: Boolean) { this.showBackMessage = showBackMessage } fun getFragments(): Stack<Fragment>? { return fragmentBackStack } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) fragmentBackStack = Stack() } fun getWidthAndHeight() { val displaymetrics = DisplayMetrics() windowManager.defaultDisplay.getMetrics(displaymetrics) screenHeight = displaymetrics.heightPixels screenWidth = displaymetrics.widthPixels } /** * To add fragment to a tab. tag -> Tab identifier fragment -> Fragment to show, in tab identified by tag shouldAnimate -> * should animate transaction. false when we switch tabs, or adding first fragment to a tab true when when we are pushing more * fragment into navigation stack. shouldAdd -> Should add to fragment navigation stack (mStacks.get(tag)). false when we are * switching tabs (except for the first time) true in all other cases. * * @param fragment the fragment * @param shouldAnimate the should animate * @param shouldAdd the should add */ @Synchronized fun pushAddFragments(fragment: Fragment?, shouldAnimate: Boolean, shouldAdd: Boolean) { try { if (fragment != null) { fragmentBackStack?.push(fragment) val manager = supportFragmentManager val ft = manager.beginTransaction() ft.replace(R.id.contentFrame, fragment, fragmentBackStack?.size.toString()) ft.commit() manager.executePendingTransactions() } } catch (e: Exception) { e.printStackTrace() } } /** * Select the second last fragment in current tab's stack.. which will be shown after the fragment transaction given below * * @param shouldAnimate the should animate */ @Synchronized fun popFragments(shouldAnimate: Boolean) { var fragment: Fragment? = null if (fragmentBackStack!!.size > 1) fragment = fragmentBackStack!!.elementAt(fragmentBackStack!!.size - 2) else if (!fragmentBackStack!!.isEmpty()) fragment = fragmentBackStack!!.elementAt(fragmentBackStack!!.size - 1) var manager: FragmentManager = supportFragmentManager var ft: FragmentTransaction = manager.beginTransaction() if (fragment!!.isAdded()) ft.remove(fragmentBackStack!!.elementAt(fragmentBackStack!!.size - 1)) if (fragmentBackStack!!.size > 1) { ft.show(fragment).commit() } else ft.replace(R.id.contentFrame, fragment).commit() fragmentBackStack!!.pop() manager.executePendingTransactions() } fun doubleTapOnBackPress() { if (doubleBackToExitPressedOnce){ finish() overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right) return } this.doubleBackToExitPressedOnce = true Toast.makeText(this@BaseActivity, "press back again", Toast.LENGTH_SHORT).show() Handler().postDelayed({ doubleBackToExitPressedOnce = false }, 1000) } override fun onBackPressed() { if (fragmentBackStack!!.size <= 1) { if (showBackMessage!!) { doubleTapOnBackPress() } else { finish() overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); } } else { } } fun showProgressDialog(isCancelable: Boolean) { if (dialog != null && dialog?.isShowing!!) { dialog!!.dismiss() } dialog = ProgressDialog(this) dialog!!.setMessage(getString(R.string.msg_please_wait)) dialog!!.setCancelable(isCancelable) dialog!!.show() } fun hideProgressDialog() { if (dialog != null) { dialog!!.dismiss() } } }<file_sep>package com.app.kotlinbasews.helper import android.content.Context import android.content.Intent import android.graphics.Typeface import android.net.ConnectivityManager import android.widget.EditText import com.app.kotlinbasews.R import com.app.kotlinbasews.custom.MDToast import com.app.kotlinbasews.ui.BaseActivity import java.util.regex.Pattern object Functions { val EMAIL_PATTERN: String = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$" fun fireIntent(baseActivity: BaseActivity, cls: Class<*>, isNewActivity: Boolean) { val i = Intent(baseActivity, cls) baseActivity.startActivity(i) if (!isNewActivity) { baseActivity.overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right) } else { baseActivity.overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left) } } fun fireIntent(baseActivity: BaseActivity, cls: Class<*>, isNewActivity: Boolean, isFinished: Boolean) { if (isFinished) baseActivity.finish() val i = Intent(baseActivity, cls) baseActivity.startActivity(i) if (!isNewActivity) { baseActivity.overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right) } else { baseActivity.overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left) } } open fun fireIntent(baseActivity: BaseActivity, intent: Intent, isNewActivity: Boolean) { baseActivity.startActivity(intent) if (!isNewActivity) { baseActivity.overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right) } else { baseActivity.overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left) } } open fun fireIntent(baseActivity: BaseActivity, isNewActivity: Boolean) { baseActivity.finish() if (!isNewActivity) { baseActivity.overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right) } else { baseActivity.overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left) } } open fun fireIntentForResult(baseActivity: BaseActivity, cls: Class<*>, requestCode: Int, isNewActivity: Boolean) { val intent = Intent(baseActivity, cls) baseActivity.startActivityForResult(intent, requestCode) if (!isNewActivity) { baseActivity.overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right) } else { baseActivity.overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left) } } fun getRegularFont(_context: Context): Typeface { return Typeface.createFromAsset(_context.assets, "fonts/regular.ttf") } fun getBoldFont(_context: Context): Typeface { return Typeface.createFromAsset(_context.assets, "fonts/bold.ttf") } fun emailValidation(email: String): Boolean { val pattern = Pattern.compile(EMAIL_PATTERN) val matcher = pattern.matcher(email) return matcher.matches() } fun toStr(editText: EditText): String { return editText.text.toString().trim { it <= ' ' } } fun toLength(editText: EditText): Int { return editText.text.toString().trim { it <= ' ' }.length } fun isConnected(context: Context): Boolean { val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val activeNetwork = cm.activeNetworkInfo return activeNetwork != null && activeNetwork.isConnectedOrConnecting } fun showToast(context: Context, message: String, type: Int) { val mdToast = MDToast.makeText(context, message, MDToast.LENGTH_SHORT, type) mdToast.show() } } <file_sep>package com.app.kotlinbasews.ui import android.os.Bundle import android.os.CountDownTimer import com.app.kotlinbasews.R import com.app.kotlinbasews.helper.Functions class SplashActivity : BaseActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash) navigateToLogin() setShowBackMessage(false) } private fun navigateToLogin() { val longestDelay:Long=1200 val longestDuration:Long=3000 var oneTouchTimer = object : CountDownTimer(longestDelay+longestDuration+500,1000){ override fun onFinish() { Functions.fireIntent(this@SplashActivity,LoginActivity::class.java,true,true) } override fun onTick(millisUntilFinished: Long) { } } oneTouchTimer.start() } } <file_sep>package com.app.kotlinbasews import android.app.Application import com.app.kotlinbasews.api.RestClient class KotlinApplication : Application() { override fun onCreate() { super.onCreate() } } <file_sep>package com.app.kotlinbasews.fragments import android.app.ProgressDialog import android.os.Bundle import android.support.v4.app.Fragment import android.view.View import com.app.kotlinbasews.R import com.app.kotlinbasews.ui.BaseActivity /** * Created by chintans on 15-02-2018. */ class BaseFragment : Fragment() { private var dialog: ProgressDialog? = null /*protected UserDetails userDetails;*/ protected val viewbase: View? = null /** * The Activity. */ /** * Gets base activity. * * @return the base activity */ /** * Sets base activity. * * @param baseActivity the base activity */ var baseActivity: BaseActivity? = null /** * On fragment back press boolean. * * @return the boolean */ fun onFragmentBackPress(): Boolean { return false } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } fun showProgressDialog(isCancelable: Boolean) { if (dialog != null && dialog!!.isShowing) { dialog!!.dismiss() } dialog = ProgressDialog(baseActivity) dialog!!.setMessage(baseActivity!!.getString(R.string.msg_please_wait)) dialog!!.setCancelable(isCancelable) dialog!!.show() } fun hideProgressDialog() { if (dialog != null) { dialog!!.dismiss() } } } <file_sep>package com.app.kotlinbasews.api.responsepojos data class User( val LoginId: Int, // 30259 var FirstName: String, // Prashant val LastName: String, // Prajapati val Gender: String, // M val ContactNo: String, // 9825612321 val EmailAddress: String, // <EMAIL> val ProfilePicUrl: String, // http://ws-srv-net.in.webmyne.com/Applications/eatup/EatUp_Admin/Uploads/UserImages/6790a61f-424a-4230-b7e8-c371e8c9e142.png val IsEmailVerified: Boolean, // true var CartId: Int, // 10208 val CartQuantity: Int, // 3 val cartRestaurentId: Int, // 51 val NetAmount: Double, // 186.87 val RestaurantName: String, // <NAME> val CurrentOrders: Int, // 35 val OrderProcessAlerts: Boolean, // true val OffersAlerts: Boolean, // true val ReadNtfCounter: Int // 4 )<file_sep>package com.app.kotlinbasews.helper class IncompleteBuilderException : IllegalArgumentException { /** * Constructs an IncompleteBuilderException with no detail message. * A detail message is a String that describes this particular * exception. */ constructor() : super() {} /** * Constructs an IncompleteBuilderException with the specified * detail message. A detail message is a String that describes * this particular exception. * * @param msg the detail message. */ constructor(msg: String) : super(msg) {} }<file_sep>package com.app.kotlinbasews.api.responsepojos import java.io.Serializable class BaseResponse<T> : Serializable { var status: String = "" var responseData: T? = null var message: String? = null } <file_sep>package com.app.kotlinbasews.ui import android.os.Bundle import com.app.kotlinbasews.R import com.app.kotlinbasews.api.responsepojos.User import com.app.kotlinbasews.custom.MDToast import com.app.kotlinbasews.helper.Functions import kotlinx.android.synthetic.main.activity_login.* class LoginActivity : BaseActivity() { var user: User? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) setShowBackMessage(false) if (Functions.isConnected(this@LoginActivity)) callLoginApi() else Functions.showToast(this@LoginActivity, getString(R.string.internet_connection), MDToast.TYPE_ERROR) // Java /*if (firstName.equals("Dan")) { person.setTeam(programmers); } else if (lastName.equals("Dihiansan")) { person.setTeam(designers); } else { person.setTeam(others); }*/ // Kotlin when { edtEmail.text.toString() == "chintan" -> user?.FirstName = "dfbh" edtPassword.text.toString() == "<PASSWORD>" -> user?.CartId = 0 } /*// Java switch (firstName) { case "Dan": person.setTeam(programmers) break; case "Jay": person.setTeam(programmers) break; case "Jamie": person.setTeam(designers) break; default: person.setTeam(others) } // Kotlin when (firstName) { "Dan", "Jay" -> person.team = programmers "Jamie" -> person.team = designers else -> person.team = others }*/ /*// Java public String fullName() { return getFirstName() + " " + getLastName(); } // Kotlin fun fullName() = "${firstName} ${lastName}"*/ /*// Java if (name.toLowerCase().contains(firstName.toLowerCase())) { ... } // Kotlin if (name.contains(firstName, true)) { ... }*/ /*// Java if (message != null) { System.out.println(message) } // Kotlin message?.let { println(it) }*/ val items = listOf("apple", "banana", "kiwifruit") for (item in items) { println(item) } for (x in 1..5) { print(x) } } private fun callLoginApi() { showProgressDialog(false) } }<file_sep>package com.app.kotlinbasews.helper object AppConstants { private val BASE_HOST = String.format("%s", "http://ws-srv-net.in.webmyne.com:80/Applications/eatup/EatUp_Services/api/") fun getBaseHost(): String { return BASE_HOST } val LOGIN_URL: String = "User/Login" }<file_sep>package com.app.kotlinbasews.api import com.app.kotlinbasews.helper.AppConstants import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit class RestClient { companion object { val okHttpClient = OkHttpClient.Builder() .readTimeout(40, TimeUnit.SECONDS) .connectTimeout(40, TimeUnit.SECONDS) .addInterceptor(HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY }) .retryOnConnectionFailure(false) .build() fun getService(): AppApi { var retrofit = Retrofit.Builder() .baseUrl(AppConstants.getBaseHost()) .addConverterFactory(GsonConverterFactory.create()) .client(okHttpClient) .build() return retrofit.create<AppApi>(AppApi::class.java) } } } <file_sep>package com.app.kotlinbasews.custom import android.content.Context import android.content.res.TypedArray import android.graphics.Rect import android.graphics.drawable.Drawable import android.support.v4.content.ContextCompat import android.support.v7.widget.AppCompatEditText import android.text.Editable import android.text.TextWatcher import android.util.AttributeSet import android.view.MotionEvent import android.view.View import com.app.kotlinbasews.R import com.app.kotlinbasews.helper.Functions class MyEditTextWithCloseBtn : AppCompatEditText { var contextInstance: Context?=null private val imgCloseButton = resources.getDrawable(R.drawable.ic_cancel) private var tintColor: Int = 0 constructor(context: Context) : super(context) { this.contextInstance = context init() } constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) { this.contextInstance = context if (!isInEditMode) { val a = context.obtainStyledAttributes(attrs, R.styleable.TfEditTextClose, 0, 0) try { tintColor = a.getColor(R.styleable.TfEditTextClose_tintColor, ContextCompat.getColor(context, R.color.white)) } finally { a.recycle() } } init() } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { this.contextInstance = context if (!isInEditMode) { val a = context.obtainStyledAttributes(attrs, R.styleable.TfEditTextClose, 0, 0) try { tintColor = a.getColor(R.styleable.TfEditTextClose_tintColor, ContextCompat.getColor(context, R.color.white)) } finally { a.recycle() } } init() } internal fun init() { setPadding(18, 0, 10, 0) imgCloseButton?.setBounds(0, 0, imgCloseButton.intrinsicWidth, imgCloseButton.intrinsicHeight) imgCloseButton?.setColorFilter(tintColor, android.graphics.PorterDuff.Mode.SRC_IN) //setTypeface(Typeface.createFromAsset(getContext().getAssets(), "Dosis-Regular.otf")/*, -1*/); handleClearButton() this.setOnTouchListener(android.view.View.OnTouchListener { v, event -> val et = this@MyEditTextWithCloseBtn if (et.compoundDrawables[2] == null) return@OnTouchListener false if (event.action != MotionEvent.ACTION_UP) return@OnTouchListener false if (event.x > (et.width - et.paddingRight - imgCloseButton!!.intrinsicWidth)) { et.setText("") this@MyEditTextWithCloseBtn.handleClearButton() } false }) this.addTextChangedListener(object : TextWatcher { override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { this@MyEditTextWithCloseBtn.handleClearButton() } override fun afterTextChanged(arg0: Editable) {} override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { } }) typeface = Functions.getRegularFont(context) } internal fun handleClearButton() { if (this.text.toString() == "") { this.setCompoundDrawables(this.compoundDrawables[0], this.compoundDrawables[1], null, this.compoundDrawables[3]) } else { this.setCompoundDrawables(this.compoundDrawables[0], this.compoundDrawables[1], imgCloseButton, this.compoundDrawables[3]) } } override fun onFocusChanged(focused: Boolean, direction: Int, previouslyFocusedRect: Rect?) { super.onFocusChanged(focused, direction, previouslyFocusedRect) if (this.text.toString() == "") { this.setCompoundDrawables(this.compoundDrawables[0], this.compoundDrawables[1], null, this.compoundDrawables[3]) } else { if (focused) { this.setCompoundDrawables(this.compoundDrawables[0], this.compoundDrawables[1], imgCloseButton, this.compoundDrawables[3]) } else { this.setCompoundDrawables(this.compoundDrawables[0], this.compoundDrawables[1], null, this.compoundDrawables[3]) } } } }
a6945d28a1051ad5be53775f68afe421624c57e1
[ "Kotlin" ]
12
Kotlin
chintansonis/kotlin_base_ws
e4d51131f9316c77a8e799a4cb3754eed9da5274
0d7304847c6c4198a31530573b543b3a775b38c1
refs/heads/master
<file_sep>package parameters import ( "net/url" "strconv" ) // ProjectColumnSearch is the structure for the params of `project.column.search` query type ProjectColumnSearch struct { Constraints struct { Projects []string } } // ToConduitParams turns the structure to url.Values func (p ProjectColumnSearch) ToConduitParams() url.Values { params := url.Values{} for i, v := range p.Constraints.Projects { params.Add("constraints[projects]["+strconv.Itoa(i)+"]", v) } return params } <file_sep>package responses import "encoding/json" // ConduitBasic is the base response stricture for any conduit request type ConduitBasic struct { Result json.RawMessage `json:"result"` ErrorCode string `json:"error_code"` ErrorInfo string `json:"error_info"` } <file_sep>package responses // UserWhoAmI is the response stricture for the reuqest `user.whoami` type UserWhoAmI struct { Phid string `json:"phid"` UserName string `json:"userName"` RealName string `json:"realName"` Image string `json:"image"` URI string `json:"uri"` Roles []string `json:"roles"` PrimaryEmail string `json:"primaryEmail"` } <file_sep>package parameters import ( "net/url" "strconv" ) // ProjectSearch is the structure for the params of `project.search` query type ProjectSearch struct { QueryKey []int Constraints struct { PHIDs []string Members []string } } // ToConduitParams turns the structure to url.Values func (p ProjectSearch) ToConduitParams() url.Values { params := url.Values{} for i, v := range p.Constraints.PHIDs { params.Add("constraints[phids]["+strconv.Itoa(i)+"]", v) } for i, v := range p.Constraints.Members { params.Add("constraints[members]["+strconv.Itoa(i)+"]", v) } return params } <file_sep>package parameters import ( "net/url" "strconv" "github.com/glUk-skywalker/conduitclient/objects" ) // DifferentialRevisionEdit is the structure for the params of `differential.revision.edit` query type DifferentialRevisionEdit struct { Transactions []objects.URLParamAppendable ObjectIdentifier string } // ToConduitParams turns the structure to url.Values func (p DifferentialRevisionEdit) ToConduitParams() url.Values { params := url.Values{} params.Set("objectIdentifier", p.ObjectIdentifier) for i, transaction := range p.Transactions { transactionPrefix := "transactions[" + strconv.Itoa(i) + "]" transaction.AppendTo(&params, transactionPrefix) } return params } <file_sep>package urlvalues import ( "net/url" "sort" "strconv" "strings" ) // URLValues is own implementation of url.Values (with proper sorting, required // for Phabricator) type URLValues url.Values // Encode encodes parameters with proper indexing func (v URLValues) Encode() string { if v == nil { return "" } var buf strings.Builder keys := make([]string, 0, len(v)) for k := range v { keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { vs := v[k] keyEscaped := url.QueryEscape(k) for i, v := range vs { if buf.Len() > 0 { buf.WriteByte('&') } if len(vs) > 1 { keyEscaped = url.QueryEscape(k + "[" + strconv.Itoa(i) + "]") } buf.WriteString(keyEscaped) buf.WriteByte('=') buf.WriteString(url.QueryEscape(v)) } } return buf.String() } // Set is just a wrapper for url.Values.Set func (v URLValues) Set(key string, value string) { url.Values(v).Set(key, value) } // Add is just a wrapper for url.Values.Add func (v URLValues) Add(key string, value string) { url.Values(v).Add(key, value) } <file_sep>package parameters import ( "net/url" "strconv" ) // ManiphestGetTaskTransactions is the structure for the params of `maniphest.gettasktransactions` query type ManiphestGetTaskTransactions []int // ToConduitParams turns the structure to url.Values func (p ManiphestGetTaskTransactions) ToConduitParams() url.Values { params := url.Values{} for i, v := range p { params.Add("ids["+strconv.Itoa(i)+"]", strconv.Itoa(v)) } return params } <file_sep>package responses import ( "github.com/glUk-skywalker/conduitclient/objects" "github.com/glUk-skywalker/conduitclient/serviceobjects" ) // ProjectSearch is the response stricture for the reuqest `project.search` type ProjectSearch struct { Data []objects.Project `json:"data"` Maps struct { SlugMap struct{} `json:"slugMap"` } `json:"maps"` Query struct { QueryKey struct{} `json:"queryKey"` } `json:"query"` Cursor serviceobjects.PaginationCursor `json:"cursor"` } <file_sep>package objects // Task is the struct for the task data type Task struct { ID int `json:"id"` Type string `json:"type"` PHID string `json:"phid"` Fields struct { Name string `json:"name"` DateClosed int64 `json:"dateClosed"` DateCreated int64 `json:"dateCreated"` DateModified int `json:"dateModified"` Description struct { Raw string `json:"raw"` } `json:"description"` AuthorPHID string `json:"authorPHID"` OwnerPHID string `json:"ownerPHID"` СloserPHID string `json:"closerPHID"` Status struct { Value string `json:"value"` Name string `json:"name"` } `json:"status"` Priority struct { Value int `json:"value"` Name string `json:"name"` Color string `json:"color"` } `json:"priority"` CustomType string `json:"custom.type"` CustomVersion string `json:"custom.version"` } `json:"fields"` Attachments struct { Projects struct { ProjectPHIDs []string `json:"projectPHIDs"` } `json:"projects"` Columns struct { // Boards map[string]struct { // Columns []struct { // ID int `json:"id"` // PHID string `json:"phid"` // Name string `json:"name"` // } // } `json:"boards"` } `json:"columns"` } `json:"attachments"` } <file_sep>package objects import ( "net/url" "strconv" ) // URLParamAppendable is the interface for structs that can be appended as url.Params type URLParamAppendable interface { AppendTo(params *url.Values, transactionPrefix string) } // ColumnTransaction is the structure for status transactions type ColumnTransaction struct { Value []string } // AppendTo appends itself to the passed url.Values with the passed prefix func (t ColumnTransaction) AppendTo(params *url.Values, transactionPrefix string) { params.Add(transactionPrefix+"[type]", "column") for i, v := range t.Value { params.Add(transactionPrefix+"[value]["+strconv.Itoa(i)+"]", v) } } // StatusTransaction is the structure for status transactions type StatusTransaction struct { Value string } // AppendTo appends itself to the passed url.Values with the passed prefix func (t StatusTransaction) AppendTo(params *url.Values, transactionPrefix string) { params.Add(transactionPrefix+"[type]", "status") params.Add(transactionPrefix+"[value]", t.Value) } // AddTask is the structure for add task transactions type AddTask struct { Value []string } // AppendTo appends itself to the passed url.Values with the passed prefix func (t AddTask) AppendTo(params *url.Values, transactionPrefix string) { params.Add(transactionPrefix+"[type]", "tasks.add") for i, v := range t.Value { params.Add(transactionPrefix+"[value]["+strconv.Itoa(i)+"]", v) } } // AddComment is the structure for add comment transactions type AddComment struct { Value string } // AppendTo appends itself to the passed url.Values with the passed prefix func (c AddComment) AppendTo(params *url.Values, transactionPrefix string) { params.Add(transactionPrefix+"[type]", "comment") params.Add(transactionPrefix+"[value]", c.Value) } <file_sep>package parameters import "net/url" // DifferentialGetCommitMessage is the structure for the params of `differential.getcommitmessage` query type DifferentialGetCommitMessage struct { RevisionID string } // ToConduitParams turns the structure to url.Values func (d DifferentialGetCommitMessage) ToConduitParams() url.Values { params := url.Values{} params.Set("revision_id", d.RevisionID) return params } <file_sep>package serviceobjects // PaginationCursor is the structure for data stored under `cursor` key in some responses type PaginationCursor struct { Limit int `json:"limit"` After string `json:"after"` Before string `json:"before"` Order []string `json:"order"` } <file_sep>package objects // Attachment is the struct for the attachment data type Attachment struct{} <file_sep>package objects // Transaction is the struct for maniphest transaction data type Transaction struct { TaskID string `json:"taskID"` TransactionID string `json:"transactionID"` TransactionPHID string `json:"transactionPHID"` TransactionType string `json:"transactionType"` Comments string `json:"comments"` DateCreated string `json:"dateCreated"` } <file_sep>package objects // Column is the struct for the clumn data type Column struct { ID int `json:"id"` Type string `json:"type"` PHID string `json:"phid"` Fields struct { Name string `json:"name"` } `json:"fields"` } <file_sep>package conduitclient import ( "encoding/json" "errors" "fmt" "io/ioutil" "net/http" "net/url" "strconv" "github.com/glUk-skywalker/conduitclient/parameters" "github.com/glUk-skywalker/conduitclient/responses" ) // New creates and instance of Client func New(path string, token string) Client { return Client{url: path, token: token} } // DifferentialGetCommitMessage performs the `differential.getcommitmessage` request func (c Client) DifferentialGetCommitMessage(params parameters.DifferentialGetCommitMessage) (string, error) { var message string resp, err := c.request("differential.getcommitmessage", params) if err != nil { return message, fmt.Errorf("differential.getcommitmessage request error: %s", err) } err = json.Unmarshal(resp, &message) if err != nil { return message, fmt.Errorf("response parsing error: %s", err) } return message, nil } // DifferentialRevisionEdit performs the `differential.revision.edit` request func (c Client) DifferentialRevisionEdit(params parameters.DifferentialRevisionEdit) error { _, err := c.request("differential.revision.edit", params) if err != nil { return fmt.Errorf("differential.revision.edit request error: %s", err) } return nil } // UserWhoAmI performs the `service.whoami` request func (c Client) UserWhoAmI() (responses.UserWhoAmI, error) { var userData responses.UserWhoAmI basicResp, err := c.request("user.whoami", parameters.UserWhoAmI{}) if err != nil { return userData, errors.New("whoami request error: " + err.Error()) } err = json.Unmarshal(basicResp, &userData) if err != nil { return userData, errors.New("response parsing error: " + err.Error()) } return userData, nil } // ProjectSearch performs the `project.search` request func (c Client) ProjectSearch(params parameters.ProjectSearch) (responses.ProjectSearch, error) { var projectData responses.ProjectSearch basicResp, err := c.request("project.search", params) if err != nil { return projectData, errors.New("project.search request error: " + err.Error()) } err = json.Unmarshal(basicResp, &projectData) if err != nil { return projectData, errors.New("response parsing error: " + err.Error()) } return projectData, nil } func (c Client) ManiphestSearch(params parameters.ManiphestSearch) (responses.ManiphestSearch, error) { var tasksData responses.ManiphestSearch basicResp, err := c.request("maniphest.search", params) if err != nil { return tasksData, errors.New("maniphest.search request error: " + err.Error()) } err = json.Unmarshal(basicResp, &tasksData) if err != nil { return tasksData, errors.New("response parsing error: " + err.Error()) } return tasksData, nil } // ProjectColumnSearch performs the `project.column.search` request func (c Client) ProjectColumnSearch(params parameters.ProjectColumnSearch) (responses.ProjectColumnSearch, error) { var columnsData responses.ProjectColumnSearch basicResp, err := c.request("project.column.search", params) if err != nil { return columnsData, errors.New("project.column.search request error: " + err.Error()) } err = json.Unmarshal(basicResp, &columnsData) if err != nil { return columnsData, errors.New("response parsing error: " + err.Error()) } return columnsData, nil } // ManiphestEdit performs the `maniphest.edit` request func (c Client) ManiphestEdit(params parameters.ManiphestEdit) (responses.ManiphestEdit, error) { var editData responses.ManiphestEdit basicResp, err := c.request("maniphest.edit", params) if err != nil { return editData, errors.New("maniphest.edit request error: " + err.Error()) } err = json.Unmarshal(basicResp, &editData) if err != nil { return editData, errors.New("response parsing error: " + err.Error()) } return editData, nil } // ManiphestGetTaskTransactions performs the `maniphest.gettasktransactions` request func (c Client) ManiphestGetTaskTransactions(ids parameters.ManiphestGetTaskTransactions) (responses.ManiphestGetTaskTransactions, error) { var transactions responses.ManiphestGetTaskTransactions basicResp, err := c.request("maniphest.gettasktransactions", ids) if err != nil { return transactions, errors.New("maniphest.gettasktransactions rquest error: " + err.Error()) } err = json.Unmarshal(basicResp, &transactions) if err != nil { return transactions, errors.New("response parsing error: " + err.Error()) } return transactions, nil } // Client is object for interaction with the Phabricator conduit API type Client struct { url string token string } func (c Client) generateURL(conduitMethod string, params url.Values) string { return c.url + "/api/" + conduitMethod + "?" + params.Encode() } func (c Client) request(path string, params interface{ ToConduitParams() url.Values }) (json.RawMessage, error) { urlParams := params.ToConduitParams() urlParams.Set("api.token", c.token) resp, err := http.Get(c.generateURL(path, urlParams)) if err != nil { return []byte{}, errors.New("request error: " + err.Error()) } if resp.StatusCode != 200 { return []byte{}, errors.New("bad response code: " + strconv.Itoa(resp.StatusCode) + " - " + http.StatusText(resp.StatusCode)) } defer resp.Body.Close() content, err := ioutil.ReadAll(resp.Body) if err != nil { return []byte{}, errors.New("reading response error: " + err.Error()) } var conduitResp responses.ConduitBasic err = json.Unmarshal(content, &conduitResp) if err != nil { return []byte{}, errors.New("response parsing error: " + err.Error()) } if conduitResp.ErrorCode != "" { return []byte{}, errors.New("conduit error: [" + conduitResp.ErrorCode + "] " + conduitResp.ErrorInfo) } return conduitResp.Result, nil } <file_sep>package parameters import ( "net/url" ) // UserWhoAmI is the structure for the params of `project.search` query type UserWhoAmI struct{} // ToConduitParams turns the structure to url.Values func (p UserWhoAmI) ToConduitParams() url.Values { return url.Values{} } <file_sep>package responses import ( "github.com/glUk-skywalker/conduitclient/objects" "github.com/glUk-skywalker/conduitclient/serviceobjects" ) // ProjectColumnSearch is the response stricture for the reuqest `project.column.search` type ProjectColumnSearch struct { Data []objects.Column `json:"data"` Maps struct{} `json:"maps"` Query struct { QueryKey struct{} `json:"queryKey"` } `json:"query"` Cursor serviceobjects.PaginationCursor `json:"cursor"` } <file_sep>module github.com/glUk-skywalker/conduitclient go 1.17 <file_sep>package objects // Project is the struct for the project data type Project struct { ID int `json:"id"` Type string `json:"type"` PHID string `json:"phid"` Fields struct { Name string `json:"name"` Slug string `json:"slug"` Milestone int `json:"milestone"` Depth int64 `json:"depth"` Parent struct { ID int `json:"id"` PHID string `json:"phid"` Name string `json:"name"` } `json:"parent"` Icon struct { Key string `json:"key"` Name string `json:"name"` Icon string `json:"icon"` } `json:"icon"` Color struct { Key string `json:"color"` Name string `json:"name"` } `json:"color"` SpacePHID string `json:"spacePHID"` DateCreated int64 `json:"dateCreated"` DateModified int64 `json:"dateModified"` Policy struct { View string `json:"view"` Edit string `json:"edit"` Join string `json:"join"` } `json:"policy"` Description string `json:"description"` } `json:"fields"` Attachments Attachment `json:"attachments"` } <file_sep>package responses // ManiphestEdit is the response stricture for the reuqest `maniphest.edit` type ManiphestEdit struct{} <file_sep>package responses import ( "github.com/glUk-skywalker/conduitclient/objects" ) // ManiphestGetTaskTransactions is the response stricture for the reuqest `maniphest.gettasktransactions` type ManiphestGetTaskTransactions map[string][]objects.Transaction <file_sep>package parameters import ( "net/url" "strconv" ) // ManiphestSearch is the structure for the params of `maniphest.search` query type ManiphestSearch struct { Constraints struct { IDs []int Statuses []string Projects []string Priorities []int ModifiedStart int64 ModifiedEnd int64 } Order []string After string Attachments map[string]bool } // ToConduitParams turns the structure to url.Values func (p ManiphestSearch) ToConduitParams() url.Values { params := url.Values{} for i, v := range p.Constraints.IDs { params.Add("constraints[ids]["+strconv.Itoa(i)+"]", strconv.Itoa(v)) } for i, v := range p.Constraints.Statuses { params.Add("constraints[statuses]["+strconv.Itoa(i)+"]", v) } for i, v := range p.Constraints.Projects { params.Add("constraints[projects]["+strconv.Itoa(i)+"]", v) } for i, v := range p.Constraints.Priorities { params.Add("constraints[priorities]["+strconv.Itoa(i)+"]", strconv.Itoa(v)) } if p.Constraints.ModifiedStart != 0 { params.Add("constraints[modifiedStart]", strconv.FormatInt(p.Constraints.ModifiedStart, 10)) } if p.Constraints.ModifiedEnd != 0 { params.Add("constraints[modifiedEnd]", strconv.FormatInt(p.Constraints.ModifiedStart, 10)) } for i, v := range p.Order { params.Add("order["+strconv.Itoa(i)+"]", v) } if p.After != "" { params.Add("after", p.After) } for key, v := range p.Attachments { params.Add("attachments["+key+"]", btos(v)) } return params } func btos(b bool) string { if b { return "1" } return "0" } <file_sep>package parameters import ( "net/url" "strconv" "github.com/glUk-skywalker/conduitclient/objects" ) // ManiphestEdit is the structure for the params of `maniphest.edit` query type ManiphestEdit struct { ObjectIdentifier string Transactions []objects.URLParamAppendable } // ToConduitParams turns the structure to url.Values func (p ManiphestEdit) ToConduitParams() url.Values { params := url.Values{} params.Set("objectIdentifier", p.ObjectIdentifier) for iTransaction, vTransaction := range p.Transactions { transactionPrefix := "transactions[" + strconv.Itoa(iTransaction) + "]" vTransaction.AppendTo(&params, transactionPrefix) } return params }
78a3af3e7076248e96e06250811af702641ad56c
[ "Go Module", "Go" ]
24
Go
glUk-skywalker/conduitclient
984958a5431e0d2ba983b07d5569c492cd01d632
aabc799cedd95a72ff39b43fc7b756c976ad7faf
refs/heads/master
<repo_name>axelolsson/coffee-monster<file_sep>/src/containers/FreshBrews/FreshBrews.jsx import React, { useState } from 'react'; import Filter from '../../components/Filter/Filter'; import Photo from '../../components/Photo/Photo'; import './FreshBrews.css'; const defaultPhotos = [ { title: 'Title 1', category: 'category1', src: 'https://source.unsplash.com/collection/1215/360x270', }, { title: 'Title 2', category: 'category2', src: 'https://source.unsplash.com/collection/189929/360x270', }, { title: 'Title 3', category: 'category3', src: 'https://source.unsplash.com/collection/415854/360x270', }, { title: 'Title 4', category: 'category4', src: 'https://source.unsplash.com/collection/147415/360x270', }, { title: 'Title 5', category: 'category5', src: 'https://source.unsplash.com/collection/166770/360x270', }, ]; const FreshBrews = () => { const [photos, setPhotos] = useState(defaultPhotos); const handleClick = (filters) => { let filteredPhotos = [...defaultPhotos]; filteredPhotos = filteredPhotos .filter(({ category }) => filters.some(({ value, active }) => value === category && active)); if (filteredPhotos.length === 0) { setPhotos(defaultPhotos); } else { setPhotos(filteredPhotos); } }; return ( <div> <section className="main-section" id="FreshBrews"> <div className="container"> <h2>Fresh brews</h2> <h6>Fresh coffee pics that will keep you wanting a brew yourself.</h6> <Filter onClick={handleClick} /> <div className="freshBrewsContainer"> <Photo photos={photos} /> </div> </div> </section> </div> ); }; export default FreshBrews; <file_sep>/public/img/monsters/README.md All of these images are shamelessly stolen from http://www.vonnbriggs.com/ <file_sep>/src/containers/OtherMonsters/OtherMonsters.jsx import React from 'react'; import './OtherMonsters.css'; function OtherMonsters() { return ( <div> <section className="main-section monsters" id="monsters"> <div className="container"> <h2>monsters</h2> <h6> Take a closer look at other coffee monsters. We won’t bite, hard. </h6> <div className="monsters-leader-block clearfix"> <div className="monsters-leader-box"> <div className="monsters-leader"> <div className="monsters-leader-shadow" /> <img src="img/monsters/bear.jpg" alt="" /> </div> <h3>Name</h3> <span>Monster type</span> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin consequat sollicitudin cursus. Dolor sit amet, consectetur adipiscing elit proin consequat. </p> </div> <div className="monsters-leader-box"> <div className="monsters-leader"> <div className="monsters-leader-shadow" /> <img src="img/monsters/bear-2.jpg" alt="" /> </div> <h3>Name</h3> <span>Monster type</span> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin consequat sollicitudin cursus. Dolor sit amet, consectetur adipiscing elit proin consequat. </p> </div> <div className="monsters-leader-box"> <div className="monsters-leader"> <div className="monsters-leader-shadow" /> <img src="img/monsters/beast.jpg" alt="" /> </div> <h3>Name</h3> <span>Monster type</span> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin consequat sollicitudin cursus. Dolor sit amet, consectetur adipiscing elit proin consequat. </p> </div> <div className="monsters-leader-box"> <div className="monsters-leader"> <div className="monsters-leader-shadow" /> <img src="img/monsters/bear.jpg" alt="" /> </div> <h3>Name</h3> <span>Monster type</span> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin consequat sollicitudin cursus. Dolor sit amet, consectetur adipiscing elit proin consequat. </p> </div> <div className="monsters-leader-box"> <div className="monsters-leader"> <div className="monsters-leader-shadow" /> <img src="img/monsters/bear-2.jpg" alt="" /> </div> <h3>Name</h3> <span>Monster type</span> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin consequat sollicitudin cursus. Dolor sit amet, consectetur adipiscing elit proin consequat. </p> </div> <div className="monsters-leader-box"> <div className="monsters-leader"> <div className="monsters-leader-shadow" /> <img src="img/monsters/beast.jpg" alt="" /> </div> <h3>Name</h3> <span>Monster type</span> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin consequat sollicitudin cursus. Dolor sit amet, consectetur adipiscing elit proin consequat. </p> </div> <div className="monsters-leader-box"> <div className="monsters-leader"> <div className="monsters-leader-shadow" /> <img src="img/monsters/bear.jpg" alt="" /> </div> <h3>Name</h3> <span>Monster type</span> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin consequat sollicitudin cursus. Dolor sit amet, consectetur adipiscing elit proin consequat. </p> </div> <div className="monsters-leader-box"> <div className="monsters-leader"> <div className="monsters-leader-shadow"> <span>Some text</span> </div> <img src="img/monsters/bear-2.jpg" alt="" /> </div> <h3>Name</h3> <span>Monster type</span> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin consequat sollicitudin cursus. Dolor sit amet, consectetur adipiscing elit proin consequat. </p> </div> <div className="monsters-leader-box"> <div className="monsters-leader"> <div className="monsters-leader-shadow" /> <img src="img/monsters/beast.jpg" alt="" /> </div> <h3>Name</h3> <span>Monster type</span> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin consequat sollicitudin cursus. Dolor sit amet, consectetur adipiscing elit proin consequat. </p> </div> </div> </div> </section> </div> ); } export default OtherMonsters; <file_sep>/README.md # Coffee Monster A little React playground app, contains coffee... and monsters. <file_sep>/src/components/Header/Header.jsx import React from 'react'; import { NavLink } from 'react-router-dom'; import './Header.css'; const Header = () => ( <div className="App-header"> <nav className="main-nav-outer"> <div className="container"> <ul className="main-nav"> <li> <NavLink exact to="/">Home</NavLink> </li> <li> <NavLink exact to="/fresh">Fresh brews</NavLink> </li> <li> <NavLink exact to="/monsters">Monsters!</NavLink> </li> <li className="small-logo"> <a href="#header"> <img src={`${process.env.PUBLIC_URL}img/logo.png`} alt="" /> </a> </li> </ul> <a className="res-nav_click" href="/"> <i className="fa-bars" /> </a> </div> </nav> </div> ); export default Header;
7c9496a274e0715be6bf1661255dea7c2eb7e7a1
[ "JavaScript", "Markdown" ]
5
JavaScript
axelolsson/coffee-monster
6852d57e7365eefca992d494f27e6d874b1bdfe2
394010a8c3c63d2c3c1a818fa60d447a62240d52
refs/heads/main
<file_sep>package com.example.mymovies; import androidx.room.Dao; import androidx.room.Insert; import androidx.room.Query; import androidx.room.Transaction; import java.util.List; @Dao public interface MovieWithCategoriesDao { @Transaction @Insert void insert(List<MovieCategoriesCrossRef> movieWithCategoriesList); @Query("SELECT * FROM movieCategoriesCR WHERE movieId = :id") List<MovieCategoriesCrossRef> getMovieCategoryByMovieId(long id); } <file_sep>package com.example.mymovies; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.Button; import com.google.android.material.textfield.TextInputLayout; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class LogInActivity extends AppCompatActivity { boolean foundEmail=false; boolean foundPassword=false; private Button btnLogIn,btnSignUp; private TextInputLayout textInputLayoutEmail,textInputLayoutPassword; private FirebaseDatabase database; private String uid; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log_in); database = FirebaseDatabase.getInstance(); final DatabaseReference myRef = database.getReference("MyMovies"); myRef.keepSynced(true); btnLogIn=findViewById(R.id.btnLogIn); btnLogIn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (validateEmail(myRef) & validatePassword(myRef)){ textInputLayoutEmail=findViewById(R.id.textInputLayoutEmail); final String emailText =textInputLayoutEmail.getEditText().getText().toString().trim(); database = FirebaseDatabase.getInstance(); DatabaseReference myRef = database.getReference("MyMovies"); myRef.keepSynced(true); myRef.child("Users").addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { if (snapshot.exists()) { for (DataSnapshot dn : snapshot.getChildren()) { User user = dn.getValue(User.class); if (user.getEmail().equals(emailText)) { uid = user.getUid(); } } } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); final MovieDB movieDB = MovieDB.getInstanta(getApplicationContext()); myRef.child("UsersWithMovies").addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { if (snapshot.exists()) { for(DataSnapshot dn : snapshot.getChildren()){ if(dn.getKey().equals(uid)){ ExtractMovie extractMovie = new ExtractMovie((Long) dn.getValue(), movieDB,true); extractMovie.execute(); } } } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); SharedPreferences settingsFile = getSharedPreferences("prefs", 0); SharedPreferences.Editor myEditor = settingsFile.edit(); String currentDate = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date()); myEditor.putString("authentication", currentDate); myEditor.putString("email", emailText); myEditor.apply(); Intent intent=new Intent(getApplicationContext(),MainActivity.class); startActivity(intent); finish(); } } }); btnSignUp=findViewById(R.id.btnSignUpL); btnSignUp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(getApplicationContext(),SignUpActivity.class); startActivity(intent); finish(); } }); } private boolean validateEmail(DatabaseReference myRef){ textInputLayoutEmail=findViewById(R.id.textInputLayoutEmail); final String email=textInputLayoutEmail.getEditText().getText().toString().trim(); if (email.isEmpty()) {textInputLayoutEmail.setError("Field can't be empty!"); return false; } else if (!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {textInputLayoutEmail.setError("Please enter a valid email address!"); return false; } else { myRef.child("Users").addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { if (snapshot.exists()) { for (DataSnapshot dn : snapshot.getChildren()) { User user = dn.getValue(User.class); if (user.getEmail().equals(email)) { foundEmail = true; } else { foundEmail = false; } } } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); if (foundEmail) { textInputLayoutEmail.setError(null); return true; } else { textInputLayoutEmail.setError("This email doesn't exist!"); return false; } } } private boolean validatePassword(DatabaseReference myRef){ textInputLayoutPassword=findViewById(R.id.textInputLayoutPassword); final String password = textInputLayoutPassword.getEditText().getText().toString().trim(); final String email=textInputLayoutEmail.getEditText().getText().toString().trim(); if (password.isEmpty()){ textInputLayoutPassword.setError("Field can't be empty!"); return false;} else { myRef.child("Users").addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { if (snapshot.exists()) { for (DataSnapshot dn : snapshot.getChildren()) { User user = dn.getValue(User.class); if (user.getPassword().equals(password) && user.getEmail().equals(email)) { foundPassword = true; } else { foundPassword = false; } } } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); if (foundPassword) { textInputLayoutPassword.setError(null); return true; } else { textInputLayoutPassword.setError("Password incorrect!"); return false; } } } }<file_sep>package com.example.mymovies; import android.content.Intent; import android.os.Bundle; import android.widget.SearchView; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; import java.util.List; public class DiscoverMoreActivity extends AppCompatActivity { private List<Movie> movieList; private RecyclerView recyclerView; private int categoryId=-1; private String title="Top Rated Movies"; private SearchView sv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_discover_more); overridePendingTransition(R.anim.slide_up,R.anim.stay); movieList = new ArrayList<>(); recyclerView = findViewById(R.id.discoverMoreRecyclerView); Intent intent = getIntent(); if (intent.hasExtra("categoryId")) { Bundle bundle = intent.getExtras(); categoryId=bundle.getInt("categoryId"); title=bundle.getString("categoryName"); } sv=findViewById(R.id.sv); sv.setQueryHint("Search your movie"); ExtractDiscoverMoreMovies extractMovies = new ExtractDiscoverMoreMovies(getApplicationContext(), movieList, recyclerView, categoryId,sv); extractMovies.execute(); setTitle(title); } @Override public void onBackPressed() { super.onBackPressed(); overridePendingTransition(R.anim.stay, R.anim.slide_down); } }<file_sep>package com.example.mymovies; import android.content.Context; import android.os.AsyncTask; import android.widget.SearchView; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; public class ExtractDiscoverMoreMovies extends AsyncTask<String, Void, String> { private Context context; private List<Movie> movieList; private RecyclerView recyclerView; private int categoryId; private SearchView sv; public ExtractDiscoverMoreMovies(Context context, List<Movie> movieList, RecyclerView recyclerView, int categoryId,SearchView sv) { this.context = context; this.movieList = movieList; this.recyclerView = recyclerView; this.categoryId=categoryId; this.sv=sv; } @Override protected String doInBackground(String... strings) { String current = ""; try{ URL url; HttpURLConnection urlConnection = null; try{ String link=null; if (categoryId==-1){ link= "https://api.themoviedb.org/3/movie/top_rated?api_key=<KEY>"; }else{ link="https://api.themoviedb.org/3/discover/movie?api_key=<KEY>&with_genres="+categoryId; } url = new URL(link); urlConnection = (HttpURLConnection) url.openConnection(); InputStream is = urlConnection.getInputStream(); InputStreamReader isr = new InputStreamReader(is); int data = isr.read(); while(data != -1){ current += (char) data; data = isr.read(); } return current; } catch (IOException e) { e.printStackTrace(); } finally { if(urlConnection != null){ urlConnection.disconnect(); } } } catch (Exception e) { e.printStackTrace(); } return current; } @Override protected void onPostExecute(String s) { try{ JSONObject jsonObject = new JSONObject(s); JSONArray jsonArray = jsonObject.getJSONArray("results"); for(int i=0;i<jsonArray.length();i++){ JSONObject jsonMovie = jsonArray.getJSONObject(i); Movie movie = new Movie(); movie.setMovieId(jsonMovie.getLong("id")); movie.setTitle(jsonMovie.getString("title")); movie.setOverview(jsonMovie.getString("overview")); movie.setRelease_date(jsonMovie.getString("release_date")); JSONArray genres = jsonMovie.getJSONArray("genre_ids"); List<Integer> genres_ids = new ArrayList<>(); for(int j=0;j<genres.length(); j++){ genres_ids.add(genres.getInt(j)); } movie.setGenres(genres_ids); movie.setVote_average(jsonMovie.getDouble("vote_average")); movie.setVote_count(jsonMovie.getInt("vote_count")); movie.setBackdrop_path(jsonMovie.getString("backdrop_path")); movie.setPoster_path(jsonMovie.getString("poster_path")); movieList.add(movie); } } catch (JSONException e) { e.printStackTrace(); } PutDataIntoRecyclerView(movieList); } private void PutDataIntoRecyclerView(List<Movie> movieList){ final DiscoverMoreMovieAdapter adapter = new DiscoverMoreMovieAdapter(context, movieList); recyclerView.setLayoutManager(new LinearLayoutManager(context)); recyclerView.setAdapter(adapter); sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(String newText) { adapter.getFilter().filter(newText); return false; } }); } } <file_sep>package com.example.mymovies; import androidx.room.Dao; import androidx.room.Delete; import androidx.room.Insert; import androidx.room.Query; import java.util.List; @Dao public interface MovieCategoryDao { @Insert void insert(List<MovieCategory> movieCategoryList); @Query("SELECT * FROM MOVIECATEGORY") List<MovieCategory> getAllCategories(); @Query("DELETE FROM MOVIECATEGORY") void deleteAllCategories(); @Query("SELECT * FROM movieCategory WHERE categoryId = :id") MovieCategory getMovieCategoryById(int id); @Delete void deleteMovieCategory(MovieCategory movieCategory); } <file_sep>package com.example.mymovies; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import android.os.Bundle; import android.view.MenuItem; import com.google.android.material.bottomnavigation.BottomNavigationView; public class MainActivity extends AppCompatActivity { private ProfileFragment profile; private MoviesFragment movies; private DiscoverFragment discover; private Fragment fragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); BottomNavigationView bottomNavView = findViewById(R.id.bottomNavView); bottomNavView.setSelectedItemId(R.id.discover); movies = new MoviesFragment(); discover = new DiscoverFragment(); profile = new ProfileFragment(); getSupportFragmentManager().beginTransaction().replace(R.id.mainFrame, discover).commit(); bottomNavView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { fragment = null; switch (item.getItemId()){ case R.id.movies: fragment = movies; break; case R.id.discover: fragment = discover; break; case R.id.profile: fragment = profile; break; } getSupportFragmentManager() .beginTransaction() .replace(R.id.mainFrame, fragment) .commit(); return true; } }); } }<file_sep>package com.example.mymovies; import java.io.Serializable; public class User implements Serializable { private String uid; private String email; private String password; private String firstname; private String lastname; private String gender; private String origin; public User() { } public User(String email, String password, String firstname, String lastname, String gender, String origin) { this.email = email; this.password = <PASSWORD>; this.firstname = firstname; this.lastname = lastname; this.gender=gender; this.origin=origin; } public User(String email, String password, String firstname, String lastname, String gender, String origin, String uid) { this.email = email; this.password = <PASSWORD>; this.firstname = firstname; this.lastname = lastname; this.gender=gender; this.origin=origin; this.uid = uid; } public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public String getEmail() { return email; } public String getPassword() { return <PASSWORD>; } public String getFirstname() { return firstname; } public String getLastname() { return lastname; } public String getGender() { return gender; } public String getOrigin() { return origin; } public void setPassword(String password) { this.password = <PASSWORD>; } public void setFirstname(String firstname) { this.firstname = firstname; } public void setLastname(String lastname) { this.lastname = lastname; } public void setGender(String gender) { this.gender = gender; } public void setOrigin(String origin) { this.origin = origin; } } <file_sep>package com.example.mymovies; import android.app.Activity; import android.content.Context; import android.media.Image; import android.os.AsyncTask; import android.widget.ImageView; import android.widget.RatingBar; import android.widget.TextView; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; public class ExtractMovie extends AsyncTask<String, Void, String> { private MovieDB movieDB; private long id; private boolean source; private Movie movie; private Activity activity; public ExtractMovie(long id, MovieDB movieDB,boolean source) { this.id = id; this.movieDB = movieDB; this.source=source; } public ExtractMovie(long id,boolean source,Activity activity) { this.id = id; this.source=source; this.activity=activity; } @Override protected String doInBackground(String... strings) { String current = ""; try{ URL url; HttpURLConnection urlConnection = null; try{ String movie = "https://api.themoviedb.org/3/movie/" + id + "?api_key=<KEY>"; url = new URL(movie); urlConnection = (HttpURLConnection) url.openConnection(); InputStream is = urlConnection.getInputStream(); InputStreamReader isr = new InputStreamReader(is); int data = isr.read(); while(data != -1){ current += (char) data; data = isr.read(); } return current; } catch (IOException e) { e.printStackTrace(); } finally { if(urlConnection != null){ urlConnection.disconnect(); } } } catch (Exception e) { e.printStackTrace(); } return current; } @Override protected void onPostExecute(String s) { try{ JSONObject jsonObject = new JSONObject(s); movie=new Movie(); movie.setMovieId(jsonObject.getLong("id")); movie.setTitle(jsonObject.getString("title")); movie.setOverview(jsonObject.getString("overview")); movie.setRuntime(jsonObject.getInt("runtime")); movie.setRelease_date(jsonObject.getString("release_date")); movie.setVote_average(jsonObject.getDouble("vote_average")); movie.setVote_count(jsonObject.getInt("vote_count")); movie.setBackdrop_path(jsonObject.getString("backdrop_path")); movie.setPoster_path(jsonObject.getString("poster_path")); movie.setMy_rating(0); JSONArray genres = jsonObject.getJSONArray("genres"); List<MovieCategory> categories = new ArrayList<>(); if (source){ List<MovieCategoriesCrossRef> movieCategoriesCrossRefsList = new ArrayList<>(); List<MovieCategory> categoriesDB=movieDB.getMovieCategoryDao().getAllCategories(); for(int j=0;j<genres.length(); j++){ JSONObject genre = genres.getJSONObject(j); MovieCategory movieCategory = new MovieCategory(); movieCategory.setCategoryId(genre.getInt("id")); movieCategory.setCategoryName(genre.getString("name")); if (categoriesDB.size()==0){ categories.add(movieCategory); }else{ boolean verify=true; for (MovieCategory mc:categoriesDB){ if (movieCategory.getCategoryId()==mc.getCategoryId()){ verify=false; } } if (verify){ categories.add(movieCategory); } } MovieCategoriesCrossRef movieCategoriesCrossRef = new MovieCategoriesCrossRef(); movieCategoriesCrossRef.setMovieId(id); movieCategoriesCrossRef.setCategoryId(genre.getInt("id")); movieCategoriesCrossRefsList.add(movieCategoriesCrossRef); } movieDB.getMovieDao().insert(movie); movieDB.getMovieCategoryDao().insert(categories); movieDB.getMovieWithCategoriesDao().insert(movieCategoriesCrossRefsList); }else{ for(int j=0;j<genres.length(); j++){ JSONObject genre = genres.getJSONObject(j); MovieCategory movieCategory = new MovieCategory(); movieCategory.setCategoryId(genre.getInt("id")); movieCategory.setCategoryName(genre.getString("name")); categories.add(movieCategory); } ImageView imageView=activity.findViewById(R.id.imgViewPoster); String imageString = "https://image.tmdb.org/t/p/original"; Glide.with(activity.getApplication()) .load(imageString + movie.getBackdrop_path()) .into(imageView); TextView tvTitle=activity.findViewById(R.id.tvTitle); tvTitle.setText(movie.getTitle()); TextView tvRuntime=activity.findViewById(R.id.tvRuntime); tvRuntime.setText(String.valueOf(movie.getRuntime()/60) + " h " + String.valueOf(movie.getRuntime()%60) + " min"); String allCategories=categories.get(0).getCategoryName()+", "; for (int i=1;i<categories.size()-1;i++){ allCategories+=categories.get(i).getCategoryName()+", "; } allCategories+=categories.get(categories.size()-1).getCategoryName(); TextView tvCategories=activity.findViewById(R.id.tvCategories); tvCategories.setText(allCategories); TextView tvReleaseDate=activity.findViewById(R.id.tvReleaseDate); tvReleaseDate.setText(movie.getRelease_date()); RatingBar ratingBar=activity.findViewById(R.id.ratingBar); ratingBar.setNumStars(5); ratingBar.setRating((float) (movie.getVote_average()*0.5)); double voteAverage=movie.getVote_average()*0.5; TextView tvVoteAverage=activity.findViewById(R.id.tvVoteAverage); tvVoteAverage.setText(voteAverage+"/5"); TextView tvVoteCount=activity.findViewById(R.id.tvVoteCount); tvVoteCount.setText(movie.getVote_count()+""); TextView tvOverview=activity.findViewById(R.id.overview); tvOverview.setText(movie.getOverview()); } } catch (JSONException e) { e.printStackTrace(); } } public Activity getActivity() { return activity; } } <file_sep>package com.example.mymovies; import android.content.Context; import android.os.AsyncTask; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; public class ExtractMoviesForCategory extends AsyncTask<String, Void, String> { private Context context; private List<Movie> movieList; private int id; private RecyclerView recyclerView; public ExtractMoviesForCategory(Context context, List<Movie> movieList, int id, RecyclerView recyclerView) { this.context = context; this.movieList = movieList; this.id = id; this.recyclerView = recyclerView; } @Override protected String doInBackground(String... strings) { String current = ""; try{ URL url; HttpURLConnection urlConnection = null; try{ String moviesForCategory = "https://api.themoviedb.org/3/discover/movie?api_key=<KEY>&with_genres=" + id; url = new URL(moviesForCategory); urlConnection = (HttpURLConnection) url.openConnection(); InputStream is = urlConnection.getInputStream(); InputStreamReader isr = new InputStreamReader(is); int data = isr.read(); while(data != -1){ current += (char) data; data = isr.read(); } return current; } catch (IOException e) { e.printStackTrace(); } finally { if(urlConnection != null){ urlConnection.disconnect(); } } } catch (Exception e) { e.printStackTrace(); } return current; } @Override protected void onPostExecute(String s) { try{ JSONObject jsonObject = new JSONObject(s); JSONArray jsonArray = jsonObject.getJSONArray("results"); for(int i=0;i<jsonArray.length() / 2;i++){ JSONObject jsonMovie = jsonArray.getJSONObject(i); Movie movie = new Movie(); movie.setMovieId(jsonMovie.getLong("id")); movie.setTitle(jsonMovie.getString("title")); movie.setOverview(jsonMovie.getString("overview")); movie.setRelease_date(jsonMovie.getString("release_date")); JSONArray genres = jsonMovie.getJSONArray("genre_ids"); List<Integer> genres_ids = new ArrayList<>(); for(int j=0;j<genres.length(); j++){ genres_ids.add(genres.getInt(j)); } movie.setGenres(genres_ids); movie.setVote_average(jsonMovie.getDouble("vote_average")); movie.setVote_count(jsonMovie.getInt("vote_count")); movie.setBackdrop_path(jsonMovie.getString("backdrop_path")); movie.setPoster_path(jsonMovie.getString("poster_path")); movieList.add(movie); } } catch (JSONException e) { e.printStackTrace(); } PutDataIntoRecyclerView(movieList); } private void PutDataIntoRecyclerView(List<Movie> movieList){ CategoryMovieAdapter categoryMovieAdapter = new CategoryMovieAdapter(context, movieList); LinearLayoutManager layoutManager = new LinearLayoutManager(context, RecyclerView.HORIZONTAL, false); recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(categoryMovieAdapter); } } <file_sep>package com.example.mymovies; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; public class SplashScreenActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash_screen); SharedPreferences settingsFile = getSharedPreferences("prefs", 0); final String email=settingsFile.getString("email",null); if (email!=null){ Intent intent=new Intent(getApplicationContext(),MainActivity.class); startActivity(intent); }else { Intent intent=new Intent(getApplicationContext(),LogInActivity.class); startActivity(intent); } finish(); } }<file_sep>package com.example.mymovies; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Filter; import android.widget.Filterable; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.cardview.widget.CardView; import androidx.core.content.ContextCompat; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import java.util.ArrayList; import java.util.Collection; import java.util.List; public class DiscoverMoreMovieAdapter extends RecyclerView.Adapter<DiscoverMoreMovieAdapter.MyViewHolder> implements Filterable { private Context context; private List<Movie> movieList; private List<Movie> movieListAll; public DiscoverMoreMovieAdapter(Context context, List<Movie> movieList) { this.context = context; this.movieList = movieList; this.movieListAll = new ArrayList<>(movieList); } @NonNull @Override public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view; LayoutInflater inflater = LayoutInflater.from(context); view = inflater.inflate(R.layout.discover_more_card_view, parent, false); return new MyViewHolder(view, movieList); } @Override public void onBindViewHolder(@NonNull MyViewHolder holder, int position) { holder.tvMovieTitle.setText(movieList.get(position).getTitle()); long id = movieList.get(position).getMovieId(); final MovieDB movieDB = MovieDB.getInstanta(context); Movie movie = movieDB.getMovieDao().getMovieById(id); if(movie != null){ holder.checkImgButton.setBackground(ContextCompat.getDrawable(context, R.drawable.ic_check_16_with_background)); holder.pressed = true; } else { holder.checkImgButton.setBackground(ContextCompat.getDrawable(context, R.drawable.ic_add_16_with_background)); holder.pressed = false; } String imageString = "https://image.tmdb.org/t/p/original"; Glide.with(context) .load(imageString + movieList.get(position).getBackdrop_path()) .into(holder.img); } @Override public int getItemCount() { return movieList.size(); } @Override public Filter getFilter() { return filter; } Filter filter=new Filter() { @Override protected FilterResults performFiltering(CharSequence constraint) { List<Movie> filteredList=new ArrayList<>(); if (constraint.toString().isEmpty()){ filteredList.addAll(movieListAll); }else{ for (Movie movie:movieListAll){ if (movie.getTitle().toLowerCase().contains(constraint.toString().toLowerCase())){ filteredList.add(movie); } } } FilterResults filterResults=new FilterResults(); filterResults.values=filteredList; return filterResults; } @Override protected void publishResults(CharSequence constraint, FilterResults results) { movieList.clear(); movieList.addAll((Collection<? extends Movie>) results.values); notifyDataSetChanged(); } }; public static class MyViewHolder extends RecyclerView.ViewHolder { private TextView tvMovieTitle; private ImageButton checkImgButton; private ImageView img; private boolean pressed; public MyViewHolder(@NonNull final View itemView, final List<Movie> movieList) { super(itemView); tvMovieTitle = itemView.findViewById(R.id.tvDiscoverMore_Title); img = itemView.findViewById(R.id.discoverMoreImageView); CardView cardView = itemView.findViewById(R.id.discoverMoreCardView); checkImgButton = itemView.findViewById(R.id.discoverMoreCheckImageButton); cardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int position=getAdapterPosition(); Intent intent = new Intent(v.getContext(), MovieDetailsActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra("movieId",movieList.get(position).getMovieId()); v.getContext().startActivity(intent); } }); checkImgButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final int position = getAdapterPosition(); final MovieDB movieDB = MovieDB.getInstanta(v.getContext()); if(pressed){ v.setBackground(ContextCompat.getDrawable(v.getContext(), R.drawable.ic_add_16_with_background)); movieDB.getMovieDao().deleteMovie(movieList.get(position)); } else { v.setBackground(ContextCompat.getDrawable(v.getContext(), R.drawable.ic_check_16_with_background)); ExtractMovie extractMovie = new ExtractMovie(movieList.get(position).getMovieId(), movieDB,true); extractMovie.execute(); } pressed=!pressed; } }); } } } <file_sep># Android Project Movies Tracking Application Contributors: <NAME> <NAME> <file_sep>package com.example.mymovies; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.ImageView; import androidx.annotation.NonNull; import androidx.cardview.widget.CardView; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import java.util.List; public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.MyViewHolder> { private Context context; private List<Movie> movieList; private RecyclerView recyclerView; public MovieAdapter(Context context, List<Movie> movieList,RecyclerView recyclerView) { this.context = context; this.movieList = movieList; this.recyclerView=recyclerView; } @NonNull @Override public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view; LayoutInflater inflater = LayoutInflater.from(parent.getContext()); view = inflater.inflate(R.layout.movies_fragment_card_view, parent, false); return new MyViewHolder(view); } @Override public void onBindViewHolder(@NonNull MyViewHolder holder, final int position) { String posterImageString = "https://image.tmdb.org/t/p/w500"; Glide.with(context) .load(posterImageString + movieList.get(position).getPoster_path()) .into(holder.img); holder.imageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MovieDB movieDB=MovieDB.getInstanta(v.getContext()); movieDB.getMovieDao().deleteMovie(movieList.get(position)); movieList=movieDB.getMovieDao().getAll(); MovieAdapter adapter = new MovieAdapter(v.getContext(), movieList,recyclerView); recyclerView.setLayoutManager(new GridLayoutManager(v.getContext(), 3)); recyclerView.setAdapter(adapter); } }); } @Override public int getItemCount() { return movieList.size(); } public class MyViewHolder extends RecyclerView.ViewHolder{ private ImageView img; private ImageButton imageButton; public MyViewHolder(@NonNull View itemView) { super(itemView); img = itemView.findViewById(R.id.moviesImageView); imageButton=itemView.findViewById(R.id.moviesImgButton); CardView cardView = itemView.findViewById(R.id.moviesCardView); cardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int position=getAdapterPosition(); Intent intent = new Intent(v.getContext(), MovieDetailsActivity.class); intent.putExtra("movieId",movieList.get(position).getMovieId()); v.getContext().startActivity(intent); } }); } } } <file_sep>package com.example.mymovies; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Spinner; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import com.google.android.material.textfield.TextInputLayout; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; public class EditProfileActivity extends AppCompatActivity { private static final Pattern PASSWORD_PATTERN=Pattern.compile("^"+"(?=.*[0-9])"+"(?=.*[a-z])"+"(?=.*[A-Z])"+".{4,}"+"$"); TextInputLayout textInputLayoutFirstnameEdit, textInputLayoutLastnameEdit,textInputLayoutPasswordEdit,textInputLayoutConfirmPasswordEdit; RadioButton genderEdit; RadioGroup radioGroup; Spinner originEdit; Button btnEditProfileAct; User user; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_profile); final Intent intent = getIntent(); if (intent.hasExtra("user")) { user = (User) intent.getSerializableExtra("user"); textInputLayoutFirstnameEdit = findViewById(R.id.textInputLayoutFirstnameEdit); textInputLayoutFirstnameEdit.getEditText().setText(user.getFirstname()); textInputLayoutLastnameEdit = findViewById(R.id.textInputLayoutLastnameEdit); textInputLayoutLastnameEdit.getEditText().setText(user.getLastname()); if (user.getGender().equals("Male")) { genderEdit = findViewById(R.id.radioBtnMaleEdit); genderEdit.setChecked(true); } else { genderEdit = findViewById(R.id.radioBtnFemaleEdit); genderEdit.setChecked(true); } originEdit = findViewById(R.id.spinnerOriginEdit); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.countries_array, android.R.layout.simple_spinner_dropdown_item); originEdit.setAdapter(adapter); adapter = (ArrayAdapter<CharSequence>) originEdit.getAdapter(); int position = adapter.getPosition(user.getOrigin()); originEdit.setSelection(position); textInputLayoutPasswordEdit = findViewById(R.id.textInputLayoutPasswordEdit); textInputLayoutPasswordEdit.getEditText().setText(user.getPassword()); textInputLayoutConfirmPasswordEdit = findViewById(R.id.textInputLayoutConfirmPassEdit); textInputLayoutConfirmPasswordEdit.getEditText().setText(user.getPassword()); btnEditProfileAct = findViewById(R.id.btnEditProfileAct); btnEditProfileAct.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (validateFirstname() & validateLastname() & validatePassword() & validateConfirmPassword()) { radioGroup = findViewById(R.id.radioBtnGroupEdit); final RadioButton radioButtonSelected = findViewById(radioGroup.getCheckedRadioButtonId()); SharedPreferences mySettings = getSharedPreferences("prefs", 0); final String email = mySettings.getString("email", null); final DatabaseReference myRef = FirebaseDatabase.getInstance().getReference("MyMovies"); myRef.keepSynced(true); myRef.child("Users").addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { for (DataSnapshot dn : snapshot.getChildren()) { final User user = dn.getValue(User.class); if (user.getEmail().equals(email)) { myRef.child("Users").child(user.getUid()); Map<String, Object> updates = new HashMap<String, Object>(); updates.put("email",user.getEmail()); updates.put("firstname", textInputLayoutFirstnameEdit.getEditText().getText().toString()); updates.put("gender", radioButtonSelected.getText().toString()); updates.put("lastname", textInputLayoutLastnameEdit.getEditText().getText().toString()); updates.put("origin", originEdit.getSelectedItem().toString()); updates.put("password", textInputLayoutPasswordEdit.getEditText().getText().toString()); updates.put("uid",user.getUid()); myRef.child("Users").child(user.getUid()).setValue(updates); } } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); finish(); } } }); } } private boolean validateFirstname() { textInputLayoutFirstnameEdit=findViewById(R.id.textInputLayoutFirstnameEdit); String firstname=textInputLayoutFirstnameEdit.getEditText().getText().toString().trim(); if (firstname.isEmpty()){ textInputLayoutFirstnameEdit.setError("Field can't be empty!"); return false; }else {textInputLayoutFirstnameEdit.setError(null); return true; } } private boolean validateLastname() { textInputLayoutLastnameEdit=findViewById(R.id.textInputLayoutLastnameEdit); String lastname=textInputLayoutLastnameEdit.getEditText().getText().toString().trim(); if (lastname.isEmpty()){ textInputLayoutLastnameEdit.setError("Field can't be empty!"); return false; }else {textInputLayoutLastnameEdit.setError(null); return true; } } private boolean validatePassword(){ textInputLayoutPasswordEdit=findViewById(R.id.textInputLayoutPasswordEdit); String password = textInputLayoutPasswordEdit.getEditText().getText().toString().trim(); if (password.isEmpty()){ textInputLayoutPasswordEdit.setError("Field can't be empty!"); return false;} else if(!PASSWORD_PATTERN.matcher(password).matches()){ textInputLayoutPasswordEdit.setError("Password too week!"); return false; }else{ textInputLayoutPasswordEdit.setError(null); return true; } } private boolean validateConfirmPassword() { textInputLayoutConfirmPasswordEdit = findViewById(R.id.textInputLayoutConfirmPassEdit); String confirmPass = textInputLayoutConfirmPasswordEdit.getEditText().getText().toString().trim(); textInputLayoutPasswordEdit = findViewById(R.id.textInputLayoutPasswordEdit); String password = textInputLayoutPasswordEdit.getEditText().getText().toString().trim(); if (confirmPass.isEmpty()) { textInputLayoutConfirmPasswordEdit.setError("Field can't be empty!"); return false; } else if (!confirmPass.equals(password)) { textInputLayoutConfirmPasswordEdit.setError("Password doesn't match!"); return false; } else { textInputLayoutConfirmPasswordEdit.setError(null); return true; } } }
110589a953539a3b48c8ae4e9fee698df31c3597
[ "Markdown", "Java" ]
14
Java
andreeaplesa/Proiect-Android
1dedfcb9038d675dde2a919db3e7186656f71272
2994630f080190561d3e50c36ea157d570ef96db
refs/heads/master
<repo_name>sanchguy/CocosCreator_UIFrameWork<file_sep>/assets/Script/UIScript/UISetting.ts import UISetting_Auto from "../AutoScripts/UISetting_Auto"; import AdapterMgr from "../UIFrame/AdapterMgr"; import CocosHelper from "../UIFrame/CocosHelper"; import { UIWindow } from "../UIFrame/UIForm"; import UIPop from "./UIPop"; const {ccclass, property} = cc._decorator; @ccclass export default class UISetting extends UIWindow { willDestory = true; static prefabPath = "Forms/Windows/UISetting"; view: UISetting_Auto; // onLoad () {} start () { this.view.Close.addClick(() => { this.closeSelf(); }, this); this.view.Pop.addClick(() => { UIPop.openView(1); }, this); } async showEffect() { let len = AdapterMgr.inst.visibleSize.height/2 + 300; this.node.y = len; await CocosHelper.runTweenSync(this.node, cc.tween().to(0.5, {y: 0}, cc.easeBackOut())); } async hideEffect() { let len = AdapterMgr.inst.visibleSize.height/2 + 300; this.node.y = 0; await CocosHelper.runTweenSync(this.node, cc.tween().to(0.3, {y: len}, cc.easeBackIn())); } // update (dt) {} } <file_sep>/assets/Script/UIFrame/lib/aa-mobx.d.ts type IObservableMapInitialValues<K, V> = IMapEntries<K, V> | KeyValueMap<V> | IMap<K, V> // interface IMobxConfigurationOptions { // +enforceActions?: boolean | "strict", // computedRequiresReaction?: boolean, // isolateGlobalState?: boolean, // disableErrorBoundaries?: boolean, // arrayBuffer?: number, // reactionScheduler?: (f: () => void) => void // } interface IMobxConfigurationOptions { } declare function configure(options: IMobxConfigurationOptions): void interface IAutorunOptions { delay?: number, name?: string, scheduler?: (callback: () => void) => any, onError?: (error: any) => void } interface IReactionOptions extends IAutorunOptions { fireImmediately?: boolean, equals?: IEqualsComparer<any> } interface IInterceptable<T> { interceptors: IInterceptor<T>[] | any, intercept(handler: IInterceptor<T>): Lambda } type IEqualsComparer<T> = (a: T, b: T) => boolean type IInterceptor<T> = (change: T) => T type IMapEntry<K, V> = [K, V] type IMapEntries<K, V> = IMapEntry<K, V>[] interface IMap<K, V> { clear(): void, delete(key: K): boolean, forEach(callbackfn: (value: V, index: K, map: IMap<K, V>) => void, thisArg?: any): void, get(key: K): V | any, has(key: K): boolean, set(key: K, value?: V): any, size: number } declare function isObservableMap(x: any): boolean interface IComputedValueOptions<T> { get?: () => T, set?: (value: T) => void, name?: string, equals?: IEqualsComparer<T>, context?: any } interface IComputed { <T>(func: () => T, setter?: (value: T) => void): IComputedValue<T>, <T>(func: () => T, options: IComputedValueOptions<T>): IComputedValue<T>, (target: Object, key: string, baseDescriptor?: PropertyDescriptor): void, struct(target: Object, key: string, baseDescriptor?: PropertyDescriptor): void } interface IDependencyTree { name: string, dependencies?: IDependencyTree[] } interface IObserverTree { name: string, observers?: IObserverTree[] } interface IAtom { reportObserved: () => void, reportChanged: () => void } interface IComputedValue<T> { get(): T, set(value: T): void, observe(listener: (newValue: T, oldValue: T) => void, fireImmediately?: boolean): Lambda } interface IObservable { } interface IDepTreeNode { name: string, observing?: IObservable[] } interface IDerivation { name: string } interface IReactionPublic { dispose: () => void, trace: (enterBreakPoint?: boolean) => void } declare class IListenable { observe(handler: (change: any, oldValue?: any) => void, fireImmediately?: boolean): Lambda } interface IObservableArray<T> extends Array<T> { spliceWithArray(index: number, deleteCount?: number, newItems?: T[]): T[], observe( listener: (changeData: IArrayChange<T> | IArraySplice<T>) => void, fireImmediately?: boolean ): Lambda, intercept(handler: IInterceptor<IArrayWillChange<T> | IArrayWillSplice<T>>): Lambda, intercept(handler: IInterceptor<IArrayChange<T> | IArraySplice<T>>): Lambda, intercept<T>(handler: IInterceptor<IArrayChange<T> | IArraySplice<T>>): Lambda, clear(): T[], replace(newItems: T[]): T[], find( predicate: (item: T, index: number, array: Array<T>) => boolean, thisArg?: any, fromIndex?: number ): T | any, findIndex( predicate: (item: T, index: number, array: Array<T>) => boolean, thisArg?: any, fromIndex?: number ): number, remove(value: T): boolean } interface IArrayChange<T> { type: "update", object: IObservableArray<T>, index: number, newValue: T, oldValue: T } interface IArraySplice<T> { type: "splice", object: IObservableArray<T>, index: number, added: T[], addedCount: number, removed: T[], removedCount: number } interface IArrayWillChange<T> { type: "update", object: IObservableArray<T>, index: number, newValue: T } interface IArrayWillSplice<T> { type: "splice", object: IObservableArray<T>, index: number, added: T[], removedCount: number } type KeyValueMap<V> = { [key: string]: V } interface IMapChange<K, T> { object: ObservableMap<K, T>, type: "update" | "add" | "delete", name: K, newValue?: any, oldValue?: any } interface IMapWillChange<K, T> { object: ObservableMap<K, T>, type: "update" | "add" | "delete", name: K, newValue?: any } interface IObservableObject { } interface IObjectChange { name: string, object: any, type: "update" | "add" | "remove", oldValue?: any, newValue: any } interface IObjectWillChange { object: any, type: "update" | "add" | "remove", name: string, newValue: any } interface IValueWillChange<T> { object: any, type: "update", newValue: T } interface IValueDidChange<T> extends IValueWillChange<T> { oldValue?: T } interface IObservableValue<T> { get(): T, set(value: T): void, intercept(handler: IInterceptor<IValueWillChange<T>>): Lambda, observe(listener: (change: IValueDidChange<T>) => void, fireImmediately?: boolean): Lambda } interface IEnhancer<T> { (newValue: T, oldValue: T | void, name: string): T } interface IObservableFactory { // observable overloads (target: Object, key: string, baseDescriptor?: PropertyDescriptor): any, <T>(value: Array<T>): IObservableArray<T>, <T>(value: null | void): IObservableValue<T>, (value: null | void): IObservableValue<any>, <T>(value: IMap<string | number | boolean, T>): ObservableMap<T, any>, <T, Object>(value: T): T } type IObservableDecorator = { (target: Object, property: string, descriptor?: PropertyDescriptor): void, enhancer: IEnhancer<any> } type CreateObservableOptions = { name?: string, deep?: boolean, defaultDecorator?: IObservableDecorator } declare class IObservableFactories { box<T>(value?: T, options?: CreateObservableOptions): IObservableValue<T> array<T>(initialValues?: T[], options?: CreateObservableOptions): IObservableArray<T> map<K, V>( initialValues?: IObservableMapInitialValues<K, V>, options?: CreateObservableOptions ): ObservableMap<K, V> object<T>(props: T, options?: CreateObservableOptions): T & IObservableObject ref(target: Object, property?: string, descriptor?: PropertyDescriptor): IObservableDecorator shallow( target: Object, property?: string, descriptor?: PropertyDescriptor ): IObservableDecorator deep(target: Object, property?: string, descriptor?: PropertyDescriptor): IObservableDecorator } interface Iterator<T> { next(): { done: boolean, value?: T } } interface Lambda { (): void, name?: string } interface IActionFactory { (a1: any, a2?: any, a3?: any, a4?: any, a6?: any): any, bound(target: Object, propertyKey: string, descriptor?: PropertyDescriptor): void } declare class ObservableMap<K, V> { constructor(initialData?: IMapEntries<K, V> | KeyValueMap<V>, valueModeFunc?: Function); has(key: K): boolean set(key: K, value: V): void delete(key: K): boolean get(key: K): V keys(): Iterator<K> values(): Iterator<V> entries(): IMapEntries<K, V> & Iterator<IMapEntry<K, V>> forEach(callback: (value: V, key: K, object: KeyValueMap<V>) => void, thisArg?: any): void merge(other: ObservableMap<K, V> | KeyValueMap<V>): ObservableMap<K, V> clear(): void replace(other: ObservableMap<K, V> | KeyValueMap<V>): ObservableMap<K, V> size: number toJS(): Map<K, V> toPOJO(): KeyValueMap<V> toJSON(): KeyValueMap<V> toString(): string observe(listener: (changes: IMapChange<K, V>) => void, fireImmediately?: boolean): Lambda intercept(handler: IInterceptor<IMapWillChange<K, V>>): Lambda } declare function action( targetOrName: any, propertyKeyOrFuc?: any, descriptor?: PropertyDescriptor ): any declare function action<T>(name: string, func: T): T declare function action<T>(func: T): T declare function runInAction<T>(name: string, block: () => T): T declare function runInAction<T>(block: () => T): T declare function isAction(thing: any): boolean declare function autorun( nameOrFunction: string | ((r: IReactionPublic) => any), options?: IAutorunOptions ): any declare function reaction<T>( expression: (r: IReactionPublic) => T, effect: (arg: T, r: IReactionPublic) => void, opts?: IReactionOptions ): any interface IWhenOptions { name?: string, timeout?: number, onError?: (error: any) => void } declare function when(cond: () => boolean, effect: Lambda, options?: IWhenOptions): any declare function when(cond: () => boolean, options?: IWhenOptions): Promise<any> declare function computed<T>( target: any, key?: string, baseDescriptor?: PropertyDescriptor ): any declare function extendObservable<A, B>( target: A, properties: B, decorators?: any, options?: any ): A & B declare function intercept( object: Object, property: string, handler: IInterceptor<any> ): Lambda declare function isComputed(value: any): boolean declare function isComputedProp(value: any, property: string): boolean declare function isObservable(value: any): boolean declare function isObservableProp(value: any, property: string): boolean declare var observable: IObservableFactory & IObservableFactories & { deep: { struct<T>(initialValue?: T): T }, ref: { struct<T>(initialValue?: T): T } } declare function observe<T>( value: IObservableValue<T> | IComputedValue<T>, listener: (change: IValueDidChange<T>) => void, fireImmediately?: boolean ): Lambda declare function observe<T>( observableArray: IObservableArray<T>, listener: (change: IArrayChange<T> | IArraySplice<T>) => void, fireImmediately?: boolean ): Lambda declare function observe<K, T>( observableMap: ObservableMap<K, T>, listener: (change: IMapChange<K, T>) => void, fireImmediately?: boolean ): Lambda declare function observe<K, T>( observableMap: ObservableMap<K, T>, property: string, listener: (change: IValueDidChange<T>) => void, fireImmediately?: boolean ): Lambda declare function observe( object: any, listener: (change: IObjectChange) => void, fireImmediately?: boolean ): Lambda declare function observe( object: any, property: string, listener: (change: IValueDidChange<any>) => void, fireImmediately?: boolean ): Lambda interface ToJSOptions { detectCycles?: boolean, exportMapsAsObjects?: boolean } declare function toJS<T>(source: T, options?: ToJSOptions): T declare function untracked<T>(action: () => T): T declare function spy(listener: (change: any) => void): Lambda declare function transaction<T>(action: () => T, thisArg?: any, report?: boolean): T declare function isObservableArray(thing: any): boolean declare function isObservableObject<T>(thing: T): boolean declare function isArrayLike(x: any): boolean declare class Reaction { name: string isDisposed: boolean constructor(name: string, onInvalidate: () => void) schedule(): void isScheduled(): boolean track(fn: () => void): void dispose(): void getDisposer(): Lambda & { $mosbservable: Reaction } toString(): string trace(enterBreakPoint?: boolean): void } declare function createAtom( name: string, onBecomeObservedHandler?: () => void, onBecomeUnobservedHandler?: () => void ): IAtom declare function decorate<T>(target: T, decorators: any): T declare function flow<T>(fn: (...args: any[]) => T): (...args: any[]) => Promise<T> declare function flow<T>( name: string, fn: (...args: any[]) => T ): (...args: any[]) => Promise<T> declare function keys<K>(map: ObservableMap<K, any>): K[] declare function keys(obj: any): string[] declare function values<K, T>(map: ObservableMap<K, T>): T[] declare function values<T>(ar: IObservableArray<T>): T[] declare function values(obj: any): any[] declare function set<V>(obj: ObservableMap<string, V>, values: { [key: string]: V }): void declare function set<K, V>(obj: ObservableMap<K, V>, key: K, value: V): void declare function set<T>(obj: IObservableArray<T>, index: number, value: T): void declare function set(obj: any, values: { [key: string]: any }): void declare function set(obj: any, key: string, value: any): void declare function remove<K, V>(obj: ObservableMap<K, V>, key: K): void declare function remove<T>(obj: IObservableArray<T>, index: number): void declare function remove(obj: any, key: string): void declare function has<K>(obj: ObservableMap<K, any>, key: K): boolean declare function has<T>(obj: IObservableArray<T>, index: number): boolean declare function has(obj: any, key: string): boolean declare function get<K, V>(obj: ObservableMap<K, V>, key: K): V | void declare function get<T>(obj: IObservableArray<T>, index: number): T | void declare function get(obj: any, key: string): any declare function onReactionError( handler: (error: any, derivation: IDerivation) => void ): () => void declare function onBecomeObserved( value: IObservable | IComputedValue<any> | IObservableArray<any> | ObservableMap<any, any>, listener: Lambda ): Lambda declare function onBecomeObserved<K>( value: ObservableMap<K, any> | Object, property: K, listener: Lambda ): Lambda declare function onBecomeUnobserved( value: IObservable | IComputedValue<any> | IObservableArray<any> | ObservableMap<any, any>, listener: Lambda ): Lambda declare function onBecomeUnobserved<K>( value: ObservableMap<K, any> | Object, property: K, listener: Lambda ): Lambda declare function getAtom(thing: any, property?: string): IDepTreeNode declare function getDebugName(thing: any, property?: string): string declare function getDependencyTree(thing: any, property?: string): IDependencyTree declare function getObserverTree(thing: any, property?: string): IObserverTree <file_sep>/assets/Script/UIScript/UISound.ts import AdapterMgr, { AdaptaterType } from "../UIFrame/AdapterMgr"; import { UIFixed } from "../UIFrame/UIForm"; const {ccclass, property} = cc._decorator; @ccclass export default class UISound extends UIFixed { static prefabPath = "Forms/Fixed/UISound" // LIFE-CYCLE CALLBACKS: // onLoad () {} start () { AdapterMgr.inst.adapatByType(AdaptaterType.Right, this.node); AdapterMgr.inst.adapatByType(AdaptaterType.Top, this.node); } // update (dt) {} } <file_sep>/assets/Script/UIScript/UITips.ts import UITips_Auto from "../AutoScripts/UITips_Auto"; import UIBase from "../UIFrame/UIBase"; const {ccclass, property} = cc._decorator; @ccclass export default class UITips extends UIBase { static prefabPath = "Forms/Windows/UITips" view: UITips_Auto; // onLoad () {} start () { } onShow(str: string) { this.view.Tips.string = str; } // update (dt) {} } <file_sep>/README.md ## 使用过程中有任何问题 可以添加我的QQ 1099263878 ### Cocos Creator交流群: 521643513 # 基于cocos creator的UI框架, 当前使用的cocos creator版本2.4.3版本 中心思想, 将所有的UI窗体分为4类管理(screen窗体, 固定窗体, 弹出窗体, 独立窗体), 再将窗体制作成预制体, 动态加载与释放; 使用UIManager.getInstance().openUIForm("窗体名字"); 显示窗体 -Scene(管理UIManager) -- UIROOT(UIManager脚本挂载结点) ---- screen(普通窗体) ---- fixed(固定窗体) ---- popup(弹出窗体) ---- TopTips(独立窗体) 不同类型的窗体放置在不同的节点上, 统一管理 - UIManager.ts 核心脚本,包括了加载,显示,隐藏窗体等功能. - UIBase.ts 包好了生命周期函数,如load,init,onShow,onHide等 - AdapterMgr.ts 适配管理 - ModalMgr.ts - UIModalScript.ts 弹窗模态层管理 - EventCenter.ts 事件管理 - ResMgr.ts 资源管理,包括加载释放等 - SoundMgr.ts 音频管理,包括播放,暂停,声音大小,本地保存等 - Binder.ts 自动绑定结点, 通过特殊的结点命名方式 ## 使用方法 下载本项目后, 将assets\Script下的UIFrame文件夹拷贝到自己的项目, 如果你希望使用ButtonPlus和MaskPlus等扩展组件, 那么还需将packages下的文件夹拷贝到你的项目packages下 新建一个预制体,并将其放在resources目录下. 在新建一个脚本继承于UIBase, 重写prefabPath指定预制体路径(注意: prefabPath需要使用static声明)和窗体类型formType, 将脚本挂载在预制体根节点上. ``` 这是项目中的例子, 继承UIBase,重写prefabPath和formType. const {ccclass, property} = cc._decorator; @ccclass export default class UIHall extends UIBase { static prefabPath = "UIForms/UIHall"; // resources下的路径 public formType = FormType.Screen; // 窗体类型 ... } ``` 最后使用UIHall.openView(); 既可. 项目结点都是动态生成的, 使用UIManger.getInstance()时就会动态创建Scene结点和UIROOT等结点. # 基本功能 ![](https://github.com/kirikayakazuto/UIFrameWorld/blob/master/yanshi.png) 我们将这个场景分成5个部分, 1, 表示Top部分的玩家信息 2, 表示左侧的玩家列表 3, 表示房间入口按钮 4, 表示底部的功能列表 5, 表示背景 前4个我们将其挂载在Fixed结点上, 5号挂载在Normal结点上并设置HideOther属性然后使用AdapterMgr组件使结点在个个位置适配 演示视屏: 暂无 ## 2021/01/31 Binder plus, 升级了项目中的自动结点绑定 注意: 目前第一次生成脚本时无法立即绑定到对应结点上, 需要再次执行一次run 即可. 支持代码生成和结点绑定 ![](https://github.com/kirikayakazuto/UIFrameWorld/blob/master/doc/autobinder.gif) ## 2020/10/19 Mask Plus, 支持自定义遮罩 扩展了cc.Mask, 添加了一种枚举类型Polygon ![](https://github.com/kirikayakazuto/UIFrameWorld/blob/master/doc/addMaskPlus.gif) ## 2020/10/15 添加2d光线功能 2d光影效果, 项目在2dlight分支, 目前还在优化中 关键代码在Script/Common/light下, 有兴趣的可以看看, ![](https://github.com/kirikayakazuto/UIFrameWorld/blob/master/doc/2dlight.png) ## 2020/7/28 集成ECharts 集成了ECharts, 在ECharts-Support分支, 有需要的可以看看 ## 2020/7/10 新增功能 集成Mobx,对于Mobx的使用详情可以前往Mobx的官网了解,github地址 https://github.com/mobxjs/mobx 对于cocos使用例子可以看项目中UIHall的实现 注意事项:将mobx导入为插件时需要将允许编辑器加载打上勾✅ ## 2020/5/10 项目结构修改 UIManager -> UIBase UIManager控制UIBase的加载,释放,显示,隐藏 UIMaskManager -> UIMaskScript UIMaskManager控制UIMaskScript的显示,隐藏 UIBase继承UIBinder,默认自动绑定UI节点,添加onShow, onHide,showAnimation, hideAnimation的接口 生命周期 load -> onShow -> onLoad -> start -> onHide -> onDestory EventCenter替换GEventManager,EventCenter使用双层Map,优化了emit的速度 去掉了一些冗余属性和方法,优化了属性,方法名称,精简才是王道 ## 2019/10/16 新增功能 1, 将BaseUIBinder分离出来作为BaseUIView的父类, 如果希望使用BaseUIBinder的功能, 请为你的结点添加BaseUIView组件, 你也可以自己继承BaseUIBinder, 然后调用_preInit方法 为什么这么做? 对于UIForm的控制我尝试过多种方法, 这一次是希望实现一个类似MVC的控制结构, 对于一个UIForm, 我们为其添加C(控制)和V(视图)组件 例如, 我在LoginForm预制体添加的组件一样, 将Form的动画, 显示放在View脚本中, 而事件的监听, 游戏逻辑则放在Control脚本中, 当然View脚本不是必须的 你也可以只实现Control脚本 2, 场景切换(在本单场景管理, 即是Normal结点的更换), 添加加载过度动画 如何使用: 1, 在游戏的Main脚本中设置UIIndependentManager.getInstance().setLoadingForm("UIForm/LoadingForm"); 过度场景 2, 在加载场景时使用UIManager.GetInstance().ShowUIFormWithLoading("UIForm/HallForm"); 如上, 在HallForm中需要提前加载的UIform或者其他资源, 可以放在HallForm的load方法中, 这样就会在load内资源加载完毕, 在关闭LoadingForm, 完美实现场景切换 3, 新增了Independent结点与类型 Independent类似常驻结点, 是独立于其他窗体的特殊窗体, 不会受到其他窗体的影响, 例如加载过度窗体, 就属于独立窗体, 不会因为其他窗体设置了HideOther属性就将其隐藏 ## 2019年9月26日新增功能 扩展button, 为button组件添加了 1. 点击button播放音效 2. 屏蔽连续点击 需要注意的是, ButtonPlus.ts需要配合插件使用, 插件路径位于UIFrameWorld\packages\buttonplus, 原因是 在ButtonPlus中@inspector('packages://buttonplus/inspector.js'), 需要引入插件中的inspector.js, 用户也可以在inspector自定义编辑器上ButtonPlus显示格式. ## 2019年9月19日新增功能 添加UIHelper自动绑定规范命名的结点, UIHelper的功能, 在用脚本控制UI的 时候, 绑定UI是一件很烦人的事情, 尤其是将UI拖到面板上绑定, 就更加繁琐, 或者在onload, start上 使用getChildByName() 或者cc.find() 查找结点, 又会显得代码冗长大部分时候, 在我创建这个结点的时候, 我就已经想好要让这个结点完成什么功能了(针对渲染结点), 所有我希望在取名字的时候,通过特殊的命名规则, 就可以在脚本中直接使用此结点, UIHelper就来完成此功能 1. 给结点取一个规范的名字, 例如 _Label$NickName _Sprite&HeadImage 我分别解释每一部分的意思 * _表示这个结点需要被自动绑定 * Label表示脚本中属性的类型 * $表示分隔符, 后面紧接这个表示变量名字 * NickName就表示这个变量的名字 所以在脚本中, 你可以通过 this._Labels.NickName 获得这个结点上的cc.Label组件 需要注意的是 自动绑定的结点必须是是挂载脚本的结点或者子节点, 如图 ![](https://github.com/kirikayakazuto/UIFrameWorld/blob/master/UIBind_dist.png) 只会在BindTest结点的子节点自动绑定结点, 那么我现在有一个结点希望自动绑定, 但是其父节点没有挂载脚本, 怎么办呢. UIHelper还提供了了bindNode()方法, 将对方结点或者其父节点传入, 那么你就可以在其他脚本将结点自动绑定 还需要注意的是 重复绑定, 因为每次进行查询绑定操作时, 都会对其所有的子节点进行查找, 所有可能会出现重复绑定! ## 8月3日新增功能 BaseUIForm中添加CloseAndDestory属性, 当此属性为true时, 关闭此窗体将会销毁此结点,并且释放结点资源 对于已经显示的窗体, 不会二次显示 <file_sep>/assets/Script/Common/BroadCasts/TmpBroadCast.ts import { Broadcast } from "../../UIFrame/BroadCast"; export class TestData { id: number; name: string; } export class TestBroadcast { static testData = new Broadcast<TestData>(); }
9a99218aa71ea8a0345ac64467054298bf7a9d8e
[ "Markdown", "TypeScript" ]
6
TypeScript
sanchguy/CocosCreator_UIFrameWork
9c7cfab7c5219f52a83d93f83135b5fde1405940
c2fa689a8cc3969d59960e911b9d088beadad27c
refs/heads/master
<repo_name>monisha2214/c-programs<file_sep>/swaping.c #include<stdio.h> #include<conio.h> void main() { int x,y,temp; clrscr(); printf("enter two integer values\n") scanf("%d%d",&x,&y); printf("before swaping \n first integer=%d \n second integer=%d \n",x,y); temp=x; x=y; y=temp; printf("after swaping \n first integer=%d \n second integer=%d \n"x,y); return=0 } <file_sep>/time_greeter_using_only_if.c #include<stdio.h> #include<conio.h> void main() { int time; char night[] = "Good night guys!"; char morning[] = "Good morning guys!"; char afternoon[] = "Good afternoon guys!"; char evening[] = "Good evening guys!"; printf("Enter the time in 24H format: \n"); scanf("%d",&time); printf("The time you have entered is %d \n",time); if(time>=0 && time<5) { printf("%s\n",night); } else if(time>=5 && time<12) { printf("%s\n",morning); } else if(time>=12 && time<16) { printf("%s\n",afternoon); } else if(time>=16 && time<19) { printf ("%s\n",evening); } else if(time>=19 && time<24) { printf("%s\n",night); } } <file_sep>/addition_and_subtraction_using_switch.c #include <stdio.h> int main () { int choice, firstNumber, secondNumber, result; printf("1. Addition\n2. Subtraction\nPlease enter your choice:"); scanf("%d", &choice); if(choice > 0 || choice <= 2) { printf("Yes you have entered a valid choice\n"); printf("Your entered choice is %d\n", &choice); } printf("please enter two numbers:"); scanf("%d %d", &firstNumber, &secondNumber); switch (choice) { case 1: result = firstNumber+secondNumber; printf("addition of two numbers is %d", &result); break; case 2: result = firstNumber - secondNumber; printf("subtraction of two numbers is %d", &result); break; default: printf("invalid input\n"); } return 0; }
ecda63baacd1063ce2a30580f12b983fc2650c58
[ "C" ]
3
C
monisha2214/c-programs
40ee1961c7d4127870d69e92971fe26bc7519bce
801645f713f9ab943a407df3482c49d6135180c5
refs/heads/master
<repo_name>brad-jones/teamcity-playground<file_sep>/ts-schema/schema/rest-api/deno/types/ObjectParamAPI.ts import { ResponseContext, RequestContext, HttpFile } from '../http/http.ts'; import * as models from '../models/all.ts'; import { Configuration} from '../configuration.ts' import { Agent } from '../models/Agent.ts'; import { AgentLocator } from '../models/AgentLocator.ts'; import { AgentPool } from '../models/AgentPool.ts'; import { AgentPoolLocator } from '../models/AgentPoolLocator.ts'; import { AgentPools } from '../models/AgentPools.ts'; import { AgentRequirement } from '../models/AgentRequirement.ts'; import { AgentRequirements } from '../models/AgentRequirements.ts'; import { Agents } from '../models/Agents.ts'; import { ArtifactDependencies } from '../models/ArtifactDependencies.ts'; import { ArtifactDependency } from '../models/ArtifactDependency.ts'; import { AuditAction } from '../models/AuditAction.ts'; import { AuditEvent } from '../models/AuditEvent.ts'; import { AuditEvents } from '../models/AuditEvents.ts'; import { AuditLocator } from '../models/AuditLocator.ts'; import { AuthorizedInfo } from '../models/AuthorizedInfo.ts'; import { Branch } from '../models/Branch.ts'; import { BranchLocator } from '../models/BranchLocator.ts'; import { BranchVersion } from '../models/BranchVersion.ts'; import { Branches } from '../models/Branches.ts'; import { Build } from '../models/Build.ts'; import { BuildCancelRequest } from '../models/BuildCancelRequest.ts'; import { BuildChange } from '../models/BuildChange.ts'; import { BuildChanges } from '../models/BuildChanges.ts'; import { BuildLocator } from '../models/BuildLocator.ts'; import { BuildQueueLocator } from '../models/BuildQueueLocator.ts'; import { BuildTriggeringOptions } from '../models/BuildTriggeringOptions.ts'; import { BuildType } from '../models/BuildType.ts'; import { BuildTypeLocator } from '../models/BuildTypeLocator.ts'; import { BuildTypes } from '../models/BuildTypes.ts'; import { Builds } from '../models/Builds.ts'; import { Change } from '../models/Change.ts'; import { ChangeLocator } from '../models/ChangeLocator.ts'; import { Changes } from '../models/Changes.ts'; import { CloudImage } from '../models/CloudImage.ts'; import { CloudImages } from '../models/CloudImages.ts'; import { CloudInstance } from '../models/CloudInstance.ts'; import { CloudInstances } from '../models/CloudInstances.ts'; import { CloudProfile } from '../models/CloudProfile.ts'; import { CloudProfiles } from '../models/CloudProfiles.ts'; import { Comment } from '../models/Comment.ts'; import { Compatibilities } from '../models/Compatibilities.ts'; import { Compatibility } from '../models/Compatibility.ts'; import { CompatibilityPolicy } from '../models/CompatibilityPolicy.ts'; import { Customizations } from '../models/Customizations.ts'; import { Datas } from '../models/Datas.ts'; import { EnabledInfo } from '../models/EnabledInfo.ts'; import { Entries } from '../models/Entries.ts'; import { Entry } from '../models/Entry.ts'; import { Environment } from '../models/Environment.ts'; import { Feature } from '../models/Feature.ts'; import { Features } from '../models/Features.ts'; import { File } from '../models/File.ts'; import { FileChange } from '../models/FileChange.ts'; import { FileChanges } from '../models/FileChanges.ts'; import { Files } from '../models/Files.ts'; import { Group } from '../models/Group.ts'; import { Groups } from '../models/Groups.ts'; import { Href } from '../models/Href.ts'; import { Investigation } from '../models/Investigation.ts'; import { InvestigationLocator } from '../models/InvestigationLocator.ts'; import { Investigations } from '../models/Investigations.ts'; import { Issue } from '../models/Issue.ts'; import { IssueUsage } from '../models/IssueUsage.ts'; import { Issues } from '../models/Issues.ts'; import { IssuesUsages } from '../models/IssuesUsages.ts'; import { Items } from '../models/Items.ts'; import { LicenseKey } from '../models/LicenseKey.ts'; import { LicenseKeys } from '../models/LicenseKeys.ts'; import { LicensingData } from '../models/LicensingData.ts'; import { Link } from '../models/Link.ts'; import { Links } from '../models/Links.ts'; import { MetaData } from '../models/MetaData.ts'; import { Metric } from '../models/Metric.ts'; import { MetricTag } from '../models/MetricTag.ts'; import { MetricTags } from '../models/MetricTags.ts'; import { MetricValue } from '../models/MetricValue.ts'; import { MetricValues } from '../models/MetricValues.ts'; import { Metrics } from '../models/Metrics.ts'; import { MultipleOperationResult } from '../models/MultipleOperationResult.ts'; import { Mute } from '../models/Mute.ts'; import { MuteLocator } from '../models/MuteLocator.ts'; import { Mutes } from '../models/Mutes.ts'; import { NewBuildTypeDescription } from '../models/NewBuildTypeDescription.ts'; import { NewProjectDescription } from '../models/NewProjectDescription.ts'; import { OperationResult } from '../models/OperationResult.ts'; import { ParsedTestName } from '../models/ParsedTestName.ts'; import { Permission } from '../models/Permission.ts'; import { PermissionAssignment } from '../models/PermissionAssignment.ts'; import { PermissionAssignments } from '../models/PermissionAssignments.ts'; import { PermissionRestriction } from '../models/PermissionRestriction.ts'; import { PermissionRestrictions } from '../models/PermissionRestrictions.ts'; import { PinInfo } from '../models/PinInfo.ts'; import { Plugin } from '../models/Plugin.ts'; import { Plugins } from '../models/Plugins.ts'; import { Problem } from '../models/Problem.ts'; import { ProblemLocator } from '../models/ProblemLocator.ts'; import { ProblemOccurrence } from '../models/ProblemOccurrence.ts'; import { ProblemOccurrenceLocator } from '../models/ProblemOccurrenceLocator.ts'; import { ProblemOccurrences } from '../models/ProblemOccurrences.ts'; import { ProblemScope } from '../models/ProblemScope.ts'; import { ProblemTarget } from '../models/ProblemTarget.ts'; import { Problems } from '../models/Problems.ts'; import { ProgressInfo } from '../models/ProgressInfo.ts'; import { Project } from '../models/Project.ts'; import { ProjectFeature } from '../models/ProjectFeature.ts'; import { ProjectFeatures } from '../models/ProjectFeatures.ts'; import { ProjectLocator } from '../models/ProjectLocator.ts'; import { Projects } from '../models/Projects.ts'; import { Properties } from '../models/Properties.ts'; import { Property } from '../models/Property.ts'; import { Related } from '../models/Related.ts'; import { RelatedEntities } from '../models/RelatedEntities.ts'; import { RelatedEntity } from '../models/RelatedEntity.ts'; import { RepositoryState } from '../models/RepositoryState.ts'; import { Requirements } from '../models/Requirements.ts'; import { Resolution } from '../models/Resolution.ts'; import { Revision } from '../models/Revision.ts'; import { Revisions } from '../models/Revisions.ts'; import { Role } from '../models/Role.ts'; import { Roles } from '../models/Roles.ts'; import { Server } from '../models/Server.ts'; import { SnapshotDependencies } from '../models/SnapshotDependencies.ts'; import { SnapshotDependency } from '../models/SnapshotDependency.ts'; import { StateField } from '../models/StateField.ts'; import { Step } from '../models/Step.ts'; import { Steps } from '../models/Steps.ts'; import { Tag } from '../models/Tag.ts'; import { TagLocator } from '../models/TagLocator.ts'; import { Tags } from '../models/Tags.ts'; import { Test } from '../models/Test.ts'; import { TestCounters } from '../models/TestCounters.ts'; import { TestLocator } from '../models/TestLocator.ts'; import { TestOccurrence } from '../models/TestOccurrence.ts'; import { TestOccurrenceLocator } from '../models/TestOccurrenceLocator.ts'; import { TestOccurrences } from '../models/TestOccurrences.ts'; import { TestRunMetadata } from '../models/TestRunMetadata.ts'; import { Tests } from '../models/Tests.ts'; import { Token } from '../models/Token.ts'; import { Tokens } from '../models/Tokens.ts'; import { Trigger } from '../models/Trigger.ts'; import { TriggeredBy } from '../models/TriggeredBy.ts'; import { Triggers } from '../models/Triggers.ts'; import { Type } from '../models/Type.ts'; import { TypedValue } from '../models/TypedValue.ts'; import { User } from '../models/User.ts'; import { UserGroupLocator } from '../models/UserGroupLocator.ts'; import { UserLocator } from '../models/UserLocator.ts'; import { Users } from '../models/Users.ts'; import { VcsCheckStatus } from '../models/VcsCheckStatus.ts'; import { VcsLabel } from '../models/VcsLabel.ts'; import { VcsLabels } from '../models/VcsLabels.ts'; import { VcsRoot } from '../models/VcsRoot.ts'; import { VcsRootEntries } from '../models/VcsRootEntries.ts'; import { VcsRootEntry } from '../models/VcsRootEntry.ts'; import { VcsRootInstance } from '../models/VcsRootInstance.ts'; import { VcsRootInstanceLocator } from '../models/VcsRootInstanceLocator.ts'; import { VcsRootInstances } from '../models/VcsRootInstances.ts'; import { VcsRootLocator } from '../models/VcsRootLocator.ts'; import { VcsRoots } from '../models/VcsRoots.ts'; import { VcsStatus } from '../models/VcsStatus.ts'; import { ObservableAgentApi } from "./ObservableAPI.ts"; import { AgentApiRequestFactory, AgentApiResponseProcessor} from "../apis/AgentApi.ts"; export interface AgentApiDeleteAgentRequest { /** * * @type string * @memberof AgentApideleteAgent */ agentLocator: string } export interface AgentApiGetAgentRequest { /** * * @type string * @memberof AgentApigetAgent */ agentLocator: string /** * * @type string * @memberof AgentApigetAgent */ fields?: string } export interface AgentApiGetAgentFieldRequest { /** * * @type string * @memberof AgentApigetAgentField */ agentLocator: string /** * * @type string * @memberof AgentApigetAgentField */ field: string } export interface AgentApiGetAgentPoolRequest { /** * * @type string * @memberof AgentApigetAgentPool */ agentLocator: string /** * * @type string * @memberof AgentApigetAgentPool */ fields?: string } export interface AgentApiGetAllAgentsRequest { /** * * @type string * @memberof AgentApigetAllAgents */ locator?: string /** * * @type string * @memberof AgentApigetAllAgents */ fields?: string } export interface AgentApiGetAuthorizedInfoRequest { /** * * @type string * @memberof AgentApigetAuthorizedInfo */ agentLocator: string /** * * @type string * @memberof AgentApigetAuthorizedInfo */ fields?: string } export interface AgentApiGetBuildConfigurationRunPolicyRequest { /** * * @type string * @memberof AgentApigetBuildConfigurationRunPolicy */ agentLocator: string /** * * @type string * @memberof AgentApigetBuildConfigurationRunPolicy */ fields?: string } export interface AgentApiGetCompatibleBuildTypesRequest { /** * * @type string * @memberof AgentApigetCompatibleBuildTypes */ agentLocator: string /** * * @type string * @memberof AgentApigetCompatibleBuildTypes */ fields?: string } export interface AgentApiGetEnabledInfoRequest { /** * * @type string * @memberof AgentApigetEnabledInfo */ agentLocator: string /** * * @type string * @memberof AgentApigetEnabledInfo */ fields?: string } export interface AgentApiGetIncompatibleBuildTypesRequest { /** * * @type string * @memberof AgentApigetIncompatibleBuildTypes */ agentLocator: string /** * * @type string * @memberof AgentApigetIncompatibleBuildTypes */ fields?: string } export interface AgentApiSetAgentFieldRequest { /** * * @type string * @memberof AgentApisetAgentField */ agentLocator: string /** * * @type string * @memberof AgentApisetAgentField */ field: string /** * * @type string * @memberof AgentApisetAgentField */ body?: string } export interface AgentApiSetAgentPoolRequest { /** * * @type string * @memberof AgentApisetAgentPool */ agentLocator: string /** * * @type string * @memberof AgentApisetAgentPool */ fields?: string /** * * @type AgentPool * @memberof AgentApisetAgentPool */ body?: AgentPool } export interface AgentApiSetAuthorizedInfoRequest { /** * * @type string * @memberof AgentApisetAuthorizedInfo */ agentLocator: string /** * * @type string * @memberof AgentApisetAuthorizedInfo */ fields?: string /** * * @type AuthorizedInfo * @memberof AgentApisetAuthorizedInfo */ body?: AuthorizedInfo } export interface AgentApiSetBuildConfigurationRunPolicyRequest { /** * * @type string * @memberof AgentApisetBuildConfigurationRunPolicy */ agentLocator: string /** * * @type string * @memberof AgentApisetBuildConfigurationRunPolicy */ fields?: string /** * * @type CompatibilityPolicy * @memberof AgentApisetBuildConfigurationRunPolicy */ body?: CompatibilityPolicy } export interface AgentApiSetEnabledInfoRequest { /** * * @type string * @memberof AgentApisetEnabledInfo */ agentLocator: string /** * * @type string * @memberof AgentApisetEnabledInfo */ fields?: string /** * * @type EnabledInfo * @memberof AgentApisetEnabledInfo */ body?: EnabledInfo } export class ObjectAgentApi { private api: ObservableAgentApi public constructor(configuration: Configuration, requestFactory?: AgentApiRequestFactory, responseProcessor?: AgentApiResponseProcessor) { this.api = new ObservableAgentApi(configuration, requestFactory, responseProcessor); } /** * Delete an inactive agent. * @param param the request object */ public deleteAgent(param: AgentApiDeleteAgentRequest, options?: Configuration): Promise<void> { return this.api.deleteAgent(param.agentLocator, options).toPromise(); } /** * Get agent matching the locator. * @param param the request object */ public getAgent(param: AgentApiGetAgentRequest, options?: Configuration): Promise<Agent> { return this.api.getAgent(param.agentLocator, param.fields, options).toPromise(); } /** * Get a field of the matching agent. * @param param the request object */ public getAgentField(param: AgentApiGetAgentFieldRequest, options?: Configuration): Promise<string> { return this.api.getAgentField(param.agentLocator, param.field, options).toPromise(); } /** * Get the agent pool of the matching agent. * @param param the request object */ public getAgentPool(param: AgentApiGetAgentPoolRequest, options?: Configuration): Promise<AgentPool> { return this.api.getAgentPool(param.agentLocator, param.fields, options).toPromise(); } /** * Get all known agents. * @param param the request object */ public getAllAgents(param: AgentApiGetAllAgentsRequest, options?: Configuration): Promise<Agents> { return this.api.getAllAgents(param.locator, param.fields, options).toPromise(); } /** * Get the authorization info of the matching agent. * @param param the request object */ public getAuthorizedInfo(param: AgentApiGetAuthorizedInfoRequest, options?: Configuration): Promise<AuthorizedInfo> { return this.api.getAuthorizedInfo(param.agentLocator, param.fields, options).toPromise(); } /** * Get the build configuration run policy of the matching agent. * @param param the request object */ public getBuildConfigurationRunPolicy(param: AgentApiGetBuildConfigurationRunPolicyRequest, options?: Configuration): Promise<CompatibilityPolicy> { return this.api.getBuildConfigurationRunPolicy(param.agentLocator, param.fields, options).toPromise(); } /** * Get build types compatible with the matching agent. * @param param the request object */ public getCompatibleBuildTypes(param: AgentApiGetCompatibleBuildTypesRequest, options?: Configuration): Promise<BuildTypes> { return this.api.getCompatibleBuildTypes(param.agentLocator, param.fields, options).toPromise(); } /** * Check if the matching agent is enabled. * @param param the request object */ public getEnabledInfo(param: AgentApiGetEnabledInfoRequest, options?: Configuration): Promise<EnabledInfo> { return this.api.getEnabledInfo(param.agentLocator, param.fields, options).toPromise(); } /** * Get build types incompatible with the matching agent. * @param param the request object */ public getIncompatibleBuildTypes(param: AgentApiGetIncompatibleBuildTypesRequest, options?: Configuration): Promise<Compatibilities> { return this.api.getIncompatibleBuildTypes(param.agentLocator, param.fields, options).toPromise(); } /** * Update a field of the matching agent. * @param param the request object */ public setAgentField(param: AgentApiSetAgentFieldRequest, options?: Configuration): Promise<string> { return this.api.setAgentField(param.agentLocator, param.field, param.body, options).toPromise(); } /** * Assign the matching agent to the specified agent pool. * @param param the request object */ public setAgentPool(param: AgentApiSetAgentPoolRequest, options?: Configuration): Promise<AgentPool> { return this.api.setAgentPool(param.agentLocator, param.fields, param.body, options).toPromise(); } /** * Update the authorization info of the matching agent. * @param param the request object */ public setAuthorizedInfo(param: AgentApiSetAuthorizedInfoRequest, options?: Configuration): Promise<AuthorizedInfo> { return this.api.setAuthorizedInfo(param.agentLocator, param.fields, param.body, options).toPromise(); } /** * Update build configuration run policy of agent matching locator. * @param param the request object */ public setBuildConfigurationRunPolicy(param: AgentApiSetBuildConfigurationRunPolicyRequest, options?: Configuration): Promise<CompatibilityPolicy> { return this.api.setBuildConfigurationRunPolicy(param.agentLocator, param.fields, param.body, options).toPromise(); } /** * Update the enablement status of the matching agent. * @param param the request object */ public setEnabledInfo(param: AgentApiSetEnabledInfoRequest, options?: Configuration): Promise<EnabledInfo> { return this.api.setEnabledInfo(param.agentLocator, param.fields, param.body, options).toPromise(); } } import { ObservableAgentPoolApi } from "./ObservableAPI.ts"; import { AgentPoolApiRequestFactory, AgentPoolApiResponseProcessor} from "../apis/AgentPoolApi.ts"; export interface AgentPoolApiAddAgentToAgentPoolRequest { /** * * @type string * @memberof AgentPoolApiaddAgentToAgentPool */ agentPoolLocator: string /** * * @type string * @memberof AgentPoolApiaddAgentToAgentPool */ fields?: string /** * * @type Agent * @memberof AgentPoolApiaddAgentToAgentPool */ body?: Agent } export interface AgentPoolApiAddProjectToAgentPoolRequest { /** * * @type string * @memberof AgentPoolApiaddProjectToAgentPool */ agentPoolLocator: string /** * * @type Project * @memberof AgentPoolApiaddProjectToAgentPool */ body?: Project } export interface AgentPoolApiCreateAgentPoolRequest { /** * * @type AgentPool * @memberof AgentPoolApicreateAgentPool */ body?: AgentPool } export interface AgentPoolApiDeleteAgentPoolRequest { /** * * @type string * @memberof AgentPoolApideleteAgentPool */ agentPoolLocator: string } export interface AgentPoolApiDeleteAllProjectsFromAgentPoolRequest { /** * * @type string * @memberof AgentPoolApideleteAllProjectsFromAgentPool */ agentPoolLocator: string } export interface AgentPoolApiDeleteProjectFromAgentPoolRequest { /** * * @type string * @memberof AgentPoolApideleteProjectFromAgentPool */ agentPoolLocator: string /** * * @type string * @memberof AgentPoolApideleteProjectFromAgentPool */ projectLocator: string } export interface AgentPoolApiGetAgentPoolOfAgentPoolRequest { /** * * @type string * @memberof AgentPoolApigetAgentPoolOfAgentPool */ agentPoolLocator: string /** * * @type string * @memberof AgentPoolApigetAgentPoolOfAgentPool */ fields?: string } export interface AgentPoolApiGetAllAgentPoolsRequest { /** * * @type string * @memberof AgentPoolApigetAllAgentPools */ locator?: string /** * * @type string * @memberof AgentPoolApigetAllAgentPools */ fields?: string } export interface AgentPoolApiGetAllAgentsFromAgentPoolRequest { /** * * @type string * @memberof AgentPoolApigetAllAgentsFromAgentPool */ agentPoolLocator: string /** * * @type string * @memberof AgentPoolApigetAllAgentsFromAgentPool */ locator?: string /** * * @type string * @memberof AgentPoolApigetAllAgentsFromAgentPool */ fields?: string } export interface AgentPoolApiGetAllProjectsFromAgentPoolRequest { /** * * @type string * @memberof AgentPoolApigetAllProjectsFromAgentPool */ agentPoolLocator: string /** * * @type string * @memberof AgentPoolApigetAllProjectsFromAgentPool */ fields?: string } export interface AgentPoolApiGetFieldFromAgentPoolRequest { /** * * @type string * @memberof AgentPoolApigetFieldFromAgentPool */ agentPoolLocator: string /** * * @type string * @memberof AgentPoolApigetFieldFromAgentPool */ field: string } export interface AgentPoolApiSetAgentPoolFieldRequest { /** * * @type string * @memberof AgentPoolApisetAgentPoolField */ agentPoolLocator: string /** * * @type string * @memberof AgentPoolApisetAgentPoolField */ field: string /** * * @type string * @memberof AgentPoolApisetAgentPoolField */ body?: string } export interface AgentPoolApiSetAgentPoolProjectsRequest { /** * * @type string * @memberof AgentPoolApisetAgentPoolProjects */ agentPoolLocator: string /** * * @type Projects * @memberof AgentPoolApisetAgentPoolProjects */ body?: Projects } export class ObjectAgentPoolApi { private api: ObservableAgentPoolApi public constructor(configuration: Configuration, requestFactory?: AgentPoolApiRequestFactory, responseProcessor?: AgentPoolApiResponseProcessor) { this.api = new ObservableAgentPoolApi(configuration, requestFactory, responseProcessor); } /** * Assign the agent to the matching agent pool. * @param param the request object */ public addAgentToAgentPool(param: AgentPoolApiAddAgentToAgentPoolRequest, options?: Configuration): Promise<Agent> { return this.api.addAgentToAgentPool(param.agentPoolLocator, param.fields, param.body, options).toPromise(); } /** * Assign the project to the matching agent pool. * @param param the request object */ public addProjectToAgentPool(param: AgentPoolApiAddProjectToAgentPoolRequest, options?: Configuration): Promise<Project> { return this.api.addProjectToAgentPool(param.agentPoolLocator, param.body, options).toPromise(); } /** * Create a new agent pool. * @param param the request object */ public createAgentPool(param: AgentPoolApiCreateAgentPoolRequest, options?: Configuration): Promise<AgentPool> { return this.api.createAgentPool(param.body, options).toPromise(); } /** * Delete the agent pool matching the locator. * @param param the request object */ public deleteAgentPool(param: AgentPoolApiDeleteAgentPoolRequest, options?: Configuration): Promise<void> { return this.api.deleteAgentPool(param.agentPoolLocator, options).toPromise(); } /** * Unassign all projects from the matching agent pool. * @param param the request object */ public deleteAllProjectsFromAgentPool(param: AgentPoolApiDeleteAllProjectsFromAgentPoolRequest, options?: Configuration): Promise<void> { return this.api.deleteAllProjectsFromAgentPool(param.agentPoolLocator, options).toPromise(); } /** * Unassign the project from the matching agent pool. * @param param the request object */ public deleteProjectFromAgentPool(param: AgentPoolApiDeleteProjectFromAgentPoolRequest, options?: Configuration): Promise<void> { return this.api.deleteProjectFromAgentPool(param.agentPoolLocator, param.projectLocator, options).toPromise(); } /** * Get the agent pool matching the locator. * @param param the request object */ public getAgentPoolOfAgentPool(param: AgentPoolApiGetAgentPoolOfAgentPoolRequest, options?: Configuration): Promise<AgentPool> { return this.api.getAgentPoolOfAgentPool(param.agentPoolLocator, param.fields, options).toPromise(); } /** * Get all agent pools. * @param param the request object */ public getAllAgentPools(param: AgentPoolApiGetAllAgentPoolsRequest, options?: Configuration): Promise<AgentPools> { return this.api.getAllAgentPools(param.locator, param.fields, options).toPromise(); } /** * Get the agent of the matching agent pool. * @param param the request object */ public getAllAgentsFromAgentPool(param: AgentPoolApiGetAllAgentsFromAgentPoolRequest, options?: Configuration): Promise<Agents> { return this.api.getAllAgentsFromAgentPool(param.agentPoolLocator, param.locator, param.fields, options).toPromise(); } /** * Get all projects of the matching agent pool. * @param param the request object */ public getAllProjectsFromAgentPool(param: AgentPoolApiGetAllProjectsFromAgentPoolRequest, options?: Configuration): Promise<Projects> { return this.api.getAllProjectsFromAgentPool(param.agentPoolLocator, param.fields, options).toPromise(); } /** * Get a field of the matching agent pool. * @param param the request object */ public getFieldFromAgentPool(param: AgentPoolApiGetFieldFromAgentPoolRequest, options?: Configuration): Promise<string> { return this.api.getFieldFromAgentPool(param.agentPoolLocator, param.field, options).toPromise(); } /** * Update a field of the matching agent pool. * @param param the request object */ public setAgentPoolField(param: AgentPoolApiSetAgentPoolFieldRequest, options?: Configuration): Promise<string> { return this.api.setAgentPoolField(param.agentPoolLocator, param.field, param.body, options).toPromise(); } /** * Update projects of the matching agent pool. * @param param the request object */ public setAgentPoolProjects(param: AgentPoolApiSetAgentPoolProjectsRequest, options?: Configuration): Promise<Projects> { return this.api.setAgentPoolProjects(param.agentPoolLocator, param.body, options).toPromise(); } } import { ObservableAuditApi } from "./ObservableAPI.ts"; import { AuditApiRequestFactory, AuditApiResponseProcessor} from "../apis/AuditApi.ts"; export interface AuditApiGetAllAuditEventsRequest { /** * * @type string * @memberof AuditApigetAllAuditEvents */ locator?: string /** * * @type string * @memberof AuditApigetAllAuditEvents */ fields?: string } export interface AuditApiGetAuditEventRequest { /** * * @type string * @memberof AuditApigetAuditEvent */ auditEventLocator: string /** * * @type string * @memberof AuditApigetAuditEvent */ fields?: string } export class ObjectAuditApi { private api: ObservableAuditApi public constructor(configuration: Configuration, requestFactory?: AuditApiRequestFactory, responseProcessor?: AuditApiResponseProcessor) { this.api = new ObservableAuditApi(configuration, requestFactory, responseProcessor); } /** * Get all audit events. * @param param the request object */ public getAllAuditEvents(param: AuditApiGetAllAuditEventsRequest, options?: Configuration): Promise<AuditEvents> { return this.api.getAllAuditEvents(param.locator, param.fields, options).toPromise(); } /** * Get audit event matching the locator. * @param param the request object */ public getAuditEvent(param: AuditApiGetAuditEventRequest, options?: Configuration): Promise<AuditEvent> { return this.api.getAuditEvent(param.auditEventLocator, param.fields, options).toPromise(); } } import { ObservableBuildApi } from "./ObservableAPI.ts"; import { BuildApiRequestFactory, BuildApiResponseProcessor} from "../apis/BuildApi.ts"; export interface BuildApiAddBuildVcsLabelRequest { /** * * @type string * @memberof BuildApiaddBuildVcsLabel */ buildLocator: string /** * * @type string * @memberof BuildApiaddBuildVcsLabel */ locator?: string /** * * @type string * @memberof BuildApiaddBuildVcsLabel */ fields?: string /** * * @type string * @memberof BuildApiaddBuildVcsLabel */ body?: string } export interface BuildApiAddLogMessageToBuildRequest { /** * * @type string * @memberof BuildApiaddLogMessageToBuild */ buildLocator: string /** * * @type string * @memberof BuildApiaddLogMessageToBuild */ fields?: string /** * * @type string * @memberof BuildApiaddLogMessageToBuild */ body?: string } export interface BuildApiAddProblemToBuildRequest { /** * * @type string * @memberof BuildApiaddProblemToBuild */ buildLocator: string /** * * @type string * @memberof BuildApiaddProblemToBuild */ fields?: string /** * * @type string * @memberof BuildApiaddProblemToBuild */ body?: string } export interface BuildApiAddTagsToBuildRequest { /** * * @type string * @memberof BuildApiaddTagsToBuild */ buildLocator: string /** * * @type string * @memberof BuildApiaddTagsToBuild */ fields?: string /** * * @type Tags * @memberof BuildApiaddTagsToBuild */ body?: Tags } export interface BuildApiAddTagsToMultipleBuildsRequest { /** * * @type string * @memberof BuildApiaddTagsToMultipleBuilds */ buildLocator: string /** * * @type string * @memberof BuildApiaddTagsToMultipleBuilds */ fields?: string /** * * @type Tags * @memberof BuildApiaddTagsToMultipleBuilds */ body?: Tags } export interface BuildApiDeleteBuildRequest { /** * * @type string * @memberof BuildApideleteBuild */ buildLocator: string } export interface BuildApiDeleteBuildCommentRequest { /** * * @type string * @memberof BuildApideleteBuildComment */ buildLocator: string } export interface BuildApiDeleteMultipleBuildCommentsRequest { /** * * @type string * @memberof BuildApideleteMultipleBuildComments */ buildLocator: string /** * * @type string * @memberof BuildApideleteMultipleBuildComments */ fields?: string } export interface BuildApiDeleteMultipleBuildsRequest { /** * * @type string * @memberof BuildApideleteMultipleBuilds */ buildLocator: string /** * * @type string * @memberof BuildApideleteMultipleBuilds */ fields?: string } export interface BuildApiDownloadFileOfBuildRequest { /** * * @type string * @memberof BuildApidownloadFileOfBuild */ path: string /** * * @type string * @memberof BuildApidownloadFileOfBuild */ buildLocator: string /** * * @type boolean * @memberof BuildApidownloadFileOfBuild */ resolveParameters?: boolean /** * * @type boolean * @memberof BuildApidownloadFileOfBuild */ logBuildUsage?: boolean } export interface BuildApiGetAggregatedBuildStatusRequest { /** * * @type string * @memberof BuildApigetAggregatedBuildStatus */ buildLocator: string } export interface BuildApiGetAggregatedBuildStatusIconRequest { /** * * @type string * @memberof BuildApigetAggregatedBuildStatusIcon */ buildLocator: string /** * * @type string * @memberof BuildApigetAggregatedBuildStatusIcon */ suffix: string } export interface BuildApiGetAllBuildsRequest { /** * * @type string * @memberof BuildApigetAllBuilds */ locator?: string /** * * @type string * @memberof BuildApigetAllBuilds */ fields?: string } export interface BuildApiGetArtifactDependencyChangesRequest { /** * * @type string * @memberof BuildApigetArtifactDependencyChanges */ buildLocator: string /** * * @type string * @memberof BuildApigetArtifactDependencyChanges */ fields?: string } export interface BuildApiGetArtifactsDirectoryRequest { /** * * @type string * @memberof BuildApigetArtifactsDirectory */ buildLocator: string } export interface BuildApiGetBuildRequest { /** * * @type string * @memberof BuildApigetBuild */ buildLocator: string /** * * @type string * @memberof BuildApigetBuild */ fields?: string } export interface BuildApiGetBuildActualParametersRequest { /** * * @type string * @memberof BuildApigetBuildActualParameters */ buildLocator: string /** * * @type string * @memberof BuildApigetBuildActualParameters */ fields?: string } export interface BuildApiGetBuildFieldRequest { /** * * @type string * @memberof BuildApigetBuildField */ buildLocator: string /** * * @type string * @memberof BuildApigetBuildField */ field: string } export interface BuildApiGetBuildFinishDateRequest { /** * * @type string * @memberof BuildApigetBuildFinishDate */ buildLocator: string } export interface BuildApiGetBuildNumberRequest { /** * * @type string * @memberof BuildApigetBuildNumber */ buildLocator: string } export interface BuildApiGetBuildPinInfoRequest { /** * * @type string * @memberof BuildApigetBuildPinInfo */ buildLocator: string /** * * @type string * @memberof BuildApigetBuildPinInfo */ fields?: string } export interface BuildApiGetBuildProblemsRequest { /** * * @type string * @memberof BuildApigetBuildProblems */ buildLocator: string /** * * @type string * @memberof BuildApigetBuildProblems */ fields?: string } export interface BuildApiGetBuildRelatedIssuesRequest { /** * * @type string * @memberof BuildApigetBuildRelatedIssues */ buildLocator: string /** * * @type string * @memberof BuildApigetBuildRelatedIssues */ fields?: string } export interface BuildApiGetBuildResolvedRequest { /** * * @type string * @memberof BuildApigetBuildResolved */ buildLocator: string /** * * @type string * @memberof BuildApigetBuildResolved */ value: string } export interface BuildApiGetBuildResultingPropertiesRequest { /** * * @type string * @memberof BuildApigetBuildResultingProperties */ buildLocator: string /** * * @type string * @memberof BuildApigetBuildResultingProperties */ propertyName: string } export interface BuildApiGetBuildSourceFileRequest { /** * * @type string * @memberof BuildApigetBuildSourceFile */ buildLocator: string /** * * @type string * @memberof BuildApigetBuildSourceFile */ fileName: string } export interface BuildApiGetBuildStatisticValueRequest { /** * * @type string * @memberof BuildApigetBuildStatisticValue */ buildLocator: string /** * * @type string * @memberof BuildApigetBuildStatisticValue */ name: string } export interface BuildApiGetBuildStatisticValuesRequest { /** * * @type string * @memberof BuildApigetBuildStatisticValues */ buildLocator: string /** * * @type string * @memberof BuildApigetBuildStatisticValues */ fields?: string } export interface BuildApiGetBuildStatusIconRequest { /** * * @type string * @memberof BuildApigetBuildStatusIcon */ buildLocator: string /** * * @type string * @memberof BuildApigetBuildStatusIcon */ suffix: string } export interface BuildApiGetBuildStatusTextRequest { /** * * @type string * @memberof BuildApigetBuildStatusText */ buildLocator: string } export interface BuildApiGetBuildTagsRequest { /** * * @type string * @memberof BuildApigetBuildTags */ buildLocator: string /** * * @type string * @memberof BuildApigetBuildTags */ locator?: string /** * * @type string * @memberof BuildApigetBuildTags */ fields?: string } export interface BuildApiGetBuildTestOccurrencesRequest { /** * * @type string * @memberof BuildApigetBuildTestOccurrences */ buildLocator: string /** * * @type string * @memberof BuildApigetBuildTestOccurrences */ fields?: string } export interface BuildApiGetBuildVcsLabelsRequest { /** * * @type string * @memberof BuildApigetBuildVcsLabels */ buildLocator: string /** * * @type string * @memberof BuildApigetBuildVcsLabels */ fields?: string } export interface BuildApiGetCanceledInfoRequest { /** * * @type string * @memberof BuildApigetCanceledInfo */ buildLocator: string /** * * @type string * @memberof BuildApigetCanceledInfo */ fields?: string } export interface BuildApiGetFileMetadataOfBuildRequest { /** * * @type string * @memberof BuildApigetFileMetadataOfBuild */ path: string /** * * @type string * @memberof BuildApigetFileMetadataOfBuild */ buildLocator: string /** * * @type string * @memberof BuildApigetFileMetadataOfBuild */ fields?: string /** * * @type boolean * @memberof BuildApigetFileMetadataOfBuild */ resolveParameters?: boolean /** * * @type boolean * @memberof BuildApigetFileMetadataOfBuild */ logBuildUsage?: boolean } export interface BuildApiGetFilesListForSubpathOfBuildRequest { /** * * @type string * @memberof BuildApigetFilesListForSubpathOfBuild */ path: string /** * * @type string * @memberof BuildApigetFilesListForSubpathOfBuild */ buildLocator: string /** * * @type string * @memberof BuildApigetFilesListForSubpathOfBuild */ basePath?: string /** * * @type string * @memberof BuildApigetFilesListForSubpathOfBuild */ locator?: string /** * * @type string * @memberof BuildApigetFilesListForSubpathOfBuild */ fields?: string /** * * @type boolean * @memberof BuildApigetFilesListForSubpathOfBuild */ resolveParameters?: boolean /** * * @type boolean * @memberof BuildApigetFilesListForSubpathOfBuild */ logBuildUsage?: boolean } export interface BuildApiGetFilesListOfBuildRequest { /** * * @type string * @memberof BuildApigetFilesListOfBuild */ buildLocator: string /** * * @type string * @memberof BuildApigetFilesListOfBuild */ basePath?: string /** * * @type string * @memberof BuildApigetFilesListOfBuild */ locator?: string /** * * @type string * @memberof BuildApigetFilesListOfBuild */ fields?: string /** * * @type boolean * @memberof BuildApigetFilesListOfBuild */ resolveParameters?: boolean /** * * @type boolean * @memberof BuildApigetFilesListOfBuild */ logBuildUsage?: boolean } export interface BuildApiGetMultipleBuildsRequest { /** * * @type string * @memberof BuildApigetMultipleBuilds */ buildLocator: string /** * * @type string * @memberof BuildApigetMultipleBuilds */ fields?: string } export interface BuildApiGetZippedFileOfBuildRequest { /** * * @type string * @memberof BuildApigetZippedFileOfBuild */ path: string /** * * @type string * @memberof BuildApigetZippedFileOfBuild */ buildLocator: string /** * * @type string * @memberof BuildApigetZippedFileOfBuild */ basePath?: string /** * * @type string * @memberof BuildApigetZippedFileOfBuild */ locator?: string /** * * @type string * @memberof BuildApigetZippedFileOfBuild */ name?: string /** * * @type boolean * @memberof BuildApigetZippedFileOfBuild */ resolveParameters?: boolean /** * * @type boolean * @memberof BuildApigetZippedFileOfBuild */ logBuildUsage?: boolean } export interface BuildApiMarkBuildAsRunningRequest { /** * * @type string * @memberof BuildApimarkBuildAsRunning */ buildLocator: string /** * * @type string * @memberof BuildApimarkBuildAsRunning */ fields?: string /** * * @type string * @memberof BuildApimarkBuildAsRunning */ body?: string } export interface BuildApiPinMultipleBuildsRequest { /** * * @type string * @memberof BuildApipinMultipleBuilds */ buildLocator: string /** * * @type string * @memberof BuildApipinMultipleBuilds */ fields?: string /** * * @type PinInfo * @memberof BuildApipinMultipleBuilds */ body?: PinInfo } export interface BuildApiRemoveMultipleBuildTagsRequest { /** * * @type string * @memberof BuildApiremoveMultipleBuildTags */ buildLocator: string /** * * @type string * @memberof BuildApiremoveMultipleBuildTags */ fields?: string /** * * @type Tags * @memberof BuildApiremoveMultipleBuildTags */ body?: Tags } export interface BuildApiResetBuildFinishPropertiesRequest { /** * * @type string * @memberof BuildApiresetBuildFinishProperties */ buildLocator: string } export interface BuildApiSetBuildCommentRequest { /** * * @type string * @memberof BuildApisetBuildComment */ buildLocator: string /** * * @type string * @memberof BuildApisetBuildComment */ body?: string } export interface BuildApiSetBuildFinishDateRequest { /** * * @type string * @memberof BuildApisetBuildFinishDate */ buildLocator: string /** * * @type string * @memberof BuildApisetBuildFinishDate */ body?: string } export interface BuildApiSetBuildNumberRequest { /** * * @type string * @memberof BuildApisetBuildNumber */ buildLocator: string /** * * @type string * @memberof BuildApisetBuildNumber */ body?: string } export interface BuildApiSetBuildPinInfoRequest { /** * * @type string * @memberof BuildApisetBuildPinInfo */ buildLocator: string /** * * @type string * @memberof BuildApisetBuildPinInfo */ fields?: string /** * * @type PinInfo * @memberof BuildApisetBuildPinInfo */ body?: PinInfo } export interface BuildApiSetBuildStatusTextRequest { /** * * @type string * @memberof BuildApisetBuildStatusText */ buildLocator: string /** * * @type string * @memberof BuildApisetBuildStatusText */ body?: string } export interface BuildApiSetBuildTagsRequest { /** * * @type string * @memberof BuildApisetBuildTags */ buildLocator: string /** * * @type string * @memberof BuildApisetBuildTags */ locator?: string /** * * @type string * @memberof BuildApisetBuildTags */ fields?: string /** * * @type Tags * @memberof BuildApisetBuildTags */ body?: Tags } export interface BuildApiSetFinishedTimeRequest { /** * * @type string * @memberof BuildApisetFinishedTime */ buildLocator: string } export interface BuildApiSetMultipleBuildCommentsRequest { /** * * @type string * @memberof BuildApisetMultipleBuildComments */ buildLocator: string /** * * @type string * @memberof BuildApisetMultipleBuildComments */ fields?: string /** * * @type string * @memberof BuildApisetMultipleBuildComments */ body?: string } export class ObjectBuildApi { private api: ObservableBuildApi public constructor(configuration: Configuration, requestFactory?: BuildApiRequestFactory, responseProcessor?: BuildApiResponseProcessor) { this.api = new ObservableBuildApi(configuration, requestFactory, responseProcessor); } /** * Add a VCS label to the matching build. * @param param the request object */ public addBuildVcsLabel(param: BuildApiAddBuildVcsLabelRequest, options?: Configuration): Promise<VcsLabels> { return this.api.addBuildVcsLabel(param.buildLocator, param.locator, param.fields, param.body, options).toPromise(); } /** * Adds a message to the build log. Service messages are accepted. * @param param the request object */ public addLogMessageToBuild(param: BuildApiAddLogMessageToBuildRequest, options?: Configuration): Promise<void> { return this.api.addLogMessageToBuild(param.buildLocator, param.fields, param.body, options).toPromise(); } /** * Add a build problem to the matching build. * @param param the request object */ public addProblemToBuild(param: BuildApiAddProblemToBuildRequest, options?: Configuration): Promise<ProblemOccurrence> { return this.api.addProblemToBuild(param.buildLocator, param.fields, param.body, options).toPromise(); } /** * Add tags to the matching build. * @param param the request object */ public addTagsToBuild(param: BuildApiAddTagsToBuildRequest, options?: Configuration): Promise<Tags> { return this.api.addTagsToBuild(param.buildLocator, param.fields, param.body, options).toPromise(); } /** * Add tags to multiple matching builds. * @param param the request object */ public addTagsToMultipleBuilds(param: BuildApiAddTagsToMultipleBuildsRequest, options?: Configuration): Promise<MultipleOperationResult> { return this.api.addTagsToMultipleBuilds(param.buildLocator, param.fields, param.body, options).toPromise(); } /** * Delete build matching the locator. * @param param the request object */ public deleteBuild(param: BuildApiDeleteBuildRequest, options?: Configuration): Promise<void> { return this.api.deleteBuild(param.buildLocator, options).toPromise(); } /** * Remove the build comment matching the locator. * @param param the request object */ public deleteBuildComment(param: BuildApiDeleteBuildCommentRequest, options?: Configuration): Promise<void> { return this.api.deleteBuildComment(param.buildLocator, options).toPromise(); } /** * Delete comments of multiple matching builds. * @param param the request object */ public deleteMultipleBuildComments(param: BuildApiDeleteMultipleBuildCommentsRequest, options?: Configuration): Promise<MultipleOperationResult> { return this.api.deleteMultipleBuildComments(param.buildLocator, param.fields, options).toPromise(); } /** * Delete multiple builds matching the locator. * @param param the request object */ public deleteMultipleBuilds(param: BuildApiDeleteMultipleBuildsRequest, options?: Configuration): Promise<MultipleOperationResult> { return this.api.deleteMultipleBuilds(param.buildLocator, param.fields, options).toPromise(); } /** * Download specific file. * @param param the request object */ public downloadFileOfBuild(param: BuildApiDownloadFileOfBuildRequest, options?: Configuration): Promise<void> { return this.api.downloadFileOfBuild(param.path, param.buildLocator, param.resolveParameters, param.logBuildUsage, options).toPromise(); } /** * Get the build status of aggregated matching builds. * @param param the request object */ public getAggregatedBuildStatus(param: BuildApiGetAggregatedBuildStatusRequest, options?: Configuration): Promise<string> { return this.api.getAggregatedBuildStatus(param.buildLocator, options).toPromise(); } /** * Get the status icon (in specified format) of aggregated matching builds. * @param param the request object */ public getAggregatedBuildStatusIcon(param: BuildApiGetAggregatedBuildStatusIconRequest, options?: Configuration): Promise<void> { return this.api.getAggregatedBuildStatusIcon(param.buildLocator, param.suffix, options).toPromise(); } /** * Get all builds. * @param param the request object */ public getAllBuilds(param: BuildApiGetAllBuildsRequest, options?: Configuration): Promise<Builds> { return this.api.getAllBuilds(param.locator, param.fields, options).toPromise(); } /** * Get artifact dependency changes of the matching build. * @param param the request object */ public getArtifactDependencyChanges(param: BuildApiGetArtifactDependencyChangesRequest, options?: Configuration): Promise<BuildChanges> { return this.api.getArtifactDependencyChanges(param.buildLocator, param.fields, options).toPromise(); } /** * Get the artifacts' directory of the matching build. * @param param the request object */ public getArtifactsDirectory(param: BuildApiGetArtifactsDirectoryRequest, options?: Configuration): Promise<string> { return this.api.getArtifactsDirectory(param.buildLocator, options).toPromise(); } /** * Get build matching the locator. * @param param the request object */ public getBuild(param: BuildApiGetBuildRequest, options?: Configuration): Promise<Build> { return this.api.getBuild(param.buildLocator, param.fields, options).toPromise(); } /** * Get actual build parameters of the matching build. * @param param the request object */ public getBuildActualParameters(param: BuildApiGetBuildActualParametersRequest, options?: Configuration): Promise<Properties> { return this.api.getBuildActualParameters(param.buildLocator, param.fields, options).toPromise(); } /** * Get a field of the matching build. * @param param the request object */ public getBuildField(param: BuildApiGetBuildFieldRequest, options?: Configuration): Promise<string> { return this.api.getBuildField(param.buildLocator, param.field, options).toPromise(); } /** * Get the finish date of the matching build. * @param param the request object */ public getBuildFinishDate(param: BuildApiGetBuildFinishDateRequest, options?: Configuration): Promise<string> { return this.api.getBuildFinishDate(param.buildLocator, options).toPromise(); } /** * Get the number of the matching build. * @param param the request object */ public getBuildNumber(param: BuildApiGetBuildNumberRequest, options?: Configuration): Promise<string> { return this.api.getBuildNumber(param.buildLocator, options).toPromise(); } /** * Check if the matching build is pinned. * @param param the request object */ public getBuildPinInfo(param: BuildApiGetBuildPinInfoRequest, options?: Configuration): Promise<PinInfo> { return this.api.getBuildPinInfo(param.buildLocator, param.fields, options).toPromise(); } /** * Get build problems of the matching build. * @param param the request object */ public getBuildProblems(param: BuildApiGetBuildProblemsRequest, options?: Configuration): Promise<ProblemOccurrences> { return this.api.getBuildProblems(param.buildLocator, param.fields, options).toPromise(); } /** * Get related issues of the matching build. * @param param the request object */ public getBuildRelatedIssues(param: BuildApiGetBuildRelatedIssuesRequest, options?: Configuration): Promise<IssuesUsages> { return this.api.getBuildRelatedIssues(param.buildLocator, param.fields, options).toPromise(); } /** * Get the resolvement status of the matching build. * @param param the request object */ public getBuildResolved(param: BuildApiGetBuildResolvedRequest, options?: Configuration): Promise<string> { return this.api.getBuildResolved(param.buildLocator, param.value, options).toPromise(); } /** * Update a build parameter of the matching build. * @param param the request object */ public getBuildResultingProperties(param: BuildApiGetBuildResultingPropertiesRequest, options?: Configuration): Promise<string> { return this.api.getBuildResultingProperties(param.buildLocator, param.propertyName, options).toPromise(); } /** * Get a source file of the matching build. * @param param the request object */ public getBuildSourceFile(param: BuildApiGetBuildSourceFileRequest, options?: Configuration): Promise<void> { return this.api.getBuildSourceFile(param.buildLocator, param.fileName, options).toPromise(); } /** * Get a statistical value of the matching build. * @param param the request object */ public getBuildStatisticValue(param: BuildApiGetBuildStatisticValueRequest, options?: Configuration): Promise<string> { return this.api.getBuildStatisticValue(param.buildLocator, param.name, options).toPromise(); } /** * Get all statistical values of the matching build. * @param param the request object */ public getBuildStatisticValues(param: BuildApiGetBuildStatisticValuesRequest, options?: Configuration): Promise<Properties> { return this.api.getBuildStatisticValues(param.buildLocator, param.fields, options).toPromise(); } /** * Get the status icon (in specified format) of the matching build. * @param param the request object */ public getBuildStatusIcon(param: BuildApiGetBuildStatusIconRequest, options?: Configuration): Promise<void> { return this.api.getBuildStatusIcon(param.buildLocator, param.suffix, options).toPromise(); } /** * Get the build status text of the matching build. * @param param the request object */ public getBuildStatusText(param: BuildApiGetBuildStatusTextRequest, options?: Configuration): Promise<string> { return this.api.getBuildStatusText(param.buildLocator, options).toPromise(); } /** * Get tags of the matching build. * @param param the request object */ public getBuildTags(param: BuildApiGetBuildTagsRequest, options?: Configuration): Promise<Tags> { return this.api.getBuildTags(param.buildLocator, param.locator, param.fields, options).toPromise(); } /** * Get test occurrences of the matching build. * @param param the request object */ public getBuildTestOccurrences(param: BuildApiGetBuildTestOccurrencesRequest, options?: Configuration): Promise<TestOccurrences> { return this.api.getBuildTestOccurrences(param.buildLocator, param.fields, options).toPromise(); } /** * Get VCS labels of the matching build. * @param param the request object */ public getBuildVcsLabels(param: BuildApiGetBuildVcsLabelsRequest, options?: Configuration): Promise<VcsLabels> { return this.api.getBuildVcsLabels(param.buildLocator, param.fields, options).toPromise(); } /** * Check if the matching build is canceled. * @param param the request object */ public getCanceledInfo(param: BuildApiGetCanceledInfoRequest, options?: Configuration): Promise<Comment> { return this.api.getCanceledInfo(param.buildLocator, param.fields, options).toPromise(); } /** * Get metadata of specific file. * @param param the request object */ public getFileMetadataOfBuild(param: BuildApiGetFileMetadataOfBuildRequest, options?: Configuration): Promise<any> { return this.api.getFileMetadataOfBuild(param.path, param.buildLocator, param.fields, param.resolveParameters, param.logBuildUsage, options).toPromise(); } /** * List files under this path. * @param param the request object */ public getFilesListForSubpathOfBuild(param: BuildApiGetFilesListForSubpathOfBuildRequest, options?: Configuration): Promise<Files> { return this.api.getFilesListForSubpathOfBuild(param.path, param.buildLocator, param.basePath, param.locator, param.fields, param.resolveParameters, param.logBuildUsage, options).toPromise(); } /** * List all files. * @param param the request object */ public getFilesListOfBuild(param: BuildApiGetFilesListOfBuildRequest, options?: Configuration): Promise<Files> { return this.api.getFilesListOfBuild(param.buildLocator, param.basePath, param.locator, param.fields, param.resolveParameters, param.logBuildUsage, options).toPromise(); } /** * Get multiple builds matching the locator. * @param param the request object */ public getMultipleBuilds(param: BuildApiGetMultipleBuildsRequest, options?: Configuration): Promise<Builds> { return this.api.getMultipleBuilds(param.buildLocator, param.fields, options).toPromise(); } /** * Get specific file zipped. * @param param the request object */ public getZippedFileOfBuild(param: BuildApiGetZippedFileOfBuildRequest, options?: Configuration): Promise<void> { return this.api.getZippedFileOfBuild(param.path, param.buildLocator, param.basePath, param.locator, param.name, param.resolveParameters, param.logBuildUsage, options).toPromise(); } /** * Starts the queued build as an agent-less build and returns the corresponding running build. * @param param the request object */ public markBuildAsRunning(param: BuildApiMarkBuildAsRunningRequest, options?: Configuration): Promise<Build> { return this.api.markBuildAsRunning(param.buildLocator, param.fields, param.body, options).toPromise(); } /** * Pin multiple matching builds. * @param param the request object */ public pinMultipleBuilds(param: BuildApiPinMultipleBuildsRequest, options?: Configuration): Promise<MultipleOperationResult> { return this.api.pinMultipleBuilds(param.buildLocator, param.fields, param.body, options).toPromise(); } /** * Remove tags from multiple matching builds. * @param param the request object */ public removeMultipleBuildTags(param: BuildApiRemoveMultipleBuildTagsRequest, options?: Configuration): Promise<MultipleOperationResult> { return this.api.removeMultipleBuildTags(param.buildLocator, param.fields, param.body, options).toPromise(); } /** * Remove build parameters from the matching build. * @param param the request object */ public resetBuildFinishProperties(param: BuildApiResetBuildFinishPropertiesRequest, options?: Configuration): Promise<void> { return this.api.resetBuildFinishProperties(param.buildLocator, options).toPromise(); } /** * Update the comment on the matching build. * @param param the request object */ public setBuildComment(param: BuildApiSetBuildCommentRequest, options?: Configuration): Promise<void> { return this.api.setBuildComment(param.buildLocator, param.body, options).toPromise(); } /** * Marks the running build as finished by passing agent the current time of the build to finish. * @param param the request object */ public setBuildFinishDate(param: BuildApiSetBuildFinishDateRequest, options?: Configuration): Promise<string> { return this.api.setBuildFinishDate(param.buildLocator, param.body, options).toPromise(); } /** * Update the number of the matching build. * @param param the request object */ public setBuildNumber(param: BuildApiSetBuildNumberRequest, options?: Configuration): Promise<string> { return this.api.setBuildNumber(param.buildLocator, param.body, options).toPromise(); } /** * Update the pin info of the matching build. * @param param the request object */ public setBuildPinInfo(param: BuildApiSetBuildPinInfoRequest, options?: Configuration): Promise<PinInfo> { return this.api.setBuildPinInfo(param.buildLocator, param.fields, param.body, options).toPromise(); } /** * Update the build status of the matching build. * @param param the request object */ public setBuildStatusText(param: BuildApiSetBuildStatusTextRequest, options?: Configuration): Promise<string> { return this.api.setBuildStatusText(param.buildLocator, param.body, options).toPromise(); } /** * Update tags of the matching build. * @param param the request object */ public setBuildTags(param: BuildApiSetBuildTagsRequest, options?: Configuration): Promise<Tags> { return this.api.setBuildTags(param.buildLocator, param.locator, param.fields, param.body, options).toPromise(); } /** * Marks the running build as finished by passing agent the current time of the build to finish. * @param param the request object */ public setFinishedTime(param: BuildApiSetFinishedTimeRequest, options?: Configuration): Promise<string> { return this.api.setFinishedTime(param.buildLocator, options).toPromise(); } /** * Update comments in multiple matching builds. * @param param the request object */ public setMultipleBuildComments(param: BuildApiSetMultipleBuildCommentsRequest, options?: Configuration): Promise<MultipleOperationResult> { return this.api.setMultipleBuildComments(param.buildLocator, param.fields, param.body, options).toPromise(); } } import { ObservableBuildQueueApi } from "./ObservableAPI.ts"; import { BuildQueueApiRequestFactory, BuildQueueApiResponseProcessor} from "../apis/BuildQueueApi.ts"; export interface BuildQueueApiAddBuildToQueueRequest { /** * * @type boolean * @memberof BuildQueueApiaddBuildToQueue */ moveToTop?: boolean /** * * @type Build * @memberof BuildQueueApiaddBuildToQueue */ body?: Build } export interface BuildQueueApiAddTagsToBuildOfBuildQueueRequest { /** * * @type string * @memberof BuildQueueApiaddTagsToBuildOfBuildQueue */ buildLocator: string /** * * @type Tags * @memberof BuildQueueApiaddTagsToBuildOfBuildQueue */ body?: Tags } export interface BuildQueueApiCancelQueuedBuildRequest { /** * * @type string * @memberof BuildQueueApicancelQueuedBuild */ queuedBuildLocator: string /** * * @type BuildCancelRequest * @memberof BuildQueueApicancelQueuedBuild */ body?: BuildCancelRequest } export interface BuildQueueApiDeleteAllQueuedBuildsRequest { /** * * @type string * @memberof BuildQueueApideleteAllQueuedBuilds */ locator?: string /** * * @type string * @memberof BuildQueueApideleteAllQueuedBuilds */ fields?: string } export interface BuildQueueApiDeleteQueuedBuildRequest { /** * * @type string * @memberof BuildQueueApideleteQueuedBuild */ queuedBuildLocator: string } export interface BuildQueueApiGetAllQueuedBuildsRequest { /** * * @type string * @memberof BuildQueueApigetAllQueuedBuilds */ locator?: string /** * * @type string * @memberof BuildQueueApigetAllQueuedBuilds */ fields?: string } export interface BuildQueueApiGetCompatibleAgentsForBuildRequest { /** * * @type string * @memberof BuildQueueApigetCompatibleAgentsForBuild */ queuedBuildLocator: string /** * * @type string * @memberof BuildQueueApigetCompatibleAgentsForBuild */ fields?: string } export interface BuildQueueApiGetQueuedBuildRequest { /** * * @type string * @memberof BuildQueueApigetQueuedBuild */ queuedBuildLocator: string /** * * @type string * @memberof BuildQueueApigetQueuedBuild */ fields?: string } export interface BuildQueueApiGetQueuedBuildPositionRequest { /** * * @type string * @memberof BuildQueueApigetQueuedBuildPosition */ queuePosition: string /** * * @type string * @memberof BuildQueueApigetQueuedBuildPosition */ fields?: string } export interface BuildQueueApiGetQueuedBuildTagsRequest { /** * * @type string * @memberof BuildQueueApigetQueuedBuildTags */ buildLocator: string /** * * @type string * @memberof BuildQueueApigetQueuedBuildTags */ locator?: string /** * * @type string * @memberof BuildQueueApigetQueuedBuildTags */ fields?: string } export interface BuildQueueApiSetQueuedBuildPositionRequest { /** * * @type string * @memberof BuildQueueApisetQueuedBuildPosition */ queuePosition: string /** * * @type string * @memberof BuildQueueApisetQueuedBuildPosition */ fields?: string /** * * @type Build * @memberof BuildQueueApisetQueuedBuildPosition */ body?: Build } export interface BuildQueueApiSetQueuedBuildsOrderRequest { /** * * @type string * @memberof BuildQueueApisetQueuedBuildsOrder */ fields?: string /** * * @type Builds * @memberof BuildQueueApisetQueuedBuildsOrder */ body?: Builds } export class ObjectBuildQueueApi { private api: ObservableBuildQueueApi public constructor(configuration: Configuration, requestFactory?: BuildQueueApiRequestFactory, responseProcessor?: BuildQueueApiResponseProcessor) { this.api = new ObservableBuildQueueApi(configuration, requestFactory, responseProcessor); } /** * Add a new build to the queue. * @param param the request object */ public addBuildToQueue(param: BuildQueueApiAddBuildToQueueRequest, options?: Configuration): Promise<Build> { return this.api.addBuildToQueue(param.moveToTop, param.body, options).toPromise(); } /** * Add tags to the matching build. * @param param the request object */ public addTagsToBuildOfBuildQueue(param: BuildQueueApiAddTagsToBuildOfBuildQueueRequest, options?: Configuration): Promise<void> { return this.api.addTagsToBuildOfBuildQueue(param.buildLocator, param.body, options).toPromise(); } /** * Cancel a queued matching build. * @param param the request object */ public cancelQueuedBuild(param: BuildQueueApiCancelQueuedBuildRequest, options?: Configuration): Promise<Build> { return this.api.cancelQueuedBuild(param.queuedBuildLocator, param.body, options).toPromise(); } /** * Delete all queued builds. * @param param the request object */ public deleteAllQueuedBuilds(param: BuildQueueApiDeleteAllQueuedBuildsRequest, options?: Configuration): Promise<void> { return this.api.deleteAllQueuedBuilds(param.locator, param.fields, options).toPromise(); } /** * Delete a queued matching build. * @param param the request object */ public deleteQueuedBuild(param: BuildQueueApiDeleteQueuedBuildRequest, options?: Configuration): Promise<void> { return this.api.deleteQueuedBuild(param.queuedBuildLocator, options).toPromise(); } /** * Get all queued builds. * @param param the request object */ public getAllQueuedBuilds(param: BuildQueueApiGetAllQueuedBuildsRequest, options?: Configuration): Promise<Builds> { return this.api.getAllQueuedBuilds(param.locator, param.fields, options).toPromise(); } /** * Get compatible agents for a queued matching build. * @param param the request object */ public getCompatibleAgentsForBuild(param: BuildQueueApiGetCompatibleAgentsForBuildRequest, options?: Configuration): Promise<Agents> { return this.api.getCompatibleAgentsForBuild(param.queuedBuildLocator, param.fields, options).toPromise(); } /** * Get a queued matching build. * @param param the request object */ public getQueuedBuild(param: BuildQueueApiGetQueuedBuildRequest, options?: Configuration): Promise<Build> { return this.api.getQueuedBuild(param.queuedBuildLocator, param.fields, options).toPromise(); } /** * Get the queue position of a queued matching build. * @param param the request object */ public getQueuedBuildPosition(param: BuildQueueApiGetQueuedBuildPositionRequest, options?: Configuration): Promise<Build> { return this.api.getQueuedBuildPosition(param.queuePosition, param.fields, options).toPromise(); } /** * Get tags of the queued matching build. * @param param the request object */ public getQueuedBuildTags(param: BuildQueueApiGetQueuedBuildTagsRequest, options?: Configuration): Promise<Tags> { return this.api.getQueuedBuildTags(param.buildLocator, param.locator, param.fields, options).toPromise(); } /** * Update the queue position of a queued matching build. * @param param the request object */ public setQueuedBuildPosition(param: BuildQueueApiSetQueuedBuildPositionRequest, options?: Configuration): Promise<Build> { return this.api.setQueuedBuildPosition(param.queuePosition, param.fields, param.body, options).toPromise(); } /** * Update the build queue order. * @param param the request object */ public setQueuedBuildsOrder(param: BuildQueueApiSetQueuedBuildsOrderRequest, options?: Configuration): Promise<Builds> { return this.api.setQueuedBuildsOrder(param.fields, param.body, options).toPromise(); } } import { ObservableBuildTypeApi } from "./ObservableAPI.ts"; import { BuildTypeApiRequestFactory, BuildTypeApiResponseProcessor} from "../apis/BuildTypeApi.ts"; export interface BuildTypeApiAddAgentRequirementToBuildTypeRequest { /** * * @type string * @memberof BuildTypeApiaddAgentRequirementToBuildType */ btLocator: string /** * * @type string * @memberof BuildTypeApiaddAgentRequirementToBuildType */ fields?: string /** * * @type AgentRequirement * @memberof BuildTypeApiaddAgentRequirementToBuildType */ body?: AgentRequirement } export interface BuildTypeApiAddArtifactDependencyToBuildTypeRequest { /** * * @type string * @memberof BuildTypeApiaddArtifactDependencyToBuildType */ btLocator: string /** * * @type string * @memberof BuildTypeApiaddArtifactDependencyToBuildType */ fields?: string /** * * @type ArtifactDependency * @memberof BuildTypeApiaddArtifactDependencyToBuildType */ body?: ArtifactDependency } export interface BuildTypeApiAddBuildFeatureToBuildTypeRequest { /** * * @type string * @memberof BuildTypeApiaddBuildFeatureToBuildType */ btLocator: string /** * * @type string * @memberof BuildTypeApiaddBuildFeatureToBuildType */ fields?: string /** * * @type Feature * @memberof BuildTypeApiaddBuildFeatureToBuildType */ body?: Feature } export interface BuildTypeApiAddBuildStepToBuildTypeRequest { /** * * @type string * @memberof BuildTypeApiaddBuildStepToBuildType */ btLocator: string /** * * @type string * @memberof BuildTypeApiaddBuildStepToBuildType */ fields?: string /** * * @type Step * @memberof BuildTypeApiaddBuildStepToBuildType */ body?: Step } export interface BuildTypeApiAddBuildTemplateRequest { /** * * @type string * @memberof BuildTypeApiaddBuildTemplate */ btLocator: string /** * * @type boolean * @memberof BuildTypeApiaddBuildTemplate */ optimizeSettings?: boolean /** * * @type string * @memberof BuildTypeApiaddBuildTemplate */ fields?: string /** * * @type BuildType * @memberof BuildTypeApiaddBuildTemplate */ body?: BuildType } export interface BuildTypeApiAddParameterToBuildFeatureRequest { /** * * @type string * @memberof BuildTypeApiaddParameterToBuildFeature */ btLocator: string /** * * @type string * @memberof BuildTypeApiaddParameterToBuildFeature */ featureId: string /** * * @type string * @memberof BuildTypeApiaddParameterToBuildFeature */ parameterName: string /** * * @type string * @memberof BuildTypeApiaddParameterToBuildFeature */ body?: string } export interface BuildTypeApiAddParameterToBuildStepRequest { /** * * @type string * @memberof BuildTypeApiaddParameterToBuildStep */ btLocator: string /** * * @type string * @memberof BuildTypeApiaddParameterToBuildStep */ stepId: string /** * * @type string * @memberof BuildTypeApiaddParameterToBuildStep */ parameterName: string /** * * @type string * @memberof BuildTypeApiaddParameterToBuildStep */ body?: string } export interface BuildTypeApiAddSnapshotDependencyToBuildTypeRequest { /** * * @type string * @memberof BuildTypeApiaddSnapshotDependencyToBuildType */ btLocator: string /** * * @type string * @memberof BuildTypeApiaddSnapshotDependencyToBuildType */ fields?: string /** * * @type SnapshotDependency * @memberof BuildTypeApiaddSnapshotDependencyToBuildType */ body?: SnapshotDependency } export interface BuildTypeApiAddTriggerToBuildTypeRequest { /** * * @type string * @memberof BuildTypeApiaddTriggerToBuildType */ btLocator: string /** * * @type string * @memberof BuildTypeApiaddTriggerToBuildType */ fields?: string /** * * @type Trigger * @memberof BuildTypeApiaddTriggerToBuildType */ body?: Trigger } export interface BuildTypeApiAddVcsRootToBuildTypeRequest { /** * * @type string * @memberof BuildTypeApiaddVcsRootToBuildType */ btLocator: string /** * * @type string * @memberof BuildTypeApiaddVcsRootToBuildType */ fields?: string /** * * @type VcsRootEntry * @memberof BuildTypeApiaddVcsRootToBuildType */ body?: VcsRootEntry } export interface BuildTypeApiCreateBuildParameterOfBuildTypeRequest { /** * * @type string * @memberof BuildTypeApicreateBuildParameterOfBuildType */ btLocator: string /** * * @type string * @memberof BuildTypeApicreateBuildParameterOfBuildType */ fields?: string /** * * @type Property * @memberof BuildTypeApicreateBuildParameterOfBuildType */ body?: Property } export interface BuildTypeApiCreateBuildTypeRequest { /** * * @type string * @memberof BuildTypeApicreateBuildType */ fields?: string /** * * @type BuildType * @memberof BuildTypeApicreateBuildType */ body?: BuildType } export interface BuildTypeApiDeleteAgentRequirementRequest { /** * * @type string * @memberof BuildTypeApideleteAgentRequirement */ btLocator: string /** * * @type string * @memberof BuildTypeApideleteAgentRequirement */ agentRequirementLocator: string } export interface BuildTypeApiDeleteArtifactDependencyRequest { /** * * @type string * @memberof BuildTypeApideleteArtifactDependency */ btLocator: string /** * * @type string * @memberof BuildTypeApideleteArtifactDependency */ artifactDepLocator: string } export interface BuildTypeApiDeleteBuildParameterOfBuildTypeRequest { /** * * @type string * @memberof BuildTypeApideleteBuildParameterOfBuildType */ name: string /** * * @type string * @memberof BuildTypeApideleteBuildParameterOfBuildType */ btLocator: string } export interface BuildTypeApiDeleteBuildParametersOfBuildTypeRequest { /** * * @type string * @memberof BuildTypeApideleteBuildParametersOfBuildType */ btLocator: string } export interface BuildTypeApiDeleteBuildStepRequest { /** * * @type string * @memberof BuildTypeApideleteBuildStep */ btLocator: string /** * * @type string * @memberof BuildTypeApideleteBuildStep */ stepId: string } export interface BuildTypeApiDeleteBuildStepParametersRequest { /** * * @type string * @memberof BuildTypeApideleteBuildStepParameters */ btLocator: string /** * * @type string * @memberof BuildTypeApideleteBuildStepParameters */ stepId: string /** * * @type string * @memberof BuildTypeApideleteBuildStepParameters */ fields?: string /** * * @type Properties * @memberof BuildTypeApideleteBuildStepParameters */ body?: Properties } export interface BuildTypeApiDeleteBuildTypeRequest { /** * * @type string * @memberof BuildTypeApideleteBuildType */ btLocator: string } export interface BuildTypeApiDeleteFeatureOfBuildTypeRequest { /** * * @type string * @memberof BuildTypeApideleteFeatureOfBuildType */ btLocator: string /** * * @type string * @memberof BuildTypeApideleteFeatureOfBuildType */ featureId: string } export interface BuildTypeApiDeleteSnapshotDependencyRequest { /** * * @type string * @memberof BuildTypeApideleteSnapshotDependency */ btLocator: string /** * * @type string * @memberof BuildTypeApideleteSnapshotDependency */ snapshotDepLocator: string } export interface BuildTypeApiDeleteTriggerRequest { /** * * @type string * @memberof BuildTypeApideleteTrigger */ btLocator: string /** * * @type string * @memberof BuildTypeApideleteTrigger */ triggerLocator: string } export interface BuildTypeApiDeleteVcsRootOfBuildTypeRequest { /** * * @type string * @memberof BuildTypeApideleteVcsRootOfBuildType */ btLocator: string /** * * @type string * @memberof BuildTypeApideleteVcsRootOfBuildType */ vcsRootLocator: string } export interface BuildTypeApiDownloadFileOfBuildTypeRequest { /** * * @type string * @memberof BuildTypeApidownloadFileOfBuildType */ path: string /** * * @type string * @memberof BuildTypeApidownloadFileOfBuildType */ btLocator: string /** * * @type boolean * @memberof BuildTypeApidownloadFileOfBuildType */ resolveParameters?: boolean } export interface BuildTypeApiGetAgentRequirementRequest { /** * * @type string * @memberof BuildTypeApigetAgentRequirement */ btLocator: string /** * * @type string * @memberof BuildTypeApigetAgentRequirement */ agentRequirementLocator: string /** * * @type string * @memberof BuildTypeApigetAgentRequirement */ fields?: string } export interface BuildTypeApiGetAgentRequirementParameterRequest { /** * * @type string * @memberof BuildTypeApigetAgentRequirementParameter */ btLocator: string /** * * @type string * @memberof BuildTypeApigetAgentRequirementParameter */ agentRequirementLocator: string /** * * @type string * @memberof BuildTypeApigetAgentRequirementParameter */ fieldName: string } export interface BuildTypeApiGetAliasesRequest { /** * * @type string * @memberof BuildTypeApigetAliases */ btLocator: string /** * * @type string * @memberof BuildTypeApigetAliases */ field?: string } export interface BuildTypeApiGetAllAgentRequirementsRequest { /** * * @type string * @memberof BuildTypeApigetAllAgentRequirements */ btLocator: string /** * * @type string * @memberof BuildTypeApigetAllAgentRequirements */ fields?: string } export interface BuildTypeApiGetAllArtifactDependenciesRequest { /** * * @type string * @memberof BuildTypeApigetAllArtifactDependencies */ btLocator: string /** * * @type string * @memberof BuildTypeApigetAllArtifactDependencies */ fields?: string } export interface BuildTypeApiGetAllBranchesOfBuildTypeRequest { /** * * @type string * @memberof BuildTypeApigetAllBranchesOfBuildType */ btLocator: string /** * * @type string * @memberof BuildTypeApigetAllBranchesOfBuildType */ locator?: string /** * * @type string * @memberof BuildTypeApigetAllBranchesOfBuildType */ fields?: string } export interface BuildTypeApiGetAllBuildFeatureParametersRequest { /** * * @type string * @memberof BuildTypeApigetAllBuildFeatureParameters */ btLocator: string /** * * @type string * @memberof BuildTypeApigetAllBuildFeatureParameters */ featureId: string /** * * @type string * @memberof BuildTypeApigetAllBuildFeatureParameters */ fields?: string } export interface BuildTypeApiGetAllBuildFeaturesRequest { /** * * @type string * @memberof BuildTypeApigetAllBuildFeatures */ btLocator: string /** * * @type string * @memberof BuildTypeApigetAllBuildFeatures */ fields?: string } export interface BuildTypeApiGetAllBuildStepParametersRequest { /** * * @type string * @memberof BuildTypeApigetAllBuildStepParameters */ btLocator: string /** * * @type string * @memberof BuildTypeApigetAllBuildStepParameters */ stepId: string /** * * @type string * @memberof BuildTypeApigetAllBuildStepParameters */ fields?: string } export interface BuildTypeApiGetAllBuildStepsRequest { /** * * @type string * @memberof BuildTypeApigetAllBuildSteps */ btLocator: string /** * * @type string * @memberof BuildTypeApigetAllBuildSteps */ fields?: string } export interface BuildTypeApiGetAllBuildTemplatesRequest { /** * * @type string * @memberof BuildTypeApigetAllBuildTemplates */ btLocator: string /** * * @type string * @memberof BuildTypeApigetAllBuildTemplates */ fields?: string } export interface BuildTypeApiGetAllBuildTypesRequest { /** * * @type string * @memberof BuildTypeApigetAllBuildTypes */ locator?: string /** * * @type string * @memberof BuildTypeApigetAllBuildTypes */ fields?: string } export interface BuildTypeApiGetAllInvestigationsOfBuildTypeRequest { /** * * @type string * @memberof BuildTypeApigetAllInvestigationsOfBuildType */ btLocator: string /** * * @type string * @memberof BuildTypeApigetAllInvestigationsOfBuildType */ fields?: string } export interface BuildTypeApiGetAllSnapshotDependenciesRequest { /** * * @type string * @memberof BuildTypeApigetAllSnapshotDependencies */ btLocator: string /** * * @type string * @memberof BuildTypeApigetAllSnapshotDependencies */ fields?: string } export interface BuildTypeApiGetAllTriggersRequest { /** * * @type string * @memberof BuildTypeApigetAllTriggers */ btLocator: string /** * * @type string * @memberof BuildTypeApigetAllTriggers */ fields?: string } export interface BuildTypeApiGetAllVcsRootsOfBuildTypeRequest { /** * * @type string * @memberof BuildTypeApigetAllVcsRootsOfBuildType */ btLocator: string /** * * @type string * @memberof BuildTypeApigetAllVcsRootsOfBuildType */ fields?: string } export interface BuildTypeApiGetArtifactDependencyRequest { /** * * @type string * @memberof BuildTypeApigetArtifactDependency */ btLocator: string /** * * @type string * @memberof BuildTypeApigetArtifactDependency */ artifactDepLocator: string /** * * @type string * @memberof BuildTypeApigetArtifactDependency */ fields?: string } export interface BuildTypeApiGetArtifactDependencyParameterRequest { /** * * @type string * @memberof BuildTypeApigetArtifactDependencyParameter */ btLocator: string /** * * @type string * @memberof BuildTypeApigetArtifactDependencyParameter */ artifactDepLocator: string /** * * @type string * @memberof BuildTypeApigetArtifactDependencyParameter */ fieldName: string } export interface BuildTypeApiGetBuildFeatureRequest { /** * * @type string * @memberof BuildTypeApigetBuildFeature */ btLocator: string /** * * @type string * @memberof BuildTypeApigetBuildFeature */ featureId: string /** * * @type string * @memberof BuildTypeApigetBuildFeature */ fields?: string } export interface BuildTypeApiGetBuildFeatureParameterRequest { /** * * @type string * @memberof BuildTypeApigetBuildFeatureParameter */ btLocator: string /** * * @type string * @memberof BuildTypeApigetBuildFeatureParameter */ featureId: string /** * * @type string * @memberof BuildTypeApigetBuildFeatureParameter */ parameterName: string } export interface BuildTypeApiGetBuildFeatureSettingRequest { /** * * @type string * @memberof BuildTypeApigetBuildFeatureSetting */ btLocator: string /** * * @type string * @memberof BuildTypeApigetBuildFeatureSetting */ featureId: string /** * * @type string * @memberof BuildTypeApigetBuildFeatureSetting */ name: string } export interface BuildTypeApiGetBuildParameterOfBuildTypeRequest { /** * * @type string * @memberof BuildTypeApigetBuildParameterOfBuildType */ name: string /** * * @type string * @memberof BuildTypeApigetBuildParameterOfBuildType */ btLocator: string /** * * @type string * @memberof BuildTypeApigetBuildParameterOfBuildType */ fields?: string } export interface BuildTypeApiGetBuildParameterSpecificationOfBuildTypeRequest { /** * * @type string * @memberof BuildTypeApigetBuildParameterSpecificationOfBuildType */ name: string /** * * @type string * @memberof BuildTypeApigetBuildParameterSpecificationOfBuildType */ btLocator: string } export interface BuildTypeApiGetBuildParameterTypeOfBuildTypeRequest { /** * * @type string * @memberof BuildTypeApigetBuildParameterTypeOfBuildType */ name: string /** * * @type string * @memberof BuildTypeApigetBuildParameterTypeOfBuildType */ btLocator: string } export interface BuildTypeApiGetBuildParameterValueOfBuildTypeRequest { /** * * @type string * @memberof BuildTypeApigetBuildParameterValueOfBuildType */ name: string /** * * @type string * @memberof BuildTypeApigetBuildParameterValueOfBuildType */ btLocator: string } export interface BuildTypeApiGetBuildParametersOfBuildTypeRequest { /** * * @type string * @memberof BuildTypeApigetBuildParametersOfBuildType */ btLocator: string /** * * @type string * @memberof BuildTypeApigetBuildParametersOfBuildType */ locator?: string /** * * @type string * @memberof BuildTypeApigetBuildParametersOfBuildType */ fields?: string } export interface BuildTypeApiGetBuildStepRequest { /** * * @type string * @memberof BuildTypeApigetBuildStep */ btLocator: string /** * * @type string * @memberof BuildTypeApigetBuildStep */ stepId: string /** * * @type string * @memberof BuildTypeApigetBuildStep */ fields?: string } export interface BuildTypeApiGetBuildStepParameterRequest { /** * * @type string * @memberof BuildTypeApigetBuildStepParameter */ btLocator: string /** * * @type string * @memberof BuildTypeApigetBuildStepParameter */ stepId: string /** * * @type string * @memberof BuildTypeApigetBuildStepParameter */ parameterName: string } export interface BuildTypeApiGetBuildStepSettingRequest { /** * * @type string * @memberof BuildTypeApigetBuildStepSetting */ btLocator: string /** * * @type string * @memberof BuildTypeApigetBuildStepSetting */ stepId: string /** * * @type string * @memberof BuildTypeApigetBuildStepSetting */ fieldName: string } export interface BuildTypeApiGetBuildTemplateRequest { /** * * @type string * @memberof BuildTypeApigetBuildTemplate */ btLocator: string /** * * @type string * @memberof BuildTypeApigetBuildTemplate */ templateLocator: string /** * * @type string * @memberof BuildTypeApigetBuildTemplate */ fields?: string } export interface BuildTypeApiGetBuildTypeRequest { /** * * @type string * @memberof BuildTypeApigetBuildType */ btLocator: string /** * * @type string * @memberof BuildTypeApigetBuildType */ fields?: string } export interface BuildTypeApiGetBuildTypeBuildTagsRequest { /** * * @type string * @memberof BuildTypeApigetBuildTypeBuildTags */ btLocator: string /** * * @type string * @memberof BuildTypeApigetBuildTypeBuildTags */ field?: string } export interface BuildTypeApiGetBuildTypeBuildsRequest { /** * * @type string * @memberof BuildTypeApigetBuildTypeBuilds */ btLocator: string /** * * @type string * @memberof BuildTypeApigetBuildTypeBuilds */ fields?: string } export interface BuildTypeApiGetBuildTypeFieldRequest { /** * * @type string * @memberof BuildTypeApigetBuildTypeField */ btLocator: string /** * * @type string * @memberof BuildTypeApigetBuildTypeField */ field: string } export interface BuildTypeApiGetBuildTypeSettingsFileRequest { /** * * @type string * @memberof BuildTypeApigetBuildTypeSettingsFile */ btLocator: string } export interface BuildTypeApiGetFileMetadataOfBuildTypeRequest { /** * * @type string * @memberof BuildTypeApigetFileMetadataOfBuildType */ path: string /** * * @type string * @memberof BuildTypeApigetFileMetadataOfBuildType */ btLocator: string /** * * @type string * @memberof BuildTypeApigetFileMetadataOfBuildType */ fields?: string /** * * @type boolean * @memberof BuildTypeApigetFileMetadataOfBuildType */ resolveParameters?: boolean } export interface BuildTypeApiGetFilesListForSubpathOfBuildTypeRequest { /** * * @type string * @memberof BuildTypeApigetFilesListForSubpathOfBuildType */ path: string /** * * @type string * @memberof BuildTypeApigetFilesListForSubpathOfBuildType */ btLocator: string /** * * @type string * @memberof BuildTypeApigetFilesListForSubpathOfBuildType */ basePath?: string /** * * @type string * @memberof BuildTypeApigetFilesListForSubpathOfBuildType */ locator?: string /** * * @type string * @memberof BuildTypeApigetFilesListForSubpathOfBuildType */ fields?: string /** * * @type boolean * @memberof BuildTypeApigetFilesListForSubpathOfBuildType */ resolveParameters?: boolean } export interface BuildTypeApiGetFilesListOfBuildTypeRequest { /** * * @type string * @memberof BuildTypeApigetFilesListOfBuildType */ btLocator: string /** * * @type string * @memberof BuildTypeApigetFilesListOfBuildType */ basePath?: string /** * * @type string * @memberof BuildTypeApigetFilesListOfBuildType */ locator?: string /** * * @type string * @memberof BuildTypeApigetFilesListOfBuildType */ fields?: string /** * * @type boolean * @memberof BuildTypeApigetFilesListOfBuildType */ resolveParameters?: boolean } export interface BuildTypeApiGetSnapshotDependencyRequest { /** * * @type string * @memberof BuildTypeApigetSnapshotDependency */ btLocator: string /** * * @type string * @memberof BuildTypeApigetSnapshotDependency */ snapshotDepLocator: string /** * * @type string * @memberof BuildTypeApigetSnapshotDependency */ fields?: string } export interface BuildTypeApiGetTriggerRequest { /** * * @type string * @memberof BuildTypeApigetTrigger */ btLocator: string /** * * @type string * @memberof BuildTypeApigetTrigger */ triggerLocator: string /** * * @type string * @memberof BuildTypeApigetTrigger */ fields?: string } export interface BuildTypeApiGetTriggerParameterRequest { /** * * @type string * @memberof BuildTypeApigetTriggerParameter */ btLocator: string /** * * @type string * @memberof BuildTypeApigetTriggerParameter */ triggerLocator: string /** * * @type string * @memberof BuildTypeApigetTriggerParameter */ fieldName: string } export interface BuildTypeApiGetVcsRootRequest { /** * * @type string * @memberof BuildTypeApigetVcsRoot */ btLocator: string /** * * @type string * @memberof BuildTypeApigetVcsRoot */ vcsRootLocator: string /** * * @type string * @memberof BuildTypeApigetVcsRoot */ fields?: string } export interface BuildTypeApiGetVcsRootCheckoutRulesRequest { /** * * @type string * @memberof BuildTypeApigetVcsRootCheckoutRules */ btLocator: string /** * * @type string * @memberof BuildTypeApigetVcsRootCheckoutRules */ vcsRootLocator: string } export interface BuildTypeApiGetVcsRootInstancesOfBuildTypeRequest { /** * * @type string * @memberof BuildTypeApigetVcsRootInstancesOfBuildType */ btLocator: string /** * * @type string * @memberof BuildTypeApigetVcsRootInstancesOfBuildType */ fields?: string } export interface BuildTypeApiGetZippedFileOfBuildTypeRequest { /** * * @type string * @memberof BuildTypeApigetZippedFileOfBuildType */ path: string /** * * @type string * @memberof BuildTypeApigetZippedFileOfBuildType */ btLocator: string /** * * @type string * @memberof BuildTypeApigetZippedFileOfBuildType */ basePath?: string /** * * @type string * @memberof BuildTypeApigetZippedFileOfBuildType */ locator?: string /** * * @type string * @memberof BuildTypeApigetZippedFileOfBuildType */ name?: string /** * * @type boolean * @memberof BuildTypeApigetZippedFileOfBuildType */ resolveParameters?: boolean } export interface BuildTypeApiRemoveAllTemplatesRequest { /** * * @type string * @memberof BuildTypeApiremoveAllTemplates */ btLocator: string /** * * @type boolean * @memberof BuildTypeApiremoveAllTemplates */ inlineSettings?: boolean } export interface BuildTypeApiRemoveTemplateRequest { /** * * @type string * @memberof BuildTypeApiremoveTemplate */ btLocator: string /** * * @type string * @memberof BuildTypeApiremoveTemplate */ templateLocator: string /** * * @type boolean * @memberof BuildTypeApiremoveTemplate */ inlineSettings?: boolean } export interface BuildTypeApiReplaceAgentRequirementRequest { /** * * @type string * @memberof BuildTypeApireplaceAgentRequirement */ btLocator: string /** * * @type string * @memberof BuildTypeApireplaceAgentRequirement */ agentRequirementLocator: string /** * * @type string * @memberof BuildTypeApireplaceAgentRequirement */ fields?: string /** * * @type AgentRequirement * @memberof BuildTypeApireplaceAgentRequirement */ body?: AgentRequirement } export interface BuildTypeApiReplaceAllAgentRequirementsRequest { /** * * @type string * @memberof BuildTypeApireplaceAllAgentRequirements */ btLocator: string /** * * @type string * @memberof BuildTypeApireplaceAllAgentRequirements */ fields?: string /** * * @type AgentRequirements * @memberof BuildTypeApireplaceAllAgentRequirements */ body?: AgentRequirements } export interface BuildTypeApiReplaceAllArtifactDependenciesRequest { /** * * @type string * @memberof BuildTypeApireplaceAllArtifactDependencies */ btLocator: string /** * * @type string * @memberof BuildTypeApireplaceAllArtifactDependencies */ fields?: string /** * * @type ArtifactDependencies * @memberof BuildTypeApireplaceAllArtifactDependencies */ body?: ArtifactDependencies } export interface BuildTypeApiReplaceAllBuildFeaturesRequest { /** * * @type string * @memberof BuildTypeApireplaceAllBuildFeatures */ btLocator: string /** * * @type string * @memberof BuildTypeApireplaceAllBuildFeatures */ fields?: string /** * * @type Features * @memberof BuildTypeApireplaceAllBuildFeatures */ body?: Features } export interface BuildTypeApiReplaceAllBuildStepsRequest { /** * * @type string * @memberof BuildTypeApireplaceAllBuildSteps */ btLocator: string /** * * @type string * @memberof BuildTypeApireplaceAllBuildSteps */ fields?: string /** * * @type Steps * @memberof BuildTypeApireplaceAllBuildSteps */ body?: Steps } export interface BuildTypeApiReplaceAllSnapshotDependenciesRequest { /** * * @type string * @memberof BuildTypeApireplaceAllSnapshotDependencies */ btLocator: string /** * * @type string * @memberof BuildTypeApireplaceAllSnapshotDependencies */ fields?: string /** * * @type SnapshotDependencies * @memberof BuildTypeApireplaceAllSnapshotDependencies */ body?: SnapshotDependencies } export interface BuildTypeApiReplaceAllTriggersRequest { /** * * @type string * @memberof BuildTypeApireplaceAllTriggers */ btLocator: string /** * * @type string * @memberof BuildTypeApireplaceAllTriggers */ fields?: string /** * * @type Triggers * @memberof BuildTypeApireplaceAllTriggers */ body?: Triggers } export interface BuildTypeApiReplaceAllVcsRootsRequest { /** * * @type string * @memberof BuildTypeApireplaceAllVcsRoots */ btLocator: string /** * * @type string * @memberof BuildTypeApireplaceAllVcsRoots */ fields?: string /** * * @type VcsRootEntries * @memberof BuildTypeApireplaceAllVcsRoots */ body?: VcsRootEntries } export interface BuildTypeApiReplaceArtifactDependencyRequest { /** * * @type string * @memberof BuildTypeApireplaceArtifactDependency */ btLocator: string /** * * @type string * @memberof BuildTypeApireplaceArtifactDependency */ artifactDepLocator: string /** * * @type string * @memberof BuildTypeApireplaceArtifactDependency */ fields?: string /** * * @type ArtifactDependency * @memberof BuildTypeApireplaceArtifactDependency */ body?: ArtifactDependency } export interface BuildTypeApiReplaceBuildFeatureRequest { /** * * @type string * @memberof BuildTypeApireplaceBuildFeature */ btLocator: string /** * * @type string * @memberof BuildTypeApireplaceBuildFeature */ featureId: string /** * * @type string * @memberof BuildTypeApireplaceBuildFeature */ fields?: string /** * * @type Feature * @memberof BuildTypeApireplaceBuildFeature */ body?: Feature } export interface BuildTypeApiReplaceBuildFeatureParametersRequest { /** * * @type string * @memberof BuildTypeApireplaceBuildFeatureParameters */ btLocator: string /** * * @type string * @memberof BuildTypeApireplaceBuildFeatureParameters */ featureId: string /** * * @type string * @memberof BuildTypeApireplaceBuildFeatureParameters */ fields?: string /** * * @type Properties * @memberof BuildTypeApireplaceBuildFeatureParameters */ body?: Properties } export interface BuildTypeApiReplaceBuildStepRequest { /** * * @type string * @memberof BuildTypeApireplaceBuildStep */ btLocator: string /** * * @type string * @memberof BuildTypeApireplaceBuildStep */ stepId: string /** * * @type string * @memberof BuildTypeApireplaceBuildStep */ fields?: string /** * * @type Step * @memberof BuildTypeApireplaceBuildStep */ body?: Step } export interface BuildTypeApiReplaceSnapshotDependencyRequest { /** * * @type string * @memberof BuildTypeApireplaceSnapshotDependency */ btLocator: string /** * * @type string * @memberof BuildTypeApireplaceSnapshotDependency */ snapshotDepLocator: string /** * * @type string * @memberof BuildTypeApireplaceSnapshotDependency */ fields?: string /** * * @type SnapshotDependency * @memberof BuildTypeApireplaceSnapshotDependency */ body?: SnapshotDependency } export interface BuildTypeApiReplaceTriggerRequest { /** * * @type string * @memberof BuildTypeApireplaceTrigger */ btLocator: string /** * * @type string * @memberof BuildTypeApireplaceTrigger */ triggerLocator: string /** * * @type string * @memberof BuildTypeApireplaceTrigger */ fields?: string /** * * @type Trigger * @memberof BuildTypeApireplaceTrigger */ body?: Trigger } export interface BuildTypeApiSetAgentRequirementParameterRequest { /** * * @type string * @memberof BuildTypeApisetAgentRequirementParameter */ btLocator: string /** * * @type string * @memberof BuildTypeApisetAgentRequirementParameter */ agentRequirementLocator: string /** * * @type string * @memberof BuildTypeApisetAgentRequirementParameter */ fieldName: string /** * * @type string * @memberof BuildTypeApisetAgentRequirementParameter */ body?: string } export interface BuildTypeApiSetArtifactDependencyParameterRequest { /** * * @type string * @memberof BuildTypeApisetArtifactDependencyParameter */ btLocator: string /** * * @type string * @memberof BuildTypeApisetArtifactDependencyParameter */ artifactDepLocator: string /** * * @type string * @memberof BuildTypeApisetArtifactDependencyParameter */ fieldName: string /** * * @type string * @memberof BuildTypeApisetArtifactDependencyParameter */ body?: string } export interface BuildTypeApiSetBuildFeatureParameterRequest { /** * * @type string * @memberof BuildTypeApisetBuildFeatureParameter */ btLocator: string /** * * @type string * @memberof BuildTypeApisetBuildFeatureParameter */ featureId: string /** * * @type string * @memberof BuildTypeApisetBuildFeatureParameter */ name: string /** * * @type string * @memberof BuildTypeApisetBuildFeatureParameter */ body?: string } export interface BuildTypeApiSetBuildStepParameterRequest { /** * * @type string * @memberof BuildTypeApisetBuildStepParameter */ btLocator: string /** * * @type string * @memberof BuildTypeApisetBuildStepParameter */ stepId: string /** * * @type string * @memberof BuildTypeApisetBuildStepParameter */ fieldName: string /** * * @type string * @memberof BuildTypeApisetBuildStepParameter */ body?: string } export interface BuildTypeApiSetBuildTypeFieldRequest { /** * * @type string * @memberof BuildTypeApisetBuildTypeField */ btLocator: string /** * * @type string * @memberof BuildTypeApisetBuildTypeField */ field: string /** * * @type string * @memberof BuildTypeApisetBuildTypeField */ body?: string } export interface BuildTypeApiSetBuildTypeTemplatesRequest { /** * * @type string * @memberof BuildTypeApisetBuildTypeTemplates */ btLocator: string /** * * @type boolean * @memberof BuildTypeApisetBuildTypeTemplates */ optimizeSettings?: boolean /** * * @type string * @memberof BuildTypeApisetBuildTypeTemplates */ fields?: string /** * * @type BuildTypes * @memberof BuildTypeApisetBuildTypeTemplates */ body?: BuildTypes } export interface BuildTypeApiSetTriggerParameterRequest { /** * * @type string * @memberof BuildTypeApisetTriggerParameter */ btLocator: string /** * * @type string * @memberof BuildTypeApisetTriggerParameter */ triggerLocator: string /** * * @type string * @memberof BuildTypeApisetTriggerParameter */ fieldName: string /** * * @type string * @memberof BuildTypeApisetTriggerParameter */ body?: string } export interface BuildTypeApiUpdateBuildParameterOfBuildTypeRequest { /** * * @type string * @memberof BuildTypeApiupdateBuildParameterOfBuildType */ name: string /** * * @type string * @memberof BuildTypeApiupdateBuildParameterOfBuildType */ btLocator: string /** * * @type string * @memberof BuildTypeApiupdateBuildParameterOfBuildType */ fields?: string /** * * @type Property * @memberof BuildTypeApiupdateBuildParameterOfBuildType */ body?: Property } export interface BuildTypeApiUpdateBuildParameterSpecificationOfBuildTypeRequest { /** * * @type string * @memberof BuildTypeApiupdateBuildParameterSpecificationOfBuildType */ name: string /** * * @type string * @memberof BuildTypeApiupdateBuildParameterSpecificationOfBuildType */ btLocator: string /** * * @type string * @memberof BuildTypeApiupdateBuildParameterSpecificationOfBuildType */ body?: string } export interface BuildTypeApiUpdateBuildParameterTypeOfBuildTypeRequest { /** * * @type string * @memberof BuildTypeApiupdateBuildParameterTypeOfBuildType */ name: string /** * * @type string * @memberof BuildTypeApiupdateBuildParameterTypeOfBuildType */ btLocator: string /** * * @type Type * @memberof BuildTypeApiupdateBuildParameterTypeOfBuildType */ body?: Type } export interface BuildTypeApiUpdateBuildParameterValueOfBuildTypeRequest { /** * * @type string * @memberof BuildTypeApiupdateBuildParameterValueOfBuildType */ name: string /** * * @type string * @memberof BuildTypeApiupdateBuildParameterValueOfBuildType */ btLocator: string /** * * @type string * @memberof BuildTypeApiupdateBuildParameterValueOfBuildType */ body?: string } export interface BuildTypeApiUpdateBuildParametersOfBuildTypeRequest { /** * * @type string * @memberof BuildTypeApiupdateBuildParametersOfBuildType */ btLocator: string /** * * @type string * @memberof BuildTypeApiupdateBuildParametersOfBuildType */ fields?: string /** * * @type Properties * @memberof BuildTypeApiupdateBuildParametersOfBuildType */ body?: Properties } export interface BuildTypeApiUpdateBuildTypeVcsRootRequest { /** * * @type string * @memberof BuildTypeApiupdateBuildTypeVcsRoot */ btLocator: string /** * * @type string * @memberof BuildTypeApiupdateBuildTypeVcsRoot */ vcsRootLocator: string /** * * @type string * @memberof BuildTypeApiupdateBuildTypeVcsRoot */ fields?: string /** * * @type VcsRootEntry * @memberof BuildTypeApiupdateBuildTypeVcsRoot */ body?: VcsRootEntry } export interface BuildTypeApiUpdateBuildTypeVcsRootCheckoutRulesRequest { /** * * @type string * @memberof BuildTypeApiupdateBuildTypeVcsRootCheckoutRules */ btLocator: string /** * * @type string * @memberof BuildTypeApiupdateBuildTypeVcsRootCheckoutRules */ vcsRootLocator: string /** * * @type string * @memberof BuildTypeApiupdateBuildTypeVcsRootCheckoutRules */ body?: string } export class ObjectBuildTypeApi { private api: ObservableBuildTypeApi public constructor(configuration: Configuration, requestFactory?: BuildTypeApiRequestFactory, responseProcessor?: BuildTypeApiResponseProcessor) { this.api = new ObservableBuildTypeApi(configuration, requestFactory, responseProcessor); } /** * Add an agent requirement to the matching build configuration. * @param param the request object */ public addAgentRequirementToBuildType(param: BuildTypeApiAddAgentRequirementToBuildTypeRequest, options?: Configuration): Promise<AgentRequirement> { return this.api.addAgentRequirementToBuildType(param.btLocator, param.fields, param.body, options).toPromise(); } /** * Add an artifact dependency to the matching build configuration. * @param param the request object */ public addArtifactDependencyToBuildType(param: BuildTypeApiAddArtifactDependencyToBuildTypeRequest, options?: Configuration): Promise<ArtifactDependency> { return this.api.addArtifactDependencyToBuildType(param.btLocator, param.fields, param.body, options).toPromise(); } /** * Add build feature to the matching build configuration. * @param param the request object */ public addBuildFeatureToBuildType(param: BuildTypeApiAddBuildFeatureToBuildTypeRequest, options?: Configuration): Promise<Feature> { return this.api.addBuildFeatureToBuildType(param.btLocator, param.fields, param.body, options).toPromise(); } /** * Add a build step to the matching build configuration. * @param param the request object */ public addBuildStepToBuildType(param: BuildTypeApiAddBuildStepToBuildTypeRequest, options?: Configuration): Promise<Step> { return this.api.addBuildStepToBuildType(param.btLocator, param.fields, param.body, options).toPromise(); } /** * Add a build template to the matching build configuration. * @param param the request object */ public addBuildTemplate(param: BuildTypeApiAddBuildTemplateRequest, options?: Configuration): Promise<BuildType> { return this.api.addBuildTemplate(param.btLocator, param.optimizeSettings, param.fields, param.body, options).toPromise(); } /** * Update build feature parameter for the matching build configuration. * @param param the request object */ public addParameterToBuildFeature(param: BuildTypeApiAddParameterToBuildFeatureRequest, options?: Configuration): Promise<string> { return this.api.addParameterToBuildFeature(param.btLocator, param.featureId, param.parameterName, param.body, options).toPromise(); } /** * Add a parameter to a build step of the matching build configuration. * @param param the request object */ public addParameterToBuildStep(param: BuildTypeApiAddParameterToBuildStepRequest, options?: Configuration): Promise<string> { return this.api.addParameterToBuildStep(param.btLocator, param.stepId, param.parameterName, param.body, options).toPromise(); } /** * Add a snapshot dependency to the matching build configuration. * @param param the request object */ public addSnapshotDependencyToBuildType(param: BuildTypeApiAddSnapshotDependencyToBuildTypeRequest, options?: Configuration): Promise<SnapshotDependency> { return this.api.addSnapshotDependencyToBuildType(param.btLocator, param.fields, param.body, options).toPromise(); } /** * Add a trigger to the matching build configuration. * @param param the request object */ public addTriggerToBuildType(param: BuildTypeApiAddTriggerToBuildTypeRequest, options?: Configuration): Promise<Trigger> { return this.api.addTriggerToBuildType(param.btLocator, param.fields, param.body, options).toPromise(); } /** * Add a VCS root to the matching build. * @param param the request object */ public addVcsRootToBuildType(param: BuildTypeApiAddVcsRootToBuildTypeRequest, options?: Configuration): Promise<VcsRootEntry> { return this.api.addVcsRootToBuildType(param.btLocator, param.fields, param.body, options).toPromise(); } /** * Create a build parameter. * @param param the request object */ public createBuildParameterOfBuildType(param: BuildTypeApiCreateBuildParameterOfBuildTypeRequest, options?: Configuration): Promise<Property> { return this.api.createBuildParameterOfBuildType(param.btLocator, param.fields, param.body, options).toPromise(); } /** * Create a new build configuration. * @param param the request object */ public createBuildType(param: BuildTypeApiCreateBuildTypeRequest, options?: Configuration): Promise<BuildType> { return this.api.createBuildType(param.fields, param.body, options).toPromise(); } /** * Remove an agent requirement of the matching build configuration. * @param param the request object */ public deleteAgentRequirement(param: BuildTypeApiDeleteAgentRequirementRequest, options?: Configuration): Promise<void> { return this.api.deleteAgentRequirement(param.btLocator, param.agentRequirementLocator, options).toPromise(); } /** * Remove an artifact dependency from the matching build configuration. * @param param the request object */ public deleteArtifactDependency(param: BuildTypeApiDeleteArtifactDependencyRequest, options?: Configuration): Promise<void> { return this.api.deleteArtifactDependency(param.btLocator, param.artifactDepLocator, options).toPromise(); } /** * Delete build parameter. * @param param the request object */ public deleteBuildParameterOfBuildType(param: BuildTypeApiDeleteBuildParameterOfBuildTypeRequest, options?: Configuration): Promise<void> { return this.api.deleteBuildParameterOfBuildType(param.name, param.btLocator, options).toPromise(); } /** * Delete all build parameters. * @param param the request object */ public deleteBuildParametersOfBuildType(param: BuildTypeApiDeleteBuildParametersOfBuildTypeRequest, options?: Configuration): Promise<void> { return this.api.deleteBuildParametersOfBuildType(param.btLocator, options).toPromise(); } /** * Delete a build step of the matching build configuration. * @param param the request object */ public deleteBuildStep(param: BuildTypeApiDeleteBuildStepRequest, options?: Configuration): Promise<void> { return this.api.deleteBuildStep(param.btLocator, param.stepId, options).toPromise(); } /** * Update a parameter of a build step of the matching build configuration. * @param param the request object */ public deleteBuildStepParameters(param: BuildTypeApiDeleteBuildStepParametersRequest, options?: Configuration): Promise<Properties> { return this.api.deleteBuildStepParameters(param.btLocator, param.stepId, param.fields, param.body, options).toPromise(); } /** * Delete build configuration matching the locator. * @param param the request object */ public deleteBuildType(param: BuildTypeApiDeleteBuildTypeRequest, options?: Configuration): Promise<void> { return this.api.deleteBuildType(param.btLocator, options).toPromise(); } /** * Remove a build feature of the matching build configuration. * @param param the request object */ public deleteFeatureOfBuildType(param: BuildTypeApiDeleteFeatureOfBuildTypeRequest, options?: Configuration): Promise<void> { return this.api.deleteFeatureOfBuildType(param.btLocator, param.featureId, options).toPromise(); } /** * Delete a snapshot dependency of the matching build configuration. * @param param the request object */ public deleteSnapshotDependency(param: BuildTypeApiDeleteSnapshotDependencyRequest, options?: Configuration): Promise<void> { return this.api.deleteSnapshotDependency(param.btLocator, param.snapshotDepLocator, options).toPromise(); } /** * Delete a trigger of the matching build configuration. * @param param the request object */ public deleteTrigger(param: BuildTypeApiDeleteTriggerRequest, options?: Configuration): Promise<void> { return this.api.deleteTrigger(param.btLocator, param.triggerLocator, options).toPromise(); } /** * Remove a VCS root of the matching build configuration. * @param param the request object */ public deleteVcsRootOfBuildType(param: BuildTypeApiDeleteVcsRootOfBuildTypeRequest, options?: Configuration): Promise<void> { return this.api.deleteVcsRootOfBuildType(param.btLocator, param.vcsRootLocator, options).toPromise(); } /** * Download specific file. * @param param the request object */ public downloadFileOfBuildType(param: BuildTypeApiDownloadFileOfBuildTypeRequest, options?: Configuration): Promise<void> { return this.api.downloadFileOfBuildType(param.path, param.btLocator, param.resolveParameters, options).toPromise(); } /** * Get an agent requirement of the matching build configuration. * @param param the request object */ public getAgentRequirement(param: BuildTypeApiGetAgentRequirementRequest, options?: Configuration): Promise<AgentRequirement> { return this.api.getAgentRequirement(param.btLocator, param.agentRequirementLocator, param.fields, options).toPromise(); } /** * Get a setting of an agent requirement of the matching build configuration. * @param param the request object */ public getAgentRequirementParameter(param: BuildTypeApiGetAgentRequirementParameterRequest, options?: Configuration): Promise<string> { return this.api.getAgentRequirementParameter(param.btLocator, param.agentRequirementLocator, param.fieldName, options).toPromise(); } /** * Get external IDs of the matching build configuration. * @param param the request object */ public getAliases(param: BuildTypeApiGetAliasesRequest, options?: Configuration): Promise<Items> { return this.api.getAliases(param.btLocator, param.field, options).toPromise(); } /** * Get all agent requirements of the matching build configuration. * @param param the request object */ public getAllAgentRequirements(param: BuildTypeApiGetAllAgentRequirementsRequest, options?: Configuration): Promise<AgentRequirements> { return this.api.getAllAgentRequirements(param.btLocator, param.fields, options).toPromise(); } /** * Get all artifact dependencies of the matching build configuration. * @param param the request object */ public getAllArtifactDependencies(param: BuildTypeApiGetAllArtifactDependenciesRequest, options?: Configuration): Promise<ArtifactDependencies> { return this.api.getAllArtifactDependencies(param.btLocator, param.fields, options).toPromise(); } /** * Get all branches of the matching build configuration. * @param param the request object */ public getAllBranchesOfBuildType(param: BuildTypeApiGetAllBranchesOfBuildTypeRequest, options?: Configuration): Promise<Branches> { return this.api.getAllBranchesOfBuildType(param.btLocator, param.locator, param.fields, options).toPromise(); } /** * Get all parameters of a build feature of the matching build configuration. * @param param the request object */ public getAllBuildFeatureParameters(param: BuildTypeApiGetAllBuildFeatureParametersRequest, options?: Configuration): Promise<Properties> { return this.api.getAllBuildFeatureParameters(param.btLocator, param.featureId, param.fields, options).toPromise(); } /** * Get all build features of the matching build configuration. * @param param the request object */ public getAllBuildFeatures(param: BuildTypeApiGetAllBuildFeaturesRequest, options?: Configuration): Promise<Features> { return this.api.getAllBuildFeatures(param.btLocator, param.fields, options).toPromise(); } /** * Get all parameters of a build step of the matching build configuration. * @param param the request object */ public getAllBuildStepParameters(param: BuildTypeApiGetAllBuildStepParametersRequest, options?: Configuration): Promise<Properties> { return this.api.getAllBuildStepParameters(param.btLocator, param.stepId, param.fields, options).toPromise(); } /** * Get all build steps of the matching build configuration. * @param param the request object */ public getAllBuildSteps(param: BuildTypeApiGetAllBuildStepsRequest, options?: Configuration): Promise<Steps> { return this.api.getAllBuildSteps(param.btLocator, param.fields, options).toPromise(); } /** * Get all build templates of the matching build configuration. * @param param the request object */ public getAllBuildTemplates(param: BuildTypeApiGetAllBuildTemplatesRequest, options?: Configuration): Promise<BuildTypes> { return this.api.getAllBuildTemplates(param.btLocator, param.fields, options).toPromise(); } /** * Get all build configurations. * @param param the request object */ public getAllBuildTypes(param: BuildTypeApiGetAllBuildTypesRequest, options?: Configuration): Promise<BuildTypes> { return this.api.getAllBuildTypes(param.locator, param.fields, options).toPromise(); } /** * Get all investigations of the matching build configuration. * @param param the request object */ public getAllInvestigationsOfBuildType(param: BuildTypeApiGetAllInvestigationsOfBuildTypeRequest, options?: Configuration): Promise<Investigations> { return this.api.getAllInvestigationsOfBuildType(param.btLocator, param.fields, options).toPromise(); } /** * Get all snapshot dependencies of the matching build configuration. * @param param the request object */ public getAllSnapshotDependencies(param: BuildTypeApiGetAllSnapshotDependenciesRequest, options?: Configuration): Promise<SnapshotDependencies> { return this.api.getAllSnapshotDependencies(param.btLocator, param.fields, options).toPromise(); } /** * Get all triggers of the matching build configuration. * @param param the request object */ public getAllTriggers(param: BuildTypeApiGetAllTriggersRequest, options?: Configuration): Promise<Triggers> { return this.api.getAllTriggers(param.btLocator, param.fields, options).toPromise(); } /** * Get all VCS roots of the matching build configuration. * @param param the request object */ public getAllVcsRootsOfBuildType(param: BuildTypeApiGetAllVcsRootsOfBuildTypeRequest, options?: Configuration): Promise<VcsRootEntries> { return this.api.getAllVcsRootsOfBuildType(param.btLocator, param.fields, options).toPromise(); } /** * Get an artifact dependency of the matching build configuration. * @param param the request object */ public getArtifactDependency(param: BuildTypeApiGetArtifactDependencyRequest, options?: Configuration): Promise<ArtifactDependency> { return this.api.getArtifactDependency(param.btLocator, param.artifactDepLocator, param.fields, options).toPromise(); } /** * Get a parameter of an artifact dependency of the matching build configuration. * @param param the request object */ public getArtifactDependencyParameter(param: BuildTypeApiGetArtifactDependencyParameterRequest, options?: Configuration): Promise<string> { return this.api.getArtifactDependencyParameter(param.btLocator, param.artifactDepLocator, param.fieldName, options).toPromise(); } /** * Get a build feature of the matching build configuration. * @param param the request object */ public getBuildFeature(param: BuildTypeApiGetBuildFeatureRequest, options?: Configuration): Promise<Feature> { return this.api.getBuildFeature(param.btLocator, param.featureId, param.fields, options).toPromise(); } /** * Get a parameter of a build feature of the matching build configuration. * @param param the request object */ public getBuildFeatureParameter(param: BuildTypeApiGetBuildFeatureParameterRequest, options?: Configuration): Promise<string> { return this.api.getBuildFeatureParameter(param.btLocator, param.featureId, param.parameterName, options).toPromise(); } /** * Get the setting of a build feature of the matching build configuration. * @param param the request object */ public getBuildFeatureSetting(param: BuildTypeApiGetBuildFeatureSettingRequest, options?: Configuration): Promise<string> { return this.api.getBuildFeatureSetting(param.btLocator, param.featureId, param.name, options).toPromise(); } /** * Get build parameter. * @param param the request object */ public getBuildParameterOfBuildType(param: BuildTypeApiGetBuildParameterOfBuildTypeRequest, options?: Configuration): Promise<Property> { return this.api.getBuildParameterOfBuildType(param.name, param.btLocator, param.fields, options).toPromise(); } /** * Get build parameter specification. * @param param the request object */ public getBuildParameterSpecificationOfBuildType(param: BuildTypeApiGetBuildParameterSpecificationOfBuildTypeRequest, options?: Configuration): Promise<string> { return this.api.getBuildParameterSpecificationOfBuildType(param.name, param.btLocator, options).toPromise(); } /** * Get type of build parameter. * @param param the request object */ public getBuildParameterTypeOfBuildType(param: BuildTypeApiGetBuildParameterTypeOfBuildTypeRequest, options?: Configuration): Promise<Type> { return this.api.getBuildParameterTypeOfBuildType(param.name, param.btLocator, options).toPromise(); } /** * Get value of build parameter. * @param param the request object */ public getBuildParameterValueOfBuildType(param: BuildTypeApiGetBuildParameterValueOfBuildTypeRequest, options?: Configuration): Promise<string> { return this.api.getBuildParameterValueOfBuildType(param.name, param.btLocator, options).toPromise(); } /** * Get build parameters. * @param param the request object */ public getBuildParametersOfBuildType(param: BuildTypeApiGetBuildParametersOfBuildTypeRequest, options?: Configuration): Promise<Properties> { return this.api.getBuildParametersOfBuildType(param.btLocator, param.locator, param.fields, options).toPromise(); } /** * Get a build step of the matching build configuration. * @param param the request object */ public getBuildStep(param: BuildTypeApiGetBuildStepRequest, options?: Configuration): Promise<Step> { return this.api.getBuildStep(param.btLocator, param.stepId, param.fields, options).toPromise(); } /** * Get a parameter of a build step of the matching build configuration. * @param param the request object */ public getBuildStepParameter(param: BuildTypeApiGetBuildStepParameterRequest, options?: Configuration): Promise<string> { return this.api.getBuildStepParameter(param.btLocator, param.stepId, param.parameterName, options).toPromise(); } /** * Get the setting of a build step of the matching build configuration. * @param param the request object */ public getBuildStepSetting(param: BuildTypeApiGetBuildStepSettingRequest, options?: Configuration): Promise<string> { return this.api.getBuildStepSetting(param.btLocator, param.stepId, param.fieldName, options).toPromise(); } /** * Get a template of the matching build configuration. * @param param the request object */ public getBuildTemplate(param: BuildTypeApiGetBuildTemplateRequest, options?: Configuration): Promise<BuildType> { return this.api.getBuildTemplate(param.btLocator, param.templateLocator, param.fields, options).toPromise(); } /** * Get build configuration matching the locator. * @param param the request object */ public getBuildType(param: BuildTypeApiGetBuildTypeRequest, options?: Configuration): Promise<BuildType> { return this.api.getBuildType(param.btLocator, param.fields, options).toPromise(); } /** * Get tags of builds of the matching build configuration. * @param param the request object */ public getBuildTypeBuildTags(param: BuildTypeApiGetBuildTypeBuildTagsRequest, options?: Configuration): Promise<Tags> { return this.api.getBuildTypeBuildTags(param.btLocator, param.field, options).toPromise(); } /** * Get builds of the matching build configuration. * @param param the request object */ public getBuildTypeBuilds(param: BuildTypeApiGetBuildTypeBuildsRequest, options?: Configuration): Promise<Builds> { return this.api.getBuildTypeBuilds(param.btLocator, param.fields, options).toPromise(); } /** * Get a field of the matching build configuration. * @param param the request object */ public getBuildTypeField(param: BuildTypeApiGetBuildTypeFieldRequest, options?: Configuration): Promise<string> { return this.api.getBuildTypeField(param.btLocator, param.field, options).toPromise(); } /** * Get the settings file of the matching build configuration. * @param param the request object */ public getBuildTypeSettingsFile(param: BuildTypeApiGetBuildTypeSettingsFileRequest, options?: Configuration): Promise<string> { return this.api.getBuildTypeSettingsFile(param.btLocator, options).toPromise(); } /** * Get metadata of specific file. * @param param the request object */ public getFileMetadataOfBuildType(param: BuildTypeApiGetFileMetadataOfBuildTypeRequest, options?: Configuration): Promise<any> { return this.api.getFileMetadataOfBuildType(param.path, param.btLocator, param.fields, param.resolveParameters, options).toPromise(); } /** * List files under this path. * @param param the request object */ public getFilesListForSubpathOfBuildType(param: BuildTypeApiGetFilesListForSubpathOfBuildTypeRequest, options?: Configuration): Promise<Files> { return this.api.getFilesListForSubpathOfBuildType(param.path, param.btLocator, param.basePath, param.locator, param.fields, param.resolveParameters, options).toPromise(); } /** * List all files. * @param param the request object */ public getFilesListOfBuildType(param: BuildTypeApiGetFilesListOfBuildTypeRequest, options?: Configuration): Promise<Files> { return this.api.getFilesListOfBuildType(param.btLocator, param.basePath, param.locator, param.fields, param.resolveParameters, options).toPromise(); } /** * Get a snapshot dependency of the matching build configuration. * @param param the request object */ public getSnapshotDependency(param: BuildTypeApiGetSnapshotDependencyRequest, options?: Configuration): Promise<SnapshotDependency> { return this.api.getSnapshotDependency(param.btLocator, param.snapshotDepLocator, param.fields, options).toPromise(); } /** * Get a trigger of the matching build configuration. * @param param the request object */ public getTrigger(param: BuildTypeApiGetTriggerRequest, options?: Configuration): Promise<Trigger> { return this.api.getTrigger(param.btLocator, param.triggerLocator, param.fields, options).toPromise(); } /** * Get a parameter of a trigger of the matching build configuration. * @param param the request object */ public getTriggerParameter(param: BuildTypeApiGetTriggerParameterRequest, options?: Configuration): Promise<string> { return this.api.getTriggerParameter(param.btLocator, param.triggerLocator, param.fieldName, options).toPromise(); } /** * Get a VCS root of the matching build configuration. * @param param the request object */ public getVcsRoot(param: BuildTypeApiGetVcsRootRequest, options?: Configuration): Promise<VcsRootEntry> { return this.api.getVcsRoot(param.btLocator, param.vcsRootLocator, param.fields, options).toPromise(); } /** * Get checkout rules of a VCS root of the matching build configuration. * @param param the request object */ public getVcsRootCheckoutRules(param: BuildTypeApiGetVcsRootCheckoutRulesRequest, options?: Configuration): Promise<string> { return this.api.getVcsRootCheckoutRules(param.btLocator, param.vcsRootLocator, options).toPromise(); } /** * Get all VCS root instances of the matching build configuration. * @param param the request object */ public getVcsRootInstancesOfBuildType(param: BuildTypeApiGetVcsRootInstancesOfBuildTypeRequest, options?: Configuration): Promise<VcsRootInstances> { return this.api.getVcsRootInstancesOfBuildType(param.btLocator, param.fields, options).toPromise(); } /** * Get specific file zipped. * @param param the request object */ public getZippedFileOfBuildType(param: BuildTypeApiGetZippedFileOfBuildTypeRequest, options?: Configuration): Promise<void> { return this.api.getZippedFileOfBuildType(param.path, param.btLocator, param.basePath, param.locator, param.name, param.resolveParameters, options).toPromise(); } /** * Detach all templates from the matching build configuration. * @param param the request object */ public removeAllTemplates(param: BuildTypeApiRemoveAllTemplatesRequest, options?: Configuration): Promise<void> { return this.api.removeAllTemplates(param.btLocator, param.inlineSettings, options).toPromise(); } /** * Detach a template from the matching build configuration. * @param param the request object */ public removeTemplate(param: BuildTypeApiRemoveTemplateRequest, options?: Configuration): Promise<void> { return this.api.removeTemplate(param.btLocator, param.templateLocator, param.inlineSettings, options).toPromise(); } /** * Update an agent requirement of the matching build configuration. * @param param the request object */ public replaceAgentRequirement(param: BuildTypeApiReplaceAgentRequirementRequest, options?: Configuration): Promise<AgentRequirement> { return this.api.replaceAgentRequirement(param.btLocator, param.agentRequirementLocator, param.fields, param.body, options).toPromise(); } /** * Update all agent requirements of the matching build configuration. * @param param the request object */ public replaceAllAgentRequirements(param: BuildTypeApiReplaceAllAgentRequirementsRequest, options?: Configuration): Promise<AgentRequirements> { return this.api.replaceAllAgentRequirements(param.btLocator, param.fields, param.body, options).toPromise(); } /** * Update all artifact dependencies of the matching build configuration. * @param param the request object */ public replaceAllArtifactDependencies(param: BuildTypeApiReplaceAllArtifactDependenciesRequest, options?: Configuration): Promise<ArtifactDependencies> { return this.api.replaceAllArtifactDependencies(param.btLocator, param.fields, param.body, options).toPromise(); } /** * Update all build features of the matching build configuration. * @param param the request object */ public replaceAllBuildFeatures(param: BuildTypeApiReplaceAllBuildFeaturesRequest, options?: Configuration): Promise<Features> { return this.api.replaceAllBuildFeatures(param.btLocator, param.fields, param.body, options).toPromise(); } /** * Update all build steps of the matching build configuration. * @param param the request object */ public replaceAllBuildSteps(param: BuildTypeApiReplaceAllBuildStepsRequest, options?: Configuration): Promise<Steps> { return this.api.replaceAllBuildSteps(param.btLocator, param.fields, param.body, options).toPromise(); } /** * Update all snapshot dependencies of the matching build configuration. * @param param the request object */ public replaceAllSnapshotDependencies(param: BuildTypeApiReplaceAllSnapshotDependenciesRequest, options?: Configuration): Promise<SnapshotDependencies> { return this.api.replaceAllSnapshotDependencies(param.btLocator, param.fields, param.body, options).toPromise(); } /** * Update all triggers of the matching build configuration. * @param param the request object */ public replaceAllTriggers(param: BuildTypeApiReplaceAllTriggersRequest, options?: Configuration): Promise<Triggers> { return this.api.replaceAllTriggers(param.btLocator, param.fields, param.body, options).toPromise(); } /** * Update all VCS roots of the matching build configuration. * @param param the request object */ public replaceAllVcsRoots(param: BuildTypeApiReplaceAllVcsRootsRequest, options?: Configuration): Promise<VcsRootEntries> { return this.api.replaceAllVcsRoots(param.btLocator, param.fields, param.body, options).toPromise(); } /** * Update an artifact dependency of the matching build configuration. * @param param the request object */ public replaceArtifactDependency(param: BuildTypeApiReplaceArtifactDependencyRequest, options?: Configuration): Promise<ArtifactDependency> { return this.api.replaceArtifactDependency(param.btLocator, param.artifactDepLocator, param.fields, param.body, options).toPromise(); } /** * Update a build feature of the matching build configuration. * @param param the request object */ public replaceBuildFeature(param: BuildTypeApiReplaceBuildFeatureRequest, options?: Configuration): Promise<Feature> { return this.api.replaceBuildFeature(param.btLocator, param.featureId, param.fields, param.body, options).toPromise(); } /** * Update a parameter of a build feature of the matching build configuration. * @param param the request object */ public replaceBuildFeatureParameters(param: BuildTypeApiReplaceBuildFeatureParametersRequest, options?: Configuration): Promise<Properties> { return this.api.replaceBuildFeatureParameters(param.btLocator, param.featureId, param.fields, param.body, options).toPromise(); } /** * Replace a build step of the matching build configuration. * @param param the request object */ public replaceBuildStep(param: BuildTypeApiReplaceBuildStepRequest, options?: Configuration): Promise<Step> { return this.api.replaceBuildStep(param.btLocator, param.stepId, param.fields, param.body, options).toPromise(); } /** * Update a snapshot dependency of the matching build configuration. * @param param the request object */ public replaceSnapshotDependency(param: BuildTypeApiReplaceSnapshotDependencyRequest, options?: Configuration): Promise<SnapshotDependency> { return this.api.replaceSnapshotDependency(param.btLocator, param.snapshotDepLocator, param.fields, param.body, options).toPromise(); } /** * Update a trigger of the matching build configuration. * @param param the request object */ public replaceTrigger(param: BuildTypeApiReplaceTriggerRequest, options?: Configuration): Promise<Trigger> { return this.api.replaceTrigger(param.btLocator, param.triggerLocator, param.fields, param.body, options).toPromise(); } /** * Update a parameter of an agent requirement of the matching build configuration. * @param param the request object */ public setAgentRequirementParameter(param: BuildTypeApiSetAgentRequirementParameterRequest, options?: Configuration): Promise<string> { return this.api.setAgentRequirementParameter(param.btLocator, param.agentRequirementLocator, param.fieldName, param.body, options).toPromise(); } /** * Update a parameter of an artifact dependency of the matching build configuration. * @param param the request object */ public setArtifactDependencyParameter(param: BuildTypeApiSetArtifactDependencyParameterRequest, options?: Configuration): Promise<string> { return this.api.setArtifactDependencyParameter(param.btLocator, param.artifactDepLocator, param.fieldName, param.body, options).toPromise(); } /** * Update a parameter of a build feature of the matching build configuration. * @param param the request object */ public setBuildFeatureParameter(param: BuildTypeApiSetBuildFeatureParameterRequest, options?: Configuration): Promise<string> { return this.api.setBuildFeatureParameter(param.btLocator, param.featureId, param.name, param.body, options).toPromise(); } /** * Update a parameter of a build step of the matching build configuration. * @param param the request object */ public setBuildStepParameter(param: BuildTypeApiSetBuildStepParameterRequest, options?: Configuration): Promise<string> { return this.api.setBuildStepParameter(param.btLocator, param.stepId, param.fieldName, param.body, options).toPromise(); } /** * Update a field of the matching build configuration. * @param param the request object */ public setBuildTypeField(param: BuildTypeApiSetBuildTypeFieldRequest, options?: Configuration): Promise<string> { return this.api.setBuildTypeField(param.btLocator, param.field, param.body, options).toPromise(); } /** * Update all templates of the matching build configuration. * @param param the request object */ public setBuildTypeTemplates(param: BuildTypeApiSetBuildTypeTemplatesRequest, options?: Configuration): Promise<BuildTypes> { return this.api.setBuildTypeTemplates(param.btLocator, param.optimizeSettings, param.fields, param.body, options).toPromise(); } /** * Update a parameter of a trigger of the matching build configuration. * @param param the request object */ public setTriggerParameter(param: BuildTypeApiSetTriggerParameterRequest, options?: Configuration): Promise<string> { return this.api.setTriggerParameter(param.btLocator, param.triggerLocator, param.fieldName, param.body, options).toPromise(); } /** * Update build parameter. * @param param the request object */ public updateBuildParameterOfBuildType(param: BuildTypeApiUpdateBuildParameterOfBuildTypeRequest, options?: Configuration): Promise<Property> { return this.api.updateBuildParameterOfBuildType(param.name, param.btLocator, param.fields, param.body, options).toPromise(); } /** * Update build parameter specification. * @param param the request object */ public updateBuildParameterSpecificationOfBuildType(param: BuildTypeApiUpdateBuildParameterSpecificationOfBuildTypeRequest, options?: Configuration): Promise<string> { return this.api.updateBuildParameterSpecificationOfBuildType(param.name, param.btLocator, param.body, options).toPromise(); } /** * Update type of build parameter. * @param param the request object */ public updateBuildParameterTypeOfBuildType(param: BuildTypeApiUpdateBuildParameterTypeOfBuildTypeRequest, options?: Configuration): Promise<Type> { return this.api.updateBuildParameterTypeOfBuildType(param.name, param.btLocator, param.body, options).toPromise(); } /** * Update value of build parameter. * @param param the request object */ public updateBuildParameterValueOfBuildType(param: BuildTypeApiUpdateBuildParameterValueOfBuildTypeRequest, options?: Configuration): Promise<string> { return this.api.updateBuildParameterValueOfBuildType(param.name, param.btLocator, param.body, options).toPromise(); } /** * Update build parameters. * @param param the request object */ public updateBuildParametersOfBuildType(param: BuildTypeApiUpdateBuildParametersOfBuildTypeRequest, options?: Configuration): Promise<Properties> { return this.api.updateBuildParametersOfBuildType(param.btLocator, param.fields, param.body, options).toPromise(); } /** * Update a VCS root of the matching build configuration. * @param param the request object */ public updateBuildTypeVcsRoot(param: BuildTypeApiUpdateBuildTypeVcsRootRequest, options?: Configuration): Promise<VcsRootEntry> { return this.api.updateBuildTypeVcsRoot(param.btLocator, param.vcsRootLocator, param.fields, param.body, options).toPromise(); } /** * Update checkout rules of a VCS root of the matching build configuration. * @param param the request object */ public updateBuildTypeVcsRootCheckoutRules(param: BuildTypeApiUpdateBuildTypeVcsRootCheckoutRulesRequest, options?: Configuration): Promise<string> { return this.api.updateBuildTypeVcsRootCheckoutRules(param.btLocator, param.vcsRootLocator, param.body, options).toPromise(); } } import { ObservableChangeApi } from "./ObservableAPI.ts"; import { ChangeApiRequestFactory, ChangeApiResponseProcessor} from "../apis/ChangeApi.ts"; export interface ChangeApiGetAllChangesRequest { /** * * @type string * @memberof ChangeApigetAllChanges */ locator?: string /** * * @type string * @memberof ChangeApigetAllChanges */ fields?: string } export interface ChangeApiGetChangeRequest { /** * * @type string * @memberof ChangeApigetChange */ changeLocator: string /** * * @type string * @memberof ChangeApigetChange */ fields?: string } export interface ChangeApiGetChangeAttributesRequest { /** * * @type string * @memberof ChangeApigetChangeAttributes */ changeLocator: string /** * * @type string * @memberof ChangeApigetChangeAttributes */ fields?: string } export interface ChangeApiGetChangeDuplicatesRequest { /** * * @type string * @memberof ChangeApigetChangeDuplicates */ changeLocator: string /** * * @type string * @memberof ChangeApigetChangeDuplicates */ fields?: string } export interface ChangeApiGetChangeFieldRequest { /** * * @type string * @memberof ChangeApigetChangeField */ changeLocator: string /** * * @type string * @memberof ChangeApigetChangeField */ field: string } export interface ChangeApiGetChangeFirstBuildsRequest { /** * * @type string * @memberof ChangeApigetChangeFirstBuilds */ changeLocator: string /** * * @type string * @memberof ChangeApigetChangeFirstBuilds */ fields?: string } export interface ChangeApiGetChangeIssueRequest { /** * * @type string * @memberof ChangeApigetChangeIssue */ changeLocator: string } export interface ChangeApiGetChangeParentChangesRequest { /** * * @type string * @memberof ChangeApigetChangeParentChanges */ changeLocator: string /** * * @type string * @memberof ChangeApigetChangeParentChanges */ fields?: string } export interface ChangeApiGetChangeParentRevisionsRequest { /** * * @type string * @memberof ChangeApigetChangeParentRevisions */ changeLocator: string } export interface ChangeApiGetChangeRelatedBuildTypesRequest { /** * * @type string * @memberof ChangeApigetChangeRelatedBuildTypes */ changeLocator: string /** * * @type string * @memberof ChangeApigetChangeRelatedBuildTypes */ fields?: string } export interface ChangeApiGetChangeVcsRootRequest { /** * * @type string * @memberof ChangeApigetChangeVcsRoot */ changeLocator: string /** * * @type string * @memberof ChangeApigetChangeVcsRoot */ fields?: string } export class ObjectChangeApi { private api: ObservableChangeApi public constructor(configuration: Configuration, requestFactory?: ChangeApiRequestFactory, responseProcessor?: ChangeApiResponseProcessor) { this.api = new ObservableChangeApi(configuration, requestFactory, responseProcessor); } /** * Get all changes. * @param param the request object */ public getAllChanges(param: ChangeApiGetAllChangesRequest, options?: Configuration): Promise<Changes> { return this.api.getAllChanges(param.locator, param.fields, options).toPromise(); } /** * Get change matching the locator. * @param param the request object */ public getChange(param: ChangeApiGetChangeRequest, options?: Configuration): Promise<Change> { return this.api.getChange(param.changeLocator, param.fields, options).toPromise(); } /** * Get attributes of the matching change. * @param param the request object */ public getChangeAttributes(param: ChangeApiGetChangeAttributesRequest, options?: Configuration): Promise<Entries> { return this.api.getChangeAttributes(param.changeLocator, param.fields, options).toPromise(); } /** * Get duplicates of the matching change. * @param param the request object */ public getChangeDuplicates(param: ChangeApiGetChangeDuplicatesRequest, options?: Configuration): Promise<Changes> { return this.api.getChangeDuplicates(param.changeLocator, param.fields, options).toPromise(); } /** * Get a field of the matching change. * @param param the request object */ public getChangeField(param: ChangeApiGetChangeFieldRequest, options?: Configuration): Promise<string> { return this.api.getChangeField(param.changeLocator, param.field, options).toPromise(); } /** * Get first builds of the matching change. * @param param the request object */ public getChangeFirstBuilds(param: ChangeApiGetChangeFirstBuildsRequest, options?: Configuration): Promise<Builds> { return this.api.getChangeFirstBuilds(param.changeLocator, param.fields, options).toPromise(); } /** * Get issues of the matching change. * @param param the request object */ public getChangeIssue(param: ChangeApiGetChangeIssueRequest, options?: Configuration): Promise<Issues> { return this.api.getChangeIssue(param.changeLocator, options).toPromise(); } /** * Get parent changes of the matching change. * @param param the request object */ public getChangeParentChanges(param: ChangeApiGetChangeParentChangesRequest, options?: Configuration): Promise<Changes> { return this.api.getChangeParentChanges(param.changeLocator, param.fields, options).toPromise(); } /** * Get parent revisions of the matching change. * @param param the request object */ public getChangeParentRevisions(param: ChangeApiGetChangeParentRevisionsRequest, options?: Configuration): Promise<Items> { return this.api.getChangeParentRevisions(param.changeLocator, options).toPromise(); } /** * Get build configurations related to the matching change. * @param param the request object */ public getChangeRelatedBuildTypes(param: ChangeApiGetChangeRelatedBuildTypesRequest, options?: Configuration): Promise<BuildTypes> { return this.api.getChangeRelatedBuildTypes(param.changeLocator, param.fields, options).toPromise(); } /** * Get a VCS root instance of the matching change. * @param param the request object */ public getChangeVcsRoot(param: ChangeApiGetChangeVcsRootRequest, options?: Configuration): Promise<VcsRootInstance> { return this.api.getChangeVcsRoot(param.changeLocator, param.fields, options).toPromise(); } } import { ObservableCloudInstanceApi } from "./ObservableAPI.ts"; import { CloudInstanceApiRequestFactory, CloudInstanceApiResponseProcessor} from "../apis/CloudInstanceApi.ts"; export interface CloudInstanceApiGetAllCloudImagesRequest { /** * * @type string * @memberof CloudInstanceApigetAllCloudImages */ locator?: string /** * * @type string * @memberof CloudInstanceApigetAllCloudImages */ fields?: string } export interface CloudInstanceApiGetAllCloudInstancesRequest { /** * * @type string * @memberof CloudInstanceApigetAllCloudInstances */ locator?: string /** * * @type string * @memberof CloudInstanceApigetAllCloudInstances */ fields?: string } export interface CloudInstanceApiGetAllCloudProfilesRequest { /** * * @type string * @memberof CloudInstanceApigetAllCloudProfiles */ locator?: string /** * * @type string * @memberof CloudInstanceApigetAllCloudProfiles */ fields?: string } export interface CloudInstanceApiGetCloudImageRequest { /** * * @type string * @memberof CloudInstanceApigetCloudImage */ imageLocator: string /** * * @type string * @memberof CloudInstanceApigetCloudImage */ fields?: string } export interface CloudInstanceApiGetCloudInstanceRequest { /** * * @type string * @memberof CloudInstanceApigetCloudInstance */ instanceLocator: string /** * * @type string * @memberof CloudInstanceApigetCloudInstance */ fields?: string } export interface CloudInstanceApiGetCloudProfileRequest { /** * * @type string * @memberof CloudInstanceApigetCloudProfile */ profileLocator: string /** * * @type string * @memberof CloudInstanceApigetCloudProfile */ fields?: string } export interface CloudInstanceApiStartInstanceRequest { /** * * @type string * @memberof CloudInstanceApistartInstance */ fields?: string /** * * @type CloudInstance * @memberof CloudInstanceApistartInstance */ body?: CloudInstance } export interface CloudInstanceApiStopInstanceRequest { /** * * @type string * @memberof CloudInstanceApistopInstance */ instanceLocator: string } export class ObjectCloudInstanceApi { private api: ObservableCloudInstanceApi public constructor(configuration: Configuration, requestFactory?: CloudInstanceApiRequestFactory, responseProcessor?: CloudInstanceApiResponseProcessor) { this.api = new ObservableCloudInstanceApi(configuration, requestFactory, responseProcessor); } /** * Get all cloud images. * @param param the request object */ public getAllCloudImages(param: CloudInstanceApiGetAllCloudImagesRequest, options?: Configuration): Promise<CloudImages> { return this.api.getAllCloudImages(param.locator, param.fields, options).toPromise(); } /** * Get all cloud instances. * @param param the request object */ public getAllCloudInstances(param: CloudInstanceApiGetAllCloudInstancesRequest, options?: Configuration): Promise<CloudInstances> { return this.api.getAllCloudInstances(param.locator, param.fields, options).toPromise(); } /** * Get all cloud profiles. * @param param the request object */ public getAllCloudProfiles(param: CloudInstanceApiGetAllCloudProfilesRequest, options?: Configuration): Promise<CloudProfiles> { return this.api.getAllCloudProfiles(param.locator, param.fields, options).toPromise(); } /** * Get cloud image matching the locator. * @param param the request object */ public getCloudImage(param: CloudInstanceApiGetCloudImageRequest, options?: Configuration): Promise<CloudImage> { return this.api.getCloudImage(param.imageLocator, param.fields, options).toPromise(); } /** * Get cloud instance matching the locator. * @param param the request object */ public getCloudInstance(param: CloudInstanceApiGetCloudInstanceRequest, options?: Configuration): Promise<CloudInstance> { return this.api.getCloudInstance(param.instanceLocator, param.fields, options).toPromise(); } /** * Get cloud profile matching the locator. * @param param the request object */ public getCloudProfile(param: CloudInstanceApiGetCloudProfileRequest, options?: Configuration): Promise<CloudProfile> { return this.api.getCloudProfile(param.profileLocator, param.fields, options).toPromise(); } /** * Start a new cloud instance. * @param param the request object */ public startInstance(param: CloudInstanceApiStartInstanceRequest, options?: Configuration): Promise<void> { return this.api.startInstance(param.fields, param.body, options).toPromise(); } /** * Stop cloud instance matching the locator. * @param param the request object */ public stopInstance(param: CloudInstanceApiStopInstanceRequest, options?: Configuration): Promise<void> { return this.api.stopInstance(param.instanceLocator, options).toPromise(); } } import { ObservableGroupApi } from "./ObservableAPI.ts"; import { GroupApiRequestFactory, GroupApiResponseProcessor} from "../apis/GroupApi.ts"; export interface GroupApiAddGroupRequest { /** * * @type string * @memberof GroupApiaddGroup */ fields?: string /** * * @type Group * @memberof GroupApiaddGroup */ body?: Group } export interface GroupApiAddRoleAtScopeToGroupRequest { /** * * @type string * @memberof GroupApiaddRoleAtScopeToGroup */ groupLocator: string /** * * @type string * @memberof GroupApiaddRoleAtScopeToGroup */ roleId: string /** * * @type string * @memberof GroupApiaddRoleAtScopeToGroup */ scope: string } export interface GroupApiAddRoleToGroupRequest { /** * * @type string * @memberof GroupApiaddRoleToGroup */ groupLocator: string /** * * @type Role * @memberof GroupApiaddRoleToGroup */ body?: Role } export interface GroupApiDeleteGroupRequest { /** * * @type string * @memberof GroupApideleteGroup */ groupLocator: string } export interface GroupApiGetAllGroupsRequest { /** * * @type string * @memberof GroupApigetAllGroups */ fields?: string } export interface GroupApiGetGroupParentGroupsRequest { /** * * @type string * @memberof GroupApigetGroupParentGroups */ groupLocator: string /** * * @type string * @memberof GroupApigetGroupParentGroups */ fields?: string } export interface GroupApiGetGroupPropertiesRequest { /** * * @type string * @memberof GroupApigetGroupProperties */ groupLocator: string /** * * @type string * @memberof GroupApigetGroupProperties */ fields?: string } export interface GroupApiGetGroupPropertyRequest { /** * * @type string * @memberof GroupApigetGroupProperty */ groupLocator: string /** * * @type string * @memberof GroupApigetGroupProperty */ name: string } export interface GroupApiGetGroupRoleAtScopeRequest { /** * * @type string * @memberof GroupApigetGroupRoleAtScope */ groupLocator: string /** * * @type string * @memberof GroupApigetGroupRoleAtScope */ roleId: string /** * * @type string * @memberof GroupApigetGroupRoleAtScope */ scope: string } export interface GroupApiGetGroupRolesRequest { /** * * @type string * @memberof GroupApigetGroupRoles */ groupLocator: string } export interface GroupApiGetUserGroupOfGroupRequest { /** * * @type string * @memberof GroupApigetUserGroupOfGroup */ groupLocator: string /** * * @type string * @memberof GroupApigetUserGroupOfGroup */ fields?: string } export interface GroupApiRemoveGroupPropertyRequest { /** * * @type string * @memberof GroupApiremoveGroupProperty */ groupLocator: string /** * * @type string * @memberof GroupApiremoveGroupProperty */ name: string } export interface GroupApiRemoveRoleAtScopeFromGroupRequest { /** * * @type string * @memberof GroupApiremoveRoleAtScopeFromGroup */ groupLocator: string /** * * @type string * @memberof GroupApiremoveRoleAtScopeFromGroup */ roleId: string /** * * @type string * @memberof GroupApiremoveRoleAtScopeFromGroup */ scope: string } export interface GroupApiSetGroupParentGroupsRequest { /** * * @type string * @memberof GroupApisetGroupParentGroups */ groupLocator: string /** * * @type string * @memberof GroupApisetGroupParentGroups */ fields?: string /** * * @type Groups * @memberof GroupApisetGroupParentGroups */ body?: Groups } export interface GroupApiSetGroupPropertyRequest { /** * * @type string * @memberof GroupApisetGroupProperty */ groupLocator: string /** * * @type string * @memberof GroupApisetGroupProperty */ name: string /** * * @type string * @memberof GroupApisetGroupProperty */ body?: string } export interface GroupApiSetGroupRolesRequest { /** * * @type string * @memberof GroupApisetGroupRoles */ groupLocator: string /** * * @type Roles * @memberof GroupApisetGroupRoles */ body?: Roles } export class ObjectGroupApi { private api: ObservableGroupApi public constructor(configuration: Configuration, requestFactory?: GroupApiRequestFactory, responseProcessor?: GroupApiResponseProcessor) { this.api = new ObservableGroupApi(configuration, requestFactory, responseProcessor); } /** * Add a new user group. * @param param the request object */ public addGroup(param: GroupApiAddGroupRequest, options?: Configuration): Promise<Group> { return this.api.addGroup(param.fields, param.body, options).toPromise(); } /** * Add a role with the specific scope to the matching user group. * @param param the request object */ public addRoleAtScopeToGroup(param: GroupApiAddRoleAtScopeToGroupRequest, options?: Configuration): Promise<Role> { return this.api.addRoleAtScopeToGroup(param.groupLocator, param.roleId, param.scope, options).toPromise(); } /** * Add a role to the matching user group. * @param param the request object */ public addRoleToGroup(param: GroupApiAddRoleToGroupRequest, options?: Configuration): Promise<Role> { return this.api.addRoleToGroup(param.groupLocator, param.body, options).toPromise(); } /** * Delete user group matching the locator. * @param param the request object */ public deleteGroup(param: GroupApiDeleteGroupRequest, options?: Configuration): Promise<void> { return this.api.deleteGroup(param.groupLocator, options).toPromise(); } /** * Get all user groups. * @param param the request object */ public getAllGroups(param: GroupApiGetAllGroupsRequest, options?: Configuration): Promise<Groups> { return this.api.getAllGroups(param.fields, options).toPromise(); } /** * Get parent groups of the matching user group. * @param param the request object */ public getGroupParentGroups(param: GroupApiGetGroupParentGroupsRequest, options?: Configuration): Promise<Groups> { return this.api.getGroupParentGroups(param.groupLocator, param.fields, options).toPromise(); } /** * Get properties of the matching user group. * @param param the request object */ public getGroupProperties(param: GroupApiGetGroupPropertiesRequest, options?: Configuration): Promise<Properties> { return this.api.getGroupProperties(param.groupLocator, param.fields, options).toPromise(); } /** * Get a property of the matching user group. * @param param the request object */ public getGroupProperty(param: GroupApiGetGroupPropertyRequest, options?: Configuration): Promise<string> { return this.api.getGroupProperty(param.groupLocator, param.name, options).toPromise(); } /** * Get a role with the specific scope of the matching user group. * @param param the request object */ public getGroupRoleAtScope(param: GroupApiGetGroupRoleAtScopeRequest, options?: Configuration): Promise<Role> { return this.api.getGroupRoleAtScope(param.groupLocator, param.roleId, param.scope, options).toPromise(); } /** * Get all roles of the matching user group. * @param param the request object */ public getGroupRoles(param: GroupApiGetGroupRolesRequest, options?: Configuration): Promise<Roles> { return this.api.getGroupRoles(param.groupLocator, options).toPromise(); } /** * Get user group matching the locator. * @param param the request object */ public getUserGroupOfGroup(param: GroupApiGetUserGroupOfGroupRequest, options?: Configuration): Promise<Group> { return this.api.getUserGroupOfGroup(param.groupLocator, param.fields, options).toPromise(); } /** * Remove a property of the matching user group. * @param param the request object */ public removeGroupProperty(param: GroupApiRemoveGroupPropertyRequest, options?: Configuration): Promise<void> { return this.api.removeGroupProperty(param.groupLocator, param.name, options).toPromise(); } /** * Remove a role with the specific scope from the matching user group. * @param param the request object */ public removeRoleAtScopeFromGroup(param: GroupApiRemoveRoleAtScopeFromGroupRequest, options?: Configuration): Promise<void> { return this.api.removeRoleAtScopeFromGroup(param.groupLocator, param.roleId, param.scope, options).toPromise(); } /** * Update parent groups of the matching user group. * @param param the request object */ public setGroupParentGroups(param: GroupApiSetGroupParentGroupsRequest, options?: Configuration): Promise<Groups> { return this.api.setGroupParentGroups(param.groupLocator, param.fields, param.body, options).toPromise(); } /** * Update a property of the matching user group. * @param param the request object */ public setGroupProperty(param: GroupApiSetGroupPropertyRequest, options?: Configuration): Promise<string> { return this.api.setGroupProperty(param.groupLocator, param.name, param.body, options).toPromise(); } /** * Update roles of the matching user group. * @param param the request object */ public setGroupRoles(param: GroupApiSetGroupRolesRequest, options?: Configuration): Promise<Roles> { return this.api.setGroupRoles(param.groupLocator, param.body, options).toPromise(); } } import { ObservableInvestigationApi } from "./ObservableAPI.ts"; import { InvestigationApiRequestFactory, InvestigationApiResponseProcessor} from "../apis/InvestigationApi.ts"; export interface InvestigationApiAddInvestigationRequest { /** * * @type string * @memberof InvestigationApiaddInvestigation */ fields?: string /** * * @type Investigation * @memberof InvestigationApiaddInvestigation */ body?: Investigation } export interface InvestigationApiAddMultipleInvestigationsRequest { /** * * @type string * @memberof InvestigationApiaddMultipleInvestigations */ fields?: string /** * * @type Investigations * @memberof InvestigationApiaddMultipleInvestigations */ body?: Investigations } export interface InvestigationApiDeleteInvestigationRequest { /** * * @type string * @memberof InvestigationApideleteInvestigation */ investigationLocator: string } export interface InvestigationApiGetAllInvestigationsRequest { /** * * @type string * @memberof InvestigationApigetAllInvestigations */ locator?: string /** * * @type string * @memberof InvestigationApigetAllInvestigations */ fields?: string } export interface InvestigationApiGetInvestigationRequest { /** * * @type string * @memberof InvestigationApigetInvestigation */ investigationLocator: string /** * * @type string * @memberof InvestigationApigetInvestigation */ fields?: string } export interface InvestigationApiReplaceInvestigationRequest { /** * * @type string * @memberof InvestigationApireplaceInvestigation */ investigationLocator: string /** * * @type string * @memberof InvestigationApireplaceInvestigation */ fields?: string /** * * @type Investigation * @memberof InvestigationApireplaceInvestigation */ body?: Investigation } export class ObjectInvestigationApi { private api: ObservableInvestigationApi public constructor(configuration: Configuration, requestFactory?: InvestigationApiRequestFactory, responseProcessor?: InvestigationApiResponseProcessor) { this.api = new ObservableInvestigationApi(configuration, requestFactory, responseProcessor); } /** * Create a new investigation. * @param param the request object */ public addInvestigation(param: InvestigationApiAddInvestigationRequest, options?: Configuration): Promise<Investigation> { return this.api.addInvestigation(param.fields, param.body, options).toPromise(); } /** * Create multiple new investigations. * @param param the request object */ public addMultipleInvestigations(param: InvestigationApiAddMultipleInvestigationsRequest, options?: Configuration): Promise<Investigations> { return this.api.addMultipleInvestigations(param.fields, param.body, options).toPromise(); } /** * Delete investigation matching the locator. * @param param the request object */ public deleteInvestigation(param: InvestigationApiDeleteInvestigationRequest, options?: Configuration): Promise<void> { return this.api.deleteInvestigation(param.investigationLocator, options).toPromise(); } /** * Get all investigations. * @param param the request object */ public getAllInvestigations(param: InvestigationApiGetAllInvestigationsRequest, options?: Configuration): Promise<Investigations> { return this.api.getAllInvestigations(param.locator, param.fields, options).toPromise(); } /** * Get investigation matching the locator. * @param param the request object */ public getInvestigation(param: InvestigationApiGetInvestigationRequest, options?: Configuration): Promise<Investigation> { return this.api.getInvestigation(param.investigationLocator, param.fields, options).toPromise(); } /** * Update investigation matching the locator. * @param param the request object */ public replaceInvestigation(param: InvestigationApiReplaceInvestigationRequest, options?: Configuration): Promise<Investigation> { return this.api.replaceInvestigation(param.investigationLocator, param.fields, param.body, options).toPromise(); } } import { ObservableMuteApi } from "./ObservableAPI.ts"; import { MuteApiRequestFactory, MuteApiResponseProcessor} from "../apis/MuteApi.ts"; export interface MuteApiGetAllMutedTestsRequest { /** * * @type string * @memberof MuteApigetAllMutedTests */ locator?: string /** * * @type string * @memberof MuteApigetAllMutedTests */ fields?: string } export interface MuteApiGetMutedTestRequest { /** * * @type string * @memberof MuteApigetMutedTest */ muteLocator: string /** * * @type string * @memberof MuteApigetMutedTest */ fields?: string } export interface MuteApiMuteMultipleTestsRequest { /** * * @type string * @memberof MuteApimuteMultipleTests */ fields?: string /** * * @type Mutes * @memberof MuteApimuteMultipleTests */ body?: Mutes } export interface MuteApiMuteTestRequest { /** * * @type string * @memberof MuteApimuteTest */ fields?: string /** * * @type Mute * @memberof MuteApimuteTest */ body?: Mute } export interface MuteApiUnmuteTestRequest { /** * * @type string * @memberof MuteApiunmuteTest */ muteLocator: string /** * * @type string * @memberof MuteApiunmuteTest */ body?: string } export class ObjectMuteApi { private api: ObservableMuteApi public constructor(configuration: Configuration, requestFactory?: MuteApiRequestFactory, responseProcessor?: MuteApiResponseProcessor) { this.api = new ObservableMuteApi(configuration, requestFactory, responseProcessor); } /** * Get all muted tests. * @param param the request object */ public getAllMutedTests(param: MuteApiGetAllMutedTestsRequest, options?: Configuration): Promise<Mutes> { return this.api.getAllMutedTests(param.locator, param.fields, options).toPromise(); } /** * Get a muted test. * @param param the request object */ public getMutedTest(param: MuteApiGetMutedTestRequest, options?: Configuration): Promise<Mute> { return this.api.getMutedTest(param.muteLocator, param.fields, options).toPromise(); } /** * Mute multiple tests. * @param param the request object */ public muteMultipleTests(param: MuteApiMuteMultipleTestsRequest, options?: Configuration): Promise<Mutes> { return this.api.muteMultipleTests(param.fields, param.body, options).toPromise(); } /** * Mute a test. * @param param the request object */ public muteTest(param: MuteApiMuteTestRequest, options?: Configuration): Promise<Mute> { return this.api.muteTest(param.fields, param.body, options).toPromise(); } /** * Unmute the matching test. * @param param the request object */ public unmuteTest(param: MuteApiUnmuteTestRequest, options?: Configuration): Promise<void> { return this.api.unmuteTest(param.muteLocator, param.body, options).toPromise(); } } import { ObservableProblemApi } from "./ObservableAPI.ts"; import { ProblemApiRequestFactory, ProblemApiResponseProcessor} from "../apis/ProblemApi.ts"; export interface ProblemApiGetAllBuildProblemsRequest { /** * * @type string * @memberof ProblemApigetAllBuildProblems */ locator?: string /** * * @type string * @memberof ProblemApigetAllBuildProblems */ fields?: string } export interface ProblemApiGetBuildProblemRequest { /** * * @type string * @memberof ProblemApigetBuildProblem */ problemLocator: string /** * * @type string * @memberof ProblemApigetBuildProblem */ fields?: string } export class ObjectProblemApi { private api: ObservableProblemApi public constructor(configuration: Configuration, requestFactory?: ProblemApiRequestFactory, responseProcessor?: ProblemApiResponseProcessor) { this.api = new ObservableProblemApi(configuration, requestFactory, responseProcessor); } /** * Get all build problems. * @param param the request object */ public getAllBuildProblems(param: ProblemApiGetAllBuildProblemsRequest, options?: Configuration): Promise<Problems> { return this.api.getAllBuildProblems(param.locator, param.fields, options).toPromise(); } /** * Get a matching build problem. * @param param the request object */ public getBuildProblem(param: ProblemApiGetBuildProblemRequest, options?: Configuration): Promise<Problem> { return this.api.getBuildProblem(param.problemLocator, param.fields, options).toPromise(); } } import { ObservableProblemOccurrenceApi } from "./ObservableAPI.ts"; import { ProblemOccurrenceApiRequestFactory, ProblemOccurrenceApiResponseProcessor} from "../apis/ProblemOccurrenceApi.ts"; export interface ProblemOccurrenceApiGetAllBuildProblemOccurrencesRequest { /** * * @type string * @memberof ProblemOccurrenceApigetAllBuildProblemOccurrences */ locator?: string /** * * @type string * @memberof ProblemOccurrenceApigetAllBuildProblemOccurrences */ fields?: string } export interface ProblemOccurrenceApiGetBuildProblemOccurrenceRequest { /** * * @type string * @memberof ProblemOccurrenceApigetBuildProblemOccurrence */ problemLocator: string /** * * @type string * @memberof ProblemOccurrenceApigetBuildProblemOccurrence */ fields?: string } export class ObjectProblemOccurrenceApi { private api: ObservableProblemOccurrenceApi public constructor(configuration: Configuration, requestFactory?: ProblemOccurrenceApiRequestFactory, responseProcessor?: ProblemOccurrenceApiResponseProcessor) { this.api = new ObservableProblemOccurrenceApi(configuration, requestFactory, responseProcessor); } /** * Get all build problem occurrences. * @param param the request object */ public getAllBuildProblemOccurrences(param: ProblemOccurrenceApiGetAllBuildProblemOccurrencesRequest, options?: Configuration): Promise<ProblemOccurrences> { return this.api.getAllBuildProblemOccurrences(param.locator, param.fields, options).toPromise(); } /** * Get a matching build problem occurrence. * @param param the request object */ public getBuildProblemOccurrence(param: ProblemOccurrenceApiGetBuildProblemOccurrenceRequest, options?: Configuration): Promise<ProblemOccurrence> { return this.api.getBuildProblemOccurrence(param.problemLocator, param.fields, options).toPromise(); } } import { ObservableProjectApi } from "./ObservableAPI.ts"; import { ProjectApiRequestFactory, ProjectApiResponseProcessor} from "../apis/ProjectApi.ts"; export interface ProjectApiAddAgentPoolsProjectRequest { /** * * @type string * @memberof ProjectApiaddAgentPoolsProject */ projectLocator: string /** * * @type AgentPool * @memberof ProjectApiaddAgentPoolsProject */ body?: AgentPool } export interface ProjectApiAddBuildTypeRequest { /** * * @type string * @memberof ProjectApiaddBuildType */ projectLocator: string /** * * @type string * @memberof ProjectApiaddBuildType */ fields?: string /** * * @type NewBuildTypeDescription * @memberof ProjectApiaddBuildType */ body?: NewBuildTypeDescription } export interface ProjectApiAddFeatureRequest { /** * * @type string * @memberof ProjectApiaddFeature */ projectLocator: string /** * * @type string * @memberof ProjectApiaddFeature */ fields?: string /** * * @type ProjectFeature * @memberof ProjectApiaddFeature */ body?: ProjectFeature } export interface ProjectApiAddProjectRequest { /** * * @type NewProjectDescription * @memberof ProjectApiaddProject */ body?: NewProjectDescription } export interface ProjectApiAddSecureTokenRequest { /** * * @type string * @memberof ProjectApiaddSecureToken */ projectLocator: string /** * * @type string * @memberof ProjectApiaddSecureToken */ body?: string } export interface ProjectApiAddTemplateRequest { /** * * @type string * @memberof ProjectApiaddTemplate */ projectLocator: string /** * * @type string * @memberof ProjectApiaddTemplate */ fields?: string /** * * @type NewBuildTypeDescription * @memberof ProjectApiaddTemplate */ body?: NewBuildTypeDescription } export interface ProjectApiCreateBuildParameterRequest { /** * * @type string * @memberof ProjectApicreateBuildParameter */ projectLocator: string /** * * @type string * @memberof ProjectApicreateBuildParameter */ fields?: string /** * * @type Property * @memberof ProjectApicreateBuildParameter */ body?: Property } export interface ProjectApiDeleteBuildParameterRequest { /** * * @type string * @memberof ProjectApideleteBuildParameter */ name: string /** * * @type string * @memberof ProjectApideleteBuildParameter */ projectLocator: string } export interface ProjectApiDeleteBuildParametersRequest { /** * * @type string * @memberof ProjectApideleteBuildParameters */ projectLocator: string } export interface ProjectApiDeleteFeatureRequest { /** * * @type string * @memberof ProjectApideleteFeature */ featureLocator: string /** * * @type string * @memberof ProjectApideleteFeature */ projectLocator: string } export interface ProjectApiDeleteProjectRequest { /** * * @type string * @memberof ProjectApideleteProject */ projectLocator: string } export interface ProjectApiGetAgentPoolsProjectRequest { /** * * @type string * @memberof ProjectApigetAgentPoolsProject */ projectLocator: string /** * * @type string * @memberof ProjectApigetAgentPoolsProject */ fields?: string } export interface ProjectApiGetAllBranchesRequest { /** * * @type string * @memberof ProjectApigetAllBranches */ projectLocator: string /** * * @type string * @memberof ProjectApigetAllBranches */ locator?: string /** * * @type string * @memberof ProjectApigetAllBranches */ fields?: string } export interface ProjectApiGetAllProjectsRequest { /** * * @type string * @memberof ProjectApigetAllProjects */ locator?: string /** * * @type string * @memberof ProjectApigetAllProjects */ fields?: string } export interface ProjectApiGetAllSubprojectsOrderedRequest { /** * * @type string * @memberof ProjectApigetAllSubprojectsOrdered */ projectLocator: string /** * * @type string * @memberof ProjectApigetAllSubprojectsOrdered */ field?: string } export interface ProjectApiGetBuildParameterRequest { /** * * @type string * @memberof ProjectApigetBuildParameter */ name: string /** * * @type string * @memberof ProjectApigetBuildParameter */ projectLocator: string /** * * @type string * @memberof ProjectApigetBuildParameter */ fields?: string } export interface ProjectApiGetBuildParameterSpecificationRequest { /** * * @type string * @memberof ProjectApigetBuildParameterSpecification */ name: string /** * * @type string * @memberof ProjectApigetBuildParameterSpecification */ projectLocator: string } export interface ProjectApiGetBuildParameterTypeRequest { /** * * @type string * @memberof ProjectApigetBuildParameterType */ name: string /** * * @type string * @memberof ProjectApigetBuildParameterType */ projectLocator: string } export interface ProjectApiGetBuildParameterValueRequest { /** * * @type string * @memberof ProjectApigetBuildParameterValue */ name: string /** * * @type string * @memberof ProjectApigetBuildParameterValue */ projectLocator: string } export interface ProjectApiGetBuildParametersRequest { /** * * @type string * @memberof ProjectApigetBuildParameters */ projectLocator: string /** * * @type string * @memberof ProjectApigetBuildParameters */ locator?: string /** * * @type string * @memberof ProjectApigetBuildParameters */ fields?: string } export interface ProjectApiGetDefaultTemplateRequest { /** * * @type string * @memberof ProjectApigetDefaultTemplate */ projectLocator: string /** * * @type string * @memberof ProjectApigetDefaultTemplate */ fields?: string } export interface ProjectApiGetFeatureRequest { /** * * @type string * @memberof ProjectApigetFeature */ featureLocator: string /** * * @type string * @memberof ProjectApigetFeature */ projectLocator: string /** * * @type string * @memberof ProjectApigetFeature */ fields?: string } export interface ProjectApiGetFeaturesRequest { /** * * @type string * @memberof ProjectApigetFeatures */ projectLocator: string /** * * @type string * @memberof ProjectApigetFeatures */ locator?: string /** * * @type string * @memberof ProjectApigetFeatures */ fields?: string } export interface ProjectApiGetProjectRequest { /** * * @type string * @memberof ProjectApigetProject */ projectLocator: string /** * * @type string * @memberof ProjectApigetProject */ fields?: string } export interface ProjectApiGetProjectFieldRequest { /** * * @type string * @memberof ProjectApigetProjectField */ projectLocator: string /** * * @type string * @memberof ProjectApigetProjectField */ field: string } export interface ProjectApiGetProjectParentProjectRequest { /** * * @type string * @memberof ProjectApigetProjectParentProject */ projectLocator: string /** * * @type string * @memberof ProjectApigetProjectParentProject */ fields?: string } export interface ProjectApiGetProjectSettingsFileRequest { /** * * @type string * @memberof ProjectApigetProjectSettingsFile */ projectLocator: string } export interface ProjectApiGetProjectTemplatesRequest { /** * * @type string * @memberof ProjectApigetProjectTemplates */ projectLocator: string /** * * @type string * @memberof ProjectApigetProjectTemplates */ fields?: string } export interface ProjectApiGetSecureValueRequest { /** * * @type string * @memberof ProjectApigetSecureValue */ projectLocator: string /** * * @type string * @memberof ProjectApigetSecureValue */ token: string } export interface ProjectApiRemoveDefaultTemplateRequest { /** * * @type string * @memberof ProjectApiremoveDefaultTemplate */ projectLocator: string /** * * @type string * @memberof ProjectApiremoveDefaultTemplate */ fields?: string } export interface ProjectApiRemoveProjectFromAgentPoolRequest { /** * * @type string * @memberof ProjectApiremoveProjectFromAgentPool */ projectLocator: string /** * * @type string * @memberof ProjectApiremoveProjectFromAgentPool */ agentPoolLocator: string } export interface ProjectApiSetAgentPoolsProjectRequest { /** * * @type string * @memberof ProjectApisetAgentPoolsProject */ projectLocator: string /** * * @type string * @memberof ProjectApisetAgentPoolsProject */ fields?: string /** * * @type AgentPools * @memberof ProjectApisetAgentPoolsProject */ body?: AgentPools } export interface ProjectApiSetBuildTypesOrderRequest { /** * * @type string * @memberof ProjectApisetBuildTypesOrder */ projectLocator: string /** * * @type string * @memberof ProjectApisetBuildTypesOrder */ field?: string /** * * @type BuildTypes * @memberof ProjectApisetBuildTypesOrder */ body?: BuildTypes } export interface ProjectApiSetDefaultTemplateRequest { /** * * @type string * @memberof ProjectApisetDefaultTemplate */ projectLocator: string /** * * @type string * @memberof ProjectApisetDefaultTemplate */ fields?: string /** * * @type BuildType * @memberof ProjectApisetDefaultTemplate */ body?: BuildType } export interface ProjectApiSetParentProjectRequest { /** * * @type string * @memberof ProjectApisetParentProject */ projectLocator: string /** * * @type string * @memberof ProjectApisetParentProject */ fields?: string /** * * @type Project * @memberof ProjectApisetParentProject */ body?: Project } export interface ProjectApiSetProjectFieldRequest { /** * * @type string * @memberof ProjectApisetProjectField */ projectLocator: string /** * * @type string * @memberof ProjectApisetProjectField */ field: string /** * * @type string * @memberof ProjectApisetProjectField */ body?: string } export interface ProjectApiSetSubprojectsOrderRequest { /** * * @type string * @memberof ProjectApisetSubprojectsOrder */ projectLocator: string /** * * @type string * @memberof ProjectApisetSubprojectsOrder */ field?: string /** * * @type Projects * @memberof ProjectApisetSubprojectsOrder */ body?: Projects } export interface ProjectApiUpdateBuildParameterRequest { /** * * @type string * @memberof ProjectApiupdateBuildParameter */ name: string /** * * @type string * @memberof ProjectApiupdateBuildParameter */ projectLocator: string /** * * @type string * @memberof ProjectApiupdateBuildParameter */ fields?: string /** * * @type Property * @memberof ProjectApiupdateBuildParameter */ body?: Property } export interface ProjectApiUpdateBuildParameterSpecificationRequest { /** * * @type string * @memberof ProjectApiupdateBuildParameterSpecification */ name: string /** * * @type string * @memberof ProjectApiupdateBuildParameterSpecification */ projectLocator: string /** * * @type string * @memberof ProjectApiupdateBuildParameterSpecification */ body?: string } export interface ProjectApiUpdateBuildParameterTypeRequest { /** * * @type string * @memberof ProjectApiupdateBuildParameterType */ name: string /** * * @type string * @memberof ProjectApiupdateBuildParameterType */ projectLocator: string /** * * @type Type * @memberof ProjectApiupdateBuildParameterType */ body?: Type } export interface ProjectApiUpdateBuildParameterValueRequest { /** * * @type string * @memberof ProjectApiupdateBuildParameterValue */ name: string /** * * @type string * @memberof ProjectApiupdateBuildParameterValue */ projectLocator: string /** * * @type string * @memberof ProjectApiupdateBuildParameterValue */ body?: string } export interface ProjectApiUpdateBuildParametersRequest { /** * * @type string * @memberof ProjectApiupdateBuildParameters */ projectLocator: string /** * * @type string * @memberof ProjectApiupdateBuildParameters */ fields?: string /** * * @type Properties * @memberof ProjectApiupdateBuildParameters */ body?: Properties } export interface ProjectApiUpdateFeatureRequest { /** * * @type string * @memberof ProjectApiupdateFeature */ featureLocator: string /** * * @type string * @memberof ProjectApiupdateFeature */ projectLocator: string /** * * @type string * @memberof ProjectApiupdateFeature */ fields?: string /** * * @type ProjectFeature * @memberof ProjectApiupdateFeature */ body?: ProjectFeature } export interface ProjectApiUpdateFeaturesRequest { /** * * @type string * @memberof ProjectApiupdateFeatures */ projectLocator: string /** * * @type string * @memberof ProjectApiupdateFeatures */ fields?: string /** * * @type ProjectFeatures * @memberof ProjectApiupdateFeatures */ body?: ProjectFeatures } export class ObjectProjectApi { private api: ObservableProjectApi public constructor(configuration: Configuration, requestFactory?: ProjectApiRequestFactory, responseProcessor?: ProjectApiResponseProcessor) { this.api = new ObservableProjectApi(configuration, requestFactory, responseProcessor); } /** * Assign the matching project to the agent pool. * @param param the request object */ public addAgentPoolsProject(param: ProjectApiAddAgentPoolsProjectRequest, options?: Configuration): Promise<AgentPool> { return this.api.addAgentPoolsProject(param.projectLocator, param.body, options).toPromise(); } /** * Add a build configuration to the matching project. * @param param the request object */ public addBuildType(param: ProjectApiAddBuildTypeRequest, options?: Configuration): Promise<BuildType> { return this.api.addBuildType(param.projectLocator, param.fields, param.body, options).toPromise(); } /** * Add a feature. * @param param the request object */ public addFeature(param: ProjectApiAddFeatureRequest, options?: Configuration): Promise<any> { return this.api.addFeature(param.projectLocator, param.fields, param.body, options).toPromise(); } /** * Create a new project. * @param param the request object */ public addProject(param: ProjectApiAddProjectRequest, options?: Configuration): Promise<Project> { return this.api.addProject(param.body, options).toPromise(); } /** * Create a new secure token for the matching project. * @param param the request object */ public addSecureToken(param: ProjectApiAddSecureTokenRequest, options?: Configuration): Promise<string> { return this.api.addSecureToken(param.projectLocator, param.body, options).toPromise(); } /** * Add a build configuration template to the matching project. * @param param the request object */ public addTemplate(param: ProjectApiAddTemplateRequest, options?: Configuration): Promise<BuildType> { return this.api.addTemplate(param.projectLocator, param.fields, param.body, options).toPromise(); } /** * Create a build parameter. * @param param the request object */ public createBuildParameter(param: ProjectApiCreateBuildParameterRequest, options?: Configuration): Promise<Property> { return this.api.createBuildParameter(param.projectLocator, param.fields, param.body, options).toPromise(); } /** * Delete build parameter. * @param param the request object */ public deleteBuildParameter(param: ProjectApiDeleteBuildParameterRequest, options?: Configuration): Promise<void> { return this.api.deleteBuildParameter(param.name, param.projectLocator, options).toPromise(); } /** * Delete all build parameters. * @param param the request object */ public deleteBuildParameters(param: ProjectApiDeleteBuildParametersRequest, options?: Configuration): Promise<void> { return this.api.deleteBuildParameters(param.projectLocator, options).toPromise(); } /** * Delete a matching feature. * @param param the request object */ public deleteFeature(param: ProjectApiDeleteFeatureRequest, options?: Configuration): Promise<void> { return this.api.deleteFeature(param.featureLocator, param.projectLocator, options).toPromise(); } /** * Delete project matching the locator. * @param param the request object */ public deleteProject(param: ProjectApiDeleteProjectRequest, options?: Configuration): Promise<void> { return this.api.deleteProject(param.projectLocator, options).toPromise(); } /** * Get agent pools appointed to the matching project. * @param param the request object */ public getAgentPoolsProject(param: ProjectApiGetAgentPoolsProjectRequest, options?: Configuration): Promise<AgentPools> { return this.api.getAgentPoolsProject(param.projectLocator, param.fields, options).toPromise(); } /** * Get all branches of the matching project. * @param param the request object */ public getAllBranches(param: ProjectApiGetAllBranchesRequest, options?: Configuration): Promise<Branches> { return this.api.getAllBranches(param.projectLocator, param.locator, param.fields, options).toPromise(); } /** * Get all projects. * @param param the request object */ public getAllProjects(param: ProjectApiGetAllProjectsRequest, options?: Configuration): Promise<Projects> { return this.api.getAllProjects(param.locator, param.fields, options).toPromise(); } /** * Get all subprojects ordered of the matching project. * @param param the request object */ public getAllSubprojectsOrdered(param: ProjectApiGetAllSubprojectsOrderedRequest, options?: Configuration): Promise<Projects> { return this.api.getAllSubprojectsOrdered(param.projectLocator, param.field, options).toPromise(); } /** * Get build parameter. * @param param the request object */ public getBuildParameter(param: ProjectApiGetBuildParameterRequest, options?: Configuration): Promise<Property> { return this.api.getBuildParameter(param.name, param.projectLocator, param.fields, options).toPromise(); } /** * Get build parameter specification. * @param param the request object */ public getBuildParameterSpecification(param: ProjectApiGetBuildParameterSpecificationRequest, options?: Configuration): Promise<string> { return this.api.getBuildParameterSpecification(param.name, param.projectLocator, options).toPromise(); } /** * Get type of build parameter. * @param param the request object */ public getBuildParameterType(param: ProjectApiGetBuildParameterTypeRequest, options?: Configuration): Promise<Type> { return this.api.getBuildParameterType(param.name, param.projectLocator, options).toPromise(); } /** * Get value of build parameter. * @param param the request object */ public getBuildParameterValue(param: ProjectApiGetBuildParameterValueRequest, options?: Configuration): Promise<string> { return this.api.getBuildParameterValue(param.name, param.projectLocator, options).toPromise(); } /** * Get build parameters. * @param param the request object */ public getBuildParameters(param: ProjectApiGetBuildParametersRequest, options?: Configuration): Promise<Properties> { return this.api.getBuildParameters(param.projectLocator, param.locator, param.fields, options).toPromise(); } /** * Get the default template of the matching project. * @param param the request object */ public getDefaultTemplate(param: ProjectApiGetDefaultTemplateRequest, options?: Configuration): Promise<BuildType> { return this.api.getDefaultTemplate(param.projectLocator, param.fields, options).toPromise(); } /** * Get a matching feature. * @param param the request object */ public getFeature(param: ProjectApiGetFeatureRequest, options?: Configuration): Promise<any> { return this.api.getFeature(param.featureLocator, param.projectLocator, param.fields, options).toPromise(); } /** * Get all features. * @param param the request object */ public getFeatures(param: ProjectApiGetFeaturesRequest, options?: Configuration): Promise<any> { return this.api.getFeatures(param.projectLocator, param.locator, param.fields, options).toPromise(); } /** * Get project matching the locator. * @param param the request object */ public getProject(param: ProjectApiGetProjectRequest, options?: Configuration): Promise<Project> { return this.api.getProject(param.projectLocator, param.fields, options).toPromise(); } /** * Get a field of the matching project. * @param param the request object */ public getProjectField(param: ProjectApiGetProjectFieldRequest, options?: Configuration): Promise<string> { return this.api.getProjectField(param.projectLocator, param.field, options).toPromise(); } /** * Get the parent project of the matching project. * @param param the request object */ public getProjectParentProject(param: ProjectApiGetProjectParentProjectRequest, options?: Configuration): Promise<Project> { return this.api.getProjectParentProject(param.projectLocator, param.fields, options).toPromise(); } /** * Get the settings file of the matching build configuration. * @param param the request object */ public getProjectSettingsFile(param: ProjectApiGetProjectSettingsFileRequest, options?: Configuration): Promise<string> { return this.api.getProjectSettingsFile(param.projectLocator, options).toPromise(); } /** * Get all templates of the matching project. * @param param the request object */ public getProjectTemplates(param: ProjectApiGetProjectTemplatesRequest, options?: Configuration): Promise<BuildTypes> { return this.api.getProjectTemplates(param.projectLocator, param.fields, options).toPromise(); } /** * Get a secure token of the matching project. * @param param the request object */ public getSecureValue(param: ProjectApiGetSecureValueRequest, options?: Configuration): Promise<string> { return this.api.getSecureValue(param.projectLocator, param.token, options).toPromise(); } /** * Remove the default template from the matching project. * @param param the request object */ public removeDefaultTemplate(param: ProjectApiRemoveDefaultTemplateRequest, options?: Configuration): Promise<void> { return this.api.removeDefaultTemplate(param.projectLocator, param.fields, options).toPromise(); } /** * Unassign a project from the matching agent pool. * @param param the request object */ public removeProjectFromAgentPool(param: ProjectApiRemoveProjectFromAgentPoolRequest, options?: Configuration): Promise<void> { return this.api.removeProjectFromAgentPool(param.projectLocator, param.agentPoolLocator, options).toPromise(); } /** * Update agent pools apppointed to the matching project. * @param param the request object */ public setAgentPoolsProject(param: ProjectApiSetAgentPoolsProjectRequest, options?: Configuration): Promise<AgentPools> { return this.api.setAgentPoolsProject(param.projectLocator, param.fields, param.body, options).toPromise(); } /** * Update all build configurations order of the matching project. * @param param the request object */ public setBuildTypesOrder(param: ProjectApiSetBuildTypesOrderRequest, options?: Configuration): Promise<BuildTypes> { return this.api.setBuildTypesOrder(param.projectLocator, param.field, param.body, options).toPromise(); } /** * Update the default template of the matching project. * @param param the request object */ public setDefaultTemplate(param: ProjectApiSetDefaultTemplateRequest, options?: Configuration): Promise<BuildType> { return this.api.setDefaultTemplate(param.projectLocator, param.fields, param.body, options).toPromise(); } /** * Update the parent project of the matching project. * @param param the request object */ public setParentProject(param: ProjectApiSetParentProjectRequest, options?: Configuration): Promise<Project> { return this.api.setParentProject(param.projectLocator, param.fields, param.body, options).toPromise(); } /** * Update a field of the matching project. * @param param the request object */ public setProjectField(param: ProjectApiSetProjectFieldRequest, options?: Configuration): Promise<string> { return this.api.setProjectField(param.projectLocator, param.field, param.body, options).toPromise(); } /** * Update all subprojects order of the matching project. * @param param the request object */ public setSubprojectsOrder(param: ProjectApiSetSubprojectsOrderRequest, options?: Configuration): Promise<Projects> { return this.api.setSubprojectsOrder(param.projectLocator, param.field, param.body, options).toPromise(); } /** * Update build parameter. * @param param the request object */ public updateBuildParameter(param: ProjectApiUpdateBuildParameterRequest, options?: Configuration): Promise<Property> { return this.api.updateBuildParameter(param.name, param.projectLocator, param.fields, param.body, options).toPromise(); } /** * Update build parameter specification. * @param param the request object */ public updateBuildParameterSpecification(param: ProjectApiUpdateBuildParameterSpecificationRequest, options?: Configuration): Promise<string> { return this.api.updateBuildParameterSpecification(param.name, param.projectLocator, param.body, options).toPromise(); } /** * Update type of build parameter. * @param param the request object */ public updateBuildParameterType(param: ProjectApiUpdateBuildParameterTypeRequest, options?: Configuration): Promise<Type> { return this.api.updateBuildParameterType(param.name, param.projectLocator, param.body, options).toPromise(); } /** * Update value of build parameter. * @param param the request object */ public updateBuildParameterValue(param: ProjectApiUpdateBuildParameterValueRequest, options?: Configuration): Promise<string> { return this.api.updateBuildParameterValue(param.name, param.projectLocator, param.body, options).toPromise(); } /** * Update build parameters. * @param param the request object */ public updateBuildParameters(param: ProjectApiUpdateBuildParametersRequest, options?: Configuration): Promise<Properties> { return this.api.updateBuildParameters(param.projectLocator, param.fields, param.body, options).toPromise(); } /** * Update a matching feature. * @param param the request object */ public updateFeature(param: ProjectApiUpdateFeatureRequest, options?: Configuration): Promise<any> { return this.api.updateFeature(param.featureLocator, param.projectLocator, param.fields, param.body, options).toPromise(); } /** * Update all features. * @param param the request object */ public updateFeatures(param: ProjectApiUpdateFeaturesRequest, options?: Configuration): Promise<any> { return this.api.updateFeatures(param.projectLocator, param.fields, param.body, options).toPromise(); } } import { ObservableRootApi } from "./ObservableAPI.ts"; import { RootApiRequestFactory, RootApiResponseProcessor} from "../apis/RootApi.ts"; export interface RootApiGetApiVersionRequest { } export interface RootApiGetPluginInfoRequest { /** * * @type string * @memberof RootApigetPluginInfo */ fields?: string } export interface RootApiGetRootEndpointsOfRootRequest { } export interface RootApiGetVersionRequest { } export class ObjectRootApi { private api: ObservableRootApi public constructor(configuration: Configuration, requestFactory?: RootApiRequestFactory, responseProcessor?: RootApiResponseProcessor) { this.api = new ObservableRootApi(configuration, requestFactory, responseProcessor); } /** * Get the API version. * @param param the request object */ public getApiVersion(param: RootApiGetApiVersionRequest, options?: Configuration): Promise<string> { return this.api.getApiVersion( options).toPromise(); } /** * Get the plugin info. * @param param the request object */ public getPluginInfo(param: RootApiGetPluginInfoRequest, options?: Configuration): Promise<Plugin> { return this.api.getPluginInfo(param.fields, options).toPromise(); } /** * Get root endpoints. * @param param the request object */ public getRootEndpointsOfRoot(param: RootApiGetRootEndpointsOfRootRequest, options?: Configuration): Promise<string> { return this.api.getRootEndpointsOfRoot( options).toPromise(); } /** * Get the TeamCity server version. * @param param the request object */ public getVersion(param: RootApiGetVersionRequest, options?: Configuration): Promise<string> { return this.api.getVersion( options).toPromise(); } } import { ObservableServerApi } from "./ObservableAPI.ts"; import { ServerApiRequestFactory, ServerApiResponseProcessor} from "../apis/ServerApi.ts"; export interface ServerApiAddLicenseKeysRequest { /** * * @type string * @memberof ServerApiaddLicenseKeys */ fields?: string /** * * @type string * @memberof ServerApiaddLicenseKeys */ body?: string } export interface ServerApiDeleteLicenseKeyRequest { /** * * @type string * @memberof ServerApideleteLicenseKey */ licenseKey: string } export interface ServerApiDownloadFileOfServerRequest { /** * * @type string * @memberof ServerApidownloadFileOfServer */ path: string /** * * @type string * @memberof ServerApidownloadFileOfServer */ areaId: string } export interface ServerApiGetAllMetricsRequest { /** * * @type string * @memberof ServerApigetAllMetrics */ fields?: string } export interface ServerApiGetAllPluginsRequest { /** * * @type string * @memberof ServerApigetAllPlugins */ fields?: string } export interface ServerApiGetBackupStatusRequest { } export interface ServerApiGetFileMetadataOfServerRequest { /** * * @type string * @memberof ServerApigetFileMetadataOfServer */ path: string /** * * @type string * @memberof ServerApigetFileMetadataOfServer */ areaId: string /** * * @type string * @memberof ServerApigetFileMetadataOfServer */ fields?: string } export interface ServerApiGetFilesListForSubpathOfServerRequest { /** * * @type string * @memberof ServerApigetFilesListForSubpathOfServer */ path: string /** * * @type string * @memberof ServerApigetFilesListForSubpathOfServer */ areaId: string /** * * @type string * @memberof ServerApigetFilesListForSubpathOfServer */ basePath?: string /** * * @type string * @memberof ServerApigetFilesListForSubpathOfServer */ locator?: string /** * * @type string * @memberof ServerApigetFilesListForSubpathOfServer */ fields?: string } export interface ServerApiGetFilesListOfServerRequest { /** * * @type string * @memberof ServerApigetFilesListOfServer */ areaId: string /** * * @type string * @memberof ServerApigetFilesListOfServer */ basePath?: string /** * * @type string * @memberof ServerApigetFilesListOfServer */ locator?: string /** * * @type string * @memberof ServerApigetFilesListOfServer */ fields?: string } export interface ServerApiGetLicenseKeyRequest { /** * * @type string * @memberof ServerApigetLicenseKey */ licenseKey: string /** * * @type string * @memberof ServerApigetLicenseKey */ fields?: string } export interface ServerApiGetLicenseKeysRequest { /** * * @type string * @memberof ServerApigetLicenseKeys */ fields?: string } export interface ServerApiGetLicensingDataRequest { /** * * @type string * @memberof ServerApigetLicensingData */ fields?: string } export interface ServerApiGetServerFieldRequest { /** * * @type string * @memberof ServerApigetServerField */ field: string } export interface ServerApiGetServerInfoRequest { /** * * @type string * @memberof ServerApigetServerInfo */ fields?: string } export interface ServerApiGetZippedFileOfServerRequest { /** * * @type string * @memberof ServerApigetZippedFileOfServer */ path: string /** * * @type string * @memberof ServerApigetZippedFileOfServer */ areaId: string /** * * @type string * @memberof ServerApigetZippedFileOfServer */ basePath?: string /** * * @type string * @memberof ServerApigetZippedFileOfServer */ locator?: string /** * * @type string * @memberof ServerApigetZippedFileOfServer */ name?: string } export interface ServerApiStartBackupRequest { /** * * @type string * @memberof ServerApistartBackup */ fileName?: string /** * * @type boolean * @memberof ServerApistartBackup */ addTimestamp?: boolean /** * * @type boolean * @memberof ServerApistartBackup */ includeConfigs?: boolean /** * * @type boolean * @memberof ServerApistartBackup */ includeDatabase?: boolean /** * * @type boolean * @memberof ServerApistartBackup */ includeBuildLogs?: boolean /** * * @type boolean * @memberof ServerApistartBackup */ includePersonalChanges?: boolean /** * * @type boolean * @memberof ServerApistartBackup */ includeRunningBuilds?: boolean /** * * @type boolean * @memberof ServerApistartBackup */ includeSupplimentaryData?: boolean } export class ObjectServerApi { private api: ObservableServerApi public constructor(configuration: Configuration, requestFactory?: ServerApiRequestFactory, responseProcessor?: ServerApiResponseProcessor) { this.api = new ObservableServerApi(configuration, requestFactory, responseProcessor); } /** * Add license keys. * @param param the request object */ public addLicenseKeys(param: ServerApiAddLicenseKeysRequest, options?: Configuration): Promise<LicenseKeys> { return this.api.addLicenseKeys(param.fields, param.body, options).toPromise(); } /** * Delete a license key. * @param param the request object */ public deleteLicenseKey(param: ServerApiDeleteLicenseKeyRequest, options?: Configuration): Promise<void> { return this.api.deleteLicenseKey(param.licenseKey, options).toPromise(); } /** * Download specific file. * @param param the request object */ public downloadFileOfServer(param: ServerApiDownloadFileOfServerRequest, options?: Configuration): Promise<void> { return this.api.downloadFileOfServer(param.path, param.areaId, options).toPromise(); } /** * Get metrics. * @param param the request object */ public getAllMetrics(param: ServerApiGetAllMetricsRequest, options?: Configuration): Promise<Metrics> { return this.api.getAllMetrics(param.fields, options).toPromise(); } /** * Get all plugins. * @param param the request object */ public getAllPlugins(param: ServerApiGetAllPluginsRequest, options?: Configuration): Promise<Plugins> { return this.api.getAllPlugins(param.fields, options).toPromise(); } /** * Get the latest backup status. * @param param the request object */ public getBackupStatus(param: ServerApiGetBackupStatusRequest, options?: Configuration): Promise<string> { return this.api.getBackupStatus( options).toPromise(); } /** * Get metadata of specific file. * @param param the request object */ public getFileMetadataOfServer(param: ServerApiGetFileMetadataOfServerRequest, options?: Configuration): Promise<any> { return this.api.getFileMetadataOfServer(param.path, param.areaId, param.fields, options).toPromise(); } /** * List files under this path. * @param param the request object */ public getFilesListForSubpathOfServer(param: ServerApiGetFilesListForSubpathOfServerRequest, options?: Configuration): Promise<Files> { return this.api.getFilesListForSubpathOfServer(param.path, param.areaId, param.basePath, param.locator, param.fields, options).toPromise(); } /** * List all files. * @param param the request object */ public getFilesListOfServer(param: ServerApiGetFilesListOfServerRequest, options?: Configuration): Promise<Files> { return this.api.getFilesListOfServer(param.areaId, param.basePath, param.locator, param.fields, options).toPromise(); } /** * Get a license key. * @param param the request object */ public getLicenseKey(param: ServerApiGetLicenseKeyRequest, options?: Configuration): Promise<LicenseKey> { return this.api.getLicenseKey(param.licenseKey, param.fields, options).toPromise(); } /** * Get all license keys. * @param param the request object */ public getLicenseKeys(param: ServerApiGetLicenseKeysRequest, options?: Configuration): Promise<LicenseKeys> { return this.api.getLicenseKeys(param.fields, options).toPromise(); } /** * Get the licensing data. * @param param the request object */ public getLicensingData(param: ServerApiGetLicensingDataRequest, options?: Configuration): Promise<LicensingData> { return this.api.getLicensingData(param.fields, options).toPromise(); } /** * Get a field of the server info. * @param param the request object */ public getServerField(param: ServerApiGetServerFieldRequest, options?: Configuration): Promise<string> { return this.api.getServerField(param.field, options).toPromise(); } /** * Get the server info. * @param param the request object */ public getServerInfo(param: ServerApiGetServerInfoRequest, options?: Configuration): Promise<Server> { return this.api.getServerInfo(param.fields, options).toPromise(); } /** * Get specific file zipped. * @param param the request object */ public getZippedFileOfServer(param: ServerApiGetZippedFileOfServerRequest, options?: Configuration): Promise<void> { return this.api.getZippedFileOfServer(param.path, param.areaId, param.basePath, param.locator, param.name, options).toPromise(); } /** * Start a new backup. * @param param the request object */ public startBackup(param: ServerApiStartBackupRequest, options?: Configuration): Promise<string> { return this.api.startBackup(param.fileName, param.addTimestamp, param.includeConfigs, param.includeDatabase, param.includeBuildLogs, param.includePersonalChanges, param.includeRunningBuilds, param.includeSupplimentaryData, options).toPromise(); } } import { ObservableTestApi } from "./ObservableAPI.ts"; import { TestApiRequestFactory, TestApiResponseProcessor} from "../apis/TestApi.ts"; export interface TestApiGetTestRequest { /** * * @type string * @memberof TestApigetTest */ testLocator: string /** * * @type string * @memberof TestApigetTest */ fields?: string } export interface TestApiGetTestsRequest { /** * * @type string * @memberof TestApigetTests */ locator?: string /** * * @type string * @memberof TestApigetTests */ fields?: string } export class ObjectTestApi { private api: ObservableTestApi public constructor(configuration: Configuration, requestFactory?: TestApiRequestFactory, responseProcessor?: TestApiResponseProcessor) { this.api = new ObservableTestApi(configuration, requestFactory, responseProcessor); } /** * Get a matching test. * @param param the request object */ public getTest(param: TestApiGetTestRequest, options?: Configuration): Promise<Test> { return this.api.getTest(param.testLocator, param.fields, options).toPromise(); } /** * Get all tests. * @param param the request object */ public getTests(param: TestApiGetTestsRequest, options?: Configuration): Promise<Tests> { return this.api.getTests(param.locator, param.fields, options).toPromise(); } } import { ObservableTestOccurrenceApi } from "./ObservableAPI.ts"; import { TestOccurrenceApiRequestFactory, TestOccurrenceApiResponseProcessor} from "../apis/TestOccurrenceApi.ts"; export interface TestOccurrenceApiGetAllTestOccurrencesRequest { /** * * @type string * @memberof TestOccurrenceApigetAllTestOccurrences */ locator?: string /** * * @type string * @memberof TestOccurrenceApigetAllTestOccurrences */ fields?: string } export interface TestOccurrenceApiGetTestOccurrenceRequest { /** * * @type string * @memberof TestOccurrenceApigetTestOccurrence */ testLocator: string /** * * @type string * @memberof TestOccurrenceApigetTestOccurrence */ fields?: string } export class ObjectTestOccurrenceApi { private api: ObservableTestOccurrenceApi public constructor(configuration: Configuration, requestFactory?: TestOccurrenceApiRequestFactory, responseProcessor?: TestOccurrenceApiResponseProcessor) { this.api = new ObservableTestOccurrenceApi(configuration, requestFactory, responseProcessor); } /** * Get all test occurrences. * @param param the request object */ public getAllTestOccurrences(param: TestOccurrenceApiGetAllTestOccurrencesRequest, options?: Configuration): Promise<TestOccurrences> { return this.api.getAllTestOccurrences(param.locator, param.fields, options).toPromise(); } /** * Get a matching test occurrence. * @param param the request object */ public getTestOccurrence(param: TestOccurrenceApiGetTestOccurrenceRequest, options?: Configuration): Promise<TestOccurrence> { return this.api.getTestOccurrence(param.testLocator, param.fields, options).toPromise(); } } import { ObservableUserApi } from "./ObservableAPI.ts"; import { UserApiRequestFactory, UserApiResponseProcessor} from "../apis/UserApi.ts"; export interface UserApiAddRoleToUserRequest { /** * * @type string * @memberof UserApiaddRoleToUser */ userLocator: string /** * * @type Role * @memberof UserApiaddRoleToUser */ body?: Role } export interface UserApiAddRoleToUserAtScopeRequest { /** * * @type string * @memberof UserApiaddRoleToUserAtScope */ userLocator: string /** * * @type string * @memberof UserApiaddRoleToUserAtScope */ roleId: string /** * * @type string * @memberof UserApiaddRoleToUserAtScope */ scope: string } export interface UserApiAddUserRequest { /** * * @type string * @memberof UserApiaddUser */ fields?: string /** * * @type User * @memberof UserApiaddUser */ body?: User } export interface UserApiAddUserTokenRequest { /** * * @type string * @memberof UserApiaddUserToken */ userLocator: string /** * * @type string * @memberof UserApiaddUserToken */ fields?: string /** * * @type Token * @memberof UserApiaddUserToken */ body?: Token } export interface UserApiDeleteUserRequest { /** * * @type string * @memberof UserApideleteUser */ userLocator: string } export interface UserApiDeleteUserFieldRequest { /** * * @type string * @memberof UserApideleteUserField */ userLocator: string /** * * @type string * @memberof UserApideleteUserField */ field: string } export interface UserApiDeleteUserTokenRequest { /** * * @type string * @memberof UserApideleteUserToken */ userLocator: string /** * * @type string * @memberof UserApideleteUserToken */ name: string } export interface UserApiGerUserFieldRequest { /** * * @type string * @memberof UserApigerUserField */ userLocator: string /** * * @type string * @memberof UserApigerUserField */ field: string } export interface UserApiGetAllUserGroupsRequest { /** * * @type string * @memberof UserApigetAllUserGroups */ userLocator: string /** * * @type string * @memberof UserApigetAllUserGroups */ fields?: string } export interface UserApiGetAllUserRolesRequest { /** * * @type string * @memberof UserApigetAllUserRoles */ userLocator: string } export interface UserApiGetAllUsersRequest { /** * * @type string * @memberof UserApigetAllUsers */ locator?: string /** * * @type string * @memberof UserApigetAllUsers */ fields?: string } export interface UserApiGetUserRequest { /** * * @type string * @memberof UserApigetUser */ userLocator: string /** * * @type string * @memberof UserApigetUser */ fields?: string } export interface UserApiGetUserGroupRequest { /** * * @type string * @memberof UserApigetUserGroup */ userLocator: string /** * * @type string * @memberof UserApigetUserGroup */ groupLocator: string /** * * @type string * @memberof UserApigetUserGroup */ fields?: string } export interface UserApiGetUserPermissionsRequest { /** * * @type string * @memberof UserApigetUserPermissions */ userLocator: string /** * * @type string * @memberof UserApigetUserPermissions */ locator?: string /** * * @type string * @memberof UserApigetUserPermissions */ fields?: string } export interface UserApiGetUserPropertiesRequest { /** * * @type string * @memberof UserApigetUserProperties */ userLocator: string /** * * @type string * @memberof UserApigetUserProperties */ fields?: string } export interface UserApiGetUserPropertyRequest { /** * * @type string * @memberof UserApigetUserProperty */ userLocator: string /** * * @type string * @memberof UserApigetUserProperty */ name: string } export interface UserApiGetUserRolesAtScopeRequest { /** * * @type string * @memberof UserApigetUserRolesAtScope */ userLocator: string /** * * @type string * @memberof UserApigetUserRolesAtScope */ roleId: string /** * * @type string * @memberof UserApigetUserRolesAtScope */ scope: string } export interface UserApiGetUserTokensRequest { /** * * @type string * @memberof UserApigetUserTokens */ userLocator: string /** * * @type string * @memberof UserApigetUserTokens */ fields?: string } export interface UserApiRemoveUserFromGroupRequest { /** * * @type string * @memberof UserApiremoveUserFromGroup */ userLocator: string /** * * @type string * @memberof UserApiremoveUserFromGroup */ groupLocator: string /** * * @type string * @memberof UserApiremoveUserFromGroup */ fields?: string } export interface UserApiRemoveUserPropertyRequest { /** * * @type string * @memberof UserApiremoveUserProperty */ userLocator: string /** * * @type string * @memberof UserApiremoveUserProperty */ name: string } export interface UserApiRemoveUserRememberMeRequest { /** * * @type string * @memberof UserApiremoveUserRememberMe */ userLocator: string } export interface UserApiRemoveUserRoleAtScopeRequest { /** * * @type string * @memberof UserApiremoveUserRoleAtScope */ userLocator: string /** * * @type string * @memberof UserApiremoveUserRoleAtScope */ roleId: string /** * * @type string * @memberof UserApiremoveUserRoleAtScope */ scope: string } export interface UserApiReplaceUserRequest { /** * * @type string * @memberof UserApireplaceUser */ userLocator: string /** * * @type string * @memberof UserApireplaceUser */ fields?: string /** * * @type User * @memberof UserApireplaceUser */ body?: User } export interface UserApiSetUserFieldRequest { /** * * @type string * @memberof UserApisetUserField */ userLocator: string /** * * @type string * @memberof UserApisetUserField */ field: string /** * * @type string * @memberof UserApisetUserField */ body?: string } export interface UserApiSetUserGroupsRequest { /** * * @type string * @memberof UserApisetUserGroups */ userLocator: string /** * * @type string * @memberof UserApisetUserGroups */ fields?: string /** * * @type Groups * @memberof UserApisetUserGroups */ body?: Groups } export interface UserApiSetUserPropertyRequest { /** * * @type string * @memberof UserApisetUserProperty */ userLocator: string /** * * @type string * @memberof UserApisetUserProperty */ name: string /** * * @type string * @memberof UserApisetUserProperty */ body?: string } export interface UserApiSetUserRolesRequest { /** * * @type string * @memberof UserApisetUserRoles */ userLocator: string /** * * @type Roles * @memberof UserApisetUserRoles */ body?: Roles } export class ObjectUserApi { private api: ObservableUserApi public constructor(configuration: Configuration, requestFactory?: UserApiRequestFactory, responseProcessor?: UserApiResponseProcessor) { this.api = new ObservableUserApi(configuration, requestFactory, responseProcessor); } /** * Add a role to the matching user. * @param param the request object */ public addRoleToUser(param: UserApiAddRoleToUserRequest, options?: Configuration): Promise<Role> { return this.api.addRoleToUser(param.userLocator, param.body, options).toPromise(); } /** * Add a role with the specific scope to the matching user. * @param param the request object */ public addRoleToUserAtScope(param: UserApiAddRoleToUserAtScopeRequest, options?: Configuration): Promise<Role> { return this.api.addRoleToUserAtScope(param.userLocator, param.roleId, param.scope, options).toPromise(); } /** * Create a new user. * @param param the request object */ public addUser(param: UserApiAddUserRequest, options?: Configuration): Promise<User> { return this.api.addUser(param.fields, param.body, options).toPromise(); } /** * Create a new authentication token for the matching user. * @param param the request object */ public addUserToken(param: UserApiAddUserTokenRequest, options?: Configuration): Promise<Token> { return this.api.addUserToken(param.userLocator, param.fields, param.body, options).toPromise(); } /** * Delete user matching the locator. * @param param the request object */ public deleteUser(param: UserApiDeleteUserRequest, options?: Configuration): Promise<void> { return this.api.deleteUser(param.userLocator, options).toPromise(); } /** * Remove a property of the matching user. * @param param the request object */ public deleteUserField(param: UserApiDeleteUserFieldRequest, options?: Configuration): Promise<void> { return this.api.deleteUserField(param.userLocator, param.field, options).toPromise(); } /** * Remove an authentication token from the matching user. * @param param the request object */ public deleteUserToken(param: UserApiDeleteUserTokenRequest, options?: Configuration): Promise<void> { return this.api.deleteUserToken(param.userLocator, param.name, options).toPromise(); } /** * Get a field of the matching user. * @param param the request object */ public gerUserField(param: UserApiGerUserFieldRequest, options?: Configuration): Promise<string> { return this.api.gerUserField(param.userLocator, param.field, options).toPromise(); } /** * Get all groups of the matching user. * @param param the request object */ public getAllUserGroups(param: UserApiGetAllUserGroupsRequest, options?: Configuration): Promise<Groups> { return this.api.getAllUserGroups(param.userLocator, param.fields, options).toPromise(); } /** * Get all user roles of the matching user. * @param param the request object */ public getAllUserRoles(param: UserApiGetAllUserRolesRequest, options?: Configuration): Promise<Roles> { return this.api.getAllUserRoles(param.userLocator, options).toPromise(); } /** * Get all users. * @param param the request object */ public getAllUsers(param: UserApiGetAllUsersRequest, options?: Configuration): Promise<Users> { return this.api.getAllUsers(param.locator, param.fields, options).toPromise(); } /** * Get user matching the locator. * @param param the request object */ public getUser(param: UserApiGetUserRequest, options?: Configuration): Promise<User> { return this.api.getUser(param.userLocator, param.fields, options).toPromise(); } /** * Get a user group of the matching user. * @param param the request object */ public getUserGroup(param: UserApiGetUserGroupRequest, options?: Configuration): Promise<Group> { return this.api.getUserGroup(param.userLocator, param.groupLocator, param.fields, options).toPromise(); } /** * Get all permissions effective for the matching user. * @param param the request object */ public getUserPermissions(param: UserApiGetUserPermissionsRequest, options?: Configuration): Promise<PermissionAssignments> { return this.api.getUserPermissions(param.userLocator, param.locator, param.fields, options).toPromise(); } /** * Get all properties of the matching user. * @param param the request object */ public getUserProperties(param: UserApiGetUserPropertiesRequest, options?: Configuration): Promise<Properties> { return this.api.getUserProperties(param.userLocator, param.fields, options).toPromise(); } /** * Get a property of the matching user. * @param param the request object */ public getUserProperty(param: UserApiGetUserPropertyRequest, options?: Configuration): Promise<string> { return this.api.getUserProperty(param.userLocator, param.name, options).toPromise(); } /** * Get a user role with the specific scope from the matching user. * @param param the request object */ public getUserRolesAtScope(param: UserApiGetUserRolesAtScopeRequest, options?: Configuration): Promise<Role> { return this.api.getUserRolesAtScope(param.userLocator, param.roleId, param.scope, options).toPromise(); } /** * Get all authentication tokens of the matching user. * @param param the request object */ public getUserTokens(param: UserApiGetUserTokensRequest, options?: Configuration): Promise<Tokens> { return this.api.getUserTokens(param.userLocator, param.fields, options).toPromise(); } /** * Remove the matching user from the specific group. * @param param the request object */ public removeUserFromGroup(param: UserApiRemoveUserFromGroupRequest, options?: Configuration): Promise<void> { return this.api.removeUserFromGroup(param.userLocator, param.groupLocator, param.fields, options).toPromise(); } /** * Remove a property of the matching user. * @param param the request object */ public removeUserProperty(param: UserApiRemoveUserPropertyRequest, options?: Configuration): Promise<void> { return this.api.removeUserProperty(param.userLocator, param.name, options).toPromise(); } /** * Remove the RememberMe data of the matching user. * @param param the request object */ public removeUserRememberMe(param: UserApiRemoveUserRememberMeRequest, options?: Configuration): Promise<void> { return this.api.removeUserRememberMe(param.userLocator, options).toPromise(); } /** * Remove a role with the specific scope from the matching user. * @param param the request object */ public removeUserRoleAtScope(param: UserApiRemoveUserRoleAtScopeRequest, options?: Configuration): Promise<void> { return this.api.removeUserRoleAtScope(param.userLocator, param.roleId, param.scope, options).toPromise(); } /** * Update user matching the locator. * @param param the request object */ public replaceUser(param: UserApiReplaceUserRequest, options?: Configuration): Promise<User> { return this.api.replaceUser(param.userLocator, param.fields, param.body, options).toPromise(); } /** * Update a field of the matching user. * @param param the request object */ public setUserField(param: UserApiSetUserFieldRequest, options?: Configuration): Promise<string> { return this.api.setUserField(param.userLocator, param.field, param.body, options).toPromise(); } /** * Update groups of the matching user. * @param param the request object */ public setUserGroups(param: UserApiSetUserGroupsRequest, options?: Configuration): Promise<Groups> { return this.api.setUserGroups(param.userLocator, param.fields, param.body, options).toPromise(); } /** * Update a property of the matching user. * @param param the request object */ public setUserProperty(param: UserApiSetUserPropertyRequest, options?: Configuration): Promise<string> { return this.api.setUserProperty(param.userLocator, param.name, param.body, options).toPromise(); } /** * Update user roles of the matching user. * @param param the request object */ public setUserRoles(param: UserApiSetUserRolesRequest, options?: Configuration): Promise<Roles> { return this.api.setUserRoles(param.userLocator, param.body, options).toPromise(); } } import { ObservableVcsRootApi } from "./ObservableAPI.ts"; import { VcsRootApiRequestFactory, VcsRootApiResponseProcessor} from "../apis/VcsRootApi.ts"; export interface VcsRootApiAddVcsRootRequest { /** * * @type string * @memberof VcsRootApiaddVcsRoot */ fields?: string /** * * @type VcsRoot * @memberof VcsRootApiaddVcsRoot */ body?: VcsRoot } export interface VcsRootApiDeleteAllVcsRootPropertiesRequest { /** * * @type string * @memberof VcsRootApideleteAllVcsRootProperties */ vcsRootLocator: string } export interface VcsRootApiDeleteVcsRootRequest { /** * * @type string * @memberof VcsRootApideleteVcsRoot */ vcsRootLocator: string } export interface VcsRootApiDeleteVcsRootPropertyRequest { /** * * @type string * @memberof VcsRootApideleteVcsRootProperty */ vcsRootLocator: string /** * * @type string * @memberof VcsRootApideleteVcsRootProperty */ name: string } export interface VcsRootApiGetAllVcsRootPropertiesRequest { /** * * @type string * @memberof VcsRootApigetAllVcsRootProperties */ vcsRootLocator: string /** * * @type string * @memberof VcsRootApigetAllVcsRootProperties */ fields?: string } export interface VcsRootApiGetAllVcsRootsRequest { /** * * @type string * @memberof VcsRootApigetAllVcsRoots */ locator?: string /** * * @type string * @memberof VcsRootApigetAllVcsRoots */ fields?: string } export interface VcsRootApiGetRootEndpointsRequest { /** * * @type string * @memberof VcsRootApigetRootEndpoints */ vcsRootLocator: string /** * * @type string * @memberof VcsRootApigetRootEndpoints */ fields?: string } export interface VcsRootApiGetVcsRootFieldRequest { /** * * @type string * @memberof VcsRootApigetVcsRootField */ vcsRootLocator: string /** * * @type string * @memberof VcsRootApigetVcsRootField */ field: string } export interface VcsRootApiGetVcsRootInstancesRequest { /** * * @type string * @memberof VcsRootApigetVcsRootInstances */ vcsRootLocator: string /** * * @type string * @memberof VcsRootApigetVcsRootInstances */ fields?: string } export interface VcsRootApiGetVcsRootPropertyRequest { /** * * @type string * @memberof VcsRootApigetVcsRootProperty */ vcsRootLocator: string /** * * @type string * @memberof VcsRootApigetVcsRootProperty */ name: string } export interface VcsRootApiGetVcsRootSettingsFileRequest { /** * * @type string * @memberof VcsRootApigetVcsRootSettingsFile */ vcsRootLocator: string } export interface VcsRootApiSetVcsRootFieldRequest { /** * * @type string * @memberof VcsRootApisetVcsRootField */ vcsRootLocator: string /** * * @type string * @memberof VcsRootApisetVcsRootField */ field: string /** * * @type string * @memberof VcsRootApisetVcsRootField */ body?: string } export interface VcsRootApiSetVcsRootPropertiesRequest { /** * * @type string * @memberof VcsRootApisetVcsRootProperties */ vcsRootLocator: string /** * * @type string * @memberof VcsRootApisetVcsRootProperties */ fields?: string /** * * @type Properties * @memberof VcsRootApisetVcsRootProperties */ body?: Properties } export interface VcsRootApiSetVcsRootPropertyRequest { /** * * @type string * @memberof VcsRootApisetVcsRootProperty */ vcsRootLocator: string /** * * @type string * @memberof VcsRootApisetVcsRootProperty */ name: string /** * * @type string * @memberof VcsRootApisetVcsRootProperty */ body?: string } export class ObjectVcsRootApi { private api: ObservableVcsRootApi public constructor(configuration: Configuration, requestFactory?: VcsRootApiRequestFactory, responseProcessor?: VcsRootApiResponseProcessor) { this.api = new ObservableVcsRootApi(configuration, requestFactory, responseProcessor); } /** * Add a new VCS root. * @param param the request object */ public addVcsRoot(param: VcsRootApiAddVcsRootRequest, options?: Configuration): Promise<VcsRoot> { return this.api.addVcsRoot(param.fields, param.body, options).toPromise(); } /** * Delete all properties of the matching VCS root. * @param param the request object */ public deleteAllVcsRootProperties(param: VcsRootApiDeleteAllVcsRootPropertiesRequest, options?: Configuration): Promise<void> { return this.api.deleteAllVcsRootProperties(param.vcsRootLocator, options).toPromise(); } /** * Remove VCS root matching the locator. * @param param the request object */ public deleteVcsRoot(param: VcsRootApiDeleteVcsRootRequest, options?: Configuration): Promise<void> { return this.api.deleteVcsRoot(param.vcsRootLocator, options).toPromise(); } /** * Delete a property of the matching VCS root. * @param param the request object */ public deleteVcsRootProperty(param: VcsRootApiDeleteVcsRootPropertyRequest, options?: Configuration): Promise<void> { return this.api.deleteVcsRootProperty(param.vcsRootLocator, param.name, options).toPromise(); } /** * Get all properties of the matching VCS root. * @param param the request object */ public getAllVcsRootProperties(param: VcsRootApiGetAllVcsRootPropertiesRequest, options?: Configuration): Promise<Properties> { return this.api.getAllVcsRootProperties(param.vcsRootLocator, param.fields, options).toPromise(); } /** * Get all VCS roots. * @param param the request object */ public getAllVcsRoots(param: VcsRootApiGetAllVcsRootsRequest, options?: Configuration): Promise<VcsRoots> { return this.api.getAllVcsRoots(param.locator, param.fields, options).toPromise(); } /** * Get root endpoints. * @param param the request object */ public getRootEndpoints(param: VcsRootApiGetRootEndpointsRequest, options?: Configuration): Promise<VcsRoot> { return this.api.getRootEndpoints(param.vcsRootLocator, param.fields, options).toPromise(); } /** * Get a field of the matching VCS root. * @param param the request object */ public getVcsRootField(param: VcsRootApiGetVcsRootFieldRequest, options?: Configuration): Promise<string> { return this.api.getVcsRootField(param.vcsRootLocator, param.field, options).toPromise(); } /** * Get all VCS root instances of the matching VCS root. * @param param the request object */ public getVcsRootInstances(param: VcsRootApiGetVcsRootInstancesRequest, options?: Configuration): Promise<VcsRootInstances> { return this.api.getVcsRootInstances(param.vcsRootLocator, param.fields, options).toPromise(); } /** * Get a property on the matching VCS root. * @param param the request object */ public getVcsRootProperty(param: VcsRootApiGetVcsRootPropertyRequest, options?: Configuration): Promise<string> { return this.api.getVcsRootProperty(param.vcsRootLocator, param.name, options).toPromise(); } /** * Get the settings file of the matching VCS root. * @param param the request object */ public getVcsRootSettingsFile(param: VcsRootApiGetVcsRootSettingsFileRequest, options?: Configuration): Promise<string> { return this.api.getVcsRootSettingsFile(param.vcsRootLocator, options).toPromise(); } /** * Update a field of the matching VCS root. * @param param the request object */ public setVcsRootField(param: VcsRootApiSetVcsRootFieldRequest, options?: Configuration): Promise<string> { return this.api.setVcsRootField(param.vcsRootLocator, param.field, param.body, options).toPromise(); } /** * Update all properties of the matching VCS root. * @param param the request object */ public setVcsRootProperties(param: VcsRootApiSetVcsRootPropertiesRequest, options?: Configuration): Promise<Properties> { return this.api.setVcsRootProperties(param.vcsRootLocator, param.fields, param.body, options).toPromise(); } /** * Update a property of the matching VCS root. * @param param the request object */ public setVcsRootProperty(param: VcsRootApiSetVcsRootPropertyRequest, options?: Configuration): Promise<string> { return this.api.setVcsRootProperty(param.vcsRootLocator, param.name, param.body, options).toPromise(); } } import { ObservableVcsRootInstanceApi } from "./ObservableAPI.ts"; import { VcsRootInstanceApiRequestFactory, VcsRootInstanceApiResponseProcessor} from "../apis/VcsRootInstanceApi.ts"; export interface VcsRootInstanceApiDeleteVcsRootInstanceFieldRequest { /** * * @type string * @memberof VcsRootInstanceApideleteVcsRootInstanceField */ vcsRootInstanceLocator: string /** * * @type string * @memberof VcsRootInstanceApideleteVcsRootInstanceField */ field: string } export interface VcsRootInstanceApiDeleteVcsRootInstanceRepositoryStateRequest { /** * * @type string * @memberof VcsRootInstanceApideleteVcsRootInstanceRepositoryState */ vcsRootInstanceLocator: string } export interface VcsRootInstanceApiDownloadFileRequest { /** * * @type string * @memberof VcsRootInstanceApidownloadFile */ path: string /** * * @type string * @memberof VcsRootInstanceApidownloadFile */ vcsRootInstanceLocator: string } export interface VcsRootInstanceApiGetAllVcsRootInstancesRequest { /** * * @type string * @memberof VcsRootInstanceApigetAllVcsRootInstances */ locator?: string /** * * @type string * @memberof VcsRootInstanceApigetAllVcsRootInstances */ fields?: string } export interface VcsRootInstanceApiGetFileMetadataRequest { /** * * @type string * @memberof VcsRootInstanceApigetFileMetadata */ path: string /** * * @type string * @memberof VcsRootInstanceApigetFileMetadata */ vcsRootInstanceLocator: string /** * * @type string * @memberof VcsRootInstanceApigetFileMetadata */ fields?: string } export interface VcsRootInstanceApiGetFilesListRequest { /** * * @type string * @memberof VcsRootInstanceApigetFilesList */ vcsRootInstanceLocator: string /** * * @type string * @memberof VcsRootInstanceApigetFilesList */ basePath?: string /** * * @type string * @memberof VcsRootInstanceApigetFilesList */ locator?: string /** * * @type string * @memberof VcsRootInstanceApigetFilesList */ fields?: string } export interface VcsRootInstanceApiGetFilesListForSubpathRequest { /** * * @type string * @memberof VcsRootInstanceApigetFilesListForSubpath */ path: string /** * * @type string * @memberof VcsRootInstanceApigetFilesListForSubpath */ vcsRootInstanceLocator: string /** * * @type string * @memberof VcsRootInstanceApigetFilesListForSubpath */ basePath?: string /** * * @type string * @memberof VcsRootInstanceApigetFilesListForSubpath */ locator?: string /** * * @type string * @memberof VcsRootInstanceApigetFilesListForSubpath */ fields?: string } export interface VcsRootInstanceApiGetVcsRootInstanceRequest { /** * * @type string * @memberof VcsRootInstanceApigetVcsRootInstance */ vcsRootInstanceLocator: string /** * * @type string * @memberof VcsRootInstanceApigetVcsRootInstance */ fields?: string } export interface VcsRootInstanceApiGetVcsRootInstanceCreationDateRequest { /** * * @type string * @memberof VcsRootInstanceApigetVcsRootInstanceCreationDate */ vcsRootInstanceLocator: string } export interface VcsRootInstanceApiGetVcsRootInstanceFieldRequest { /** * * @type string * @memberof VcsRootInstanceApigetVcsRootInstanceField */ vcsRootInstanceLocator: string /** * * @type string * @memberof VcsRootInstanceApigetVcsRootInstanceField */ field: string } export interface VcsRootInstanceApiGetVcsRootInstancePropertiesRequest { /** * * @type string * @memberof VcsRootInstanceApigetVcsRootInstanceProperties */ vcsRootInstanceLocator: string /** * * @type string * @memberof VcsRootInstanceApigetVcsRootInstanceProperties */ fields?: string } export interface VcsRootInstanceApiGetVcsRootInstanceRepositoryStateRequest { /** * * @type string * @memberof VcsRootInstanceApigetVcsRootInstanceRepositoryState */ vcsRootInstanceLocator: string /** * * @type string * @memberof VcsRootInstanceApigetVcsRootInstanceRepositoryState */ fields?: string } export interface VcsRootInstanceApiGetZippedFileRequest { /** * * @type string * @memberof VcsRootInstanceApigetZippedFile */ path: string /** * * @type string * @memberof VcsRootInstanceApigetZippedFile */ vcsRootInstanceLocator: string /** * * @type string * @memberof VcsRootInstanceApigetZippedFile */ basePath?: string /** * * @type string * @memberof VcsRootInstanceApigetZippedFile */ locator?: string /** * * @type string * @memberof VcsRootInstanceApigetZippedFile */ name?: string } export interface VcsRootInstanceApiRequestPendingChangesCheckRequest { /** * * @type string * @memberof VcsRootInstanceApirequestPendingChangesCheck */ locator?: string /** * * @type string * @memberof VcsRootInstanceApirequestPendingChangesCheck */ requestor?: string /** * * @type string * @memberof VcsRootInstanceApirequestPendingChangesCheck */ fields?: string } export interface VcsRootInstanceApiSetVcsRootInstanceFieldRequest { /** * * @type string * @memberof VcsRootInstanceApisetVcsRootInstanceField */ vcsRootInstanceLocator: string /** * * @type string * @memberof VcsRootInstanceApisetVcsRootInstanceField */ field: string /** * * @type string * @memberof VcsRootInstanceApisetVcsRootInstanceField */ body?: string } export interface VcsRootInstanceApiSetVcsRootInstanceRepositoryStateRequest { /** * * @type string * @memberof VcsRootInstanceApisetVcsRootInstanceRepositoryState */ vcsRootInstanceLocator: string /** * * @type string * @memberof VcsRootInstanceApisetVcsRootInstanceRepositoryState */ fields?: string /** * * @type Entries * @memberof VcsRootInstanceApisetVcsRootInstanceRepositoryState */ body?: Entries } export interface VcsRootInstanceApiTriggerCommitHookNotificationRequest { /** * * @type string * @memberof VcsRootInstanceApitriggerCommitHookNotification */ locator?: string /** * * @type boolean * @memberof VcsRootInstanceApitriggerCommitHookNotification */ okOnNothingFound?: boolean } export class ObjectVcsRootInstanceApi { private api: ObservableVcsRootInstanceApi public constructor(configuration: Configuration, requestFactory?: VcsRootInstanceApiRequestFactory, responseProcessor?: VcsRootInstanceApiResponseProcessor) { this.api = new ObservableVcsRootInstanceApi(configuration, requestFactory, responseProcessor); } /** * Remove a field of the matching VCS root instance. * @param param the request object */ public deleteVcsRootInstanceField(param: VcsRootInstanceApiDeleteVcsRootInstanceFieldRequest, options?: Configuration): Promise<void> { return this.api.deleteVcsRootInstanceField(param.vcsRootInstanceLocator, param.field, options).toPromise(); } /** * Delete the last repository state of the matching VCS root instance. * @param param the request object */ public deleteVcsRootInstanceRepositoryState(param: VcsRootInstanceApiDeleteVcsRootInstanceRepositoryStateRequest, options?: Configuration): Promise<void> { return this.api.deleteVcsRootInstanceRepositoryState(param.vcsRootInstanceLocator, options).toPromise(); } /** * Download specific file. * @param param the request object */ public downloadFile(param: VcsRootInstanceApiDownloadFileRequest, options?: Configuration): Promise<void> { return this.api.downloadFile(param.path, param.vcsRootInstanceLocator, options).toPromise(); } /** * Get all VCS root instances. * @param param the request object */ public getAllVcsRootInstances(param: VcsRootInstanceApiGetAllVcsRootInstancesRequest, options?: Configuration): Promise<VcsRootInstances> { return this.api.getAllVcsRootInstances(param.locator, param.fields, options).toPromise(); } /** * Get metadata of specific file. * @param param the request object */ public getFileMetadata(param: VcsRootInstanceApiGetFileMetadataRequest, options?: Configuration): Promise<any> { return this.api.getFileMetadata(param.path, param.vcsRootInstanceLocator, param.fields, options).toPromise(); } /** * List all files. * @param param the request object */ public getFilesList(param: VcsRootInstanceApiGetFilesListRequest, options?: Configuration): Promise<Files> { return this.api.getFilesList(param.vcsRootInstanceLocator, param.basePath, param.locator, param.fields, options).toPromise(); } /** * List files under this path. * @param param the request object */ public getFilesListForSubpath(param: VcsRootInstanceApiGetFilesListForSubpathRequest, options?: Configuration): Promise<Files> { return this.api.getFilesListForSubpath(param.path, param.vcsRootInstanceLocator, param.basePath, param.locator, param.fields, options).toPromise(); } /** * Get VCS root instance matching the locator. * @param param the request object */ public getVcsRootInstance(param: VcsRootInstanceApiGetVcsRootInstanceRequest, options?: Configuration): Promise<VcsRootInstance> { return this.api.getVcsRootInstance(param.vcsRootInstanceLocator, param.fields, options).toPromise(); } /** * Get the creation date of the matching VCS root instance. * @param param the request object */ public getVcsRootInstanceCreationDate(param: VcsRootInstanceApiGetVcsRootInstanceCreationDateRequest, options?: Configuration): Promise<string> { return this.api.getVcsRootInstanceCreationDate(param.vcsRootInstanceLocator, options).toPromise(); } /** * Get a field of the matching VCS root instance. * @param param the request object */ public getVcsRootInstanceField(param: VcsRootInstanceApiGetVcsRootInstanceFieldRequest, options?: Configuration): Promise<string> { return this.api.getVcsRootInstanceField(param.vcsRootInstanceLocator, param.field, options).toPromise(); } /** * Get all properties of the matching VCS root instance. * @param param the request object */ public getVcsRootInstanceProperties(param: VcsRootInstanceApiGetVcsRootInstancePropertiesRequest, options?: Configuration): Promise<Properties> { return this.api.getVcsRootInstanceProperties(param.vcsRootInstanceLocator, param.fields, options).toPromise(); } /** * Get the repository state of the matching VCS root instance. * @param param the request object */ public getVcsRootInstanceRepositoryState(param: VcsRootInstanceApiGetVcsRootInstanceRepositoryStateRequest, options?: Configuration): Promise<Entries> { return this.api.getVcsRootInstanceRepositoryState(param.vcsRootInstanceLocator, param.fields, options).toPromise(); } /** * Get specific file zipped. * @param param the request object */ public getZippedFile(param: VcsRootInstanceApiGetZippedFileRequest, options?: Configuration): Promise<void> { return this.api.getZippedFile(param.path, param.vcsRootInstanceLocator, param.basePath, param.locator, param.name, options).toPromise(); } /** * Check for the pending changes for all VCS root instances. * @param param the request object */ public requestPendingChangesCheck(param: VcsRootInstanceApiRequestPendingChangesCheckRequest, options?: Configuration): Promise<VcsRootInstances> { return this.api.requestPendingChangesCheck(param.locator, param.requestor, param.fields, options).toPromise(); } /** * Get a field of the matching VCS root instance. * @param param the request object */ public setVcsRootInstanceField(param: VcsRootInstanceApiSetVcsRootInstanceFieldRequest, options?: Configuration): Promise<string> { return this.api.setVcsRootInstanceField(param.vcsRootInstanceLocator, param.field, param.body, options).toPromise(); } /** * Update the repository state of the matching VCS root instance. * @param param the request object */ public setVcsRootInstanceRepositoryState(param: VcsRootInstanceApiSetVcsRootInstanceRepositoryStateRequest, options?: Configuration): Promise<Entries> { return this.api.setVcsRootInstanceRepositoryState(param.vcsRootInstanceLocator, param.fields, param.body, options).toPromise(); } /** * Send the commit hook notification. * @param param the request object */ public triggerCommitHookNotification(param: VcsRootInstanceApiTriggerCommitHookNotificationRequest, options?: Configuration): Promise<void> { return this.api.triggerCommitHookNotification(param.locator, param.okOnNothingFound, options).toPromise(); } } <file_sep>/ts-schema/schema/rest-api/deno/models/LicensingData.ts /** * TeamCity REST API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * OpenAPI spec version: 2018.1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { LicenseKeys } from './LicenseKeys.ts'; import { HttpFile } from '../http/http.ts'; export class LicensingData { 'licenseUseExceeded'?: boolean; 'maxAgents'?: number; 'unlimitedAgents'?: boolean; 'agentsLeft'?: number; 'maxBuildTypes'?: number; 'unlimitedBuildTypes'?: boolean; 'buildTypesLeft'?: number; 'serverLicenseType'?: string; 'serverEffectiveReleaseDate'?: string; 'licenseKeys'?: LicenseKeys; static readonly discriminator: string | undefined = undefined; static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [ { "name": "licenseUseExceeded", "baseName": "licenseUseExceeded", "type": "boolean", "format": "" }, { "name": "maxAgents", "baseName": "maxAgents", "type": "number", "format": "int32" }, { "name": "unlimitedAgents", "baseName": "unlimitedAgents", "type": "boolean", "format": "" }, { "name": "agentsLeft", "baseName": "agentsLeft", "type": "number", "format": "int32" }, { "name": "maxBuildTypes", "baseName": "maxBuildTypes", "type": "number", "format": "int32" }, { "name": "unlimitedBuildTypes", "baseName": "unlimitedBuildTypes", "type": "boolean", "format": "" }, { "name": "buildTypesLeft", "baseName": "buildTypesLeft", "type": "number", "format": "int32" }, { "name": "serverLicenseType", "baseName": "serverLicenseType", "type": "string", "format": "" }, { "name": "serverEffectiveReleaseDate", "baseName": "serverEffectiveReleaseDate", "type": "string", "format": "" }, { "name": "licenseKeys", "baseName": "licenseKeys", "type": "LicenseKeys", "format": "" } ]; static getAttributeTypeMap() { return LicensingData.attributeTypeMap; } public constructor() { } } <file_sep>/ts-schema/schema/xml/project_extension.ts import { Parameters } from "./parameter.ts"; export interface ProjectExtensions { extension: ProjectExtension[]; } export interface ProjectExtension { "@id": string; "@type": string; parameters: Parameters; } <file_sep>/ts-schema/schema/json/build_type.ts import { AllXOR } from "../xor.ts"; import { Parameter } from "./parameter.ts"; import { UniqueArray } from "../unique_array.ts"; import { ProjectCleanup } from "./project_cleanup.ts"; import { ProjectExtensionKeepRules } from "./project_extension.ts"; /** * A build configuration is a collection of settings used to start a build and * group the sequence of the builds in the UI. Examples of build configurations * are distribution, integration tests, prepare release distribution, * "nightly" build. * * A build configuration belongs to a project and contains builds. * * It is recommended to have a separate build configuration for each sequence * of builds (that is performing a specified task in a dedicated environment). * This allows for proper features functioning, like detection of new problems/ * failed tests, first failed in/fixed in tests status, automatically removed * investigations, and so on. * * see: https://www.jetbrains.com/help/teamcity/build-configuration.html */ export interface BuildType { /** * This refers to the filename of the generated XML file stored in the * .teamcity folder of your repo & ultimately the server's Data Directory. * see: https://www.jetbrains.com/help/teamcity/teamcity-data-directory.html * * For example an id of `Foo_Bar_Baz` results in the file * `./.teamcity/MyProject/buildTypes/Foo_Bar_Baz.xml` being generated. * * This id is also used as a reference in many places * throughout the rest of this schema & for URLs, etc... * * see: https://www.jetbrains.com/help/teamcity/identifier.html */ id: string; /** * This value is used as an attribute on the root XML object. It only appears * to be used internally by TeamCity. Hence this is optional and will be * generated for you if you do not explicitly define a value. * * see: https://www.jetbrains.com/help/teamcity/identifier.html#Universally+Unique+IDs * * > NOTE: Despite what the docs say, TeamCity does not appear to automatically * > populate the UUID field for you but also doesn't seem to mind that it * > doesn't exist, go figure... */ uuid?: string; /** * A human friendly name for the build type. */ name: string; /** * An optional human friendly description of the built type. */ description?: string; /** * An optional set of options that configure how a Build Configuration works. */ options?: BuildOptions; /** * Build Types can define configuration parameters which are inherited by all BuildRunners. * * see: https://www.jetbrains.com/help/teamcity/configuring-build-parameters.html */ parameters?: Parameter[]; /** * Attach VcsRoot(s) defined at the Project level to a BuildType. * * This will ensure the repositories are checked out before your * first build step runs. * * see: https://www.jetbrains.com/help/teamcity/configuring-vcs-settings.html#Attach+VCS+Root */ vcsSettings?: VcsSettings[]; /** * Agent requirements are used in TeamCity to specify whether a build * configuration can run on a particular build agent besides agent pools * and specified build configuration restrictions. * * When a build agent registers on the TeamCity server, it provides information * about its configuration, including its environment variables, system properties, * and additional settings specified in the buildAgent.properties file. * * The administrator can specify required environment variables and system * properties for a build configuration on the Build Configuration Settings | * Agent Requirements page. * * For instance, if a particular build configuration must run on a build agent * running Windows, the administrator specifies this by adding a requirement * that the `teamcity.agent.jvm.os.name` system property on the build agent * must contain the `Windows` string. * see: https://www.jetbrains.com/help/teamcity/agent-requirements.html */ requirements?: BuildRequirement[]; /** * Once a build configuration is created, builds can be triggered manually by * clicking the Run button or initiated automatically with the help of triggers. * * A build trigger is a rule which initiates a new build on certain events. * The build is put into the build queue and is started when there are agents * available to run it. * * see: https://www.jetbrains.com/help/teamcity/configuring-build-triggers.html */ triggers?: BuildTrigger[]; /** * When creating a build configuration, it is important to configure the * sequence of build steps to be executed. * * Each build step is represented by a build runner and provides integration * with a specific build or test tool. For example, call a NAnt script before * compiling VS solutions. * * You can add as many build steps to your build configuration as needed. * * Build steps are invoked sequentially. * * see: https://www.jetbrains.com/help/teamcity/configuring-build-steps.html */ runners?: BuildRunner[]; /** * Each build can be extended with many plugins and settings. * * All or most of the things that you see in the left hand side bar of a * build configuration page in the user interface of TeamCity, things like * Build Features, Failure Conditions, etc... are all defined as extension * nodes in the XML. * * In this schema the `Extension` type is a base type and there many other * types that better represent all those other things that extend the * `BuildExtension` type which you can use here. */ extensions?: BuildExtension[]; /** * Base Clean Up configuration. * * > HINT: This can be combined with `BuildExtensionKeepRules` to cater * > for more complex needs. * * see: https://www.jetbrains.com/help/teamcity/clean-up.html#Base+Rule */ cleanUp?: BuildCleanup; } export interface BuildOptions { // START: General Settings /** * Builds of a regular build configuration can have build steps * and are executed on agents. * * Builds of a composite build configuration do not run on an agent. * The main purpose of composite build is to aggregate results from * snapshot dependencies in a single place. * * Deployment build configuration publishes / deploys artifacts of * other builds to some environment. * * Defaults to `REGULAR`. * * see: https://www.jetbrains.com/help/teamcity/deployment-build-configuration.html * also: https://www.jetbrains.com/help/teamcity/composite-build-configuration.html */ buildConfigurationType?: "REGULAR" | "DEPLOYMENT" | "COMPOSITE"; /** * A pattern which is resolved and assigned to the build number on the build start. * * The format may include `%build.counter%` as a placeholder for the build * counter value, for example, `1.%build.counter%`. It may also contain a * reference to any other available parameter, eg: `%build.vcs.number.VCSRootName%`. * * > HINT: The maximum length of a build number after all substitutions * > is 256 characters. * * Defaults to `%build.counter%`. * * see: https://www.jetbrains.com/help/teamcity/configuring-general-settings.html#ConfiguringGeneralSettings-BuildNumberFormat */ buildNumberFormat?: string; /** * Select when to publish artifacts: * * - EVEN_FAILURES: publish artifacts at the last step of a build if all * previous steps have been completed, successfully or not. * * - SUCCESSFUL: publish artifacts at the last step of a build if all * previous steps have been completed successfully. TeamCity checks * the current build status on the server before publishing artifacts. * * - ALWAYS: publish artifacts for all builds, even for interrupted ones * (for example, after the stop command was issued or after the time-out, * specified in the build failure conditions). * * This setting does not affect artifacts publishing configured in a build script. * * > HINT: If the stop command is issued during the artifacts publishing, * > the publishing operation will be stopped regardless of the * > selected option. * * see: https://www.jetbrains.com/help/teamcity/configuring-general-settings.html#ConfiguringGeneralSettings-PublishArtifacts */ publishArtifacts?: "EVEN_FAILURES" | "SUCCESSFUL" | "ALWAYS"; /** * Patterns to define artifacts of a build. After the first build is run, * you can browse the agent checkout directory to configure artifacts paths. * * Paths are in the form of `[+:]source [ => target]` to include and * `-:source [ => target]` to exclude files or directories to publish * as build artifacts. * * Ant-style wildcards are supported, e.g. use `**\/* => target_directory`, * `-: ** /folder1 => target_directory` to publish all files except for * folder1 into the target_directory. * * > HINT: `\/` should actually just be `/` in the above example * > but that means this doc block comment breaks. * * see: https://www.jetbrains.com/help/teamcity/configuring-general-settings.html#ConfiguringGeneralSettings-ArtifactPaths */ artifactPaths?: string[]; /** * Select the Enable hanging build detection option to detect probably "hanging" builds. * * A build is considered to be "hanging" if its run time significantly exceeds * the estimated average run time and if the build has not sent any messages * since the estimation was exceeded. * * To properly detect hanging builds, TeamCity has to estimate the average * time builds run based on several builds. Thus, if you have a new build * configuration, it may make sense to enable this feature after a couple * of builds have run, so that TeamCity would have enough information to * estimate the average run time. * * Defaults to `false`. * * see: https://www.jetbrains.com/help/teamcity/configuring-general-settings.html#Hanging+Build+Detection */ enableHangingBuildsDetection?: boolean; /** * To allow personal builds or not. * * A personal build is a build-out of the common build sequence which * typically uses the changes not yet committed into the version control. * * Personal builds are usually initiated from one of the supported IDEs via * the Remote Run procedure. You can also upload a patch with changes directly * to the server... * * Defaults to `false`. * * see: https://www.jetbrains.com/help/teamcity/configuring-general-settings.html#Allow+Triggering+Personal+Builds * also: https://www.jetbrains.com/help/teamcity/personal-build.html */ allowTriggeringPersonalBuilds?: boolean; /** * This option enables retrieving the status and basic details of the last * build in the build configuration without requiring any user authentication. * * Note that this also allows getting the status of any specific build in * the build configuration (however, builds cannot be listed and no other * information except the build status (success/failure/internal error/ * cancelled) is available). * * The status can be retrieved via the HTML status widget described below, * or via a single icon: with the help of REST API or via the Actions menu * in Build Configuration Home. * * Defaults to `true`; * see: https://www.jetbrains.com/help/teamcity/configuring-general-settings.html#ConfiguringGeneralSettings-EnableStatusWidget */ enableStatusWidget?: boolean; /** * Limit Number of Simultaneously Running Builds * * Specify the number of builds of the same configuration that can run * simultaneously on all agents. This option helps avoid the situation, * when all the agents are busy with the builds of a single project. * * > HINT: Enter 0 to allow an unlimited number of builds to run simultaneously. * * Defaults to `0`. * * see: https://www.jetbrains.com/help/teamcity/configuring-general-settings.html#Limit+Number+of+Simultaneously+Running+Builds */ maximumNumberOfBuilds?: number; // END: General Settings // START: Version Control Settings /** * The VCS Checkout mode is a setting that affects how project sources reach * an agent. This mode affects only sources checkout. The current revision * and changes data retrieving logic is executed by the TeamCity server, * and thus TeamCity server needs to access the VCS server in any mode. * * - **MANUAL**: TeamCity will not check out any sources automatically, * the default build checkout directory will still be created so that * you could use it to check out the sources via a build script. * * Note that TeamCity will accurately report changes only if the checkout * is performed on the revision specified by the `build.vcs.number.*` * properties passed into the build. * * The build checkout directory will not be cleaned automatically, * unless the directory expiration period is configured. * * - **ON_SERVER**: The TeamCity server will export the sources and pass * them to an agent before each build. * * Since the sources are exported rather than checked out, no administrative * data is stored in the agent's file system and version control operations * (like check-in, label or update) cannot be performed from the agent. * * TeamCity optimizes communications with the VCS servers by caching the * sources and retrieving from the VCS server only the necessary changes. * * Unless clean checkout is performed, the server sends to the agent * incremental patches to update only the files changed since the last * build on the agent in the given checkout directory. * * - **ON_AGENT**: The build agent will check out the sources before the build. * * Agent-side checkout frees more server resources and provides the ability * to access version-control-specific directories (.svn, CVS, .git ); that is, * the build script can perform VCS operations (for example, check-ins into * the version control) — in this case ensure the build script uses * credentials necessary for the check-in. * * VCS client software has to be installed on the agent * (applicable to Perforce, Mercurial, Git). * * - **PREFER_ON_AGENT**: With this setting enabled, TeamCity will use the * agent-side checkout (see `ON_AGENT`) if possible. * * If the agent-side checkout is not possible, TeamCity will display a * corresponding health report item and will use the server-side checkout * (see the `ON_SERVER`). * * TeamCity falls back to the server-side checkout in the following cases: * - No Git or Mercurial client is found on the agent * - The Git or Mercurial client is present on the agent, but is of the wrong version * - The agent has no access to the repository * - If a Perforce client cannot be found on the agent using the same rules * as while performing actual checkout or if stream depot is used and the * checkout rules are complex (other than `. => A`) * * Defaults to `ON_AGENT`. * * see: https://www.jetbrains.com/help/teamcity/vcs-checkout-mode.html */ checkoutMode?: "MANUAL" | "ON_SERVER" | "ON_AGENT" | "PREFER_ON_AGENT"; /** * The build checkout directory is a directory on the TeamCity agent machine * where all the sources of all builds are checked out into. * * > HINT: It is strongly advised to leave this value undefined and * > let TeamCity automatically generate this for you. * * see: https://www.jetbrains.com/help/teamcity/build-checkout-directory.html */ checkoutDirectory?: string; /** * Delete all files in the checkout directory before the build. * * Defaults to `true`. */ cleanBuild?: boolean; /** * Show changes from snapshot dependencies. * * For a build configuration with snapshot dependencies, you can enable * showing of changes from these dependencies transitively. * * Enabling this setting affects pending changes of a build configuration, * builds changes in builds history, the change log and issue log. * Changes from dependencies are marked with deps_changes_marker.gif. * * With this setting enabled, the Schedule Trigger with a "Trigger build * only if there are pending changes" option will consider changes from * dependencies too. * * Defaults to `false`. * * see: https://www.jetbrains.com/help/teamcity/build-dependencies-setup.html#BuildDependenciesSetup-ShowChangesfromDeps */ showDependenciesChanges?: boolean; /** * Exclude default branch changes from other branches. * * By default, when displaying pending changes in a feature branch or * changes of a build on a branch, TeamCity includes changes in the * default branch (till a build in the default branch) as well. * * This allows tracking the cases when a commit that broke a build was * fixed in the default branch, but not in a feature branch. * * However, for large projects with multiple teams simultaneously working * on lots of different branches this means that all the project committers * (regardless of the branch they are committing to) will be notified when, * for example, a commit in the default branch broke the build or if a force * push was performed. * * If you want to see the changes in a feature branch only, check the box * to exclude changes in the default branch from being displayed in other * branches. * * Defaults to `false`. * * see: https://www.jetbrains.com/help/teamcity/configuring-vcs-settings.html#ConfiguringVCSSettings-excludeDefaultBranch */ excludeDefaultBranchChanges?: boolean; /** * Limit branches available in this build configuration. * * see: https://www.jetbrains.com/help/teamcity/branch-filter.html */ branchFilter?: string[]; // END: Version Control Settings // START: Failure Conditions /** * Fail build if it runs longer than the specified limit in minutes. * * > HINT: 0 means unlimited * * Defaults to `0`. * * see: https://www.jetbrains.com/help/teamcity/build-failure-conditions.html */ executionTimeoutMin?: number; /** * One of build steps exited with an error. * e.g non-zero exit code in command line runner. * * Defaults to `true`. * * see: https://www.jetbrains.com/help/teamcity/build-failure-conditions.html */ shouldFailBuildOnBadExitCode?: boolean; /** * At least one test failed. * * Defaults to `true`. * * see: https://www.jetbrains.com/help/teamcity/build-failure-conditions.html */ shouldFailBuildIfTestsFailed?: boolean; /** * Support test retry: successful test run mutes previous test failure. * * Default to `false`. * * see: https://www.jetbrains.com/help/teamcity/build-failure-conditions.html#test-retry */ supportTestRetry?: boolean; /** * An error message is logged by build runner. * * > HINT: Some processes use stderr to output things like progress * > information and other information which may not necessarily * > mean the process failed. * * Defaults to `false`. * * see: https://www.jetbrains.com/help/teamcity/build-failure-conditions.html */ shouldFailBuildOnAnyErrorMessage?: boolean; /** * An out-of-memory or crash is detected (Java only). * * see: https://www.jetbrains.com/help/teamcity/build-failure-conditions.html */ shouldFailBuildOnJavaCrash: boolean; // END: Failure Conditions } export interface VcsSettings { /** * The ID of the VcsRoot to attach. */ vcsRootId: string; /** * A list of rules in the form of `+|-:VCSPath[=>AgentPath]` * * e.g. use `-:.` to exclude all, or `-:repository/path` to exclude only * the path from checkout or `+:repository/path => another/path` to map * to different path. * * > HINT: Checkout rules can only be set to directories, * > files are not supported. * * see: https://www.jetbrains.com/help/teamcity/vcs-checkout-rules.html */ checkOutRules?: string[]; } export type BuildRequirement = | BuildRequirementWithValue | BuildRequirementWithoutValue; export interface BuildRequirementBase { /** * This ID is not exposed in UI and is just an incrementing number. * * eg: `RQ_1`, `RQ_2`, `RQ_3`, etc... * * So if not set it will be set for you. */ id?: string; /** * The name of some parameter to match against. * * eg: `teamcity.agent.jvm.os.name` * * > HINT: The left hand side of the expression. */ name: string; } export interface BuildRequirementWithValue extends BuildRequirementBase { /** * A logical condition to apply to the parameter. */ condition: | "equals" | "does-not-equal" | "more-than" | "no-more-than" | "less-than" | "no-less-than" | "starts-with" | "contains" | "does-not-contain" | "ends-with" | "matches" | "does-not-match" | "ver-more-than" | "ver-no-more-than" | "ver-less-than" | "ver-no-less-than"; /** * The expected value for this build requirement to evaluate to true. * * > HINT: The right hand side of the expression. */ value?: string; } export interface BuildRequirementWithoutValue extends BuildRequirementBase { /** * A logical condition to apply to the parameter. */ condition: | "exists" | "not-exists"; } export type BuildTrigger = | BuildTriggerVcs | BuildTriggerCron | BuildTriggerDependency | BuildTriggerRemoteBranch | BuildTriggerRetry | BuildTriggerNuget | BuildTriggerMavenArtifact | BuildTriggerMavenSnapshot; export interface BuildTriggerBase { /** * This ID is not exposed in UI and is just an incrementing number. * * eg: `TRIGGER_1`, `TRIGGER_2`, `TRIGGER_3`, etc... * * So if not set it will be set for you. */ id?: string; } export interface BuildTriggerVcs extends BuildTriggerBase { /** * VCS triggers automatically start a new build each time TeamCity detects * new changes in the configured VCS roots and displays the change in the * pending changes. * * Multiple VCS triggers can be added to a build configuration. * * see: https://www.jetbrains.com/help/teamcity/configuring-vcs-triggers.html */ type: "vcsTrigger"; /** * If you have a build chain (that is a number of builds interconnected by * snapshot dependencies), the triggers are to be configured in the final * build in the chain. * * The VCS build trigger has another option that alters triggering behavior * for a build chain. With this options enabled, the whole build chain will * be triggered even if changes are detected in dependencies, not in the * final build. * * Defaults to `false`. * * see: https://www.jetbrains.com/help/teamcity/configuring-vcs-triggers.html#ConfiguringVCSTriggers-Triggerabuildonchangesinsnapshotdependencies */ watchChangesInDependencies?: boolean; /** * Trigger a build on each check-in. * * When this option is not enabled, several check-ins by different committers * can be made; and once they are detected, TeamCity will add only one build * to the queue with all of these changes. * * If you have fast builds and enough build agents, you can make TeamCity * launch a new build for each check-in ensuring that no other changes get * into the same build. * * Defaults to `false`. * * see: https://www.jetbrains.com/help/teamcity/configuring-vcs-triggers.html#Per-check-in+Triggering */ perCheckinTriggering?: boolean | { /** * Include several check-ins in a build if they are from the same committer. * * If enabled, TeamCity will detect a number of pending changes, * it will group them by user and start builds having single user * changes only. * * This helps to figure out whose change broke a build or caused a new test * failure, should such issue arise. * * Defaults to `false`. * * see: https://www.jetbrains.com/help/teamcity/configuring-vcs-triggers.html#Per-check-in+Triggering */ groupCheckinsByCommitter: boolean; }; /** * By specifying the quiet period you can ensure the build is not triggered * in the middle of non-atomic check-ins consisting of several VCS check-ins. * * A quiet period is a period (in seconds) that TeamCity maintains between * the moment the last VCS change is detected and a build is added into the * queue. * * If new VCS change is detected in the Build Configuration within the period, * the period starts over from the new change detection time. The build is * added into the queue only if there were no new VCS changes detected within * the quiet period. * * Note that the actual quiet period will not be less than the maximum checking * for changes interval among the VCS roots of a build configuration, as TeamCity * must ensure that changes were collected at least once during the quiet period. * * The quiet period can be set to the default value (60 seconds, can be changed * globally at the Administration | Global Settings page) or to a custom value * for a build configuration. * * > HINT: When a build is triggered by a trigger with the VCS quiet period set, * > the build is put into the queue with fixed VCS revisions. This ensures the * > build will be started with only the specific changes included. Under certain * > circumstances this build can later become a History Build. * Defaults to `DO_NOT_USE`. * * see: https://www.jetbrains.com/help/teamcity/configuring-vcs-triggers.html#ConfiguringVCSTriggers-quietPeriod */ quietPeriod?: "DO_NOT_USE" | "USE_DEFAULT" | number; /** * Queued build can be replaced with a more recent build. * * Defaults to `true`. * * see: https://www.jetbrains.com/help/teamcity/configuring-vcs-triggers.html#Build+Queue+Optimization+Settings */ enableQueueOptimization?: boolean; /** * If no trigger rules are specified, a build is triggered upon any change * detected for the build configuration. You can control what changes are * detected by changing the VCS root settings and specifying Checkout Rules. * * To limit the changes that trigger the build, use the VCS trigger rules. * * see: https://www.jetbrains.com/help/teamcity/configuring-vcs-triggers.html#ConfiguringVCSTriggers-buildTriggerRules */ triggerRules?: string[]; /** * Limit the set of branches in which builds can be triggered by this VCS trigger. * * Trigger rules and branch filter are combined by **AND**, which means that * the build is triggered only when both conditions are satisfied. * * For example, if you specify a comment text in the trigger rules field and * provide the branch specification, the build will be triggered only if a * commit has the special text and is also in a branch matched by branch filter. * * see: https://www.jetbrains.com/help/teamcity/configuring-vcs-triggers.html#branch-filter-1 */ branchFilter?: string[]; } export interface BuildTriggerCron extends BuildTriggerBase { /** * The schedule trigger allows you to set the time when a build of the * configuration will be run. Multiple schedule triggers can be added to * a build configuration. * * see: https://www.jetbrains.com/help/teamcity/configuring-schedule-triggers.html */ type: "schedulingTrigger"; /** * You can specify advanced time settings using cron -like expressions. * This format provides more flexible scheduling options. * * TeamCity uses Quartz for working with cron expressions. * See these examples or consider using the CronMaker utility * to generate expressions based on the Quartz cron format. * * see: https://www.jetbrains.com/help/teamcity/cron-expressions-in-teamcity.html#Examples * also: https://www.quartz-scheduler.org/documentation/quartz-2.3.0/tutorials/tutorial-lesson-06.html * also: http://www.cronmaker.com */ cronExpression: { second: string; minute: string; hour: string; dayOfMonth: string; month: string; dayOfWeek: string; year?: string; }; /** * A valid IANA time zone database "name". * * eg: `Australia/Melbourne` * * Defaults to `Etc/UTC`. * * see: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones */ timezone?: string; /** * Trigger only if there are pending changes. * * Defaults to `false`. */ triggerBuildWithPendingChangesOnly?: boolean; /** * If no trigger rules are specified, a build is triggered upon any change * detected for the build configuration. You can control what changes are * detected by changing the VCS root settings and specifying Checkout Rules. * * To limit the changes that trigger the build, use the VCS trigger rules. * * see: https://www.jetbrains.com/help/teamcity/configuring-vcs-triggers.html#ConfiguringVCSTriggers-buildTriggerRules */ triggerRules?: string[]; /** * Trigger only if the watched build changes. * * see: https://www.jetbrains.com/help/teamcity/configuring-schedule-triggers.html#ConfiguringScheduleTriggers-BuildChanges */ watchBuild?: { /** * The ID of the BuildType to watch for changes. */ buildTypeId: string; /** * Promote the watched build if there is a dependency (snapshot or artifact) * on its build configuration. * * Defaults to `true`. */ promoteBuild?: boolean; /** * You can select which build to watch: * - Last finished build * - Last successful build * - Last pinned build * - Last finished build with a specified build tag. */ for: "lastFinished" | "lastSuccessful" | "lastPinned" | "buildTag"; /** * The tag to watch for. * * > HINT: If `for=buildTag` this must be set to a value. */ tag?: string; }; /** * Delete all files in the checkout directory before the build. * * Defaults to `false`. */ enforceCleanCheckout?: boolean | { /** * Also apply to all snapshot dependencies? */ forDependencies: boolean; }; /** * Trigger build on all enabled and compatible agents. * * Defaults to `false`. */ triggerBuildOnAllCompatibleAgents?: boolean; /** * Queued build can be replaced with an already started build * or a more recent queued build. * * Defaults to `true`. */ enableQueueOptimization?: boolean; /** * By default, a schedule trigger works for all branches. * * see: https://www.jetbrains.com/help/teamcity/configuring-schedule-triggers.html#Branch+Filter */ branchFilter?: string[]; } export interface BuildTriggerDependency extends BuildTriggerBase { /** * The finish build trigger starts a build of the current build configuration * when a build of the selected build configuration is finished. * * see: https://www.jetbrains.com/help/teamcity/configuring-finish-build-trigger.html */ type: "buildDependencyTrigger"; /** * The ID of the BuildType that will fire this trigger when it finishes. */ buildTypeId: string; /** * Trigger after successful build only. * * Defaults to `false`. */ afterSuccessfulBuildOnly?: boolean; /** * In a build configuration with branches, you can use the branch filter to * limit the branches in which finished builds will trigger new builds of * the current configuration. * * Defaults to `+:<default>`. * * see: https://www.jetbrains.com/help/teamcity/configuring-finish-build-trigger.html#Triggering+Settings */ branchFilter?: string[]; } export interface BuildTriggerRemoteBranch extends BuildTriggerBase { /** * The branch remote run trigger automatically starts a new personal build * each time TeamCity detects changes in particular branches of the VCS roots * of the build configuration. * * Finished personal builds are listed in the build history, but only for the * users who initiated them. * * > HINT: At the moment, the branch remote run trigger supports only Git * > and Mercurial VCSs. * * see: https://www.jetbrains.com/help/teamcity/branch-remote-run-trigger.html */ type: "remoteRunOnBranch"; /** * Pattern of Branches to Monitor. * * For git: * - Defaults to `refs/heads/remote-run/*`. * * For mercurial : * - Defaults to `remote-run/*`. */ pattern?: string; } export interface BuildTriggerRetry extends BuildTriggerBase { /** * The retry build trigger automatically adds a new build to the queue if the * previous build of the current build configuration has failed. * * see: https://www.jetbrains.com/help/teamcity/configuring-retry-build-trigger.html */ type: "retryBuildTrigger"; /** * Specify seconds to wait before adding a new build to the queue. */ enqueueTimeout: number; /** * Specify how many times the trigger will try to rerun the failing build. * * > HINT: Leave undefined for unlimited number of retry attempts. */ retryAttempts?: number; /** * With this option enabled, the retry trigger will rerun a failed build * using the same source revisions. * * This option helps identify build problems that do not depend on the build * code: for example, if there are flaky tests in the build configuration or * if there was some unforeseen agent compatibility issue. * * If the build with the trigger is a part of a build chain, all the successful * builds from the previous chain run will be reused and all the failed dependency * builds, that could have contributed to the failure of the dependent build, * will be rebuilt on the same revision. * * If any build parameters or comments are specified in the custom build settings, * they will be applied to the following build runs initiated by the retry trigger. * * Defaults to `true`. */ useSameRevisions?: boolean; /** * With this option enabled, retried builds will always be put to the queue top. * * Defaults to `false`. */ moveToTheQueueTop?: boolean; /** * Apply a branch filter to rerun failed builds only in branches that match * the specified criteria. * * Defaults to `+:*`. */ branchFilter?: string[]; } export interface BuildTriggerNuget extends BuildTriggerBase { /** * The NuGet dependency trigger allows starting a new build if a NuGet * packages update is detected in the NuGet repository. * * > HINT: Currently, the NuGet dependency trigger supports only API versions * > 1 and 2 due to specifics of the Nuget.CommandLine tool. * * see: https://www.jetbrains.com/help/teamcity/nuget-dependency-trigger.html */ type: "nuget.simple"; /** * The path to the nuget executable. * * > HINT: If left undefined then we assume it will be found on the `$PATH`. */ nugetExe?: string; /** * Specify the NuGet packages feed URL to monitor packages changes. * * Defaults to `https://api.nuget.org/v3/index.json`. */ source?: string; /** * Specify username to access NuGet feed, leave undefined if no authentication * is required. */ username?: string; /** * Specify password to access NuGet feed, leave undefined if no authentication * is required. */ password?: string; /** * Specify package Id to check for updates. */ packageId: string; /** * Optionally, you can specify package version range to check for. * If not specified, TeamCity will check for latest version. * * > HINT: Supported only for TeamCity server is running under Windows with * > Microsoft .NET Framework 4.0/4.5 installed. * * TODO: As per above note, I have not been able to model this into the XML * layer as I have been running TeamCity with docker. * * see: https://docs.microsoft.com/en-us/nuget/concepts/package-versioning */ //packageVersionSpec?: string; /** * Trigger build if pre-release package version is detected. * * Defaults to `false`. */ triggerOnPreRelease?: boolean; } export interface BuildTriggerMavenArtifact extends BuildTriggerBase { /** * Maven artifact dependency trigger adds build to the queue when there is a * real modification of the dependency content which is detected by the * checksum change. * * see: https://www.jetbrains.com/help/teamcity/configuring-maven-triggers.html#Maven+Artifact+Dependency+Trigger */ type: "mavenArtifactDependencyTrigger"; /** * Specify an identifier of a group the desired Maven artifact belongs to. * * see: https://www.jetbrains.com/help/teamcity/configuring-maven-triggers.html#Maven+Artifact+Dependency+Trigger */ groupId: string; /** * Specify the artifact's identifier. * * see: https://www.jetbrains.com/help/teamcity/configuring-maven-triggers.html#Maven+Artifact+Dependency+Trigger */ artifactId: string; /** * Specify a version or version range of the artifact. * * The version range syntax is described here: * https://www.jetbrains.com/help/teamcity/configuring-maven-triggers.html#Version+Ranges * * > HINT: SNAPSHOT versions can also be used. * * see: https://www.jetbrains.com/help/teamcity/configuring-maven-triggers.html#Maven+Artifact+Dependency+Trigger */ version: string; /** * Define explicitly the type of the specified artifact. * * Defaults to `jar`. * * see: https://www.jetbrains.com/help/teamcity/configuring-maven-triggers.html#Maven+Artifact+Dependency+Trigger */ artifactType?: string; /** * (Optional) Specify the classifier of an artifact. * * see: https://www.jetbrains.com/help/teamcity/configuring-maven-triggers.html#Maven+Artifact+Dependency+Trigger */ classifier?: string; /** * Specify a URL to the Maven repository. Note that this parameter is optional. * * If the URL is not specified, then: * * - For a Maven project, the repository URL is determined from the POM and * the server-side Maven Settings. * * - For a non-Maven project, the repository URL is determined from the * server-side Maven Settings only. * * see: https://www.jetbrains.com/help/teamcity/configuring-maven-triggers.html#Maven+Artifact+Dependency+Trigger */ repoUrl?: string; /** * Allows using authorization from the effective Maven settings. * * see: https://www.jetbrains.com/help/teamcity/configuring-maven-triggers.html#Advanced+Options */ repoId?: string; /** * Allows selecting effective settings. The same as User Settings of the Maven runner. * * > HINT: If left undefined the standard Maven settings file location is used. * * see: https://www.jetbrains.com/help/teamcity/configuring-maven-triggers.html#Advanced+Options */ userSettingsPath?: string; /** * Select this option to trigger a build only after the build that produces * artifacts used here is finished. * * Defaults to `false`. * * see: https://www.jetbrains.com/help/teamcity/configuring-maven-triggers.html#Maven+Artifact+Dependency+Trigger */ skipIfRunning?: boolean; } export interface BuildTriggerMavenSnapshot extends BuildTriggerBase { /** * Maven snapshot dependency trigger adds a new build to the queue when there * is a real modification of the snapshot dependency content in the remote * repository which is detected by the checksum change. * * Dependency artifacts are resolved according to the POM and the server-side * Maven Settings. * * Since Maven deploys artifacts to remote repositories sequentially during a * build, not all artifacts may be up-to-date at the moment the snapshot * dependency trigger detects the first updated artifact. * * To avoid inconsistency, select the Do not trigger a build if currently * running builds can produce snapshot dependencies check box when adding * this trigger, which will ensure the build won't start while builds producing * snapshot dependencies are still running. * * Simultaneous usage of snapshot dependency and dependency trigger for a build * Assume build A depends on build B by both snapshot and trigger dependency. * Then, after the build B finishes, build A will be added into the queue, * only if build B is not a part of the build chain containing A. * * see: https://www.jetbrains.com/help/teamcity/configuring-maven-triggers.html#Maven+Snapshot+Dependency+Trigger */ type: "mavenSnapshotDependencyTrigger"; /** * Select this option to trigger a build only after the build that produces * artifacts used here is finished. * * Defaults to `false`. * * see: https://www.jetbrains.com/help/teamcity/configuring-maven-triggers.html#Maven+Artifact+Dependency+Trigger */ skipIfRunning?: boolean; } export type BuildRunner = | BuildRunnerCargo | BuildRunnerCommandLine | BuildRunnerDockerCommand | BuildRunnerDockerCompose | BuildRunnerDotnet | BuildRunnerDotnetDupfinder | BuildRunnerDotnetInspector | BuildRunnerDuplicator | BuildRunnerFtp | BuildRunnerFxCop | BuildRunnerGradle | BuildRunnerInspection | BuildRunnerJPS | BuildRunnerMaven2 | BuildRunnerMspec | BuildRunnerNAnt | BuildRunnerNugetInstaller | BuildRunnerNugetPack | BuildRunnerNugetPublish | BuildRunnerNUnit | BuildRunnerPowershell | BuildRunnerPython | BuildRunnerRake | BuildRunnerSBT | BuildRunnerSmb | BuildRunnerSsh | BuildRunnerSshUpload | BuildRunnerXcode; export interface BuildRunnerBase { /** * This ID is not exposed in UI and is just an incrementing number. * * eg: `RUNNER_1`, `RUNNER_2`, `RUNNER_3`, etc... * * So if not set it will be set for you. */ id?: string; /** * A human friendly name for the runner. */ name: string; /** * Determine if a build step should run based on the results of previous steps. * * - **default:** If all previous steps finished successfully: the build * analyzes only the build step status on the build agent, and doesn't * send a request to the server to check the build status and considers * only important step failures. * * - **execute_if_success:** Only if build status is successful: before * starting the step, the build agent requests the build status from the * server, and skips the step if the status is failed. This considers the * failure conditions processed by the server, like failure on test failures * or on metric change. * * Note that this still can be not exact as some failure conditions are * processed on the server asynchronously (TW-17015) * * - **execute_if_failed:** Even if some of the previous steps failed: select * to make TeamCity execute this step regardless of the status of previous * steps and status of the build. * * - **execute_always:** Always, even if build stop command was issued: select * to ensure this step is always executed, even if the build was canceled by * a user. For example, if you have two steps with this option configured, * stopping the build during the first step execution will interrupt this * step, while the second step will still run. Issuing the stop command for * the second time will result in ignoring the execution policy: the build * will be terminated. * * Defaults to `default`. * * see: https://www.jetbrains.com/help/teamcity/configuring-build-steps.html#Execution+policy */ executionPolicy?: | "default" | "execute_if_success" | "execute_if_failed" | "execute_always"; /** * When configuring a build step, you can choose a general execution policy * and, since TeamCity 2020.1, add a parameter-based execution condition. * * Execution conditions make builds more flexible and address many common use * cases, such as: * * - running the step only in the default branch * - running the step only in the release branch * - skipping the step in personal builds * * see: https://www.jetbrains.com/help/teamcity/build-step-execution-conditions.html */ conditions?: BuildCondition[]; } export type BuildRunnerCommandLine = & BuildRunnerBase & { /** * Using the Command Line build runner, you can run any script * supported by the OS. * * see: https://www.jetbrains.com/help/teamcity/command-line.html */ type: "simpleRunner"; /** * Specify the working directory where the command is to be run * (if it differs from the build checkout directory). */ cwd?: string; /** * Specify how the error output is handled by the runner: * * - `true`: any output to stderr is handled as an error * - `false`: any output to stderr is handled as a warning * * Defaults to `false`. */ fmtStdErrAsErrors?: boolean; /** * In this section, you can specify a Docker image which will be used * to run this build step. * * see: https://www.jetbrains.com/help/teamcity/docker-wrapper.html */ runInContainer?: { /** * The image to run the command inside of. */ image: string; /** * Docker now supports Linux & Windows contains natively. * What type of container is it? * * Defaults to `linux`. */ platform?: "linux" | "windows"; /** * If enabled, the image will be pulled from the repository via * `docker pull <imageName>` before the `docker run` command is launched. */ pull?: boolean; /** * Allows specifying additional options for the docker run command. * * The default argument is `--rm`, but you can provide more, for instance, * add an additional volume mapping. * * > HINT: In this field, you cannot reference environment variables using * > the `%env.FOO_BAR%` syntax because TeamCity does not pass environment * > variables from a build agent into a Docker container. If you need to * > reference an environment variable on an agent, define the configuration * > parameter `system.FOO_BAR=env_var_value` in `buildAgent.properties` * > and reference it via `%system.FOO_BAR%`. */ args?: string[]; }; } & AllXOR<[{ /** * Specify the path to an executable to be started. */ cmd: string; /** * A list of command line arguments to pass to the executable. */ args?: string[]; }, { /** * A platform-specific script which will be executed as an executable script * in Unix-like environments and as a *.cmd batch file on Windows. * * Under Unix-like OS the script is saved with the executable bit set and is * then executed by OS. This defaults to /bin/sh interpreter on the most * systems. * * If you need a specific interpreter to be used, specify shebang * (for example, #!/bin/bash) as the first line of the script. * * > HINT: TeamCity treats a string surrounded by percentage signs `%` in * > the script as a parameter reference. To prevent TeamCity from treating * > the text in the percentage signs as a property reference, use double * > percentage signs to escape them: for example, if you want to pass * > `%Y%m%d%H%M%S` into the build, change it to `%%Y%%m%%d%%H%%M%%S`. */ script: string; }]>; /** TODO: placeholder for dotnet build runner */ export interface BuildRunnerDotnet extends BuildRunnerBase { type: "dotnet"; } /** TODO: placeholder for Ant build runner */ export interface BuildRunnerAnt extends BuildRunnerBase { type: "Ant"; } /** TODO: placeholder for cargo-deploy-runner build runner */ export interface BuildRunnerCargo extends BuildRunnerBase { type: "cargo-deploy-runner"; } /** TODO: placeholder for DockerCommand build runner */ export interface BuildRunnerDockerCommand extends BuildRunnerBase { type: "DockerCommand"; } /** TODO: placeholder for DockerCompose build runner */ export interface BuildRunnerDockerCompose extends BuildRunnerBase { type: "DockerCompose"; } /** TODO: placeholder for Duplicator build runner */ export interface BuildRunnerDuplicator extends BuildRunnerBase { type: "Duplicator"; } /** TODO: placeholder for dotnet-tools-dupfinder build runner */ export interface BuildRunnerDotnetDupfinder extends BuildRunnerBase { type: "dotnet-tools-dupfinder"; } /** TODO: placeholder for ftp-deploy-runner build runner */ export interface BuildRunnerFtp extends BuildRunnerBase { type: "ftp-deploy-runner"; } /** TODO: placeholder for FxCop build runner */ export interface BuildRunnerFxCop extends BuildRunnerBase { type: "FxCop"; } /** TODO: placeholder for gradle-runner build runner */ export interface BuildRunnerGradle extends BuildRunnerBase { type: "gradle-runner"; } /** TODO: placeholder for Inspection build runner */ export interface BuildRunnerInspection extends BuildRunnerBase { type: "Inspection"; } /** TODO: placeholder for dotnet-tools-inspectcode build runner */ export interface BuildRunnerDotnetInspector extends BuildRunnerBase { type: "dotnet-tools-inspectcode"; } /** TODO: placeholder for JPS build runner */ export interface BuildRunnerJPS extends BuildRunnerBase { type: "JPS"; } /** TODO: placeholder for Maven2 build runner */ export interface BuildRunnerMaven2 extends BuildRunnerBase { type: "Maven2"; } /** TODO: placeholder for jetbrains.mspec build runner */ export interface BuildRunnerMspec extends BuildRunnerBase { type: "jetbrains.mspec"; } /** TODO: placeholder for NAnt build runner */ export interface BuildRunnerNAnt extends BuildRunnerBase { type: "NAnt"; } /** TODO: placeholder for jb.nuget.installer build runner */ export interface BuildRunnerNugetInstaller extends BuildRunnerBase { type: "jb.nuget.installer"; } /** TODO: placeholder for jb.nuget.pack build runner */ export interface BuildRunnerNugetPack extends BuildRunnerBase { type: "jb.nuget.pack"; } /** TODO: placeholder for jb.nuget.publish build runner */ export interface BuildRunnerNugetPublish extends BuildRunnerBase { type: "jb.nuget.publish"; } /** TODO: placeholder for NUnit build runner */ export interface BuildRunnerNUnit extends BuildRunnerBase { type: "NUnit"; } /** TODO: placeholder for jetbrains_powershell build runner */ export interface BuildRunnerPowershell extends BuildRunnerBase { type: "jetbrains_powershell"; } /** TODO: placeholder for python-runner build runner */ export interface BuildRunnerPython extends BuildRunnerBase { type: "python-runner"; } /** TODO: placeholder for rake-runner build runner */ export interface BuildRunnerRake extends BuildRunnerBase { type: "rake-runner"; } /** TODO: placeholder for SBT build runner */ export interface BuildRunnerSBT extends BuildRunnerBase { type: "SBT"; } /** TODO: placeholder for smb-deploy-runner build runner */ export interface BuildRunnerSmb extends BuildRunnerBase { type: "smb-deploy-runner"; } /** TODO: placeholder for ssh-exec-runner build runner */ export interface BuildRunnerSsh extends BuildRunnerBase { type: "ssh-exec-runner"; } /** TODO: placeholder for ssh-deploy-runner build runner */ export interface BuildRunnerSshUpload extends BuildRunnerBase { type: "ssh-deploy-runner"; } /** TODO: placeholder for Xcode build runner */ export interface BuildRunnerXcode extends BuildRunnerBase { type: "Xcode"; } export type BuildCondition = | BuildConditionWithValue | BuildConditionWithoutValue; export interface BuildConditionBase { /** * The name of some parameter to match against. * * eg: `teamcity.agent.jvm.os.name` * * > HINT: The left hand side of the expression. */ name: string; } export interface BuildConditionWithValue extends BuildConditionBase { /** * A logical condition to apply to the parameter. */ condition: | "equals" | "does-not-equal" | "more-than" | "no-more-than" | "less-than" | "no-less-than" | "starts-with" | "contains" | "does-not-contain" | "ends-with" | "matches" | "does-not-match" | "ver-more-than" | "ver-no-more-than" | "ver-less-than" | "ver-no-less-than"; /** * The expected value for this build requirement to evaluate to true. * * > HINT: The right hand side of the expression. */ value?: string; } export interface BuildConditionWithoutValue extends BuildConditionBase { /** * A logical condition to apply to the parameter. */ condition: | "exists" | "not-exists"; } export type BuildExtension = | BuildExtensionAgentFreeSpace | BuildExtensionAssemblyInfo | BuildExtensionAutoMergeFeature | BuildExtensionCommitStatusPublisher | BuildExtensionDockerSupport | BuildExtensionFailureOnMessage | BuildExtensionFailureOnMetric | BuildExtensionFileContentReplacer | BuildExtensionGolang | BuildExtensionInvestigationsAutoAssigner | BuildExtensionJiraCloud | BuildExtensionNotifications | BuildExtensionNugetAuth | BuildExtensionNuGetPackagesIndexer | BuildExtensionPerfmon | BuildExtensionPullRequests | BuildExtensionRubyEnvConfigurator | BuildExtensionSharedResources | BuildExtensionSshAgent | BuildExtensionSwabra | BuildExtensionVcsLabeling | BuildExtensionXmlReportPlugin | ProjectExtensionKeepRules; export interface BuildExtensionBase { /** * This ID is not exposed in UI and is just an incrementing number. * * eg: `BUILD_EXT_1`, `BUILD_EXT_2`, `BUILD_EXT_3`, etc... * * So if not set it will be set for you. */ id?: string; } export interface BuildExtensionAgentFreeSpace extends BuildExtensionBase { /** * The Free disk space build feature allows ensuring certain free disk space * on the agent before the build by deleting files managed by the TeamCity * agent (other build's checkout directories and various caches). * * When the feature is not configured, the default free space for a * build is 3 GB. * * see: https://www.jetbrains.com/help/teamcity/free-disk-space.html */ type: "jetbrains.agent.free.space"; /** * You can specify a custom free disk space value here (in bytes or using one * of the kb, mb, gb or tb suffixes). */ requiredSpace?: string; /** * Fail build if sufficient disk space cannot be freed. * * Defaults to `true`. */ failBuild?: boolean; } export interface BuildExtensionAssemblyInfo extends BuildExtensionBase { /** * The AssemblyInfo Patcher build feature allows setting a build number to an * assembly automatically, without having to patch the `AssemblyInfo.cs` files * manually. * * When adding this build feature, you only need to specify the version format. * * You can use TeamCity parameter references. * * see: https://www.jetbrains.com/help/teamcity/assemblyinfo-patcher.html */ type: "JetBrains.AssemblyInfo"; /** * Specify assembly version format to update `AssemblyVersion` attribute. * * Defaults to `%system.build.number%`. */ versionFormat?: string; /** * Specify assembly file version format to update `AssemblyFileVersion` attribute. * Leave blank to use same version as specified in assembly version. */ fileVersionFormat?: string; /** * Specify assembly informational version format to update `AssemblyInformationalVersion` attribute. * Leave blank to leave attribute unchanged. */ infoVersionFormat?: string; /** * When checked, AssemblyInfoPatcher will attempt to patch GlobalAssemblyInfo files. * * Defaults to `false`. */ patchGlobalAssemblyInfo?: boolean; } export interface BuildExtensionAutoMergeFeature extends BuildExtensionBase { /** * The Automatic Merge build feature tracks builds in branches matched by the * configured filter and merges them into a specified destination branch if * the build satisfies the condition configured (for example, the build is * successful). * * The feature is supported for Git and Mercurial VCS roots for build * configurations with enabled feature branches. * * see: https://www.jetbrains.com/help/teamcity/automatic-merge.html */ type: "AutoMergeFeature"; /** * Specify the branches whose builds' sources will be merged. * * see: https://www.jetbrains.com/help/teamcity/branch-filter.html */ srcBranchFilter: string[]; /** * A logical name of the destination branch the sources will be merged to. * * The branch must be present in a repository and included into the * Branch Specification. * * > HINT: Parameter references are supported here. */ dstBranch: string; /** * A message for a merge commit. * * Defaults to `Merge branch '%teamcity.build.branch%'`. * * > HINT: Parameter references are supported here. */ commitMsg?: string; /** * A condition defining when the merge will be performed (either for successful * builds only, or if build from the branch does not add new problems to * destination branch). * * Defaults to `successful`. */ mergeIf?: "successful" | "noNewTests"; /** * Select to create a merge commit or do a fast-forward merge. * * Defaults to `alwaysCreateMergeCommit`. */ mergePolicy?: "alwaysCreateMergeCommit" | "fastForward"; /** * Choose when to merge: * * - Merge after build finish: the build finishes, and then the merge starts. * The build duration does not include the merging time. Dependent builds * can start even if merging is still in process. * * - Merge before build finish: the build is considered finished only when the * merge is completed. Dependent builds will start only after the merge is * completed. * * Defaults to `runAfterBuildFinish`. */ runPolicy?: "runAfterBuildFinish" | "runBeforeBuildFinish"; } export type BuildExtensionCommitStatusPublisher = | BuildExtensionCommitStatusAtlassianStashPublisher | BuildExtensionCommitStatusBitbucketCloudPublisher | BuildExtensionCommitStatusGerritStatusPublisher | BuildExtensionCommitStatusGithubPublisher | BuildExtensionCommitStatusGitlabPublisher | BuildExtensionCommitStatusSpaceStatusPublisher | BuildExtensionCommitStatusTfsPublisher | BuildExtensionCommitStatusUpsourcePublisher; export interface BuildExtensionCommitStatusPublisherBase extends BuildExtensionBase { /** * Commit Status Publisher is a build feature which allows TeamCity to * automatically send build statuses of your commits to an external system. * * see: https://www.jetbrains.com/help/teamcity/commit-status-publisher.html */ type: "commit-status-publisher"; /** * The VCSRoot to publish commits status to. * * > HINT: If left undefined the Commit Status Publisher will attempt * > publishing statuses for commits in all attached VCS roots. */ vcsRootId?: string; } export interface BuildExtensionCommitStatusGithubPublisher extends BuildExtensionCommitStatusPublisherBase { /** * Publish commit statuses to Github / Github Enterprise * * see: https://www.jetbrains.com/help/teamcity/commit-status-publisher.html#GitHub */ publisherId: "githubStatusPublisher"; /** * The URL of the Github API to talk to. * * Defaults to `https://api.github.com`. * * > HINT: `http[s]://<host>[:<port>]/api/v3` for GitHub Enterprise. */ url?: string; /** * Use a personal access token or obtain a token through an OAuth connection. * * The token must have the following scopes: * - for public repositories: public_repo and repo:status * - for private repositories: repo * * > HINT: If you really truly do not want to use a `credentialsJSON` pointer * > here, instead preferring a password parameter you can still do that but * > you will have to cast the string. This is hard on purpose, you should * > always prefer `credentialsJSON` over a parameter with a password spec. */ token: `credentialsJSON:${string}`; // NOTE: Not even going to bother modeling the Username/Password option. } /** TODO: placeholder for tfs commit status publisher */ export interface BuildExtensionCommitStatusTfsPublisher extends BuildExtensionCommitStatusPublisherBase { publisherId: "tfs"; } /** TODO: placeholder for bitbucketCloudPublisher */ export interface BuildExtensionCommitStatusBitbucketCloudPublisher extends BuildExtensionCommitStatusPublisherBase { publisherId: "bitbucketCloudPublisher"; } /** TODO: placeholder for atlassianStashPublisher */ export interface BuildExtensionCommitStatusAtlassianStashPublisher extends BuildExtensionCommitStatusPublisherBase { publisherId: "atlassianStashPublisher"; } /** TODO: placeholder for gerritStatusPublisher */ export interface BuildExtensionCommitStatusGerritStatusPublisher extends BuildExtensionCommitStatusPublisherBase { publisherId: "gerritStatusPublisher"; } /** TODO: placeholder for gitlabStatusPublisher */ export interface BuildExtensionCommitStatusGitlabPublisher extends BuildExtensionCommitStatusPublisherBase { publisherId: "gitlabStatusPublisher"; } /** TODO: placeholder for spaceStatusPublisher */ export interface BuildExtensionCommitStatusSpaceStatusPublisher extends BuildExtensionCommitStatusPublisherBase { publisherId: "spaceStatusPublisher"; } /** TODO: placeholder for upsourcePublisher */ export interface BuildExtensionCommitStatusUpsourcePublisher extends BuildExtensionCommitStatusPublisherBase { publisherId: "upsourcePublisher"; } export interface BuildExtensionDockerSupport extends BuildExtensionBase { /** * The Docker Support build feature allows automatically signing in to a * Docker registry before the build start. * * Adding this feature: * * - enables the Docker events' monitoring: such operations as docker pull * and docker run will be detected by TeamCity; * * - adds the Docker Info tab to the Build Results page. The tab provides * information on Docker-related operations. * * The feature also allows: * * - cleaning up the Docker images; * * - automatically log in to an authenticated registry before the build and * log out of it after the build. * * see: https://www.jetbrains.com/help/teamcity/docker-support.html */ type: "DockerSupport"; /** * On server clean-up, delete pushed Docker images from registry. * * If you have a build configuration which publishes images, you need to * remove them at some point. You can select the corresponding option and * instruct TeamCity to remove the images published by a certain build when * the build itself is cleaned up. * * It works as follows: when an image is published, TeamCity stores the * information about the registry of the images published by the build. * * When the server clean-up is run and it deletes the build, all the configured * connections are searched for the address of this registry, and the images * published by the build are cleaned up using the credentials specified in * the found connection. * * Default to `false`. * * > HINT: This sounds like it's actually going to delete images from a registry, * > the location that you pushed the image to. As opposed to deleting the image * > on an agent after pushing it to a registry. The latter I caa understand but * > the former just seems wrong... yet another WTF moment thanks to TeamCity. * * see: https://www.jetbrains.com/help/teamcity/docker-support.html#Docker+Images+Clean-up */ cleanupPushed?: boolean; /** * To enable automatic login of a docker registry add it's ID here. * * Accepts `ProjectExtensionOAuthProviderDocker` & * `ProjectExtensionOAuthProviderAmazonDocker` IDs. * * see: https://www.jetbrains.com/help/teamcity/docker-support.html#Docker+Registry+Automatic+Login%2FLogout */ registryIds?: string[]; } export interface BuildExtensionFailureOnMessage extends BuildExtensionBase { /** * TeamCity can inspect all lines in a build log for some particular text * occurrence that indicates a build failure. * * When matching lines, the time and block name prefixes preceding each log * message are ignored. * * see: https://www.jetbrains.com/help/teamcity/build-failure-conditions.html#Fail+build+on+specific+text+in+build+log */ type: "BuildFailureOnMessage"; /** * Fail build if its build log contains some string. * * Default to `true`. * * > HINT: Set to false to invert the logic. ie: does not contain */ contains?: boolean; /** * Either an exact string to match on or a _"Java"_ regular expression. */ match: AllXOR<[{ /** * The exact sub string to match. */ exact: string; }, { /** * A _"Java"_ regular expression. * * see: http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html */ pattern: string; }]>; /** * An optional message to display in the UI and the build log * when this Failure Condition matches. */ failureMsg?: string; /** * Immediately stop the build if it fails due to the condition. * * Defaults to `true`. */ stopBuild?: boolean; } export interface BuildExtensionFailureOnMetric extends BuildExtensionBase { /** * When your build uses code examining tools like code coverage, duplicates * finders, or inspections, it generates various numeric metrics. For these * metrics, you can specify a threshold which, when exceeded, will fail a build. * * see: https://www.jetbrains.com/help/teamcity/build-failure-conditions.html#Fail+build+on+metric+change */ type: "BuildFailureOnMetric"; /** * The build metric to compare. */ metric: | "artifactsSize" | "buildDurationSecs" | "buildLogSize" | "numberOfClasses" | "numberOfCodeDuplicates" | "numberOfCoveredClasses" | "numberOfCoveredLines" | "numberOfCoveredMethods" | "numberOfFailedTests" | "numberOfIgnoredTests" | "numberOfInspectionErrors" | "numberOfInspectionWarnings" | "numberOfLinesOfCode" | "numberOfMethods" | "numberOfPassedTests" | "numberOfTests" | "percentageOfBlockCoverage" | "percentageOfBranchCoverage" | "percentageOfClassCoverage" | "percentageOfLineCoverage" | "percentageOfMethodCoverage" | "percentageOfStatementCoverage" | "testsDurationSecs" | "totalArtifactsSize"; /** * In general, there are two ways to configure this build fail condition: * * A build metric exceeds or is less than the specified constant value (threshold). * For example, Fail build if its "build duration (secs) ", compared to the * constant value, is "more" than "300 ". In this case, a build will fail if * it runs more than 300 seconds. * * A build metric has changed comparing to a specific build by a specified value. * For example, Fail build if its "build duration (secs)" compared to a value * from another build is "more" by at least "300" default units for this metric * than the value in the "Last successful build ". In this case, a build will * fail if it runs 300 seconds longer than the last successful build. * * Defaults to `CONSTANT_VALUE`. */ comparedTo?: | "CONSTANT_VALUE" | "LATEST_SUCCESSFUL_BUILD" | "LATEST_PINNED_BUILD" | "LATEST_FINISHED_BUILD" | AllXOR<[{ /** * Build with specified build number. * * see: https://www.jetbrains.com/help/teamcity/build-number.html */ buildNumber: number; }, { /** * Latest finished build with specified tag. * * see: https://www.jetbrains.com/help/teamcity/build-tag.html */ buildTag: string; }]>; /** * How to apply `byAtLeast` to the `metric`. */ is: "more" | "less" | "different"; /** * A numeric value for the comparison. */ byAtLeast: number; /** * If enabled `byAtLeast` is treated as a percentage instead of a raw unit. * * Defaults to `false`. * * > HINT: If set to `true`, `comparedTo` can not be set to `CONSTANT_VALUE` * > as you are checking for a percentage change from some other build. */ percent?: boolean; /** * Immediately stop the build if it fails due to the condition. * * Defaults to `true`. */ stopBuild?: boolean; } export interface BuildExtensionFileContentReplacer extends BuildExtensionBase { /** * File Content Replacer is the build feature which processes text files by * performing regular expression replacements before a build. After the build, * it restores the file content to the original state. * * > HINT: File Content Replacer should be used with the automatic checkout * > only: after this build feature is configured, it will run before the * > first build step. TeamCity will first perform replacement in the * > specified files found in the build checkout directory and then run * > your build. * * see: https://www.jetbrains.com/help/teamcity/file-content-replacer.html */ type: "JetBrains.FileContentReplacer"; /** * Specify paths to files where the values to be replaced will be searched. * * Rules are in the form of `+|-:[path relative to the checkout directory]`. * Ant-like wildcards are supported, for example, `dir/*.cs`. * * > HINT: Here, the pipe symbol `|` represents the **OR** command, * > as in regular expressions: use `+` for including, OR `-` * > for excluding. * * see: https://www.jetbrains.com/help/teamcity/file-content-replacer.html#File+Content+Replacer+Settings */ processFiles: string[]; /** * Disable this option to prevent build failure even if no files match the * specified pattern. * * Defaults to `true`. */ failBuild?: boolean; /** * The file encoding of the files that are being search and replaced. * * > HINT: If left undefined TeamCity will just aut detect this * > and most of the time probably work just fine. * * see: https://www.jetbrains.com/help/teamcity/file-content-replacer.html#File+Content+Replacer+Settings */ encoding?: | "US-ASCII" | "UTF-8" | "UTF-16BE" | "UTF-16LE" | { /** * When specifying a custom encoding, make sure it is supported by the agent. * * see: https://docs.oracle.com/javase/8/docs/technotes/guides/intl/encoding.doc.html */ custom: string; }; /** * You have 3 options for the actual search and replace logic. * * - fixedStrings: Where you provide a simple exact search and replace values, * no regex is used at all. * * - regex: Both the search and replace values are treated as regex patterns. * * - mixed: Where the search pattern is treated as regex but the replacement * is a static string. */ regexMode: AllXOR<[ { fixedStrings: { /** * Pattern to search for. Interpreted literally. */ search: string; /** * Replacement text. Backslashes (\) and dollar signs ($) have no special meaning. */ replace: string; }; }, { regex: { /** * Pattern to search for, in the regular expression format. * * **MULTILINE** mode is on by default. To disable it, * start the pattern with `(?-m)`. * * see: https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#sum */ search: string; /** * Replacement text. $N sequence references N-th capturing group. * All backslashes (\) and dollar signs ($) without a special meaning * should be quoted (as \\ and \$, respectively). */ replace: string; }; }, { mixed: { /** * Pattern to search for, in the regular expression format. * * **MULTILINE** mode is on by default. To disable it, * start the pattern with `(?-m)`. * * see: https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#sum */ search: string; /** * Replacement text. Backslashes (\) and dollar signs ($) have no special meaning. */ replace: string; }; }, ]>; /** * Disable for case-insensitive languages (e.g. Visual Basic). * * Defaults to `true`. */ matchCase?: boolean; } export interface BuildExtensionGolang extends BuildExtensionBase { /** * The Golang build feature enables the real-time reporting and history of * Go test results in TeamCity. * * Before running builds, make sure a Go compiler is installed on an agent. * * To enable Go tests reporting in TeamCity, run them with the `-json` flag * using one of these two methods: * * - Add this flag to the Command Line build runner's script: `go test -json`. * - Add the `env.GOFLAGS = -json` parameter to the build configuration. * * see: https://www.jetbrains.com/help/teamcity/golang.html */ type: "golang"; } export interface BuildExtensionInvestigationsAutoAssigner extends BuildExtensionBase { /** * TeamCity can analyse build problems (for example, compilation errors) and * test failures, and try to find a committer to blame for the problem using * a number of heuristics. * * see: https://www.jetbrains.com/help/teamcity/investigations-auto-assigner.html */ type: "InvestigationsAutoAssigner"; /** * Defaults to `ON_FIRST_FAILURE`. */ assign?: "ON_FIRST_FAILURE" | "ON_SECOND_FAILURE"; /** * Username of a user to assign the investigation to if no other assignee can be found. */ defaultAssignee: string; /** * Exclude these users from investigation auto-assignment. */ usersToIgnore?: string[]; /** * Build problems to ignore. */ ignore?: { /** * Defaults to `false`. */ compilationErrors?: boolean; /** * Defaults to `false`. */ exitCodes?: boolean; }; } export interface BuildExtensionJiraCloud extends BuildExtensionBase { /** * The Jira Cloud Integration build feature allows reporting build statuses * directly to Jira Cloud in real time. * * > HINT: This feature uses the Jira Software Cloud REST API and requires * > additional authentication parameters comparing to the regular integration * > with Jira. Before adding this feature to your build configuration, you * > need to create an issue tracker connection to Jira in the parent project's * > settings and provide the OAuth client ID/secret there. * * see: https://www.jetbrains.com/help/teamcity/jira-cloud-integration.html */ type: "jiraCloud"; /** * An id of a `ProjectExtensionIssueTrackerJira` object. */ issueTrackerConnectionId: string; /** * Environment information is required to show deployment status in Jira Cloud. */ environmentType: | "production" | "staging" | "testing" | "development" | "unmapped"; environmentName: string; } export type BuildExtensionNotifications = | BuildExtensionNotificationsEmail | BuildExtensionNotificationsSlack; const _events = [ "BUILD_FAILED_TO_START", "BUILD_FAILED", "BUILD_FINISHED_SUCCESSFULLY", "BUILD_PROBABLY_HANGING", "BUILD_STARTED", "FIRST_BUILD_ERROR_OCCURS", "FIRST_FAILURE_AFTER_SUCCESS", "FIRST_SUCCESS_AFTER_FAILURE", "NEW_BUILD_PROBLEM_OCCURRED", ] as const; export interface BuildExtensionNotificationsBase extends BuildExtensionBase { /** * The Notifications build feature is responsible for sending notifications * about build statuses and events to external services. Currently, the * feature provides Email Notifier and Slack Notifier. * * This feature adds to the functionality of user-level notifications that can * be assigned to a particular user or user group, but it allows configuring * notifications per build configuration. This approach does not require * referencing a specific TeamCity user and works better for group notifications. * * see: https://www.jetbrains.com/help/teamcity/notifications.html */ type: "notifications"; /** * Configure a branch filter. If it is not configured, you will receive * notifications about the default branch only. * * see: https://www.jetbrains.com/help/teamcity/branch-filter.html */ branchFilter?: string[]; /** * A list of events to subscribe to. */ events?: UniqueArray<typeof _events>; } export interface BuildExtensionNotificationsEmail extends BuildExtensionNotificationsBase { /** * see: https://www.jetbrains.com/help/teamcity/notifications.html#Email+Notifier */ notifier: "email"; /** * The email address to send the notifications to. */ to: string; } export interface BuildExtensionNotificationsSlack extends BuildExtensionNotificationsBase { /** * The Slack Notifier feature relies on a Slack connection that should be * preconfigured in the parent project's settings. * * see: https://www.jetbrains.com/help/teamcity/notifications.html#Slack+Notifier */ notifier: "slack"; /** * The id of a `ProjectExtensionOAuthProviderSlackConnection` object. */ connection: string; /** * Specify where messages should be sent. * * Channel IDs should start with the `#` symbol. * * Bot should be added to the provided channel to be able to send notifications. */ channel: string; /** * If left undefined only "simple" messages will be sent. */ msgFmt?: { /** * Adds branch name to the message. * * Defaults to `false`. */ addBranch?: boolean; /** * Adds build status text to the message. * * Defaults to `false`. */ addBuildStatus?: boolean; /** * Adds a list of changes to the message, up to the given maximum. */ addChanges?: number; }; } export interface BuildExtensionNugetAuth extends BuildExtensionBase { /** * When using NuGet packages from an external authenticated feed during a * build on TeamCity, the credentials for connecting to that feed have to * be specified. * * Adding this information to source control is not a secure practice, * so TeamCity provides the NuGet Feed Credentials build feature which * allows interacting with feeds that require authentication. * * > HINT: Only NuGet 2.0+ is supported! * * see: https://www.jetbrains.com/help/teamcity/nuget-feed-credentials.html */ type: "jb.nuget.auth"; /** * The Nuget Source URL to authenticate against. */ source: string; /** * The username for the Nuget Source URL. */ username: string; /** * The password for the Nuget Source URL. * * > HINT: If you really truly do not want to use a `credentialsJSON` pointer * > here, instead preferring a password parameter you can still do that but * > you will have to cast the string. This is hard on purpose, you should * > always prefer `credentialsJSON` over a parameter with a password spec. */ password: `<PASSWORD>:${string}`; } export interface BuildExtensionNuGetPackagesIndexer extends BuildExtensionBase { /** * NuGet packages indexer is an internal TeamCity tool that can index NuGet * packages and add them to TeamCity remote private feeds, with no need for * additional authorization. * * When the NuGet packages indexer build feature is added to a build configuration, * all .nupkg files published as build artifacts will be indexed and added to * the selected NuGet feed. Indexing is performed on the agent side. * * see: https://www.jetbrains.com/help/teamcity/nuget-packages-indexer.html */ type: "NuGetPackagesIndexer"; /**` * The fully qualified name of a `ProjectExtensionPackageRepositoryNuget` object. * * ie: `{ProjectName}/{NugetRepoName}` * * > HINT: This does not accept an ID! (Or at least I don't think it does) */ feed: string; } export interface BuildExtensionPerfmon extends BuildExtensionBase { /** * The Performance Monitor build feature allows you to get the statistics on * the CPU, disk, and memory usage during a build run on a build agent. * * Performance Monitor supports Windows, Linux, macOS, Solaris, * and FreeBSD operating systems. * * > HINT: It requires Perl to be installed on any used OS except Windows. * * see: https://www.jetbrains.com/help/teamcity/performance-monitor.html */ type: "perfmon"; } export type BuildExtensionPullRequests = | BuildExtensionPullRequestsAzureDevOps | BuildExtensionPullRequestsBitbucketCloud | BuildExtensionPullRequestsBitbucketServer | BuildExtensionPullRequestsGithub | BuildExtensionPullRequestsGitlab; export interface BuildExtensionPullRequestsBase extends BuildExtensionBase { /** * The Pull Requests build feature lets you automatically load pull request* * information and run builds on pull request branches in GitHub, Bitbucket * Server, Bitbucket Cloud, GitLab, and Azure DevOps. * * _* Or merge requests in case of GitLab._ * * When adding this build feature, you need to specify a VCS root and select * a VCS hosting type. Other settings depend on the selected VCS hosting type. * * This feature extends the original branch specification of VCS roots, * attached to the current build configuration, to include pull requests * that match the specified filtering criteria. * * > HINT: The branch specification of the VCS root must not contain patterns * > matching pull request branches. If you want to trigger builds only on * > pull requests, leave the branch specification of the VCS root empty. * * see: https://www.jetbrains.com/help/teamcity/pull-requests.html */ type: "pullRequests"; /** * The id of a `VcsRootGit` object. */ vcsRootId: string; } /** TODO: placeholder for azureDevOps pullRequests */ export interface BuildExtensionPullRequestsAzureDevOps extends BuildExtensionPullRequestsBase { /** * This feature monitors builds only on the `refs/pull/{{star}}/merge` branch. * * In case with Azure DevOps, TeamCity detects requests on a merge branch, * not on the pull request itself as with other VCSs. Each build will be * launched on a virtual branch showing an actual result of the build after * merging the PR. Thus, the build will contain both the commit with changes * and the virtual merge commit. * * > HINT: This feature ignores Azure DevOps draft pull requests. * * see: https://www.jetbrains.com/help/teamcity/pull-requests.html#Azure+DevOps+Pull+Requests */ providerType: "azureDevOps"; } /** TODO: placeholder for bitbucketCloud pullRequests */ export interface BuildExtensionPullRequestsBitbucketCloud extends BuildExtensionPullRequestsBase { /** * see: https://www.jetbrains.com/help/teamcity/pull-requests.html#Bitbucket+Cloud+Pull+Requests */ providerType: "bitbucketCloud"; } /** TODO: placeholder for bitbucketServer pullRequests */ export interface BuildExtensionPullRequestsBitbucketServer extends BuildExtensionPullRequestsBase { /** * see: https://www.jetbrains.com/help/teamcity/pull-requests.html#Bitbucket+Server+Pull+Requests */ providerType: "bitbucketServer"; } /** TODO: placeholder for github pullRequests */ export interface BuildExtensionPullRequestsGithub extends BuildExtensionPullRequestsBase { /** * see: https://www.jetbrains.com/help/teamcity/pull-requests.html#GitHub+Pull+Requests */ providerType: "github"; } /** TODO: placeholder for gitlab pullRequests */ export interface BuildExtensionPullRequestsGitlab extends BuildExtensionPullRequestsBase { /** * see: https://www.jetbrains.com/help/teamcity/pull-requests.html#GitLab+Merge+Requests */ providerType: "gitlab"; } /** TODO: placeholder for JetBrains.SharedResources build extension */ export interface BuildExtensionSharedResources extends BuildExtensionBase { type: "JetBrains.SharedResources"; } /** TODO: placeholder for ruby.env.configurator build extension */ export interface BuildExtensionRubyEnvConfigurator extends BuildExtensionBase { type: "ruby.env.configurator"; } /** TODO: placeholder for ssh-agent-build-feature build extension */ export interface BuildExtensionSshAgent extends BuildExtensionBase { type: "ssh-agent-build-feature"; } /** TODO: placeholder for swabra build extension */ export interface BuildExtensionSwabra extends BuildExtensionBase { type: "swabra"; } /** TODO: placeholder for VcsLabeling build extension */ export interface BuildExtensionVcsLabeling extends BuildExtensionBase { type: "VcsLabeling"; } /** TODO: placeholder for xml-report-plugin build extension */ export interface BuildExtensionXmlReportPlugin extends BuildExtensionBase { type: "xml-report-plugin"; } export type BuildCleanup = ProjectCleanup; <file_sep>/ts-schema/schema/rest-api/deno/models/MuteLocator.ts /** * TeamCity REST API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * OpenAPI spec version: 2018.1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { HttpFile } from '../http/http.ts'; export class MuteLocator { 'affectedProject'?: string; 'creationDate'?: Date; 'id'?: number; 'item'?: string; 'problem'?: string; 'project'?: string; 'reporter'?: string; 'resolution'?: string; 'test'?: string; 'type'?: string; 'unmuteDate'?: Date; static readonly discriminator: string | undefined = undefined; static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [ { "name": "affectedProject", "baseName": "affectedProject", "type": "string", "format": "ProjectLocator" }, { "name": "creationDate", "baseName": "creationDate", "type": "Date", "format": "date-time" }, { "name": "id", "baseName": "id", "type": "number", "format": "int32" }, { "name": "item", "baseName": "item", "type": "string", "format": "item:(&lt;locator1&gt;),item:(&lt;locator2&gt;...)" }, { "name": "problem", "baseName": "problem", "type": "string", "format": "ProblemLocator" }, { "name": "project", "baseName": "project", "type": "string", "format": "ProjectLocator" }, { "name": "reporter", "baseName": "reporter", "type": "string", "format": "" }, { "name": "resolution", "baseName": "resolution", "type": "string", "format": "" }, { "name": "test", "baseName": "test", "type": "string", "format": "TestLocator" }, { "name": "type", "baseName": "type", "type": "string", "format": "" }, { "name": "unmuteDate", "baseName": "unmuteDate", "type": "Date", "format": "date-time" } ]; static getAttributeTypeMap() { return MuteLocator.attributeTypeMap; } public constructor() { } } <file_sep>/ts-schema/schema/xml/parameter.ts import { AllXOR } from "../xor.ts"; export interface Parameters { param: Parameter[]; } export type Parameter = & { "@name": string; "@spec"?: string } & AllXOR<[ { "@value": string }, { "#text": string }, ]>; <file_sep>/ts-schema/schema/rest-api/deno/apis/MuteApi.ts // TODO: better import syntax? import { BaseAPIRequestFactory, RequiredError } from './baseapi.ts'; import {Configuration} from '../configuration.ts'; import { RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http.ts'; import {ObjectSerializer} from '../models/ObjectSerializer.ts'; import {ApiException} from './exception.ts'; import {isCodeInRange} from '../util.ts'; import { Mute } from '../models/Mute.ts'; import { Mutes } from '../models/Mutes.ts'; /** * no description */ export class MuteApiRequestFactory extends BaseAPIRequestFactory { /** * Get all muted tests. * @param locator * @param fields */ public async getAllMutedTests(locator?: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/mutes'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "")); } if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get a muted test. * @param muteLocator * @param fields */ public async getMutedTest(muteLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'muteLocator' is not null or undefined if (muteLocator === null || muteLocator === undefined) { throw new RequiredError('Required parameter muteLocator was null or undefined when calling getMutedTest.'); } // Path Params const localVarPath = '/app/rest/mutes/{muteLocator}' .replace('{' + 'muteLocator' + '}', encodeURIComponent(String(muteLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Mute multiple tests. * @param fields * @param body */ public async muteMultipleTests(fields?: string, body?: Mutes, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/mutes/multiple'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Mutes", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Mute a test. * @param fields * @param body */ public async muteTest(fields?: string, body?: Mute, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/mutes'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Mute", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Unmute the matching test. * @param muteLocator * @param body */ public async unmuteTest(muteLocator: string, body?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'muteLocator' is not null or undefined if (muteLocator === null || muteLocator === undefined) { throw new RequiredError('Required parameter muteLocator was null or undefined when calling unmuteTest.'); } // Path Params const localVarPath = '/app/rest/mutes/{muteLocator}' .replace('{' + 'muteLocator' + '}', encodeURIComponent(String(muteLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "string", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } } export class MuteApiResponseProcessor { /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAllMutedTests * @throws ApiException if the response code was not in [200, 299] */ public async getAllMutedTests(response: ResponseContext): Promise<Mutes > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Mutes = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Mutes", "" ) as Mutes; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Mutes = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Mutes", "" ) as Mutes; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getMutedTest * @throws ApiException if the response code was not in [200, 299] */ public async getMutedTest(response: ResponseContext): Promise<Mute > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Mute = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Mute", "" ) as Mute; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Mute = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Mute", "" ) as Mute; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to muteMultipleTests * @throws ApiException if the response code was not in [200, 299] */ public async muteMultipleTests(response: ResponseContext): Promise<Mutes > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Mutes = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Mutes", "" ) as Mutes; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Mutes = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Mutes", "" ) as Mutes; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to muteTest * @throws ApiException if the response code was not in [200, 299] */ public async muteTest(response: ResponseContext): Promise<Mute > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Mute = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Mute", "" ) as Mute; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Mute = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Mute", "" ) as Mute; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to unmuteTest * @throws ApiException if the response code was not in [200, 299] */ public async unmuteTest(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } } <file_sep>/ts-schema/schema/rest-api/deno/apis/VcsRootApi.ts // TODO: better import syntax? import { BaseAPIRequestFactory, RequiredError } from './baseapi.ts'; import {Configuration} from '../configuration.ts'; import { RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http.ts'; import {ObjectSerializer} from '../models/ObjectSerializer.ts'; import {ApiException} from './exception.ts'; import {isCodeInRange} from '../util.ts'; import { Properties } from '../models/Properties.ts'; import { VcsRoot } from '../models/VcsRoot.ts'; import { VcsRootInstances } from '../models/VcsRootInstances.ts'; import { VcsRoots } from '../models/VcsRoots.ts'; /** * no description */ export class VcsRootApiRequestFactory extends BaseAPIRequestFactory { /** * Add a new VCS root. * @param fields * @param body */ public async addVcsRoot(fields?: string, body?: VcsRoot, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/vcs-roots'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "VcsRoot", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Delete all properties of the matching VCS root. * @param vcsRootLocator */ public async deleteAllVcsRootProperties(vcsRootLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'vcsRootLocator' is not null or undefined if (vcsRootLocator === null || vcsRootLocator === undefined) { throw new RequiredError('Required parameter vcsRootLocator was null or undefined when calling deleteAllVcsRootProperties.'); } // Path Params const localVarPath = '/app/rest/vcs-roots/{vcsRootLocator}/properties' .replace('{' + 'vcsRootLocator' + '}', encodeURIComponent(String(vcsRootLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Remove VCS root matching the locator. * @param vcsRootLocator */ public async deleteVcsRoot(vcsRootLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'vcsRootLocator' is not null or undefined if (vcsRootLocator === null || vcsRootLocator === undefined) { throw new RequiredError('Required parameter vcsRootLocator was null or undefined when calling deleteVcsRoot.'); } // Path Params const localVarPath = '/app/rest/vcs-roots/{vcsRootLocator}' .replace('{' + 'vcsRootLocator' + '}', encodeURIComponent(String(vcsRootLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Delete a property of the matching VCS root. * @param vcsRootLocator * @param name */ public async deleteVcsRootProperty(vcsRootLocator: string, name: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'vcsRootLocator' is not null or undefined if (vcsRootLocator === null || vcsRootLocator === undefined) { throw new RequiredError('Required parameter vcsRootLocator was null or undefined when calling deleteVcsRootProperty.'); } // verify required parameter 'name' is not null or undefined if (name === null || name === undefined) { throw new RequiredError('Required parameter name was null or undefined when calling deleteVcsRootProperty.'); } // Path Params const localVarPath = '/app/rest/vcs-roots/{vcsRootLocator}/properties/{name}' .replace('{' + 'vcsRootLocator' + '}', encodeURIComponent(String(vcsRootLocator))) .replace('{' + 'name' + '}', encodeURIComponent(String(name))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all properties of the matching VCS root. * @param vcsRootLocator * @param fields */ public async getAllVcsRootProperties(vcsRootLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'vcsRootLocator' is not null or undefined if (vcsRootLocator === null || vcsRootLocator === undefined) { throw new RequiredError('Required parameter vcsRootLocator was null or undefined when calling getAllVcsRootProperties.'); } // Path Params const localVarPath = '/app/rest/vcs-roots/{vcsRootLocator}/properties' .replace('{' + 'vcsRootLocator' + '}', encodeURIComponent(String(vcsRootLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all VCS roots. * @param locator * @param fields */ public async getAllVcsRoots(locator?: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/vcs-roots'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "VcsRootLocator")); } if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get root endpoints. * @param vcsRootLocator * @param fields */ public async getRootEndpoints(vcsRootLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'vcsRootLocator' is not null or undefined if (vcsRootLocator === null || vcsRootLocator === undefined) { throw new RequiredError('Required parameter vcsRootLocator was null or undefined when calling getRootEndpoints.'); } // Path Params const localVarPath = '/app/rest/vcs-roots/{vcsRootLocator}' .replace('{' + 'vcsRootLocator' + '}', encodeURIComponent(String(vcsRootLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get a field of the matching VCS root. * @param vcsRootLocator * @param field */ public async getVcsRootField(vcsRootLocator: string, field: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'vcsRootLocator' is not null or undefined if (vcsRootLocator === null || vcsRootLocator === undefined) { throw new RequiredError('Required parameter vcsRootLocator was null or undefined when calling getVcsRootField.'); } // verify required parameter 'field' is not null or undefined if (field === null || field === undefined) { throw new RequiredError('Required parameter field was null or undefined when calling getVcsRootField.'); } // Path Params const localVarPath = '/app/rest/vcs-roots/{vcsRootLocator}/{field}' .replace('{' + 'vcsRootLocator' + '}', encodeURIComponent(String(vcsRootLocator))) .replace('{' + 'field' + '}', encodeURIComponent(String(field))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all VCS root instances of the matching VCS root. * @param vcsRootLocator * @param fields */ public async getVcsRootInstances(vcsRootLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'vcsRootLocator' is not null or undefined if (vcsRootLocator === null || vcsRootLocator === undefined) { throw new RequiredError('Required parameter vcsRootLocator was null or undefined when calling getVcsRootInstances.'); } // Path Params const localVarPath = '/app/rest/vcs-roots/{vcsRootLocator}/instances' .replace('{' + 'vcsRootLocator' + '}', encodeURIComponent(String(vcsRootLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get a property on the matching VCS root. * @param vcsRootLocator * @param name */ public async getVcsRootProperty(vcsRootLocator: string, name: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'vcsRootLocator' is not null or undefined if (vcsRootLocator === null || vcsRootLocator === undefined) { throw new RequiredError('Required parameter vcsRootLocator was null or undefined when calling getVcsRootProperty.'); } // verify required parameter 'name' is not null or undefined if (name === null || name === undefined) { throw new RequiredError('Required parameter name was null or undefined when calling getVcsRootProperty.'); } // Path Params const localVarPath = '/app/rest/vcs-roots/{vcsRootLocator}/properties/{name}' .replace('{' + 'vcsRootLocator' + '}', encodeURIComponent(String(vcsRootLocator))) .replace('{' + 'name' + '}', encodeURIComponent(String(name))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get the settings file of the matching VCS root. * @param vcsRootLocator */ public async getVcsRootSettingsFile(vcsRootLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'vcsRootLocator' is not null or undefined if (vcsRootLocator === null || vcsRootLocator === undefined) { throw new RequiredError('Required parameter vcsRootLocator was null or undefined when calling getVcsRootSettingsFile.'); } // Path Params const localVarPath = '/app/rest/vcs-roots/{vcsRootLocator}/settingsFile' .replace('{' + 'vcsRootLocator' + '}', encodeURIComponent(String(vcsRootLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update a field of the matching VCS root. * @param vcsRootLocator * @param field * @param body */ public async setVcsRootField(vcsRootLocator: string, field: string, body?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'vcsRootLocator' is not null or undefined if (vcsRootLocator === null || vcsRootLocator === undefined) { throw new RequiredError('Required parameter vcsRootLocator was null or undefined when calling setVcsRootField.'); } // verify required parameter 'field' is not null or undefined if (field === null || field === undefined) { throw new RequiredError('Required parameter field was null or undefined when calling setVcsRootField.'); } // Path Params const localVarPath = '/app/rest/vcs-roots/{vcsRootLocator}/{field}' .replace('{' + 'vcsRootLocator' + '}', encodeURIComponent(String(vcsRootLocator))) .replace('{' + 'field' + '}', encodeURIComponent(String(field))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "text/plain" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "string", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update all properties of the matching VCS root. * @param vcsRootLocator * @param fields * @param body */ public async setVcsRootProperties(vcsRootLocator: string, fields?: string, body?: Properties, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'vcsRootLocator' is not null or undefined if (vcsRootLocator === null || vcsRootLocator === undefined) { throw new RequiredError('Required parameter vcsRootLocator was null or undefined when calling setVcsRootProperties.'); } // Path Params const localVarPath = '/app/rest/vcs-roots/{vcsRootLocator}/properties' .replace('{' + 'vcsRootLocator' + '}', encodeURIComponent(String(vcsRootLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Properties", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update a property of the matching VCS root. * @param vcsRootLocator * @param name * @param body */ public async setVcsRootProperty(vcsRootLocator: string, name: string, body?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'vcsRootLocator' is not null or undefined if (vcsRootLocator === null || vcsRootLocator === undefined) { throw new RequiredError('Required parameter vcsRootLocator was null or undefined when calling setVcsRootProperty.'); } // verify required parameter 'name' is not null or undefined if (name === null || name === undefined) { throw new RequiredError('Required parameter name was null or undefined when calling setVcsRootProperty.'); } // Path Params const localVarPath = '/app/rest/vcs-roots/{vcsRootLocator}/properties/{name}' .replace('{' + 'vcsRootLocator' + '}', encodeURIComponent(String(vcsRootLocator))) .replace('{' + 'name' + '}', encodeURIComponent(String(name))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "text/plain" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "string", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } } export class VcsRootApiResponseProcessor { /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to addVcsRoot * @throws ApiException if the response code was not in [200, 299] */ public async addVcsRoot(response: ResponseContext): Promise<VcsRoot > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: VcsRoot = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "VcsRoot", "" ) as VcsRoot; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: VcsRoot = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "VcsRoot", "" ) as VcsRoot; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to deleteAllVcsRootProperties * @throws ApiException if the response code was not in [200, 299] */ public async deleteAllVcsRootProperties(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to deleteVcsRoot * @throws ApiException if the response code was not in [200, 299] */ public async deleteVcsRoot(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to deleteVcsRootProperty * @throws ApiException if the response code was not in [200, 299] */ public async deleteVcsRootProperty(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAllVcsRootProperties * @throws ApiException if the response code was not in [200, 299] */ public async getAllVcsRootProperties(response: ResponseContext): Promise<Properties > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Properties = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Properties", "" ) as Properties; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Properties = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Properties", "" ) as Properties; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAllVcsRoots * @throws ApiException if the response code was not in [200, 299] */ public async getAllVcsRoots(response: ResponseContext): Promise<VcsRoots > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: VcsRoots = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "VcsRoots", "" ) as VcsRoots; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: VcsRoots = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "VcsRoots", "" ) as VcsRoots; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getRootEndpoints * @throws ApiException if the response code was not in [200, 299] */ public async getRootEndpoints(response: ResponseContext): Promise<VcsRoot > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: VcsRoot = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "VcsRoot", "" ) as VcsRoot; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: VcsRoot = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "VcsRoot", "" ) as VcsRoot; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getVcsRootField * @throws ApiException if the response code was not in [200, 299] */ public async getVcsRootField(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getVcsRootInstances * @throws ApiException if the response code was not in [200, 299] */ public async getVcsRootInstances(response: ResponseContext): Promise<VcsRootInstances > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: VcsRootInstances = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "VcsRootInstances", "" ) as VcsRootInstances; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: VcsRootInstances = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "VcsRootInstances", "" ) as VcsRootInstances; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getVcsRootProperty * @throws ApiException if the response code was not in [200, 299] */ public async getVcsRootProperty(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getVcsRootSettingsFile * @throws ApiException if the response code was not in [200, 299] */ public async getVcsRootSettingsFile(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setVcsRootField * @throws ApiException if the response code was not in [200, 299] */ public async setVcsRootField(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setVcsRootProperties * @throws ApiException if the response code was not in [200, 299] */ public async setVcsRootProperties(response: ResponseContext): Promise<Properties > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Properties = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Properties", "" ) as Properties; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Properties = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Properties", "" ) as Properties; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setVcsRootProperty * @throws ApiException if the response code was not in [200, 299] */ public async setVcsRootProperty(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } } <file_sep>/ts-schema/schema/rest-api/deno/apis/ProblemApi.ts // TODO: better import syntax? import { BaseAPIRequestFactory, RequiredError } from './baseapi.ts'; import {Configuration} from '../configuration.ts'; import { RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http.ts'; import {ObjectSerializer} from '../models/ObjectSerializer.ts'; import {ApiException} from './exception.ts'; import {isCodeInRange} from '../util.ts'; import { Problem } from '../models/Problem.ts'; import { Problems } from '../models/Problems.ts'; /** * no description */ export class ProblemApiRequestFactory extends BaseAPIRequestFactory { /** * Get all build problems. * @param locator * @param fields */ public async getAllBuildProblems(locator?: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/problems'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "ProblemLocator")); } if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get a matching build problem. * @param problemLocator * @param fields */ public async getBuildProblem(problemLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'problemLocator' is not null or undefined if (problemLocator === null || problemLocator === undefined) { throw new RequiredError('Required parameter problemLocator was null or undefined when calling getBuildProblem.'); } // Path Params const localVarPath = '/app/rest/problems/{problemLocator}' .replace('{' + 'problemLocator' + '}', encodeURIComponent(String(problemLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } } export class ProblemApiResponseProcessor { /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAllBuildProblems * @throws ApiException if the response code was not in [200, 299] */ public async getAllBuildProblems(response: ResponseContext): Promise<Problems > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Problems = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Problems", "" ) as Problems; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Problems = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Problems", "" ) as Problems; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuildProblem * @throws ApiException if the response code was not in [200, 299] */ public async getBuildProblem(response: ResponseContext): Promise<Problem > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Problem = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Problem", "" ) as Problem; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Problem = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Problem", "" ) as Problem; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } } <file_sep>/ts-schema/schema/rest-api/deno/models/TestCounters.ts /** * TeamCity REST API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * OpenAPI spec version: 2018.1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { HttpFile } from '../http/http.ts'; export class TestCounters { 'ignored'?: number; 'failed'?: number; 'muted'?: number; 'success'?: number; 'all'?: number; static readonly discriminator: string | undefined = undefined; static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [ { "name": "ignored", "baseName": "ignored", "type": "number", "format": "int32" }, { "name": "failed", "baseName": "failed", "type": "number", "format": "int32" }, { "name": "muted", "baseName": "muted", "type": "number", "format": "int32" }, { "name": "success", "baseName": "success", "type": "number", "format": "int32" }, { "name": "all", "baseName": "all", "type": "number", "format": "int32" } ]; static getAttributeTypeMap() { return TestCounters.attributeTypeMap; } public constructor() { } } <file_sep>/README.md # Teamcity Playground I hate the TeamCity Kotlin DSL because: - I'm not that familiar with Java and thus not that familiar with Kotlin - To clarify Kotlin as a language looks pretty cool but it's also just that much different to other more main stream languages that it creates a barrier to entry. - Java/Kotlin tooling support sucks in VsCode, if it was better I might be more inclined to learn the tech. Sorry but IMHO the tooling around a language or platform really does make or break it. And I really do not want to run something like IntelliJ what a behemoth... - But most of all the DSL docs suck, not the Kotlin language docs, no they look adequate, it's the actual documentation for TeamCity's Kotlin DSL that is severely lacking. Or at least it was at the time of writing. - Also even if you want to use XML instead of Kotlin, there really are no docs. None. Zip. Zilch. Zero. - This is the most frustrating thing in my day to day life at the moment. Yeah you heard me, my "LIFE"! :rage: :cursing_face: ## Rant Over Ok with that out of the way, what is this? Essentially I created a local teamcity server running inside docker, I then created a new project and connected it to this repo but I set it to use XML instead of Kotlin. I then manually went through the UI and modified every conceivable option one thing at a time. Each time I took a screenshot of the change I made and TeamCity pushed a new commit with the XML changes. I then attached the screenshot to the commit via a Github comment. So essentially you should be able to do a blame on a particular line in the xml and see a commit with a screenshot of where that value surfaces in the UI. From there you can go a read the TeamCity docs that have been written from UIs perspective. Longer term my plan is to take this data, create a decent JSON/YAML Schema and then create a little Go tool that will convert YAML to XML for you. And then you can build a TeamCity pipeline using the easy familiarity of YAML. ## Notable Exceptions Ok so most of the time teamCity didn't care to actually check that the values I provided actually make sense which was great as I was able to speed through most things just inputting nonsensical data. But some things did require actual validation and other infrastructure to actually for realz exist and thus those things are are currently missing: - Cloud Profiles - Meta-Runners - Maven Settings - Artifacts Storage Also anything to do with templating as that can be handled by a higher level DSL, eg: TypeScript. > Yes while the goal here is to provide a simple YAML to XML conversion tool > because we are going to build that tool with Deno we will also get a TypeScript > lib for free that one could use programmatically if they wished. Oh and also I have only modeled Git VcsRoots, who doesn't use git these days? Probs the same people that use TeamCity, oh well PRs welcome... And one last thing I promise, basically all the different type of Build Runners. The only one we are going to model is the `simpleRunner` as anything can be built on top of that in a loosely coupled & portable manner. Instead of relying on TeamCity servers to have XYZ Runner/Plugin installed. ## OpenAPI Rest API Ok so I always knew TeamCity had a REST API & I guess I always knew that the Swagger spec existed. I started to ask myself why don't I just generate an OpenAPI client and call it a day? Well for starters the spec is not nicely documented. Not anywhere near to the degree we have documented the types we have written so far. Secondly the REST API is not a 1:1 mapping to the underlying XML files that go into a `.teamcity` folder. It's similar but it's not similar enough that you can just give the REST API a `project-config.xml` (or part of that file) for example. And so I could only then offer a workflow where one created/updated the pipeline before pushing anything to git. I guess at the end of the day this not that dissimilar to having to generate the XML from YAML first. But then why not just use <https://github.com/cvbarros/terraform-provider-teamcity>? I tried that and it too is lacking & does not model enough of the API surface IMO. So undoubtedly we would run into things we would want to do and couldn't because the tf provider didn't support the calls. _cvbarros is locking for maintainers, maybe we take it on?_ Additionally I feel not having the XML files in the `.teamcity` folder is less explicit and harder to audit. At least if your converting YAML to XML and for whatever reason you forget to do that & push a commit and then wonder why the pipeline didn't change (or wonder why it did change in the case of some other dev pushing a commit) it should be pretty easy to work out what happened in such a case as it's all in the git log. Where as if any dev could update the pipeline by using the REST API and not have it strictly tied to a git commit then all hell could break lose... Having said that I also like the ability to be able to generate a pipeline without a git repo at all. I can see use cases for that, more on that in a sec... The advantage of the open api spec is we can automate it's generation. Totally could slap together a standalone Github Actions project that runs nightly or whenever Jetbrains release a new version of TC and then generates a new version of the client, for multiple languages too. Whatever openapi-generator supports. **This will happen, coming soon, I promise...** ## The end goal After further reflection this is where I see things heading. - Build a simple OpenAPI client generator pipeline. Then no matter what tooling we end up writing in whatever language we have someway to easily interface with TeamCity. - Finish off the types I am building here, these will then get used in this new higher level piece of tooling that I am going describe now. - A new higher level tool similar to <https://github.com/nektos/act> - But this tool will be CI provider agnostic. At first it will support GHA & TC. - It will provide another layer of abstraction over these TeamCity types and provide an interface inspired by the GHA workflow schema. - It will likely be built with Deno thus it will have a TypeScript DSL which will provide similar features that we get from the likes of Kotlin but with hopefully a much friendly interface and much better tooling support. - This means that GHA workflows get a DSL for free too. - The tool will however still support ingesting workflow definitions written in plain old JSON/YAML to lower the barrier to entry and for very simple cases this may be the preferred option. - The TypeScript DSL will offer full escape hatch support, ala CDK. We do not want to create a tool that gets in the way. - In fact I have considered using JSSI for this tool. But I prefer Deno's Go like tooling and interface better. If JSSI gets released with deno instead of node I'll certainly consider it. - But the issue with JSSI implies that say a compiled language like Go could be used for this sort of DSL. And while not impossible using a compiled language poses it's challenges. Due to the dynamic nature of loading workflow modules, etc... - Actions will be TypeScript/Javascript functions, shared with deno's package management facilities similar to Go's. So to write a new action you just write & push a new deno module to a git repo somewhere. - It will offer 3 modes: - **Execute Local:** You write a workflow and it will do it's best effort to run it locally. For simple workflows this will be fine. - Given that workflows will be able to be written in TypeScript, so long as the workflow/action author has accommodated for each different OS where that action might be run then there should be no cross platform issues to worry about. - There wouldn't even be a requirement to associate this with a CI provider. eg: you could use this as a local task runner framework. That has the future possibility of being deployed as a pipeline if desired. - **Execute Remote:** This will execute the workflow on the CI providers infrastructure but in such a way that it looks like it's running locally. This will ensure more complex workflows that say require a Windows OS (or MacOS) can still easily be executed by those not running that OS locally. _Or they just have a low powered machine & the cloud is actually faster._ - This is where we can use the likes of the TeamCity REST API to on demand build a new pipeline and execute it, streaming it's logs back to the local terminal. Even artifacts could be copied up/down as needed. - To support GHA we would essentially create a new Github repo on the fly so we have a home for the temp pipeline. As GHA doesn't support building out a pipeline via it's REST API like TC does. - Remote execution would allow you to make changes to the code and not commit them just like if you were running the workflow in local mode. - This would work similar to having a docker context. ie: we would behind the scenes upload the local source to a location that the pipeline could download it from. - There might be a few different strategies, eg: git or s3 - **Generate:** This is where we generate a `.teamcity` or `.github/workflows` folder that contains a pipeline that then executes each individual action using the CI providers built-in mechanics. ie: Instead of relying on the tools local execution engine, the tool generates say some GHA workflow yaml with the appropriate jobs & steps which then call the tool using some special CLI args that tell the tool to only execute that specific action. - This generate mode could be connected to a git hook so that it all always happens before pushing any changes to the YAML (or TypeScript) DSL. - This generate mode is what the remote mode would use but it would just create a one time only pipeline. (maybe there would be some caching & re-use depending on timings) Just had a crazy idea... We use the generated openapi client to hit a teamcity instance, editing one thing at a time, which generates our XML diff, which we can then use to generate the XML types. Basically automating what have done manually in this repo.<file_sep>/ts-schema/schema/rest-api/deno/models/Project.ts /** * TeamCity REST API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * OpenAPI spec version: 2018.1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { BuildType } from './BuildType.ts'; import { BuildTypes } from './BuildTypes.ts'; import { CloudProfiles } from './CloudProfiles.ts'; import { Links } from './Links.ts'; import { ProjectFeatures } from './ProjectFeatures.ts'; import { Projects } from './Projects.ts'; import { Properties } from './Properties.ts'; import { StateField } from './StateField.ts'; import { VcsRoots } from './VcsRoots.ts'; import { HttpFile } from '../http/http.ts'; export class Project { 'id'?: string; 'internalId'?: string; 'uuid'?: string; 'name'?: string; 'parentProjectId'?: string; 'parentProjectInternalId'?: string; 'parentProjectName'?: string; 'archived'?: boolean; 'description'?: string; 'href'?: string; 'webUrl'?: string; 'links'?: Links; 'parentProject'?: Project; 'readOnlyUI'?: StateField; 'defaultTemplate'?: BuildType; 'buildTypes'?: BuildTypes; 'templates'?: BuildTypes; 'parameters'?: Properties; 'vcsRoots'?: VcsRoots; 'projectFeatures'?: ProjectFeatures; 'projects'?: Projects; 'cloudProfiles'?: CloudProfiles; 'locator'?: string; static readonly discriminator: string | undefined = undefined; static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [ { "name": "id", "baseName": "id", "type": "string", "format": "" }, { "name": "internalId", "baseName": "internalId", "type": "string", "format": "" }, { "name": "uuid", "baseName": "uuid", "type": "string", "format": "" }, { "name": "name", "baseName": "name", "type": "string", "format": "" }, { "name": "parentProjectId", "baseName": "parentProjectId", "type": "string", "format": "" }, { "name": "parentProjectInternalId", "baseName": "parentProjectInternalId", "type": "string", "format": "" }, { "name": "parentProjectName", "baseName": "parentProjectName", "type": "string", "format": "" }, { "name": "archived", "baseName": "archived", "type": "boolean", "format": "" }, { "name": "description", "baseName": "description", "type": "string", "format": "" }, { "name": "href", "baseName": "href", "type": "string", "format": "" }, { "name": "webUrl", "baseName": "webUrl", "type": "string", "format": "" }, { "name": "links", "baseName": "links", "type": "Links", "format": "" }, { "name": "parentProject", "baseName": "parentProject", "type": "Project", "format": "" }, { "name": "readOnlyUI", "baseName": "readOnlyUI", "type": "StateField", "format": "" }, { "name": "defaultTemplate", "baseName": "defaultTemplate", "type": "BuildType", "format": "" }, { "name": "buildTypes", "baseName": "buildTypes", "type": "BuildTypes", "format": "" }, { "name": "templates", "baseName": "templates", "type": "BuildTypes", "format": "" }, { "name": "parameters", "baseName": "parameters", "type": "Properties", "format": "" }, { "name": "vcsRoots", "baseName": "vcsRoots", "type": "VcsRoots", "format": "" }, { "name": "projectFeatures", "baseName": "projectFeatures", "type": "ProjectFeatures", "format": "" }, { "name": "projects", "baseName": "projects", "type": "Projects", "format": "" }, { "name": "cloudProfiles", "baseName": "cloudProfiles", "type": "CloudProfiles", "format": "" }, { "name": "locator", "baseName": "locator", "type": "string", "format": "" } ]; static getAttributeTypeMap() { return Project.attributeTypeMap; } public constructor() { } } <file_sep>/ts-schema/schema/rest-api/deno/models/BuildType.ts /** * TeamCity REST API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * OpenAPI spec version: 2018.1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { AgentRequirements } from './AgentRequirements.ts'; import { Agents } from './Agents.ts'; import { ArtifactDependencies } from './ArtifactDependencies.ts'; import { Branches } from './Branches.ts'; import { BuildTypes } from './BuildTypes.ts'; import { Builds } from './Builds.ts'; import { Features } from './Features.ts'; import { Investigations } from './Investigations.ts'; import { Links } from './Links.ts'; import { Project } from './Project.ts'; import { Properties } from './Properties.ts'; import { SnapshotDependencies } from './SnapshotDependencies.ts'; import { Steps } from './Steps.ts'; import { Triggers } from './Triggers.ts'; import { VcsRootEntries } from './VcsRootEntries.ts'; import { VcsRootInstances } from './VcsRootInstances.ts'; import { HttpFile } from '../http/http.ts'; export class BuildType { 'id'?: string; 'internalId'?: string; 'name'?: string; 'templateFlag'?: boolean; 'type'?: string; 'paused'?: boolean; 'uuid'?: string; 'description'?: string; 'projectName'?: string; 'projectId'?: string; 'projectInternalId'?: string; 'href'?: string; 'webUrl'?: string; 'inherited'?: boolean; 'links'?: Links; 'project'?: Project; 'templates'?: BuildTypes; 'template'?: BuildType; 'vcsRootEntries'?: VcsRootEntries; 'settings'?: Properties; 'parameters'?: Properties; 'steps'?: Steps; 'features'?: Features; 'triggers'?: Triggers; 'snapshotDependencies'?: SnapshotDependencies; 'artifactDependencies'?: ArtifactDependencies; 'agentRequirements'?: AgentRequirements; 'branches'?: Branches; 'builds'?: Builds; 'investigations'?: Investigations; 'compatibleAgents'?: Agents; 'vcsRootInstances'?: VcsRootInstances; 'locator'?: string; static readonly discriminator: string | undefined = undefined; static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [ { "name": "id", "baseName": "id", "type": "string", "format": "" }, { "name": "internalId", "baseName": "internalId", "type": "string", "format": "" }, { "name": "name", "baseName": "name", "type": "string", "format": "" }, { "name": "templateFlag", "baseName": "templateFlag", "type": "boolean", "format": "" }, { "name": "type", "baseName": "type", "type": "string", "format": "" }, { "name": "paused", "baseName": "paused", "type": "boolean", "format": "" }, { "name": "uuid", "baseName": "uuid", "type": "string", "format": "" }, { "name": "description", "baseName": "description", "type": "string", "format": "" }, { "name": "projectName", "baseName": "projectName", "type": "string", "format": "" }, { "name": "projectId", "baseName": "projectId", "type": "string", "format": "" }, { "name": "projectInternalId", "baseName": "projectInternalId", "type": "string", "format": "" }, { "name": "href", "baseName": "href", "type": "string", "format": "" }, { "name": "webUrl", "baseName": "webUrl", "type": "string", "format": "" }, { "name": "inherited", "baseName": "inherited", "type": "boolean", "format": "" }, { "name": "links", "baseName": "links", "type": "Links", "format": "" }, { "name": "project", "baseName": "project", "type": "Project", "format": "" }, { "name": "templates", "baseName": "templates", "type": "BuildTypes", "format": "" }, { "name": "template", "baseName": "template", "type": "BuildType", "format": "" }, { "name": "vcsRootEntries", "baseName": "vcs-root-entries", "type": "VcsRootEntries", "format": "" }, { "name": "settings", "baseName": "settings", "type": "Properties", "format": "" }, { "name": "parameters", "baseName": "parameters", "type": "Properties", "format": "" }, { "name": "steps", "baseName": "steps", "type": "Steps", "format": "" }, { "name": "features", "baseName": "features", "type": "Features", "format": "" }, { "name": "triggers", "baseName": "triggers", "type": "Triggers", "format": "" }, { "name": "snapshotDependencies", "baseName": "snapshot-dependencies", "type": "SnapshotDependencies", "format": "" }, { "name": "artifactDependencies", "baseName": "artifact-dependencies", "type": "ArtifactDependencies", "format": "" }, { "name": "agentRequirements", "baseName": "agent-requirements", "type": "AgentRequirements", "format": "" }, { "name": "branches", "baseName": "branches", "type": "Branches", "format": "" }, { "name": "builds", "baseName": "builds", "type": "Builds", "format": "" }, { "name": "investigations", "baseName": "investigations", "type": "Investigations", "format": "" }, { "name": "compatibleAgents", "baseName": "compatibleAgents", "type": "Agents", "format": "" }, { "name": "vcsRootInstances", "baseName": "vcsRootInstances", "type": "VcsRootInstances", "format": "" }, { "name": "locator", "baseName": "locator", "type": "string", "format": "" } ]; static getAttributeTypeMap() { return BuildType.attributeTypeMap; } public constructor() { } } <file_sep>/ts-schema/schema/rest-api/deno/models/CloudImage.ts /** * TeamCity REST API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * OpenAPI spec version: 2018.1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { CloudInstances } from './CloudInstances.ts'; import { CloudProfile } from './CloudProfile.ts'; import { HttpFile } from '../http/http.ts'; export class CloudImage { 'id'?: string; 'name'?: string; 'href'?: string; 'profile'?: CloudProfile; 'instances'?: CloudInstances; 'errorMessage'?: string; 'agentTypeId'?: number; 'agentPoolId'?: number; 'operatingSystemName'?: string; 'locator'?: string; static readonly discriminator: string | undefined = undefined; static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [ { "name": "id", "baseName": "id", "type": "string", "format": "" }, { "name": "name", "baseName": "name", "type": "string", "format": "" }, { "name": "href", "baseName": "href", "type": "string", "format": "" }, { "name": "profile", "baseName": "profile", "type": "CloudProfile", "format": "" }, { "name": "instances", "baseName": "instances", "type": "CloudInstances", "format": "" }, { "name": "errorMessage", "baseName": "errorMessage", "type": "string", "format": "" }, { "name": "agentTypeId", "baseName": "agentTypeId", "type": "number", "format": "int32" }, { "name": "agentPoolId", "baseName": "agentPoolId", "type": "number", "format": "int32" }, { "name": "operatingSystemName", "baseName": "operatingSystemName", "type": "string", "format": "" }, { "name": "locator", "baseName": "locator", "type": "string", "format": "" } ]; static getAttributeTypeMap() { return CloudImage.attributeTypeMap; } public constructor() { } } <file_sep>/ts-schema/schema/rest-api/deno/models/VcsRootInstance.ts /** * TeamCity REST API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * OpenAPI spec version: 2018.1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { Items } from './Items.ts'; import { Properties } from './Properties.ts'; import { RepositoryState } from './RepositoryState.ts'; import { VcsRoot } from './VcsRoot.ts'; import { VcsStatus } from './VcsStatus.ts'; import { HttpFile } from '../http/http.ts'; export class VcsRootInstance { 'id'?: string; 'vcsRootId'?: string; 'vcsRootInternalId'?: string; 'name'?: string; 'vcsName'?: string; 'modificationCheckInterval'?: number; 'commitHookMode'?: boolean; 'lastVersion'?: string; 'lastVersionInternal'?: string; 'href'?: string; 'vcsRoot'?: VcsRoot; 'status'?: VcsStatus; 'repositoryState'?: RepositoryState; 'properties'?: Properties; 'repositoryIdStrings'?: Items; 'projectLocator'?: string; static readonly discriminator: string | undefined = undefined; static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [ { "name": "id", "baseName": "id", "type": "string", "format": "" }, { "name": "vcsRootId", "baseName": "vcs-root-id", "type": "string", "format": "" }, { "name": "vcsRootInternalId", "baseName": "vcsRootInternalId", "type": "string", "format": "" }, { "name": "name", "baseName": "name", "type": "string", "format": "" }, { "name": "vcsName", "baseName": "vcsName", "type": "string", "format": "" }, { "name": "modificationCheckInterval", "baseName": "modificationCheckInterval", "type": "number", "format": "int32" }, { "name": "commitHookMode", "baseName": "commitHookMode", "type": "boolean", "format": "" }, { "name": "lastVersion", "baseName": "lastVersion", "type": "string", "format": "" }, { "name": "lastVersionInternal", "baseName": "lastVersionInternal", "type": "string", "format": "" }, { "name": "href", "baseName": "href", "type": "string", "format": "" }, { "name": "vcsRoot", "baseName": "vcs-root", "type": "VcsRoot", "format": "" }, { "name": "status", "baseName": "status", "type": "VcsStatus", "format": "" }, { "name": "repositoryState", "baseName": "repositoryState", "type": "RepositoryState", "format": "" }, { "name": "properties", "baseName": "properties", "type": "Properties", "format": "" }, { "name": "repositoryIdStrings", "baseName": "repositoryIdStrings", "type": "Items", "format": "" }, { "name": "projectLocator", "baseName": "projectLocator", "type": "string", "format": "" } ]; static getAttributeTypeMap() { return VcsRootInstance.attributeTypeMap; } public constructor() { } } <file_sep>/ts-schema/schema/rest-api/deno/models/User.ts /** * TeamCity REST API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * OpenAPI spec version: 2018.1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { Groups } from './Groups.ts'; import { Properties } from './Properties.ts'; import { Roles } from './Roles.ts'; import { HttpFile } from '../http/http.ts'; export class User { 'username'?: string; 'name'?: string; 'id'?: number; 'email'?: string; 'lastLogin'?: string; 'password'?: string; 'hasPassword'?: boolean; 'realm'?: string; 'href'?: string; 'properties'?: Properties; 'roles'?: Roles; 'groups'?: Groups; 'locator'?: string; static readonly discriminator: string | undefined = undefined; static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [ { "name": "username", "baseName": "username", "type": "string", "format": "" }, { "name": "name", "baseName": "name", "type": "string", "format": "" }, { "name": "id", "baseName": "id", "type": "number", "format": "int64" }, { "name": "email", "baseName": "email", "type": "string", "format": "" }, { "name": "lastLogin", "baseName": "lastLogin", "type": "string", "format": "" }, { "name": "password", "baseName": "password", "type": "string", "format": "" }, { "name": "hasPassword", "baseName": "hasPassword", "type": "boolean", "format": "" }, { "name": "realm", "baseName": "realm", "type": "string", "format": "" }, { "name": "href", "baseName": "href", "type": "string", "format": "" }, { "name": "properties", "baseName": "properties", "type": "Properties", "format": "" }, { "name": "roles", "baseName": "roles", "type": "Roles", "format": "" }, { "name": "groups", "baseName": "groups", "type": "Groups", "format": "" }, { "name": "locator", "baseName": "locator", "type": "string", "format": "" } ]; static getAttributeTypeMap() { return User.attributeTypeMap; } public constructor() { } } <file_sep>/ts-schema/schema/rest-api/deno/apis/UserApi.ts // TODO: better import syntax? import { BaseAPIRequestFactory, RequiredError } from './baseapi.ts'; import {Configuration} from '../configuration.ts'; import { RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http.ts'; import {ObjectSerializer} from '../models/ObjectSerializer.ts'; import {ApiException} from './exception.ts'; import {isCodeInRange} from '../util.ts'; import { Group } from '../models/Group.ts'; import { Groups } from '../models/Groups.ts'; import { PermissionAssignments } from '../models/PermissionAssignments.ts'; import { Properties } from '../models/Properties.ts'; import { Role } from '../models/Role.ts'; import { Roles } from '../models/Roles.ts'; import { Token } from '../models/Token.ts'; import { Tokens } from '../models/Tokens.ts'; import { User } from '../models/User.ts'; import { Users } from '../models/Users.ts'; /** * no description */ export class UserApiRequestFactory extends BaseAPIRequestFactory { /** * Add a role to the matching user. * @param userLocator * @param body */ public async addRoleToUser(userLocator: string, body?: Role, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'userLocator' is not null or undefined if (userLocator === null || userLocator === undefined) { throw new RequiredError('Required parameter userLocator was null or undefined when calling addRoleToUser.'); } // Path Params const localVarPath = '/app/rest/users/{userLocator}/roles' .replace('{' + 'userLocator' + '}', encodeURIComponent(String(userLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Role", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Add a role with the specific scope to the matching user. * @param userLocator * @param roleId * @param scope */ public async addRoleToUserAtScope(userLocator: string, roleId: string, scope: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'userLocator' is not null or undefined if (userLocator === null || userLocator === undefined) { throw new RequiredError('Required parameter userLocator was null or undefined when calling addRoleToUserAtScope.'); } // verify required parameter 'roleId' is not null or undefined if (roleId === null || roleId === undefined) { throw new RequiredError('Required parameter roleId was null or undefined when calling addRoleToUserAtScope.'); } // verify required parameter 'scope' is not null or undefined if (scope === null || scope === undefined) { throw new RequiredError('Required parameter scope was null or undefined when calling addRoleToUserAtScope.'); } // Path Params const localVarPath = '/app/rest/users/{userLocator}/roles/{roleId}/{scope}' .replace('{' + 'userLocator' + '}', encodeURIComponent(String(userLocator))) .replace('{' + 'roleId' + '}', encodeURIComponent(String(roleId))) .replace('{' + 'scope' + '}', encodeURIComponent(String(scope))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Create a new user. * @param fields * @param body */ public async addUser(fields?: string, body?: User, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/users'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "User", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Create a new authentication token for the matching user. * @param userLocator * @param fields * @param body */ public async addUserToken(userLocator: string, fields?: string, body?: Token, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'userLocator' is not null or undefined if (userLocator === null || userLocator === undefined) { throw new RequiredError('Required parameter userLocator was null or undefined when calling addUserToken.'); } // Path Params const localVarPath = '/app/rest/users/{userLocator}/tokens' .replace('{' + 'userLocator' + '}', encodeURIComponent(String(userLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Token", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Delete user matching the locator. * @param userLocator */ public async deleteUser(userLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'userLocator' is not null or undefined if (userLocator === null || userLocator === undefined) { throw new RequiredError('Required parameter userLocator was null or undefined when calling deleteUser.'); } // Path Params const localVarPath = '/app/rest/users/{userLocator}' .replace('{' + 'userLocator' + '}', encodeURIComponent(String(userLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Remove a property of the matching user. * @param userLocator * @param field */ public async deleteUserField(userLocator: string, field: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'userLocator' is not null or undefined if (userLocator === null || userLocator === undefined) { throw new RequiredError('Required parameter userLocator was null or undefined when calling deleteUserField.'); } // verify required parameter 'field' is not null or undefined if (field === null || field === undefined) { throw new RequiredError('Required parameter field was null or undefined when calling deleteUserField.'); } // Path Params const localVarPath = '/app/rest/users/{userLocator}/{field}' .replace('{' + 'userLocator' + '}', encodeURIComponent(String(userLocator))) .replace('{' + 'field' + '}', encodeURIComponent(String(field))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Remove an authentication token from the matching user. * @param userLocator * @param name */ public async deleteUserToken(userLocator: string, name: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'userLocator' is not null or undefined if (userLocator === null || userLocator === undefined) { throw new RequiredError('Required parameter userLocator was null or undefined when calling deleteUserToken.'); } // verify required parameter 'name' is not null or undefined if (name === null || name === undefined) { throw new RequiredError('Required parameter name was null or undefined when calling deleteUserToken.'); } // Path Params const localVarPath = '/app/rest/users/{userLocator}/tokens/{name}' .replace('{' + 'userLocator' + '}', encodeURIComponent(String(userLocator))) .replace('{' + 'name' + '}', encodeURIComponent(String(name))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get a field of the matching user. * @param userLocator * @param field */ public async gerUserField(userLocator: string, field: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'userLocator' is not null or undefined if (userLocator === null || userLocator === undefined) { throw new RequiredError('Required parameter userLocator was null or undefined when calling gerUserField.'); } // verify required parameter 'field' is not null or undefined if (field === null || field === undefined) { throw new RequiredError('Required parameter field was null or undefined when calling gerUserField.'); } // Path Params const localVarPath = '/app/rest/users/{userLocator}/{field}' .replace('{' + 'userLocator' + '}', encodeURIComponent(String(userLocator))) .replace('{' + 'field' + '}', encodeURIComponent(String(field))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all groups of the matching user. * @param userLocator * @param fields */ public async getAllUserGroups(userLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'userLocator' is not null or undefined if (userLocator === null || userLocator === undefined) { throw new RequiredError('Required parameter userLocator was null or undefined when calling getAllUserGroups.'); } // Path Params const localVarPath = '/app/rest/users/{userLocator}/groups' .replace('{' + 'userLocator' + '}', encodeURIComponent(String(userLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all user roles of the matching user. * @param userLocator */ public async getAllUserRoles(userLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'userLocator' is not null or undefined if (userLocator === null || userLocator === undefined) { throw new RequiredError('Required parameter userLocator was null or undefined when calling getAllUserRoles.'); } // Path Params const localVarPath = '/app/rest/users/{userLocator}/roles' .replace('{' + 'userLocator' + '}', encodeURIComponent(String(userLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all users. * @param locator * @param fields */ public async getAllUsers(locator?: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/users'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "")); } if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get user matching the locator. * @param userLocator * @param fields */ public async getUser(userLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'userLocator' is not null or undefined if (userLocator === null || userLocator === undefined) { throw new RequiredError('Required parameter userLocator was null or undefined when calling getUser.'); } // Path Params const localVarPath = '/app/rest/users/{userLocator}' .replace('{' + 'userLocator' + '}', encodeURIComponent(String(userLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get a user group of the matching user. * @param userLocator * @param groupLocator * @param fields */ public async getUserGroup(userLocator: string, groupLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'userLocator' is not null or undefined if (userLocator === null || userLocator === undefined) { throw new RequiredError('Required parameter userLocator was null or undefined when calling getUserGroup.'); } // verify required parameter 'groupLocator' is not null or undefined if (groupLocator === null || groupLocator === undefined) { throw new RequiredError('Required parameter groupLocator was null or undefined when calling getUserGroup.'); } // Path Params const localVarPath = '/app/rest/users/{userLocator}/groups/{groupLocator}' .replace('{' + 'userLocator' + '}', encodeURIComponent(String(userLocator))) .replace('{' + 'groupLocator' + '}', encodeURIComponent(String(groupLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all permissions effective for the matching user. * @param userLocator * @param locator * @param fields */ public async getUserPermissions(userLocator: string, locator?: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'userLocator' is not null or undefined if (userLocator === null || userLocator === undefined) { throw new RequiredError('Required parameter userLocator was null or undefined when calling getUserPermissions.'); } // Path Params const localVarPath = '/app/rest/users/{userLocator}/permissions' .replace('{' + 'userLocator' + '}', encodeURIComponent(String(userLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "")); } if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all properties of the matching user. * @param userLocator * @param fields */ public async getUserProperties(userLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'userLocator' is not null or undefined if (userLocator === null || userLocator === undefined) { throw new RequiredError('Required parameter userLocator was null or undefined when calling getUserProperties.'); } // Path Params const localVarPath = '/app/rest/users/{userLocator}/properties' .replace('{' + 'userLocator' + '}', encodeURIComponent(String(userLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get a property of the matching user. * @param userLocator * @param name */ public async getUserProperty(userLocator: string, name: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'userLocator' is not null or undefined if (userLocator === null || userLocator === undefined) { throw new RequiredError('Required parameter userLocator was null or undefined when calling getUserProperty.'); } // verify required parameter 'name' is not null or undefined if (name === null || name === undefined) { throw new RequiredError('Required parameter name was null or undefined when calling getUserProperty.'); } // Path Params const localVarPath = '/app/rest/users/{userLocator}/properties/{name}' .replace('{' + 'userLocator' + '}', encodeURIComponent(String(userLocator))) .replace('{' + 'name' + '}', encodeURIComponent(String(name))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get a user role with the specific scope from the matching user. * @param userLocator * @param roleId * @param scope */ public async getUserRolesAtScope(userLocator: string, roleId: string, scope: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'userLocator' is not null or undefined if (userLocator === null || userLocator === undefined) { throw new RequiredError('Required parameter userLocator was null or undefined when calling getUserRolesAtScope.'); } // verify required parameter 'roleId' is not null or undefined if (roleId === null || roleId === undefined) { throw new RequiredError('Required parameter roleId was null or undefined when calling getUserRolesAtScope.'); } // verify required parameter 'scope' is not null or undefined if (scope === null || scope === undefined) { throw new RequiredError('Required parameter scope was null or undefined when calling getUserRolesAtScope.'); } // Path Params const localVarPath = '/app/rest/users/{userLocator}/roles/{roleId}/{scope}' .replace('{' + 'userLocator' + '}', encodeURIComponent(String(userLocator))) .replace('{' + 'roleId' + '}', encodeURIComponent(String(roleId))) .replace('{' + 'scope' + '}', encodeURIComponent(String(scope))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all authentication tokens of the matching user. * @param userLocator * @param fields */ public async getUserTokens(userLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'userLocator' is not null or undefined if (userLocator === null || userLocator === undefined) { throw new RequiredError('Required parameter userLocator was null or undefined when calling getUserTokens.'); } // Path Params const localVarPath = '/app/rest/users/{userLocator}/tokens' .replace('{' + 'userLocator' + '}', encodeURIComponent(String(userLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Remove the matching user from the specific group. * @param userLocator * @param groupLocator * @param fields */ public async removeUserFromGroup(userLocator: string, groupLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'userLocator' is not null or undefined if (userLocator === null || userLocator === undefined) { throw new RequiredError('Required parameter userLocator was null or undefined when calling removeUserFromGroup.'); } // verify required parameter 'groupLocator' is not null or undefined if (groupLocator === null || groupLocator === undefined) { throw new RequiredError('Required parameter groupLocator was null or undefined when calling removeUserFromGroup.'); } // Path Params const localVarPath = '/app/rest/users/{userLocator}/groups/{groupLocator}' .replace('{' + 'userLocator' + '}', encodeURIComponent(String(userLocator))) .replace('{' + 'groupLocator' + '}', encodeURIComponent(String(groupLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Remove a property of the matching user. * @param userLocator * @param name */ public async removeUserProperty(userLocator: string, name: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'userLocator' is not null or undefined if (userLocator === null || userLocator === undefined) { throw new RequiredError('Required parameter userLocator was null or undefined when calling removeUserProperty.'); } // verify required parameter 'name' is not null or undefined if (name === null || name === undefined) { throw new RequiredError('Required parameter name was null or undefined when calling removeUserProperty.'); } // Path Params const localVarPath = '/app/rest/users/{userLocator}/properties/{name}' .replace('{' + 'userLocator' + '}', encodeURIComponent(String(userLocator))) .replace('{' + 'name' + '}', encodeURIComponent(String(name))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Remove the RememberMe data of the matching user. * @param userLocator */ public async removeUserRememberMe(userLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'userLocator' is not null or undefined if (userLocator === null || userLocator === undefined) { throw new RequiredError('Required parameter userLocator was null or undefined when calling removeUserRememberMe.'); } // Path Params const localVarPath = '/app/rest/users/{userLocator}/debug/rememberMe' .replace('{' + 'userLocator' + '}', encodeURIComponent(String(userLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Remove a role with the specific scope from the matching user. * @param userLocator * @param roleId * @param scope */ public async removeUserRoleAtScope(userLocator: string, roleId: string, scope: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'userLocator' is not null or undefined if (userLocator === null || userLocator === undefined) { throw new RequiredError('Required parameter userLocator was null or undefined when calling removeUserRoleAtScope.'); } // verify required parameter 'roleId' is not null or undefined if (roleId === null || roleId === undefined) { throw new RequiredError('Required parameter roleId was null or undefined when calling removeUserRoleAtScope.'); } // verify required parameter 'scope' is not null or undefined if (scope === null || scope === undefined) { throw new RequiredError('Required parameter scope was null or undefined when calling removeUserRoleAtScope.'); } // Path Params const localVarPath = '/app/rest/users/{userLocator}/roles/{roleId}/{scope}' .replace('{' + 'userLocator' + '}', encodeURIComponent(String(userLocator))) .replace('{' + 'roleId' + '}', encodeURIComponent(String(roleId))) .replace('{' + 'scope' + '}', encodeURIComponent(String(scope))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update user matching the locator. * @param userLocator * @param fields * @param body */ public async replaceUser(userLocator: string, fields?: string, body?: User, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'userLocator' is not null or undefined if (userLocator === null || userLocator === undefined) { throw new RequiredError('Required parameter userLocator was null or undefined when calling replaceUser.'); } // Path Params const localVarPath = '/app/rest/users/{userLocator}' .replace('{' + 'userLocator' + '}', encodeURIComponent(String(userLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "User", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update a field of the matching user. * @param userLocator * @param field * @param body */ public async setUserField(userLocator: string, field: string, body?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'userLocator' is not null or undefined if (userLocator === null || userLocator === undefined) { throw new RequiredError('Required parameter userLocator was null or undefined when calling setUserField.'); } // verify required parameter 'field' is not null or undefined if (field === null || field === undefined) { throw new RequiredError('Required parameter field was null or undefined when calling setUserField.'); } // Path Params const localVarPath = '/app/rest/users/{userLocator}/{field}' .replace('{' + 'userLocator' + '}', encodeURIComponent(String(userLocator))) .replace('{' + 'field' + '}', encodeURIComponent(String(field))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "text/plain" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "string", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update groups of the matching user. * @param userLocator * @param fields * @param body */ public async setUserGroups(userLocator: string, fields?: string, body?: Groups, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'userLocator' is not null or undefined if (userLocator === null || userLocator === undefined) { throw new RequiredError('Required parameter userLocator was null or undefined when calling setUserGroups.'); } // Path Params const localVarPath = '/app/rest/users/{userLocator}/groups' .replace('{' + 'userLocator' + '}', encodeURIComponent(String(userLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Groups", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update a property of the matching user. * @param userLocator * @param name * @param body */ public async setUserProperty(userLocator: string, name: string, body?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'userLocator' is not null or undefined if (userLocator === null || userLocator === undefined) { throw new RequiredError('Required parameter userLocator was null or undefined when calling setUserProperty.'); } // verify required parameter 'name' is not null or undefined if (name === null || name === undefined) { throw new RequiredError('Required parameter name was null or undefined when calling setUserProperty.'); } // Path Params const localVarPath = '/app/rest/users/{userLocator}/properties/{name}' .replace('{' + 'userLocator' + '}', encodeURIComponent(String(userLocator))) .replace('{' + 'name' + '}', encodeURIComponent(String(name))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "text/plain" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "string", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update user roles of the matching user. * @param userLocator * @param body */ public async setUserRoles(userLocator: string, body?: Roles, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'userLocator' is not null or undefined if (userLocator === null || userLocator === undefined) { throw new RequiredError('Required parameter userLocator was null or undefined when calling setUserRoles.'); } // Path Params const localVarPath = '/app/rest/users/{userLocator}/roles' .replace('{' + 'userLocator' + '}', encodeURIComponent(String(userLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Roles", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } } export class UserApiResponseProcessor { /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to addRoleToUser * @throws ApiException if the response code was not in [200, 299] */ public async addRoleToUser(response: ResponseContext): Promise<Role > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Role = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Role", "" ) as Role; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Role = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Role", "" ) as Role; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to addRoleToUserAtScope * @throws ApiException if the response code was not in [200, 299] */ public async addRoleToUserAtScope(response: ResponseContext): Promise<Role > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Role = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Role", "" ) as Role; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Role = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Role", "" ) as Role; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to addUser * @throws ApiException if the response code was not in [200, 299] */ public async addUser(response: ResponseContext): Promise<User > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: User = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "User", "" ) as User; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: User = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "User", "" ) as User; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to addUserToken * @throws ApiException if the response code was not in [200, 299] */ public async addUserToken(response: ResponseContext): Promise<Token > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Token = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Token", "" ) as Token; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Token = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Token", "" ) as Token; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to deleteUser * @throws ApiException if the response code was not in [200, 299] */ public async deleteUser(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to deleteUserField * @throws ApiException if the response code was not in [200, 299] */ public async deleteUserField(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to deleteUserToken * @throws ApiException if the response code was not in [200, 299] */ public async deleteUserToken(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to gerUserField * @throws ApiException if the response code was not in [200, 299] */ public async gerUserField(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAllUserGroups * @throws ApiException if the response code was not in [200, 299] */ public async getAllUserGroups(response: ResponseContext): Promise<Groups > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Groups = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Groups", "" ) as Groups; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Groups = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Groups", "" ) as Groups; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAllUserRoles * @throws ApiException if the response code was not in [200, 299] */ public async getAllUserRoles(response: ResponseContext): Promise<Roles > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Roles = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Roles", "" ) as Roles; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Roles = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Roles", "" ) as Roles; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAllUsers * @throws ApiException if the response code was not in [200, 299] */ public async getAllUsers(response: ResponseContext): Promise<Users > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Users = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Users", "" ) as Users; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Users = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Users", "" ) as Users; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getUser * @throws ApiException if the response code was not in [200, 299] */ public async getUser(response: ResponseContext): Promise<User > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: User = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "User", "" ) as User; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: User = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "User", "" ) as User; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getUserGroup * @throws ApiException if the response code was not in [200, 299] */ public async getUserGroup(response: ResponseContext): Promise<Group > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Group = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Group", "" ) as Group; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Group = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Group", "" ) as Group; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getUserPermissions * @throws ApiException if the response code was not in [200, 299] */ public async getUserPermissions(response: ResponseContext): Promise<PermissionAssignments > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: PermissionAssignments = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "PermissionAssignments", "" ) as PermissionAssignments; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: PermissionAssignments = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "PermissionAssignments", "" ) as PermissionAssignments; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getUserProperties * @throws ApiException if the response code was not in [200, 299] */ public async getUserProperties(response: ResponseContext): Promise<Properties > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Properties = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Properties", "" ) as Properties; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Properties = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Properties", "" ) as Properties; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getUserProperty * @throws ApiException if the response code was not in [200, 299] */ public async getUserProperty(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getUserRolesAtScope * @throws ApiException if the response code was not in [200, 299] */ public async getUserRolesAtScope(response: ResponseContext): Promise<Role > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Role = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Role", "" ) as Role; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Role = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Role", "" ) as Role; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getUserTokens * @throws ApiException if the response code was not in [200, 299] */ public async getUserTokens(response: ResponseContext): Promise<Tokens > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Tokens = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Tokens", "" ) as Tokens; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Tokens = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Tokens", "" ) as Tokens; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to removeUserFromGroup * @throws ApiException if the response code was not in [200, 299] */ public async removeUserFromGroup(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to removeUserProperty * @throws ApiException if the response code was not in [200, 299] */ public async removeUserProperty(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to removeUserRememberMe * @throws ApiException if the response code was not in [200, 299] */ public async removeUserRememberMe(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to removeUserRoleAtScope * @throws ApiException if the response code was not in [200, 299] */ public async removeUserRoleAtScope(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to replaceUser * @throws ApiException if the response code was not in [200, 299] */ public async replaceUser(response: ResponseContext): Promise<User > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: User = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "User", "" ) as User; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: User = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "User", "" ) as User; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setUserField * @throws ApiException if the response code was not in [200, 299] */ public async setUserField(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setUserGroups * @throws ApiException if the response code was not in [200, 299] */ public async setUserGroups(response: ResponseContext): Promise<Groups > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Groups = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Groups", "" ) as Groups; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Groups = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Groups", "" ) as Groups; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setUserProperty * @throws ApiException if the response code was not in [200, 299] */ public async setUserProperty(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setUserRoles * @throws ApiException if the response code was not in [200, 299] */ public async setUserRoles(response: ResponseContext): Promise<Roles > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Roles = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Roles", "" ) as Roles; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Roles = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Roles", "" ) as Roles; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } } <file_sep>/ts-schema/schema/rest-api/deno/models/ProblemTarget.ts /** * TeamCity REST API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * OpenAPI spec version: 2018.1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { Problems } from './Problems.ts'; import { Tests } from './Tests.ts'; import { HttpFile } from '../http/http.ts'; export class ProblemTarget { 'anyProblem'?: boolean; 'tests'?: Tests; 'problems'?: Problems; static readonly discriminator: string | undefined = undefined; static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [ { "name": "anyProblem", "baseName": "anyProblem", "type": "boolean", "format": "" }, { "name": "tests", "baseName": "tests", "type": "Tests", "format": "" }, { "name": "problems", "baseName": "problems", "type": "Problems", "format": "" } ]; static getAttributeTypeMap() { return ProblemTarget.attributeTypeMap; } public constructor() { } } <file_sep>/ts-schema/schema/rest-api/deno/models/Compatibility.ts /** * TeamCity REST API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * OpenAPI spec version: 2018.1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { Agent } from './Agent.ts'; import { BuildType } from './BuildType.ts'; import { Requirements } from './Requirements.ts'; import { HttpFile } from '../http/http.ts'; export class Compatibility { 'compatible'?: boolean; 'agent'?: Agent; 'buildType'?: BuildType; 'unmetRequirements'?: Requirements; static readonly discriminator: string | undefined = undefined; static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [ { "name": "compatible", "baseName": "compatible", "type": "boolean", "format": "" }, { "name": "agent", "baseName": "agent", "type": "Agent", "format": "" }, { "name": "buildType", "baseName": "buildType", "type": "BuildType", "format": "" }, { "name": "unmetRequirements", "baseName": "unmetRequirements", "type": "Requirements", "format": "" } ]; static getAttributeTypeMap() { return Compatibility.attributeTypeMap; } public constructor() { } } <file_sep>/ts-schema/schema/rest-api/deno/models/ChangeLocator.ts /** * TeamCity REST API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * OpenAPI spec version: 2018.1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { HttpFile } from '../http/http.ts'; export class ChangeLocator { 'build'?: string; 'buildType'?: string; 'comment'?: string; 'count'?: number; 'file'?: string; 'id'?: number; 'internalVersion'?: string; 'item'?: string; 'pending'?: boolean; 'project'?: string; 'sinceChange'?: string; 'start'?: number; 'user'?: string; 'username'?: string; 'vcsRoot'?: string; 'vcsRootInstance'?: string; 'version'?: string; static readonly discriminator: string | undefined = undefined; static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [ { "name": "build", "baseName": "build", "type": "string", "format": "BuildLocator" }, { "name": "buildType", "baseName": "buildType", "type": "string", "format": "BuildTypeLocator" }, { "name": "comment", "baseName": "comment", "type": "string", "format": "" }, { "name": "count", "baseName": "count", "type": "number", "format": "int32" }, { "name": "file", "baseName": "file", "type": "string", "format": "" }, { "name": "id", "baseName": "id", "type": "number", "format": "int32" }, { "name": "internalVersion", "baseName": "internalVersion", "type": "string", "format": "" }, { "name": "item", "baseName": "item", "type": "string", "format": "item:(&lt;locator1&gt;),item:(&lt;locator2&gt;...)" }, { "name": "pending", "baseName": "pending", "type": "boolean", "format": "" }, { "name": "project", "baseName": "project", "type": "string", "format": "ProjectLocator" }, { "name": "sinceChange", "baseName": "sinceChange", "type": "string", "format": "" }, { "name": "start", "baseName": "start", "type": "number", "format": "int32" }, { "name": "user", "baseName": "user", "type": "string", "format": "UserLocator" }, { "name": "username", "baseName": "username", "type": "string", "format": "" }, { "name": "vcsRoot", "baseName": "vcsRoot", "type": "string", "format": "VcsRootLocator" }, { "name": "vcsRootInstance", "baseName": "vcsRootInstance", "type": "string", "format": "VcsRootInstanceLocator" }, { "name": "version", "baseName": "version", "type": "string", "format": "" } ]; static getAttributeTypeMap() { return ChangeLocator.attributeTypeMap; } public constructor() { } } <file_sep>/ts-schema/schema/rest-api/deno/models/Problem.ts /** * TeamCity REST API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * OpenAPI spec version: 2018.1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { Investigations } from './Investigations.ts'; import { Mutes } from './Mutes.ts'; import { ProblemOccurrences } from './ProblemOccurrences.ts'; import { HttpFile } from '../http/http.ts'; export class Problem { 'id'?: string; 'type'?: string; 'identity'?: string; 'href'?: string; 'description'?: string; 'mutes'?: Mutes; 'investigations'?: Investigations; 'problemOccurrences'?: ProblemOccurrences; 'locator'?: string; static readonly discriminator: string | undefined = undefined; static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [ { "name": "id", "baseName": "id", "type": "string", "format": "" }, { "name": "type", "baseName": "type", "type": "string", "format": "" }, { "name": "identity", "baseName": "identity", "type": "string", "format": "" }, { "name": "href", "baseName": "href", "type": "string", "format": "" }, { "name": "description", "baseName": "description", "type": "string", "format": "" }, { "name": "mutes", "baseName": "mutes", "type": "Mutes", "format": "" }, { "name": "investigations", "baseName": "investigations", "type": "Investigations", "format": "" }, { "name": "problemOccurrences", "baseName": "problemOccurrences", "type": "ProblemOccurrences", "format": "" }, { "name": "locator", "baseName": "locator", "type": "string", "format": "" } ]; static getAttributeTypeMap() { return Problem.attributeTypeMap; } public constructor() { } } <file_sep>/ts-schema/schema/builders/project.ts import * as x from "../xml/mod.ts"; import * as j from "../json/mod.ts"; import { vcsRootBuilder } from "./vcs_root.ts"; import { buildTypeBuilder } from "./build_type.ts"; import { parameterBuilder } from "./parameter.ts"; import { projectCleanupBuilder } from "./project_cleanup.ts"; import { projectExtensionBuilder } from "./project_extension.ts"; import * as uuid from "https://deno.land/std@0.96.0/uuid/mod.ts"; export interface ProjectFiles { projectConfig: [string, x.Project]; vcsRoots: Record<string, x.VcsRoot>; buildTypes: Record<string, x.BuildType>; } export function projectBuilder(input: j.Project): ProjectFiles { const vcsRoots: Record<string, x.VcsRoot> = {}; for (const item of input.vcsRoots ?? []) { vcsRoots[`.teamcity/${input.id}/vcsRoots/${item.id}.xml`] = vcsRootBuilder( item, ); } const buildTypes: Record<string, x.BuildType> = {}; for (const item of input.buildTypes ?? []) { buildTypes[`.teamcity/${input.id}/buildTypes/${item.id}.xml`] = buildTypeBuilder( item, ); } let parameters: x.Parameters | undefined = undefined; if (typeof input.parameters !== "undefined") { parameters = { param: [] }; for (const p of input.parameters) { parameters.param.push(parameterBuilder(p)); } } let extensions: x.ProjectExtensions | undefined = undefined; if (typeof input.extensions !== "undefined") { extensions = { extension: [] }; for (const e of input.extensions) { extensions.extension.push(projectExtensionBuilder(e)); } } let cleanup: x.ProjectCleanup | undefined = undefined; if (typeof input.cleanUp !== "undefined") { cleanup = projectCleanupBuilder(input.cleanUp); } return { projectConfig: [`.teamcity/${input.id}/project-config.xml`, { "?xml": { "@version": "1.0", "@encoding": "UTF-8" }, project: { "@xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance", "@xsi:noNamespaceSchemaLocation": "https://www.jetbrains.com/teamcity/schemas/2020.1/project-config.xsd", "@uuid": input.uuid ?? uuid.v4.generate(), name: input.name, description: input.description, parameters, "project-extensions": extensions, cleanup, }, }], vcsRoots, buildTypes, }; } <file_sep>/ts-schema/schema/builders/vcs_root.ts import * as x from "../xml/mod.ts"; import * as j from "../json/mod.ts"; import * as uuid from "https://deno.land/std@0.96.0/uuid/mod.ts"; export function vcsRootBuilder(input: j.VcsRoot): x.VcsRoot { let param: x.Parameter[]; switch (input.type) { case "jetbrains.git": param = gitVcsRoot(input); break; case "cvs": param = cvsVcsRoot(input); break; case "mercurial": param = mercurialVcsRoot(input); break; case "perforce": param = perforceVcsRoot(input); break; case "starteam": param = starteamVcsRoot(input); break; case "svn": param = svnVcsRoot(input); break; case "tfs": param = tfsVcsRoot(input); break; default: throw new Error("unsupported vcs root type"); } return { "?xml": { "@version": "1.0", "@encoding": "UTF-8" }, "vcs-root": { "@xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance", "@xsi:noNamespaceSchemaLocation": "https://www.jetbrains.com/teamcity/schemas/2020.1/project-config.xsd", "@type": input.type, "@uuid": input.uuid ?? uuid.v4.generate(), "modification-check-interval": input.type === "jetbrains.git" ? input.modificationCheckInterval : undefined, name: input.name, param, }, }; } function gitVcsRoot(input: j.VcsRootGit): x.Parameter[] { const output: x.Parameter[] = []; output.push({ "@name": "url", "@value": input.url, }); if (typeof input.pushUrl !== "undefined") { output.push({ "@name": "pushUrl", "@value": input.pushUrl, }); } output.push({ "@name": "branch", "@value": input.branch ?? "refs/heads/master", }); if (typeof input.branchSpec !== "undefined") { output.push({ "@name": "teamcity:branchSpec", "#text": input.branchSpec.join("\n"), }); } output.push({ "@name": "reportTagRevisions", "@value": input?.reportTagRevisions ? "true" : "false", }); output.push({ "@name": "usernameStyle", "@value": input?.usernameStyle ?? "USERID", }); output.push({ "@name": "submoduleCheckout", "@value": input?.submoduleCheckout ? "true" : "false", }); if (typeof input.userForTags !== "undefined") { output.push({ "@name": "userForTags", "@value": input.userForTags, }); } output.push({ "@name": "serverSideAutoCrlf", "@value": input?.serverSideAutoCrlf ? "true" : "false", }); if (typeof input.agentGitPath !== "undefined") { output.push({ "@name": "agentGitPath", "@value": input.agentGitPath, }); } output.push({ "@name": "agentCleanPolicy", "@value": input?.agentCleanPolicy ?? "ALWAYS", }); output.push({ "@name": "agentCleanFilesPolicy", "@value": input?.agentCleanFilesPolicy ?? "ALL_UNTRACKED", }); if (typeof input.useAlternates !== "undefined") { output.push({ "@name": "useAlternates", "@value": input.useAlternates ? "true" : "false", }); } else { output.push({ "@name": "useAlternates", "@value": "true", }); } /** * TODO: Strange this appears in the XML but no where in the docs or in the * UI as far as I can tell. Perhaps an old deprecated feature? I mean who * would set this to true anyway... */ output.push({ "@name": "ignoreKnownHosts", "@value": input?.ignoreKnownHosts ? "true" : "false", }); output.push({ "@name": "authMethod", "@value": input.auth.type, }); // deno-lint-ignore no-explicit-any const username = (input.auth as any).username as string | undefined; if (typeof username === "string") { output.push({ "@name": "username", "@value": username, }); } switch (input.auth.type) { case "ANONYMOUS": case "PRIVATE_KEY_DEFAULT": // nothing to do here break; case "PASSWORD": output.push({ "@name": "secure:password", "@value": input.auth.secret, }); break; case "PRIVATE_KEY_FILE": output.push({ "@name": "privateKeyPath", "@value": input.auth.path, }); if (typeof input.auth.passphrase !== "undefined") { output.push({ "@name": "secure:passphrase", "@value": input.auth.passphrase, }); } break; case "TEAMCITY_SSH_KEY": output.push({ "@name": "teamcitySshKey", "@value": input.auth.keyName, }); break; default: throw new Error("unsupported auth type"); } return output; } /** TODO: placeholder for cvs converter */ function cvsVcsRoot(input: j.VcsRootCvs): x.Parameter[] { return []; } /** TODO: placeholder mercurial converter */ function mercurialVcsRoot(input: j.VcsRootMercurial): x.Parameter[] { return []; } /** TODO: placeholder for perforce converter */ function perforceVcsRoot(input: j.VcsRootPerforce): x.Parameter[] { return []; } /** TODO: placeholder for starteam converter */ function starteamVcsRoot(input: j.VcsRootStarTeam): x.Parameter[] { return []; } /** TODO: placeholder for svn converter */ function svnVcsRoot(input: j.VcsRootSvn): x.Parameter[] { return []; } /** TODO: placeholder for tfs converter */ function tfsVcsRoot(input: j.VcsRootTfs): x.Parameter[] { return []; } <file_sep>/ts-schema/schema/builders/parameter.ts import * as x from "../xml/mod.ts"; import * as j from "../json/mod.ts"; export function parameterBuilder(input: j.Parameter): x.Parameter { const p: Partial<x.Parameter> = { "@name": input.name }; // TeamCity often uses newlines as separators for lists of things, in such // cases we set the value to the XML nodes inner content instead of to a // value attribute. The XML Writer will insert CDATA tags as required. if (input.value.includes("\n")) { p["#text"] = input.value; } else { p["@value"] = input.value; } if (typeof input.spec !== "undefined") { p["@spec"] = specBuilder(input.spec); } return p as x.Parameter; } /** TODO: escape quotes??? */ function specBuilder(input: j.ParameterSpec): string { let output = `${input.type} `; if (typeof input.label === "string") { output += `label='${input.label}' `; } if (typeof input.display === "string") { output += `display='${input.display}' `; } if (typeof input.description === "string") { output += `description='${input.description}' `; } if (typeof input.readOnly === "boolean" && input.readOnly) { output += `readOnly='true' `; } switch (input.type) { case "password": // Nothing to do here break; case "text": output += `validationMode='${input?.validationMode ?? "any"}' `; if (typeof input.validationMessage === "string") { output += `validationMessage='${input.validationMessage}' `; } if (input?.validationMode === "regex") { if (typeof input?.regexp !== "string") { throw new Error("validationMode=regex but no regex has been set"); } output += `regexp='${input.regexp}' `; } break; case "checkbox": output += `checkedValue='${input.checkedValue}' `; if (typeof input.uncheckedValue === "string") { output += `uncheckedValue='${input.uncheckedValue}' `; } break; case "select": { if (typeof input.multiple === "boolean" && input.multiple) { output += `multiple='true' `; } if (typeof input.valueSeparator === "string") { output += `valueSeparator='${input.valueSeparator}' `; } const data = Array.isArray(input.items) ? input.items : Object.values(input.items); data.forEach((v, i) => { output += `data_${i++}='${v}' `; }); if (!Array.isArray(input.items)) { Object.keys(input.items).forEach((v, i) => { output += `label_${i++}='${v}' `; }); } break; } default: throw new Error("unsupported parameter spec type"); } return output.trimEnd(); } <file_sep>/ts-schema/schema/unique_array.ts // credit: https://ja.nsommer.dk/articles/type-checked-unique-arrays.html export type InArray<T, X> = // See if X is the first element in array T T extends readonly [X, ...infer _Rest] ? true : // If not, is X the only element in T? T extends readonly [X] ? true : // No match, check if there's any elements left in T and loop recursive T extends readonly [infer _, ...infer Rest] ? InArray<Rest, X> : // There's nothing left in the array and we found no match false; export type UniqueArray<T> = T extends readonly [infer X, ...infer Rest] ? // We've just extracted X from T, having Rest be the remaining values. // Let's see if X is in Rest, and if it is, we know we have a duplicate InArray<Rest, X> extends true ? ["Encountered value with duplicates:", X] : // X is not duplicated, move on to check the next value, and see if that's also unique. readonly [X, ...UniqueArray<Rest>] : // T did not extend [X, ...Rest], so there's nothing to do - just return T T; <file_sep>/ts-schema/schema/json/vcs_root.ts /** * A VCS root in TeamCity defines a connection to a version control system. * It represents a set of parameters (paths to sources, username, password, * and other settings) that determine how TeamCity communicates with a VCS * to monitor changes and get sources for a build. * * VCS roots are created in a project and are available to all the build * configurations defined in that project or its subprojects. One or more * VCS roots can be attached to a build configuration or a template. * * You can specify portions of the repository to check out and target paths * via VCS checkout rules. * * see: https://www.jetbrains.com/help/teamcity/vcs-root.html */ export type VcsRoot = | VcsRootCvs | VcsRootGit | VcsRootMercurial | VcsRootPerforce | VcsRootStarTeam | VcsRootSvn | VcsRootTfs; export interface VcsRootBase { /** * This refers to the filename of the generated XML file stored in the * .teamcity folder of your repo & ultimately the server's Data Directory. * see: https://www.jetbrains.com/help/teamcity/teamcity-data-directory.html * * For example an id of `Abc_Xyz123` results in the file * `./.teamcity/MyProject/vcsRoots/Abc_Xyz123.xml` being generated. * * This id is also used as a reference in many places * throughout the rest of this schema & for URLs, etc... * * see: https://www.jetbrains.com/help/teamcity/2020.2/identifier.html * * > HINT: ID should start with a latin letter and contain only latin letters, * digits and underscores (at most 225 characters). */ id: string; /** * This value is used as an attribute on the root XML object. It only appears * to be used internally by TeamCity. Hence this is optional and will be * generated for you if you do not explicitly define a value. * * see: https://www.jetbrains.com/help/teamcity/2020.2/identifier.html#Universally+Unique+IDs * * > NOTE: Despite what the docs say, TeamCity does not appear to automatically * > populate the UUID field for you but also doesn't seem to mind that it * > doesn't exist, go figure... */ uuid?: string; /** * A human friendly name for the project. */ name: string; } export interface VcsRootGit extends VcsRootBase { /** * Uses git as the version control system. * * see: https://www.jetbrains.com/help/teamcity/2020.2/git.html */ type: "jetbrains.git"; /** * The URL of the remote Git repository used for fetching data from the repository. */ url: string; /** * The URL of the target remote Git repository used for pushing annotated * tags created via VCS labeling build feature to the remote repository. * If blank, the fetch URL is used. */ pushUrl?: string; /** * Configures default branch. Parameter references are supported here. * * Defaults to: `refs/heads/master` */ branch?: string; /** * Lists the patterns for branch names, required for feature branches support. * The matched branches are monitored for changes in addition to the default branch. * * The syntax is similar to checkout rules: +|-:branch_name, where branch_name * is specific to the VCS, i.e. refs/heads/ in Git (with the optional * placeholder). */ branchSpec?: string[]; /** * Allows monitoring / checking out git tags as branches making branch * specification match tag names as well as branches. * * For example: `+|-:refs/tags/<tag_name>` * * Defaults to: `false`. */ reportTagRevisions?: boolean; /** * Defines a way TeamCity reports username for a VCS change. * * Changing the username style will affect only newly collected changes. * Old changes will continue to be stored with the style that was active * at the time of collecting changes. * * Defaults to: `USERID`. */ usernameStyle?: "FULL" | "NAME" | "USERID" | "EMAIL"; /** * Select whether you want to ignore the submodules, or treat them as a part * of the source tree. Submodule repositories should either not require * authentication or use the same protocol and accept the same authentication * as configured in the VCS root. * * Defaults to: `false`. */ submoduleCheckout?: boolean; /** * A custom username used for labeling. * * Format: `Username <email>` * * This is essentially setting: `user.name` & `user.email` * TeamCity will use this identity for any commits it * makes back to this repo. */ userForTags?: string; /** * The authentication method that TeamCity will use to interact with the repo. * * see: https://www.jetbrains.com/help/teamcity/2020.2/git.html#Authentication+Settings */ auth: AuthMethod; /** * Convert line-endings of all text files to CRLF (works as setting * `core.autocrlf=true` in a repository config). * * When not selected, no line-endings conversion is performed (works as * setting `core.autocrlf=false`). * * Affects the server-side checkout only. * * A change to this property causes a clean checkout. * * see: https://www.jetbrains.com/help/teamcity/2020.2/git.html#Server+Settings * * Defaults to: `false`. */ serverSideAutoCrlf?: boolean; /** * Provide the path to a Git executable to be used on the agent. * * When set to `%env.TEAMCITY_GIT_PATH%`, the automatically detected * Git will be used. * * see: https://www.jetbrains.com/help/teamcity/2020.2/git.html#agentGitPath */ agentGitPath?: string; /** * Specify here when the `git clean` command is to run on the agent, * and which files are to be removed. * * If a build configuration depends on multiple VCS roots, we suggest that * you configure separate agent checkout directories for each of these roots, * using VCS checkout rules. * * This way, `git clean` will never delete these checkout directories during cleaning. * * Defaults to: `ALWAYS`. * * see: https://www.jetbrains.com/help/teamcity/2020.2/git.html#GitAgentSettings */ agentCleanPolicy?: "ALWAYS" | "NEVER" | "ON_BRANCH_CHANGE"; /** * This option specifies which files will be removed when `git clean` command is run on agent. * * Defaults to: `ALL_UNTRACKED`. */ agentCleanFilesPolicy?: "ALL_UNTRACKED" | "IGNORED_ONLY" | "NON_IGNORED_ONLY"; /** * It is recommended to always leave this option enabled. * * When enabled (default), TeamCity clones the Git repository and creates its * mirror under the agent's `system\git` directory. TeamCity uses this mirror * as an alternate repository when updating the checkout directory for a build. * * This speeds up clean checkout (because only the build working directory is * cleaned) and saves disk space (as the mirror is the only clone of the given * Git repository on an agent). * * If you disable this option, TeamCity will clone the repository directly * under the build's working directory, unless the `teamcity.git.use.local.mirrors` * property is set to `true`. * * see: https://www.jetbrains.com/help/teamcity/2020.2/git.html#Git+mirrors+on+cloud+agents */ useAlternates?: boolean; /** * Specifies how often TeamCity polls the VCS repository for VCS changes. * * By default, the global predefined server setting is used that can be * modified on the `Administration | Global Settings` page. * * The interval time starts as soon as the last poll is finished on the * per-VCS root basis. Here you can specify a custom interval for the * current VCS root. * * Some public servers may block access if polled too frequently. * * If TeamCity detects that a VCS commit hook is used to trigger checking for * changes, this interval is automatically increased up to the predefined * value (4 hours). * * If the periodical check finds changes undetected via the commit hook, * the polling interval is reset to the specified minimum. * * see: https://www.jetbrains.com/help/teamcity/2020.2/configuring-vcs-roots.html#Common+VCS+Root+Properties * also: https://www.jetbrains.com/help/teamcity/2020.2/configuring-vcs-post-commit-hooks-for-teamcity.html */ modificationCheckInterval?: number; /** * TODO: Strange this appears in the XML but no where in the docs or in the * UI as far as I can tell. Perhaps an old deprecated feature? I mean who * would set this to true anyway... */ ignoreKnownHosts?: boolean; } export type AuthMethod = | AuthMethodAnonymous | AuthMethodPassword | AuthMethodSshKey | AuthMethodDefaultSshKey | AuthMethodCustomSshKey; export interface AuthMethodAnonymous { /** * Select this option to clone a repository with anonymous read access. */ type: "ANONYMOUS"; } export interface AuthMethodPassword { /** * Specify a valid username (if there is no username in the clone URL; the * username specified here overrides the username from the URL) and a password * to be used to clone the repository. * * For the agent-side checkout, it is supported only if Git 1.7.3+ client is * installed on the agent. See TW-18711. * * For Git hosted from Team Foundation Server 2013, specify NTLM credentials here. * * You can use a personal access token instead of a password to authenticate * in GitHub, Azure DevOps Services, GitLab, and Bitbucket. * * Note that TeamCity does not support token authentication to hosted * Azure DevOps Server (formerly, Team Foundation Server) installations. * * Beginning August 13, 2021, GitHub will no longer accept passwords when * authenticating Git operations on GitHub.com. We highly recommend that you * use an access token or SSH key instead of password when configuring a * VCS root for a GitHub.com repository. */ type: "PASSWORD"; /** * Specify the username if there is no username in the clone URL. * The username specified here overrides the username from the URL. */ username?: string; /** * This can be a password or a bearer token. * * > HINT: If you really truly do not want to use a `credentialsJSON` pointer * > here, instead preferring a password parameter you can still do that but * > you will have to cast the string. This is hard on purpose, you should * > always prefer `credentialsJSON` over a parameter with a password spec. */ secret: `credentialsJSON:${string}`; } export interface AuthMethodSshKey { /** * This refers to an uploaded SSH key. * * see: https://www.jetbrains.com/help/teamcity/2020.2/ssh-keys-management.html#SSH+Key+Usage */ type: "TEAMCITY_SSH_KEY"; /** * Specify the username if there is no username in the clone URL. * The username specified here overrides the username from the URL. */ username?: string; /** * The name of the uploaded SSH key. */ keyName: string; } export interface AuthMethodDefaultSshKey { /** * Uses the keys available on the file system in the default locations used * by common ssh tools. * * The mapping specified in <USER_HOME>/.ssh/config if the file exists or * the private key file <USER_HOME>/.ssh/id_rsa. * * The files are required to be present on the server and * also on the agent if the agent-side checkout is used. */ type: "PRIVATE_KEY_DEFAULT"; /** * Specify the username if there is no username in the clone URL. * The username specified here overrides the username from the URL. */ username?: string; } export interface AuthMethodCustomSshKey { /** * Supported only for server-side checkout. * * When this method is used, fill the Private Key Path field with an absolute * path to the private key file on the server machine. If required, specify * the passphrase to access your SSH key in the corresponding field. */ type: "PRIVATE_KEY_FILE"; /** * Specify the username if there is no username in the clone URL. * The username specified here overrides the username from the URL. */ username?: string; /** * Specify the path to the private key on the TeamCity server host. */ path: string; /** * An optional passphrase to upload the custom key. * * > HINT: If you really truly do not want to use a `credentialsJSON` pointer * > here, instead preferring a password parameter you can still do that but * > you will have to cast the string. This is hard on purpose, you should * > always prefer `credentialsJSON` over a parameter with a password spec. */ passphrase?: `<PASSWORD>:${string}`; } /** TODO: placeholder for cvs typings */ export interface VcsRootCvs extends VcsRootBase { type: "cvs"; } /** TODO: placeholder for mercurial typings */ export interface VcsRootMercurial extends VcsRootBase { type: "mercurial"; } /** TODO: placeholder for perforce typings */ export interface VcsRootPerforce extends VcsRootBase { type: "perforce"; } /** TODO: placeholder for starteam typings */ export interface VcsRootStarTeam extends VcsRootBase { type: "starteam"; } /** TODO: placeholder for svn typings */ export interface VcsRootSvn extends VcsRootBase { type: "svn"; } /** TODO: placeholder for tfs typings */ export interface VcsRootTfs extends VcsRootBase { type: "tfs"; } <file_sep>/ts-schema/schema/builders/build_type.ts import * as x from "../xml/mod.ts"; import * as j from "../json/mod.ts"; import * as uuid from "https://deno.land/std@0.96.0/uuid/mod.ts"; export function buildTypeBuilder(input: j.BuildType): x.BuildType { return { "?xml": { "@version": "1.0", "@encoding": "UTF-8" }, "build-type": { "@xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance", "@xsi:noNamespaceSchemaLocation": "https://www.jetbrains.com/teamcity/schemas/2020.1/project-config.xsd", "@uuid": input.uuid ?? uuid.v4.generate(), name: input.name, description: input.description, settings: {}, }, }; } // buildConfigurationType?: "REGULAR" | "DEPLOYMENT" | "COMPOSITE"; // the absense of this means it's a "REGULAR" type<file_sep>/ts-schema/schema/rest-api/deno/models/RelatedEntity.ts /** * TeamCity REST API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * OpenAPI spec version: 2018.1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { Agent } from './Agent.ts'; import { AgentPool } from './AgentPool.ts'; import { Build } from './Build.ts'; import { BuildType } from './BuildType.ts'; import { Change } from './Change.ts'; import { Group } from './Group.ts'; import { Problem } from './Problem.ts'; import { Project } from './Project.ts'; import { Test } from './Test.ts'; import { User } from './User.ts'; import { VcsRoot } from './VcsRoot.ts'; import { HttpFile } from '../http/http.ts'; export class RelatedEntity { 'type'?: string; 'unknown'?: boolean; 'internalId'?: string; 'text'?: string; 'build'?: Build; 'buildType'?: BuildType; 'project'?: Project; 'user'?: User; 'group'?: Group; 'test'?: Test; 'problem'?: Problem; 'agent'?: Agent; 'vcsRoot'?: VcsRoot; 'change'?: Change; 'agentPool'?: AgentPool; static readonly discriminator: string | undefined = undefined; static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [ { "name": "type", "baseName": "type", "type": "string", "format": "" }, { "name": "unknown", "baseName": "unknown", "type": "boolean", "format": "" }, { "name": "internalId", "baseName": "internalId", "type": "string", "format": "" }, { "name": "text", "baseName": "text", "type": "string", "format": "" }, { "name": "build", "baseName": "build", "type": "Build", "format": "" }, { "name": "buildType", "baseName": "buildType", "type": "BuildType", "format": "" }, { "name": "project", "baseName": "project", "type": "Project", "format": "" }, { "name": "user", "baseName": "user", "type": "User", "format": "" }, { "name": "group", "baseName": "group", "type": "Group", "format": "" }, { "name": "test", "baseName": "test", "type": "Test", "format": "" }, { "name": "problem", "baseName": "problem", "type": "Problem", "format": "" }, { "name": "agent", "baseName": "agent", "type": "Agent", "format": "" }, { "name": "vcsRoot", "baseName": "vcsRoot", "type": "VcsRoot", "format": "" }, { "name": "change", "baseName": "change", "type": "Change", "format": "" }, { "name": "agentPool", "baseName": "agentPool", "type": "AgentPool", "format": "" } ]; static getAttributeTypeMap() { return RelatedEntity.attributeTypeMap; } public constructor() { } } <file_sep>/ts-schema/schema/xor.ts /** * Get the keys of T without any keys of U. */ export type Without<T, U> = { [P in Exclude<keyof T, keyof U>]?: never; }; /** * Restrict using either exclusively the keys of T or exclusively the keys of U. * * No unique keys of T can be used simultaneously with any unique keys of U. * * Example: * `const myVar: XOR<T, U>` * * More: https://github.com/maninak/ts-xor/tree/master#description */ export type XOR<T, U> = (T | U) extends Record<string, unknown> ? (Without<T, U> & U) | (Without<U, T> & T) : T | U; /** * see: https://github.com/microsoft/TypeScript/issues/14094#issuecomment-723571692 */ export type AllXOR<T extends unknown[]> = T extends [infer Only] ? Only : T extends [infer A, infer B, ...infer Rest] ? AllXOR<[XOR<A, B>, ...Rest]> : never; <file_sep>/ts-schema/schema/rest-api/deno/apis/ServerApi.ts // TODO: better import syntax? import { BaseAPIRequestFactory, RequiredError } from './baseapi.ts'; import {Configuration} from '../configuration.ts'; import { RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http.ts'; import {ObjectSerializer} from '../models/ObjectSerializer.ts'; import {ApiException} from './exception.ts'; import {isCodeInRange} from '../util.ts'; import { Files } from '../models/Files.ts'; import { LicenseKey } from '../models/LicenseKey.ts'; import { LicenseKeys } from '../models/LicenseKeys.ts'; import { LicensingData } from '../models/LicensingData.ts'; import { Metrics } from '../models/Metrics.ts'; import { Plugins } from '../models/Plugins.ts'; import { Server } from '../models/Server.ts'; /** * no description */ export class ServerApiRequestFactory extends BaseAPIRequestFactory { /** * Add license keys. * @param fields * @param body */ public async addLicenseKeys(fields?: string, body?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/server/licensingData/licenseKeys'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "text/plain" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "string", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Delete a license key. * @param licenseKey */ public async deleteLicenseKey(licenseKey: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'licenseKey' is not null or undefined if (licenseKey === null || licenseKey === undefined) { throw new RequiredError('Required parameter licenseKey was null or undefined when calling deleteLicenseKey.'); } // Path Params const localVarPath = '/app/rest/server/licensingData/licenseKeys/{licenseKey}' .replace('{' + 'licenseKey' + '}', encodeURIComponent(String(licenseKey))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Download specific file. * @param path * @param areaId */ public async downloadFileOfServer(path: string, areaId: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'path' is not null or undefined if (path === null || path === undefined) { throw new RequiredError('Required parameter path was null or undefined when calling downloadFileOfServer.'); } // verify required parameter 'areaId' is not null or undefined if (areaId === null || areaId === undefined) { throw new RequiredError('Required parameter areaId was null or undefined when calling downloadFileOfServer.'); } // Path Params const localVarPath = '/app/rest/server/files/{areaId}/files{path}' .replace('{' + 'path' + '}', encodeURIComponent(String(path))) .replace('{' + 'areaId' + '}', encodeURIComponent(String(areaId))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get metrics. * @param fields */ public async getAllMetrics(fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/server/metrics'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all plugins. * @param fields */ public async getAllPlugins(fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/server/plugins'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get the latest backup status. */ public async getBackupStatus(options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/server/backup'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get metadata of specific file. * @param path * @param areaId * @param fields */ public async getFileMetadataOfServer(path: string, areaId: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'path' is not null or undefined if (path === null || path === undefined) { throw new RequiredError('Required parameter path was null or undefined when calling getFileMetadataOfServer.'); } // verify required parameter 'areaId' is not null or undefined if (areaId === null || areaId === undefined) { throw new RequiredError('Required parameter areaId was null or undefined when calling getFileMetadataOfServer.'); } // Path Params const localVarPath = '/app/rest/server/files/{areaId}/metadata{path}' .replace('{' + 'path' + '}', encodeURIComponent(String(path))) .replace('{' + 'areaId' + '}', encodeURIComponent(String(areaId))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * List files under this path. * @param path * @param areaId * @param basePath * @param locator * @param fields */ public async getFilesListForSubpathOfServer(path: string, areaId: string, basePath?: string, locator?: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'path' is not null or undefined if (path === null || path === undefined) { throw new RequiredError('Required parameter path was null or undefined when calling getFilesListForSubpathOfServer.'); } // verify required parameter 'areaId' is not null or undefined if (areaId === null || areaId === undefined) { throw new RequiredError('Required parameter areaId was null or undefined when calling getFilesListForSubpathOfServer.'); } // Path Params const localVarPath = '/app/rest/server/files/{areaId}/{path}' .replace('{' + 'path' + '}', encodeURIComponent(String(path))) .replace('{' + 'areaId' + '}', encodeURIComponent(String(areaId))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (basePath !== undefined) { requestContext.setQueryParam("basePath", ObjectSerializer.serialize(basePath, "string", "")); } if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "")); } if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * List all files. * @param areaId * @param basePath * @param locator * @param fields */ public async getFilesListOfServer(areaId: string, basePath?: string, locator?: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'areaId' is not null or undefined if (areaId === null || areaId === undefined) { throw new RequiredError('Required parameter areaId was null or undefined when calling getFilesListOfServer.'); } // Path Params const localVarPath = '/app/rest/server/files/{areaId}' .replace('{' + 'areaId' + '}', encodeURIComponent(String(areaId))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (basePath !== undefined) { requestContext.setQueryParam("basePath", ObjectSerializer.serialize(basePath, "string", "")); } if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "")); } if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get a license key. * @param licenseKey * @param fields */ public async getLicenseKey(licenseKey: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'licenseKey' is not null or undefined if (licenseKey === null || licenseKey === undefined) { throw new RequiredError('Required parameter licenseKey was null or undefined when calling getLicenseKey.'); } // Path Params const localVarPath = '/app/rest/server/licensingData/licenseKeys/{licenseKey}' .replace('{' + 'licenseKey' + '}', encodeURIComponent(String(licenseKey))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all license keys. * @param fields */ public async getLicenseKeys(fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/server/licensingData/licenseKeys'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get the licensing data. * @param fields */ public async getLicensingData(fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/server/licensingData'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get a field of the server info. * @param field */ public async getServerField(field: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'field' is not null or undefined if (field === null || field === undefined) { throw new RequiredError('Required parameter field was null or undefined when calling getServerField.'); } // Path Params const localVarPath = '/app/rest/server/{field}' .replace('{' + 'field' + '}', encodeURIComponent(String(field))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get the server info. * @param fields */ public async getServerInfo(fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/server'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get specific file zipped. * @param path * @param areaId * @param basePath * @param locator * @param name */ public async getZippedFileOfServer(path: string, areaId: string, basePath?: string, locator?: string, name?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'path' is not null or undefined if (path === null || path === undefined) { throw new RequiredError('Required parameter path was null or undefined when calling getZippedFileOfServer.'); } // verify required parameter 'areaId' is not null or undefined if (areaId === null || areaId === undefined) { throw new RequiredError('Required parameter areaId was null or undefined when calling getZippedFileOfServer.'); } // Path Params const localVarPath = '/app/rest/server/files/{areaId}/archived{path}' .replace('{' + 'path' + '}', encodeURIComponent(String(path))) .replace('{' + 'areaId' + '}', encodeURIComponent(String(areaId))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (basePath !== undefined) { requestContext.setQueryParam("basePath", ObjectSerializer.serialize(basePath, "string", "")); } if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "")); } if (name !== undefined) { requestContext.setQueryParam("name", ObjectSerializer.serialize(name, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Start a new backup. * @param fileName * @param addTimestamp * @param includeConfigs * @param includeDatabase * @param includeBuildLogs * @param includePersonalChanges * @param includeRunningBuilds * @param includeSupplimentaryData */ public async startBackup(fileName?: string, addTimestamp?: boolean, includeConfigs?: boolean, includeDatabase?: boolean, includeBuildLogs?: boolean, includePersonalChanges?: boolean, includeRunningBuilds?: boolean, includeSupplimentaryData?: boolean, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/server/backup'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fileName !== undefined) { requestContext.setQueryParam("fileName", ObjectSerializer.serialize(fileName, "string", "")); } if (addTimestamp !== undefined) { requestContext.setQueryParam("addTimestamp", ObjectSerializer.serialize(addTimestamp, "boolean", "")); } if (includeConfigs !== undefined) { requestContext.setQueryParam("includeConfigs", ObjectSerializer.serialize(includeConfigs, "boolean", "")); } if (includeDatabase !== undefined) { requestContext.setQueryParam("includeDatabase", ObjectSerializer.serialize(includeDatabase, "boolean", "")); } if (includeBuildLogs !== undefined) { requestContext.setQueryParam("includeBuildLogs", ObjectSerializer.serialize(includeBuildLogs, "boolean", "")); } if (includePersonalChanges !== undefined) { requestContext.setQueryParam("includePersonalChanges", ObjectSerializer.serialize(includePersonalChanges, "boolean", "")); } if (includeRunningBuilds !== undefined) { requestContext.setQueryParam("includeRunningBuilds", ObjectSerializer.serialize(includeRunningBuilds, "boolean", "")); } if (includeSupplimentaryData !== undefined) { requestContext.setQueryParam("includeSupplimentaryData", ObjectSerializer.serialize(includeSupplimentaryData, "boolean", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } } export class ServerApiResponseProcessor { /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to addLicenseKeys * @throws ApiException if the response code was not in [200, 299] */ public async addLicenseKeys(response: ResponseContext): Promise<LicenseKeys > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: LicenseKeys = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "LicenseKeys", "" ) as LicenseKeys; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: LicenseKeys = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "LicenseKeys", "" ) as LicenseKeys; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to deleteLicenseKey * @throws ApiException if the response code was not in [200, 299] */ public async deleteLicenseKey(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to downloadFileOfServer * @throws ApiException if the response code was not in [200, 299] */ public async downloadFileOfServer(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAllMetrics * @throws ApiException if the response code was not in [200, 299] */ public async getAllMetrics(response: ResponseContext): Promise<Metrics > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Metrics = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Metrics", "" ) as Metrics; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Metrics = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Metrics", "" ) as Metrics; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAllPlugins * @throws ApiException if the response code was not in [200, 299] */ public async getAllPlugins(response: ResponseContext): Promise<Plugins > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Plugins = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Plugins", "" ) as Plugins; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Plugins = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Plugins", "" ) as Plugins; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBackupStatus * @throws ApiException if the response code was not in [200, 299] */ public async getBackupStatus(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getFileMetadataOfServer * @throws ApiException if the response code was not in [200, 299] */ public async getFileMetadataOfServer(response: ResponseContext): Promise<any > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: any = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "any", "" ) as any; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: any = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "any", "" ) as any; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getFilesListForSubpathOfServer * @throws ApiException if the response code was not in [200, 299] */ public async getFilesListForSubpathOfServer(response: ResponseContext): Promise<Files > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Files = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Files", "" ) as Files; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Files = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Files", "" ) as Files; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getFilesListOfServer * @throws ApiException if the response code was not in [200, 299] */ public async getFilesListOfServer(response: ResponseContext): Promise<Files > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Files = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Files", "" ) as Files; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Files = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Files", "" ) as Files; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getLicenseKey * @throws ApiException if the response code was not in [200, 299] */ public async getLicenseKey(response: ResponseContext): Promise<LicenseKey > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: LicenseKey = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "LicenseKey", "" ) as LicenseKey; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: LicenseKey = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "LicenseKey", "" ) as LicenseKey; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getLicenseKeys * @throws ApiException if the response code was not in [200, 299] */ public async getLicenseKeys(response: ResponseContext): Promise<LicenseKeys > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: LicenseKeys = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "LicenseKeys", "" ) as LicenseKeys; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: LicenseKeys = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "LicenseKeys", "" ) as LicenseKeys; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getLicensingData * @throws ApiException if the response code was not in [200, 299] */ public async getLicensingData(response: ResponseContext): Promise<LicensingData > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: LicensingData = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "LicensingData", "" ) as LicensingData; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: LicensingData = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "LicensingData", "" ) as LicensingData; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getServerField * @throws ApiException if the response code was not in [200, 299] */ public async getServerField(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getServerInfo * @throws ApiException if the response code was not in [200, 299] */ public async getServerInfo(response: ResponseContext): Promise<Server > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Server = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Server", "" ) as Server; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Server = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Server", "" ) as Server; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getZippedFileOfServer * @throws ApiException if the response code was not in [200, 299] */ public async getZippedFileOfServer(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to startBackup * @throws ApiException if the response code was not in [200, 299] */ public async startBackup(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } } <file_sep>/ts-schema/schema/rest-api/deno/models/TestOccurrences.ts /** * TeamCity REST API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * OpenAPI spec version: 2018.1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { TestCounters } from './TestCounters.ts'; import { TestOccurrence } from './TestOccurrence.ts'; import { HttpFile } from '../http/http.ts'; export class TestOccurrences { 'count'?: number; 'href'?: string; 'nextHref'?: string; 'prevHref'?: string; 'testOccurrence'?: Array<TestOccurrence>; 'testCounters'?: TestCounters; 'passed'?: number; 'failed'?: number; 'newFailed'?: number; 'ignored'?: number; 'muted'?: number; static readonly discriminator: string | undefined = undefined; static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [ { "name": "count", "baseName": "count", "type": "number", "format": "int32" }, { "name": "href", "baseName": "href", "type": "string", "format": "" }, { "name": "nextHref", "baseName": "nextHref", "type": "string", "format": "" }, { "name": "prevHref", "baseName": "prevHref", "type": "string", "format": "" }, { "name": "testOccurrence", "baseName": "testOccurrence", "type": "Array<TestOccurrence>", "format": "" }, { "name": "testCounters", "baseName": "testCounters", "type": "TestCounters", "format": "" }, { "name": "passed", "baseName": "passed", "type": "number", "format": "int32" }, { "name": "failed", "baseName": "failed", "type": "number", "format": "int32" }, { "name": "newFailed", "baseName": "newFailed", "type": "number", "format": "int32" }, { "name": "ignored", "baseName": "ignored", "type": "number", "format": "int32" }, { "name": "muted", "baseName": "muted", "type": "number", "format": "int32" } ]; static getAttributeTypeMap() { return TestOccurrences.attributeTypeMap; } public constructor() { } } <file_sep>/ts-schema/schema/rest-api/deno/models/TestOccurrence.ts /** * TeamCity REST API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * OpenAPI spec version: 2018.1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { Build } from './Build.ts'; import { Mute } from './Mute.ts'; import { Test } from './Test.ts'; import { TestOccurrences } from './TestOccurrences.ts'; import { TestRunMetadata } from './TestRunMetadata.ts'; import { HttpFile } from '../http/http.ts'; export class TestOccurrence { 'id'?: string; 'name'?: string; 'status'?: string; 'ignored'?: boolean; 'duration'?: number; 'runOrder'?: string; 'newFailure'?: boolean; 'muted'?: boolean; 'currentlyMuted'?: boolean; 'currentlyInvestigated'?: boolean; 'href'?: string; 'ignoreDetails'?: string; 'details'?: string; 'test'?: Test; 'mute'?: Mute; 'build'?: Build; 'firstFailed'?: TestOccurrence; 'nextFixed'?: TestOccurrence; 'invocations'?: TestOccurrences; 'metadata'?: TestRunMetadata; 'logAnchor'?: string; static readonly discriminator: string | undefined = undefined; static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [ { "name": "id", "baseName": "id", "type": "string", "format": "" }, { "name": "name", "baseName": "name", "type": "string", "format": "" }, { "name": "status", "baseName": "status", "type": "string", "format": "" }, { "name": "ignored", "baseName": "ignored", "type": "boolean", "format": "" }, { "name": "duration", "baseName": "duration", "type": "number", "format": "int32" }, { "name": "runOrder", "baseName": "runOrder", "type": "string", "format": "" }, { "name": "newFailure", "baseName": "newFailure", "type": "boolean", "format": "" }, { "name": "muted", "baseName": "muted", "type": "boolean", "format": "" }, { "name": "currentlyMuted", "baseName": "currentlyMuted", "type": "boolean", "format": "" }, { "name": "currentlyInvestigated", "baseName": "currentlyInvestigated", "type": "boolean", "format": "" }, { "name": "href", "baseName": "href", "type": "string", "format": "" }, { "name": "ignoreDetails", "baseName": "ignoreDetails", "type": "string", "format": "" }, { "name": "details", "baseName": "details", "type": "string", "format": "" }, { "name": "test", "baseName": "test", "type": "Test", "format": "" }, { "name": "mute", "baseName": "mute", "type": "Mute", "format": "" }, { "name": "build", "baseName": "build", "type": "Build", "format": "" }, { "name": "firstFailed", "baseName": "firstFailed", "type": "TestOccurrence", "format": "" }, { "name": "nextFixed", "baseName": "nextFixed", "type": "TestOccurrence", "format": "" }, { "name": "invocations", "baseName": "invocations", "type": "TestOccurrences", "format": "" }, { "name": "metadata", "baseName": "metadata", "type": "TestRunMetadata", "format": "" }, { "name": "logAnchor", "baseName": "logAnchor", "type": "string", "format": "" } ]; static getAttributeTypeMap() { return TestOccurrence.attributeTypeMap; } public constructor() { } } <file_sep>/ts-schema/schema/xml/project.ts import { Parameters } from "./parameter.ts"; import { ProjectCleanup } from "./project_cleanup.ts"; import { ProjectExtensions } from "./project_extension.ts"; export interface Project { "?xml": { "@version": string; "@encoding": string }; project: { "@xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance"; "@xsi:noNamespaceSchemaLocation": "https://www.jetbrains.com/teamcity/schemas/2020.1/project-config.xsd"; "@uuid": string; name: string; description?: string; parameters?: Parameters; "project-extensions"?: ProjectExtensions; cleanup?: ProjectCleanup; }; } <file_sep>/ts-schema/schema/rest-api/deno/models/AgentPool.ts /** * TeamCity REST API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * OpenAPI spec version: 2018.1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { Agents } from './Agents.ts'; import { Project } from './Project.ts'; import { Projects } from './Projects.ts'; import { HttpFile } from '../http/http.ts'; export class AgentPool { 'id'?: number; 'name'?: string; 'href'?: string; 'maxAgents'?: number; 'ownerProject'?: Project; 'projects'?: Projects; 'agents'?: Agents; 'locator'?: string; static readonly discriminator: string | undefined = undefined; static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [ { "name": "id", "baseName": "id", "type": "number", "format": "int32" }, { "name": "name", "baseName": "name", "type": "string", "format": "" }, { "name": "href", "baseName": "href", "type": "string", "format": "" }, { "name": "maxAgents", "baseName": "maxAgents", "type": "number", "format": "int32" }, { "name": "ownerProject", "baseName": "ownerProject", "type": "Project", "format": "" }, { "name": "projects", "baseName": "projects", "type": "Projects", "format": "" }, { "name": "agents", "baseName": "agents", "type": "Agents", "format": "" }, { "name": "locator", "baseName": "locator", "type": "string", "format": "" } ]; static getAttributeTypeMap() { return AgentPool.attributeTypeMap; } public constructor() { } } <file_sep>/ts-schema/schema/json/project.ts import { VcsRoot } from "./vcs_root.ts"; import { Parameter } from "./parameter.ts"; import { BuildType } from "./build_type.ts"; import { ProjectCleanup } from "./project_cleanup.ts"; import { ProjectExtension } from "./project_extension.ts"; /** * A project is the top level of this schema, start by creating a Project object. * * see: https://www.jetbrains.com/help/teamcity/2020.2/creating-and-editing-projects.html */ export interface Project { /** * This refers to the parent folder of the generated XML file stored in the * .teamcity folder of your repo & ultimately the server's Data Directory. * see: https://www.jetbrains.com/help/teamcity/teamcity-data-directory.html * * For example an id of `Foo_Bar_Baz` results in the file * `./.teamcity/Foo_Bar_Baz/project-config.xml` being generated. * * This id is also used as a reference in many places * throughout the rest of this schema & for URLs, etc... * * see: https://www.jetbrains.com/help/teamcity/2020.2/identifier.html */ id: string; /** * This value is used as an attribute on the root XML object. It only appears * to be used internally by TeamCity. Hence this is optional and will be * generated for you if you do not explicitly define a value. * * see: https://www.jetbrains.com/help/teamcity/2020.2/identifier.html#Universally+Unique+IDs * * > NOTE: Despite what the docs say, TeamCity does not appear to automatically * > populate the UUID field for you but also doesn't seem to mind that it * > doesn't exist, go figure... */ uuid?: string; /** * A human friendly name for the project. */ name: string; /** * An optional human friendly description of the project. */ description?: string; /** * Projects can define configuration parameters which are recursively * inherited by all BuildTypes & SubProjects. * * see: https://www.jetbrains.com/help/teamcity/2020.2/configuring-build-parameters.html */ parameters?: Parameter[]; /** * Each project may define many VcsRoots. * * A VCS root in TeamCity defines a connection to a version control system. * It represents a set of parameters (paths to sources, username, password, * and other settings) that determine how TeamCity communicates with a VCS to * monitor changes and get sources for a build. * * see: https://www.jetbrains.com/help/teamcity/2020.2/configuring-vcs-roots.html */ vcsRoots?: VcsRoot[]; /** * Each project can be extended with many plugins and settings. * * All or most of the things that you see in the left hand side bar of a * project configuration page in the user interface of TeamCity, things like * Report Tabs, Connections, Shared Resources, Issue Trackers, Clean-Up Rules, * Nuget Feeds, etc... are all defined as extension nodes in the XML. * * In this schema the `ProjectExtension` type is a base type and there many * other types that better represent all those other things that extend the * `ProjectExtension` type which you can use here. */ extensions?: ProjectExtension[]; /** * A build configuration is a collection of settings used to start a build and * group the sequence of the builds in the UI. Examples of build configurations * are distribution, integration tests, prepare release distribution, "nightly" build. * * > HINT: The UI uses Build Configuration terminology but in the XML & Kotlin, * > the name Build Type is used instead, for reasons... seriously TeamCity * > sort your shit out. * * see: https://www.jetbrains.com/help/teamcity/2020.2/build-configuration.html */ buildTypes?: BuildType[]; /** * Sub projects can be used to group build configurations and define projects * hierarchy within a single project. * * see: https://www.jetbrains.com/help/teamcity/2020.2/project.html#Project+Hierarchy */ subProjects?: Project[]; /** * Base Clean Up configuration. * * > HINT: This can be combined with `ProjectExtensionKeepRules` to cater * > for more complex needs. * * see: https://www.jetbrains.com/help/teamcity/2020.2/clean-up.html#Base+Rule */ cleanUp?: ProjectCleanup; } <file_sep>/ts-schema/schema/json/project_cleanup.ts export interface ProjectCleanup { /** * Whether or not the defined clean-up policies are actually enabled or not. * * Defaults to `false`. */ disableCleanupPolicies?: boolean; /** * This setting affects clean-up of artifacts in builds of the dependency * build configurations. * * - `undefined` = Use default * - `true` = Prevent clean-up * - `false` = Do not prevent clean-up */ preventDependenciesArtifactsFromCleanup?: boolean; /** * A list of base policies to apply to this project. * * Base policies allows for preserving build data using simple settings. * The policies are applied considering branches, personal and canceled * builds, etc... * * > HINT: You can combine these with `ProjectExtensionKeepRules` to cater * > for more complex needs. * * see: https://www.jetbrains.com/help/teamcity/2020.2/clean-up.html#Base+Rule */ policies?: ProjectCleanupPolicy[]; } export type ProjectCleanupPolicy = | ProjectCleanupPolicyEverything | ProjectCleanupPolicyArtifacts | ProjectCleanupPolicyHistory; export interface ProjectCleanupPolicyBase { /** * Anything older than X days since the last build will be deleted. * * > HINT: This can be combined with `keepBuilds` but at least one * > of these options must be defined. */ keepDays?: number; /** * Only X number of successfully completed builds will be kept. */ keepBuilds?: number; } export interface ProjectCleanupPolicyEverything extends ProjectCleanupPolicyBase { /** * Clean everything including artifacts, history, and statistical data. */ cleanupLevel: "EVERYTHING"; } export interface ProjectCleanupPolicyHistory extends ProjectCleanupPolicyBase { /** * Clean history and statistical data. */ cleanupLevel: "HISTORY_ENTRY"; } export interface ProjectCleanupPolicyArtifacts extends ProjectCleanupPolicyBase { /** * Clean published artifacts. */ cleanupLevel: "ARTIFACTS"; /** * An optional list of artifact patterns to match against. * In the form of `+:/-:` Ant-style pattern wildcard. * * > HINT: If left undefined any artifact that matches the `keepDays` / * > `keepBuilds` properties will be deleted. */ patterns?: string[]; } <file_sep>/ts-schema/schema/rest-api/deno/models/VcsRoot.ts /** * TeamCity REST API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * OpenAPI spec version: 2018.1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { Items } from './Items.ts'; import { Project } from './Project.ts'; import { Properties } from './Properties.ts'; import { VcsRootInstances } from './VcsRootInstances.ts'; import { HttpFile } from '../http/http.ts'; export class VcsRoot { 'id'?: string; 'internalId'?: string; 'uuid'?: string; 'name'?: string; 'vcsName'?: string; 'modificationCheckInterval'?: number; 'href'?: string; 'project'?: Project; 'properties'?: Properties; 'vcsRootInstances'?: VcsRootInstances; 'repositoryIdStrings'?: Items; 'projectLocator'?: string; 'locator'?: string; static readonly discriminator: string | undefined = undefined; static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [ { "name": "id", "baseName": "id", "type": "string", "format": "" }, { "name": "internalId", "baseName": "internalId", "type": "string", "format": "" }, { "name": "uuid", "baseName": "uuid", "type": "string", "format": "" }, { "name": "name", "baseName": "name", "type": "string", "format": "" }, { "name": "vcsName", "baseName": "vcsName", "type": "string", "format": "" }, { "name": "modificationCheckInterval", "baseName": "modificationCheckInterval", "type": "number", "format": "int32" }, { "name": "href", "baseName": "href", "type": "string", "format": "" }, { "name": "project", "baseName": "project", "type": "Project", "format": "" }, { "name": "properties", "baseName": "properties", "type": "Properties", "format": "" }, { "name": "vcsRootInstances", "baseName": "vcsRootInstances", "type": "VcsRootInstances", "format": "" }, { "name": "repositoryIdStrings", "baseName": "repositoryIdStrings", "type": "Items", "format": "" }, { "name": "projectLocator", "baseName": "projectLocator", "type": "string", "format": "" }, { "name": "locator", "baseName": "locator", "type": "string", "format": "" } ]; static getAttributeTypeMap() { return VcsRoot.attributeTypeMap; } public constructor() { } } <file_sep>/ts-schema/schema/rest-api/deno/models/CloudInstance.ts /** * TeamCity REST API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * OpenAPI spec version: 2018.1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { Agent } from './Agent.ts'; import { CloudImage } from './CloudImage.ts'; import { HttpFile } from '../http/http.ts'; export class CloudInstance { 'id'?: string; 'name'?: string; 'state'?: string; 'startDate'?: string; 'networkAddress'?: string; 'href'?: string; 'image'?: CloudImage; 'agent'?: Agent; 'errorMessage'?: string; static readonly discriminator: string | undefined = undefined; static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [ { "name": "id", "baseName": "id", "type": "string", "format": "" }, { "name": "name", "baseName": "name", "type": "string", "format": "" }, { "name": "state", "baseName": "state", "type": "string", "format": "" }, { "name": "startDate", "baseName": "startDate", "type": "string", "format": "" }, { "name": "networkAddress", "baseName": "networkAddress", "type": "string", "format": "" }, { "name": "href", "baseName": "href", "type": "string", "format": "" }, { "name": "image", "baseName": "image", "type": "CloudImage", "format": "" }, { "name": "agent", "baseName": "agent", "type": "Agent", "format": "" }, { "name": "errorMessage", "baseName": "errorMessage", "type": "string", "format": "" } ]; static getAttributeTypeMap() { return CloudInstance.attributeTypeMap; } public constructor() { } } <file_sep>/ts-schema/schema/rest-api/test.ts import { ProjectApi, createConfiguration, ServerConfiguration } from './deno/index.ts'; const p = new ProjectApi(createConfiguration({ baseServer: new ServerConfiguration<Record<string, string>>("https://tc.example.org", {}), authMethods: { 'Authorization': 'Bearer abc' }, })); (await p.getAllProjects()).project?.forEach(_ => console.log(_.href));<file_sep>/ts-schema/schema/rest-api/deno/apis/CloudInstanceApi.ts // TODO: better import syntax? import { BaseAPIRequestFactory, RequiredError } from './baseapi.ts'; import {Configuration} from '../configuration.ts'; import { RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http.ts'; import {ObjectSerializer} from '../models/ObjectSerializer.ts'; import {ApiException} from './exception.ts'; import {isCodeInRange} from '../util.ts'; import { CloudImage } from '../models/CloudImage.ts'; import { CloudImages } from '../models/CloudImages.ts'; import { CloudInstance } from '../models/CloudInstance.ts'; import { CloudInstances } from '../models/CloudInstances.ts'; import { CloudProfile } from '../models/CloudProfile.ts'; import { CloudProfiles } from '../models/CloudProfiles.ts'; /** * no description */ export class CloudInstanceApiRequestFactory extends BaseAPIRequestFactory { /** * Get all cloud images. * @param locator * @param fields */ public async getAllCloudImages(locator?: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/cloud/images'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "")); } if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all cloud instances. * @param locator * @param fields */ public async getAllCloudInstances(locator?: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/cloud/instances'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "")); } if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all cloud profiles. * @param locator * @param fields */ public async getAllCloudProfiles(locator?: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/cloud/profiles'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "")); } if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get cloud image matching the locator. * @param imageLocator * @param fields */ public async getCloudImage(imageLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'imageLocator' is not null or undefined if (imageLocator === null || imageLocator === undefined) { throw new RequiredError('Required parameter imageLocator was null or undefined when calling getCloudImage.'); } // Path Params const localVarPath = '/app/rest/cloud/images/{imageLocator}' .replace('{' + 'imageLocator' + '}', encodeURIComponent(String(imageLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get cloud instance matching the locator. * @param instanceLocator * @param fields */ public async getCloudInstance(instanceLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'instanceLocator' is not null or undefined if (instanceLocator === null || instanceLocator === undefined) { throw new RequiredError('Required parameter instanceLocator was null or undefined when calling getCloudInstance.'); } // Path Params const localVarPath = '/app/rest/cloud/instances/{instanceLocator}' .replace('{' + 'instanceLocator' + '}', encodeURIComponent(String(instanceLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get cloud profile matching the locator. * @param profileLocator * @param fields */ public async getCloudProfile(profileLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'profileLocator' is not null or undefined if (profileLocator === null || profileLocator === undefined) { throw new RequiredError('Required parameter profileLocator was null or undefined when calling getCloudProfile.'); } // Path Params const localVarPath = '/app/rest/cloud/profiles/{profileLocator}' .replace('{' + 'profileLocator' + '}', encodeURIComponent(String(profileLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Start a new cloud instance. * @param fields * @param body */ public async startInstance(fields?: string, body?: CloudInstance, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/cloud/instances'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "CloudInstance", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Stop cloud instance matching the locator. * @param instanceLocator */ public async stopInstance(instanceLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'instanceLocator' is not null or undefined if (instanceLocator === null || instanceLocator === undefined) { throw new RequiredError('Required parameter instanceLocator was null or undefined when calling stopInstance.'); } // Path Params const localVarPath = '/app/rest/cloud/instances/{instanceLocator}' .replace('{' + 'instanceLocator' + '}', encodeURIComponent(String(instanceLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } } export class CloudInstanceApiResponseProcessor { /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAllCloudImages * @throws ApiException if the response code was not in [200, 299] */ public async getAllCloudImages(response: ResponseContext): Promise<CloudImages > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: CloudImages = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "CloudImages", "" ) as CloudImages; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: CloudImages = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "CloudImages", "" ) as CloudImages; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAllCloudInstances * @throws ApiException if the response code was not in [200, 299] */ public async getAllCloudInstances(response: ResponseContext): Promise<CloudInstances > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: CloudInstances = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "CloudInstances", "" ) as CloudInstances; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: CloudInstances = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "CloudInstances", "" ) as CloudInstances; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAllCloudProfiles * @throws ApiException if the response code was not in [200, 299] */ public async getAllCloudProfiles(response: ResponseContext): Promise<CloudProfiles > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: CloudProfiles = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "CloudProfiles", "" ) as CloudProfiles; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: CloudProfiles = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "CloudProfiles", "" ) as CloudProfiles; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getCloudImage * @throws ApiException if the response code was not in [200, 299] */ public async getCloudImage(response: ResponseContext): Promise<CloudImage > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: CloudImage = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "CloudImage", "" ) as CloudImage; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: CloudImage = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "CloudImage", "" ) as CloudImage; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getCloudInstance * @throws ApiException if the response code was not in [200, 299] */ public async getCloudInstance(response: ResponseContext): Promise<CloudInstance > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: CloudInstance = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "CloudInstance", "" ) as CloudInstance; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: CloudInstance = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "CloudInstance", "" ) as CloudInstance; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getCloudProfile * @throws ApiException if the response code was not in [200, 299] */ public async getCloudProfile(response: ResponseContext): Promise<CloudProfile > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: CloudProfile = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "CloudProfile", "" ) as CloudProfile; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: CloudProfile = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "CloudProfile", "" ) as CloudProfile; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to startInstance * @throws ApiException if the response code was not in [200, 299] */ public async startInstance(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to stopInstance * @throws ApiException if the response code was not in [200, 299] */ public async stopInstance(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } } <file_sep>/ts-schema/schema/rest-api/deno/types/ObservableAPI.ts import { ResponseContext, RequestContext, HttpFile } from '../http/http.ts'; import * as models from '../models/all.ts'; import { Configuration} from '../configuration.ts' import { Observable, of, from } from '../rxjsStub.ts'; import {mergeMap, map} from '../rxjsStub.ts'; import { Agent } from '../models/Agent.ts'; import { AgentLocator } from '../models/AgentLocator.ts'; import { AgentPool } from '../models/AgentPool.ts'; import { AgentPoolLocator } from '../models/AgentPoolLocator.ts'; import { AgentPools } from '../models/AgentPools.ts'; import { AgentRequirement } from '../models/AgentRequirement.ts'; import { AgentRequirements } from '../models/AgentRequirements.ts'; import { Agents } from '../models/Agents.ts'; import { ArtifactDependencies } from '../models/ArtifactDependencies.ts'; import { ArtifactDependency } from '../models/ArtifactDependency.ts'; import { AuditAction } from '../models/AuditAction.ts'; import { AuditEvent } from '../models/AuditEvent.ts'; import { AuditEvents } from '../models/AuditEvents.ts'; import { AuditLocator } from '../models/AuditLocator.ts'; import { AuthorizedInfo } from '../models/AuthorizedInfo.ts'; import { Branch } from '../models/Branch.ts'; import { BranchLocator } from '../models/BranchLocator.ts'; import { BranchVersion } from '../models/BranchVersion.ts'; import { Branches } from '../models/Branches.ts'; import { Build } from '../models/Build.ts'; import { BuildCancelRequest } from '../models/BuildCancelRequest.ts'; import { BuildChange } from '../models/BuildChange.ts'; import { BuildChanges } from '../models/BuildChanges.ts'; import { BuildLocator } from '../models/BuildLocator.ts'; import { BuildQueueLocator } from '../models/BuildQueueLocator.ts'; import { BuildTriggeringOptions } from '../models/BuildTriggeringOptions.ts'; import { BuildType } from '../models/BuildType.ts'; import { BuildTypeLocator } from '../models/BuildTypeLocator.ts'; import { BuildTypes } from '../models/BuildTypes.ts'; import { Builds } from '../models/Builds.ts'; import { Change } from '../models/Change.ts'; import { ChangeLocator } from '../models/ChangeLocator.ts'; import { Changes } from '../models/Changes.ts'; import { CloudImage } from '../models/CloudImage.ts'; import { CloudImages } from '../models/CloudImages.ts'; import { CloudInstance } from '../models/CloudInstance.ts'; import { CloudInstances } from '../models/CloudInstances.ts'; import { CloudProfile } from '../models/CloudProfile.ts'; import { CloudProfiles } from '../models/CloudProfiles.ts'; import { Comment } from '../models/Comment.ts'; import { Compatibilities } from '../models/Compatibilities.ts'; import { Compatibility } from '../models/Compatibility.ts'; import { CompatibilityPolicy } from '../models/CompatibilityPolicy.ts'; import { Customizations } from '../models/Customizations.ts'; import { Datas } from '../models/Datas.ts'; import { EnabledInfo } from '../models/EnabledInfo.ts'; import { Entries } from '../models/Entries.ts'; import { Entry } from '../models/Entry.ts'; import { Environment } from '../models/Environment.ts'; import { Feature } from '../models/Feature.ts'; import { Features } from '../models/Features.ts'; import { File } from '../models/File.ts'; import { FileChange } from '../models/FileChange.ts'; import { FileChanges } from '../models/FileChanges.ts'; import { Files } from '../models/Files.ts'; import { Group } from '../models/Group.ts'; import { Groups } from '../models/Groups.ts'; import { Href } from '../models/Href.ts'; import { Investigation } from '../models/Investigation.ts'; import { InvestigationLocator } from '../models/InvestigationLocator.ts'; import { Investigations } from '../models/Investigations.ts'; import { Issue } from '../models/Issue.ts'; import { IssueUsage } from '../models/IssueUsage.ts'; import { Issues } from '../models/Issues.ts'; import { IssuesUsages } from '../models/IssuesUsages.ts'; import { Items } from '../models/Items.ts'; import { LicenseKey } from '../models/LicenseKey.ts'; import { LicenseKeys } from '../models/LicenseKeys.ts'; import { LicensingData } from '../models/LicensingData.ts'; import { Link } from '../models/Link.ts'; import { Links } from '../models/Links.ts'; import { MetaData } from '../models/MetaData.ts'; import { Metric } from '../models/Metric.ts'; import { MetricTag } from '../models/MetricTag.ts'; import { MetricTags } from '../models/MetricTags.ts'; import { MetricValue } from '../models/MetricValue.ts'; import { MetricValues } from '../models/MetricValues.ts'; import { Metrics } from '../models/Metrics.ts'; import { MultipleOperationResult } from '../models/MultipleOperationResult.ts'; import { Mute } from '../models/Mute.ts'; import { MuteLocator } from '../models/MuteLocator.ts'; import { Mutes } from '../models/Mutes.ts'; import { NewBuildTypeDescription } from '../models/NewBuildTypeDescription.ts'; import { NewProjectDescription } from '../models/NewProjectDescription.ts'; import { OperationResult } from '../models/OperationResult.ts'; import { ParsedTestName } from '../models/ParsedTestName.ts'; import { Permission } from '../models/Permission.ts'; import { PermissionAssignment } from '../models/PermissionAssignment.ts'; import { PermissionAssignments } from '../models/PermissionAssignments.ts'; import { PermissionRestriction } from '../models/PermissionRestriction.ts'; import { PermissionRestrictions } from '../models/PermissionRestrictions.ts'; import { PinInfo } from '../models/PinInfo.ts'; import { Plugin } from '../models/Plugin.ts'; import { Plugins } from '../models/Plugins.ts'; import { Problem } from '../models/Problem.ts'; import { ProblemLocator } from '../models/ProblemLocator.ts'; import { ProblemOccurrence } from '../models/ProblemOccurrence.ts'; import { ProblemOccurrenceLocator } from '../models/ProblemOccurrenceLocator.ts'; import { ProblemOccurrences } from '../models/ProblemOccurrences.ts'; import { ProblemScope } from '../models/ProblemScope.ts'; import { ProblemTarget } from '../models/ProblemTarget.ts'; import { Problems } from '../models/Problems.ts'; import { ProgressInfo } from '../models/ProgressInfo.ts'; import { Project } from '../models/Project.ts'; import { ProjectFeature } from '../models/ProjectFeature.ts'; import { ProjectFeatures } from '../models/ProjectFeatures.ts'; import { ProjectLocator } from '../models/ProjectLocator.ts'; import { Projects } from '../models/Projects.ts'; import { Properties } from '../models/Properties.ts'; import { Property } from '../models/Property.ts'; import { Related } from '../models/Related.ts'; import { RelatedEntities } from '../models/RelatedEntities.ts'; import { RelatedEntity } from '../models/RelatedEntity.ts'; import { RepositoryState } from '../models/RepositoryState.ts'; import { Requirements } from '../models/Requirements.ts'; import { Resolution } from '../models/Resolution.ts'; import { Revision } from '../models/Revision.ts'; import { Revisions } from '../models/Revisions.ts'; import { Role } from '../models/Role.ts'; import { Roles } from '../models/Roles.ts'; import { Server } from '../models/Server.ts'; import { SnapshotDependencies } from '../models/SnapshotDependencies.ts'; import { SnapshotDependency } from '../models/SnapshotDependency.ts'; import { StateField } from '../models/StateField.ts'; import { Step } from '../models/Step.ts'; import { Steps } from '../models/Steps.ts'; import { Tag } from '../models/Tag.ts'; import { TagLocator } from '../models/TagLocator.ts'; import { Tags } from '../models/Tags.ts'; import { Test } from '../models/Test.ts'; import { TestCounters } from '../models/TestCounters.ts'; import { TestLocator } from '../models/TestLocator.ts'; import { TestOccurrence } from '../models/TestOccurrence.ts'; import { TestOccurrenceLocator } from '../models/TestOccurrenceLocator.ts'; import { TestOccurrences } from '../models/TestOccurrences.ts'; import { TestRunMetadata } from '../models/TestRunMetadata.ts'; import { Tests } from '../models/Tests.ts'; import { Token } from '../models/Token.ts'; import { Tokens } from '../models/Tokens.ts'; import { Trigger } from '../models/Trigger.ts'; import { TriggeredBy } from '../models/TriggeredBy.ts'; import { Triggers } from '../models/Triggers.ts'; import { Type } from '../models/Type.ts'; import { TypedValue } from '../models/TypedValue.ts'; import { User } from '../models/User.ts'; import { UserGroupLocator } from '../models/UserGroupLocator.ts'; import { UserLocator } from '../models/UserLocator.ts'; import { Users } from '../models/Users.ts'; import { VcsCheckStatus } from '../models/VcsCheckStatus.ts'; import { VcsLabel } from '../models/VcsLabel.ts'; import { VcsLabels } from '../models/VcsLabels.ts'; import { VcsRoot } from '../models/VcsRoot.ts'; import { VcsRootEntries } from '../models/VcsRootEntries.ts'; import { VcsRootEntry } from '../models/VcsRootEntry.ts'; import { VcsRootInstance } from '../models/VcsRootInstance.ts'; import { VcsRootInstanceLocator } from '../models/VcsRootInstanceLocator.ts'; import { VcsRootInstances } from '../models/VcsRootInstances.ts'; import { VcsRootLocator } from '../models/VcsRootLocator.ts'; import { VcsRoots } from '../models/VcsRoots.ts'; import { VcsStatus } from '../models/VcsStatus.ts'; import { AgentApiRequestFactory, AgentApiResponseProcessor} from "../apis/AgentApi.ts"; export class ObservableAgentApi { private requestFactory: AgentApiRequestFactory; private responseProcessor: AgentApiResponseProcessor; private configuration: Configuration; public constructor( configuration: Configuration, requestFactory?: AgentApiRequestFactory, responseProcessor?: AgentApiResponseProcessor ) { this.configuration = configuration; this.requestFactory = requestFactory || new AgentApiRequestFactory(configuration); this.responseProcessor = responseProcessor || new AgentApiResponseProcessor(); } /** * Delete an inactive agent. * @param agentLocator */ public deleteAgent(agentLocator: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.deleteAgent(agentLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.deleteAgent(rsp))); })); } /** * Get agent matching the locator. * @param agentLocator * @param fields */ public getAgent(agentLocator: string, fields?: string, options?: Configuration): Observable<Agent> { const requestContextPromise = this.requestFactory.getAgent(agentLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAgent(rsp))); })); } /** * Get a field of the matching agent. * @param agentLocator * @param field */ public getAgentField(agentLocator: string, field: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.getAgentField(agentLocator, field, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAgentField(rsp))); })); } /** * Get the agent pool of the matching agent. * @param agentLocator * @param fields */ public getAgentPool(agentLocator: string, fields?: string, options?: Configuration): Observable<AgentPool> { const requestContextPromise = this.requestFactory.getAgentPool(agentLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAgentPool(rsp))); })); } /** * Get all known agents. * @param locator * @param fields */ public getAllAgents(locator?: string, fields?: string, options?: Configuration): Observable<Agents> { const requestContextPromise = this.requestFactory.getAllAgents(locator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAllAgents(rsp))); })); } /** * Get the authorization info of the matching agent. * @param agentLocator * @param fields */ public getAuthorizedInfo(agentLocator: string, fields?: string, options?: Configuration): Observable<AuthorizedInfo> { const requestContextPromise = this.requestFactory.getAuthorizedInfo(agentLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAuthorizedInfo(rsp))); })); } /** * Get the build configuration run policy of the matching agent. * @param agentLocator * @param fields */ public getBuildConfigurationRunPolicy(agentLocator: string, fields?: string, options?: Configuration): Observable<CompatibilityPolicy> { const requestContextPromise = this.requestFactory.getBuildConfigurationRunPolicy(agentLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildConfigurationRunPolicy(rsp))); })); } /** * Get build types compatible with the matching agent. * @param agentLocator * @param fields */ public getCompatibleBuildTypes(agentLocator: string, fields?: string, options?: Configuration): Observable<BuildTypes> { const requestContextPromise = this.requestFactory.getCompatibleBuildTypes(agentLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getCompatibleBuildTypes(rsp))); })); } /** * Check if the matching agent is enabled. * @param agentLocator * @param fields */ public getEnabledInfo(agentLocator: string, fields?: string, options?: Configuration): Observable<EnabledInfo> { const requestContextPromise = this.requestFactory.getEnabledInfo(agentLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getEnabledInfo(rsp))); })); } /** * Get build types incompatible with the matching agent. * @param agentLocator * @param fields */ public getIncompatibleBuildTypes(agentLocator: string, fields?: string, options?: Configuration): Observable<Compatibilities> { const requestContextPromise = this.requestFactory.getIncompatibleBuildTypes(agentLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getIncompatibleBuildTypes(rsp))); })); } /** * Update a field of the matching agent. * @param agentLocator * @param field * @param body */ public setAgentField(agentLocator: string, field: string, body?: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.setAgentField(agentLocator, field, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setAgentField(rsp))); })); } /** * Assign the matching agent to the specified agent pool. * @param agentLocator * @param fields * @param body */ public setAgentPool(agentLocator: string, fields?: string, body?: AgentPool, options?: Configuration): Observable<AgentPool> { const requestContextPromise = this.requestFactory.setAgentPool(agentLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setAgentPool(rsp))); })); } /** * Update the authorization info of the matching agent. * @param agentLocator * @param fields * @param body */ public setAuthorizedInfo(agentLocator: string, fields?: string, body?: AuthorizedInfo, options?: Configuration): Observable<AuthorizedInfo> { const requestContextPromise = this.requestFactory.setAuthorizedInfo(agentLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setAuthorizedInfo(rsp))); })); } /** * Update build configuration run policy of agent matching locator. * @param agentLocator * @param fields * @param body */ public setBuildConfigurationRunPolicy(agentLocator: string, fields?: string, body?: CompatibilityPolicy, options?: Configuration): Observable<CompatibilityPolicy> { const requestContextPromise = this.requestFactory.setBuildConfigurationRunPolicy(agentLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setBuildConfigurationRunPolicy(rsp))); })); } /** * Update the enablement status of the matching agent. * @param agentLocator * @param fields * @param body */ public setEnabledInfo(agentLocator: string, fields?: string, body?: EnabledInfo, options?: Configuration): Observable<EnabledInfo> { const requestContextPromise = this.requestFactory.setEnabledInfo(agentLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setEnabledInfo(rsp))); })); } } import { AgentPoolApiRequestFactory, AgentPoolApiResponseProcessor} from "../apis/AgentPoolApi.ts"; export class ObservableAgentPoolApi { private requestFactory: AgentPoolApiRequestFactory; private responseProcessor: AgentPoolApiResponseProcessor; private configuration: Configuration; public constructor( configuration: Configuration, requestFactory?: AgentPoolApiRequestFactory, responseProcessor?: AgentPoolApiResponseProcessor ) { this.configuration = configuration; this.requestFactory = requestFactory || new AgentPoolApiRequestFactory(configuration); this.responseProcessor = responseProcessor || new AgentPoolApiResponseProcessor(); } /** * Assign the agent to the matching agent pool. * @param agentPoolLocator * @param fields * @param body */ public addAgentToAgentPool(agentPoolLocator: string, fields?: string, body?: Agent, options?: Configuration): Observable<Agent> { const requestContextPromise = this.requestFactory.addAgentToAgentPool(agentPoolLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.addAgentToAgentPool(rsp))); })); } /** * Assign the project to the matching agent pool. * @param agentPoolLocator * @param body */ public addProjectToAgentPool(agentPoolLocator: string, body?: Project, options?: Configuration): Observable<Project> { const requestContextPromise = this.requestFactory.addProjectToAgentPool(agentPoolLocator, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.addProjectToAgentPool(rsp))); })); } /** * Create a new agent pool. * @param body */ public createAgentPool(body?: AgentPool, options?: Configuration): Observable<AgentPool> { const requestContextPromise = this.requestFactory.createAgentPool(body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.createAgentPool(rsp))); })); } /** * Delete the agent pool matching the locator. * @param agentPoolLocator */ public deleteAgentPool(agentPoolLocator: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.deleteAgentPool(agentPoolLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.deleteAgentPool(rsp))); })); } /** * Unassign all projects from the matching agent pool. * @param agentPoolLocator */ public deleteAllProjectsFromAgentPool(agentPoolLocator: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.deleteAllProjectsFromAgentPool(agentPoolLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.deleteAllProjectsFromAgentPool(rsp))); })); } /** * Unassign the project from the matching agent pool. * @param agentPoolLocator * @param projectLocator */ public deleteProjectFromAgentPool(agentPoolLocator: string, projectLocator: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.deleteProjectFromAgentPool(agentPoolLocator, projectLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.deleteProjectFromAgentPool(rsp))); })); } /** * Get the agent pool matching the locator. * @param agentPoolLocator * @param fields */ public getAgentPoolOfAgentPool(agentPoolLocator: string, fields?: string, options?: Configuration): Observable<AgentPool> { const requestContextPromise = this.requestFactory.getAgentPoolOfAgentPool(agentPoolLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAgentPoolOfAgentPool(rsp))); })); } /** * Get all agent pools. * @param locator * @param fields */ public getAllAgentPools(locator?: string, fields?: string, options?: Configuration): Observable<AgentPools> { const requestContextPromise = this.requestFactory.getAllAgentPools(locator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAllAgentPools(rsp))); })); } /** * Get the agent of the matching agent pool. * @param agentPoolLocator * @param locator * @param fields */ public getAllAgentsFromAgentPool(agentPoolLocator: string, locator?: string, fields?: string, options?: Configuration): Observable<Agents> { const requestContextPromise = this.requestFactory.getAllAgentsFromAgentPool(agentPoolLocator, locator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAllAgentsFromAgentPool(rsp))); })); } /** * Get all projects of the matching agent pool. * @param agentPoolLocator * @param fields */ public getAllProjectsFromAgentPool(agentPoolLocator: string, fields?: string, options?: Configuration): Observable<Projects> { const requestContextPromise = this.requestFactory.getAllProjectsFromAgentPool(agentPoolLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAllProjectsFromAgentPool(rsp))); })); } /** * Get a field of the matching agent pool. * @param agentPoolLocator * @param field */ public getFieldFromAgentPool(agentPoolLocator: string, field: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.getFieldFromAgentPool(agentPoolLocator, field, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getFieldFromAgentPool(rsp))); })); } /** * Update a field of the matching agent pool. * @param agentPoolLocator * @param field * @param body */ public setAgentPoolField(agentPoolLocator: string, field: string, body?: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.setAgentPoolField(agentPoolLocator, field, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setAgentPoolField(rsp))); })); } /** * Update projects of the matching agent pool. * @param agentPoolLocator * @param body */ public setAgentPoolProjects(agentPoolLocator: string, body?: Projects, options?: Configuration): Observable<Projects> { const requestContextPromise = this.requestFactory.setAgentPoolProjects(agentPoolLocator, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setAgentPoolProjects(rsp))); })); } } import { AuditApiRequestFactory, AuditApiResponseProcessor} from "../apis/AuditApi.ts"; export class ObservableAuditApi { private requestFactory: AuditApiRequestFactory; private responseProcessor: AuditApiResponseProcessor; private configuration: Configuration; public constructor( configuration: Configuration, requestFactory?: AuditApiRequestFactory, responseProcessor?: AuditApiResponseProcessor ) { this.configuration = configuration; this.requestFactory = requestFactory || new AuditApiRequestFactory(configuration); this.responseProcessor = responseProcessor || new AuditApiResponseProcessor(); } /** * Get all audit events. * @param locator * @param fields */ public getAllAuditEvents(locator?: string, fields?: string, options?: Configuration): Observable<AuditEvents> { const requestContextPromise = this.requestFactory.getAllAuditEvents(locator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAllAuditEvents(rsp))); })); } /** * Get audit event matching the locator. * @param auditEventLocator * @param fields */ public getAuditEvent(auditEventLocator: string, fields?: string, options?: Configuration): Observable<AuditEvent> { const requestContextPromise = this.requestFactory.getAuditEvent(auditEventLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAuditEvent(rsp))); })); } } import { BuildApiRequestFactory, BuildApiResponseProcessor} from "../apis/BuildApi.ts"; export class ObservableBuildApi { private requestFactory: BuildApiRequestFactory; private responseProcessor: BuildApiResponseProcessor; private configuration: Configuration; public constructor( configuration: Configuration, requestFactory?: BuildApiRequestFactory, responseProcessor?: BuildApiResponseProcessor ) { this.configuration = configuration; this.requestFactory = requestFactory || new BuildApiRequestFactory(configuration); this.responseProcessor = responseProcessor || new BuildApiResponseProcessor(); } /** * Add a VCS label to the matching build. * @param buildLocator * @param locator * @param fields * @param body */ public addBuildVcsLabel(buildLocator: string, locator?: string, fields?: string, body?: string, options?: Configuration): Observable<VcsLabels> { const requestContextPromise = this.requestFactory.addBuildVcsLabel(buildLocator, locator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.addBuildVcsLabel(rsp))); })); } /** * Adds a message to the build log. Service messages are accepted. * @param buildLocator * @param fields * @param body */ public addLogMessageToBuild(buildLocator: string, fields?: string, body?: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.addLogMessageToBuild(buildLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.addLogMessageToBuild(rsp))); })); } /** * Add a build problem to the matching build. * @param buildLocator * @param fields * @param body */ public addProblemToBuild(buildLocator: string, fields?: string, body?: string, options?: Configuration): Observable<ProblemOccurrence> { const requestContextPromise = this.requestFactory.addProblemToBuild(buildLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.addProblemToBuild(rsp))); })); } /** * Add tags to the matching build. * @param buildLocator * @param fields * @param body */ public addTagsToBuild(buildLocator: string, fields?: string, body?: Tags, options?: Configuration): Observable<Tags> { const requestContextPromise = this.requestFactory.addTagsToBuild(buildLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.addTagsToBuild(rsp))); })); } /** * Add tags to multiple matching builds. * @param buildLocator * @param fields * @param body */ public addTagsToMultipleBuilds(buildLocator: string, fields?: string, body?: Tags, options?: Configuration): Observable<MultipleOperationResult> { const requestContextPromise = this.requestFactory.addTagsToMultipleBuilds(buildLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.addTagsToMultipleBuilds(rsp))); })); } /** * Delete build matching the locator. * @param buildLocator */ public deleteBuild(buildLocator: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.deleteBuild(buildLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.deleteBuild(rsp))); })); } /** * Remove the build comment matching the locator. * @param buildLocator */ public deleteBuildComment(buildLocator: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.deleteBuildComment(buildLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.deleteBuildComment(rsp))); })); } /** * Delete comments of multiple matching builds. * @param buildLocator * @param fields */ public deleteMultipleBuildComments(buildLocator: string, fields?: string, options?: Configuration): Observable<MultipleOperationResult> { const requestContextPromise = this.requestFactory.deleteMultipleBuildComments(buildLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.deleteMultipleBuildComments(rsp))); })); } /** * Delete multiple builds matching the locator. * @param buildLocator * @param fields */ public deleteMultipleBuilds(buildLocator: string, fields?: string, options?: Configuration): Observable<MultipleOperationResult> { const requestContextPromise = this.requestFactory.deleteMultipleBuilds(buildLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.deleteMultipleBuilds(rsp))); })); } /** * Download specific file. * @param path * @param buildLocator * @param resolveParameters * @param logBuildUsage */ public downloadFileOfBuild(path: string, buildLocator: string, resolveParameters?: boolean, logBuildUsage?: boolean, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.downloadFileOfBuild(path, buildLocator, resolveParameters, logBuildUsage, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.downloadFileOfBuild(rsp))); })); } /** * Get the build status of aggregated matching builds. * @param buildLocator */ public getAggregatedBuildStatus(buildLocator: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.getAggregatedBuildStatus(buildLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAggregatedBuildStatus(rsp))); })); } /** * Get the status icon (in specified format) of aggregated matching builds. * @param buildLocator * @param suffix */ public getAggregatedBuildStatusIcon(buildLocator: string, suffix: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.getAggregatedBuildStatusIcon(buildLocator, suffix, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAggregatedBuildStatusIcon(rsp))); })); } /** * Get all builds. * @param locator * @param fields */ public getAllBuilds(locator?: string, fields?: string, options?: Configuration): Observable<Builds> { const requestContextPromise = this.requestFactory.getAllBuilds(locator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAllBuilds(rsp))); })); } /** * Get artifact dependency changes of the matching build. * @param buildLocator * @param fields */ public getArtifactDependencyChanges(buildLocator: string, fields?: string, options?: Configuration): Observable<BuildChanges> { const requestContextPromise = this.requestFactory.getArtifactDependencyChanges(buildLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getArtifactDependencyChanges(rsp))); })); } /** * Get the artifacts' directory of the matching build. * @param buildLocator */ public getArtifactsDirectory(buildLocator: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.getArtifactsDirectory(buildLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getArtifactsDirectory(rsp))); })); } /** * Get build matching the locator. * @param buildLocator * @param fields */ public getBuild(buildLocator: string, fields?: string, options?: Configuration): Observable<Build> { const requestContextPromise = this.requestFactory.getBuild(buildLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuild(rsp))); })); } /** * Get actual build parameters of the matching build. * @param buildLocator * @param fields */ public getBuildActualParameters(buildLocator: string, fields?: string, options?: Configuration): Observable<Properties> { const requestContextPromise = this.requestFactory.getBuildActualParameters(buildLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildActualParameters(rsp))); })); } /** * Get a field of the matching build. * @param buildLocator * @param field */ public getBuildField(buildLocator: string, field: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.getBuildField(buildLocator, field, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildField(rsp))); })); } /** * Get the finish date of the matching build. * @param buildLocator */ public getBuildFinishDate(buildLocator: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.getBuildFinishDate(buildLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildFinishDate(rsp))); })); } /** * Get the number of the matching build. * @param buildLocator */ public getBuildNumber(buildLocator: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.getBuildNumber(buildLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildNumber(rsp))); })); } /** * Check if the matching build is pinned. * @param buildLocator * @param fields */ public getBuildPinInfo(buildLocator: string, fields?: string, options?: Configuration): Observable<PinInfo> { const requestContextPromise = this.requestFactory.getBuildPinInfo(buildLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildPinInfo(rsp))); })); } /** * Get build problems of the matching build. * @param buildLocator * @param fields */ public getBuildProblems(buildLocator: string, fields?: string, options?: Configuration): Observable<ProblemOccurrences> { const requestContextPromise = this.requestFactory.getBuildProblems(buildLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildProblems(rsp))); })); } /** * Get related issues of the matching build. * @param buildLocator * @param fields */ public getBuildRelatedIssues(buildLocator: string, fields?: string, options?: Configuration): Observable<IssuesUsages> { const requestContextPromise = this.requestFactory.getBuildRelatedIssues(buildLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildRelatedIssues(rsp))); })); } /** * Get the resolvement status of the matching build. * @param buildLocator * @param value */ public getBuildResolved(buildLocator: string, value: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.getBuildResolved(buildLocator, value, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildResolved(rsp))); })); } /** * Update a build parameter of the matching build. * @param buildLocator * @param propertyName */ public getBuildResultingProperties(buildLocator: string, propertyName: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.getBuildResultingProperties(buildLocator, propertyName, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildResultingProperties(rsp))); })); } /** * Get a source file of the matching build. * @param buildLocator * @param fileName */ public getBuildSourceFile(buildLocator: string, fileName: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.getBuildSourceFile(buildLocator, fileName, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildSourceFile(rsp))); })); } /** * Get a statistical value of the matching build. * @param buildLocator * @param name */ public getBuildStatisticValue(buildLocator: string, name: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.getBuildStatisticValue(buildLocator, name, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildStatisticValue(rsp))); })); } /** * Get all statistical values of the matching build. * @param buildLocator * @param fields */ public getBuildStatisticValues(buildLocator: string, fields?: string, options?: Configuration): Observable<Properties> { const requestContextPromise = this.requestFactory.getBuildStatisticValues(buildLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildStatisticValues(rsp))); })); } /** * Get the status icon (in specified format) of the matching build. * @param buildLocator * @param suffix */ public getBuildStatusIcon(buildLocator: string, suffix: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.getBuildStatusIcon(buildLocator, suffix, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildStatusIcon(rsp))); })); } /** * Get the build status text of the matching build. * @param buildLocator */ public getBuildStatusText(buildLocator: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.getBuildStatusText(buildLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildStatusText(rsp))); })); } /** * Get tags of the matching build. * @param buildLocator * @param locator * @param fields */ public getBuildTags(buildLocator: string, locator?: string, fields?: string, options?: Configuration): Observable<Tags> { const requestContextPromise = this.requestFactory.getBuildTags(buildLocator, locator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildTags(rsp))); })); } /** * Get test occurrences of the matching build. * @param buildLocator * @param fields */ public getBuildTestOccurrences(buildLocator: string, fields?: string, options?: Configuration): Observable<TestOccurrences> { const requestContextPromise = this.requestFactory.getBuildTestOccurrences(buildLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildTestOccurrences(rsp))); })); } /** * Get VCS labels of the matching build. * @param buildLocator * @param fields */ public getBuildVcsLabels(buildLocator: string, fields?: string, options?: Configuration): Observable<VcsLabels> { const requestContextPromise = this.requestFactory.getBuildVcsLabels(buildLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildVcsLabels(rsp))); })); } /** * Check if the matching build is canceled. * @param buildLocator * @param fields */ public getCanceledInfo(buildLocator: string, fields?: string, options?: Configuration): Observable<Comment> { const requestContextPromise = this.requestFactory.getCanceledInfo(buildLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getCanceledInfo(rsp))); })); } /** * Get metadata of specific file. * @param path * @param buildLocator * @param fields * @param resolveParameters * @param logBuildUsage */ public getFileMetadataOfBuild(path: string, buildLocator: string, fields?: string, resolveParameters?: boolean, logBuildUsage?: boolean, options?: Configuration): Observable<any> { const requestContextPromise = this.requestFactory.getFileMetadataOfBuild(path, buildLocator, fields, resolveParameters, logBuildUsage, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getFileMetadataOfBuild(rsp))); })); } /** * List files under this path. * @param path * @param buildLocator * @param basePath * @param locator * @param fields * @param resolveParameters * @param logBuildUsage */ public getFilesListForSubpathOfBuild(path: string, buildLocator: string, basePath?: string, locator?: string, fields?: string, resolveParameters?: boolean, logBuildUsage?: boolean, options?: Configuration): Observable<Files> { const requestContextPromise = this.requestFactory.getFilesListForSubpathOfBuild(path, buildLocator, basePath, locator, fields, resolveParameters, logBuildUsage, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getFilesListForSubpathOfBuild(rsp))); })); } /** * List all files. * @param buildLocator * @param basePath * @param locator * @param fields * @param resolveParameters * @param logBuildUsage */ public getFilesListOfBuild(buildLocator: string, basePath?: string, locator?: string, fields?: string, resolveParameters?: boolean, logBuildUsage?: boolean, options?: Configuration): Observable<Files> { const requestContextPromise = this.requestFactory.getFilesListOfBuild(buildLocator, basePath, locator, fields, resolveParameters, logBuildUsage, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getFilesListOfBuild(rsp))); })); } /** * Get multiple builds matching the locator. * @param buildLocator * @param fields */ public getMultipleBuilds(buildLocator: string, fields?: string, options?: Configuration): Observable<Builds> { const requestContextPromise = this.requestFactory.getMultipleBuilds(buildLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getMultipleBuilds(rsp))); })); } /** * Get specific file zipped. * @param path * @param buildLocator * @param basePath * @param locator * @param name * @param resolveParameters * @param logBuildUsage */ public getZippedFileOfBuild(path: string, buildLocator: string, basePath?: string, locator?: string, name?: string, resolveParameters?: boolean, logBuildUsage?: boolean, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.getZippedFileOfBuild(path, buildLocator, basePath, locator, name, resolveParameters, logBuildUsage, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getZippedFileOfBuild(rsp))); })); } /** * Starts the queued build as an agent-less build and returns the corresponding running build. * @param buildLocator * @param fields * @param body */ public markBuildAsRunning(buildLocator: string, fields?: string, body?: string, options?: Configuration): Observable<Build> { const requestContextPromise = this.requestFactory.markBuildAsRunning(buildLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.markBuildAsRunning(rsp))); })); } /** * Pin multiple matching builds. * @param buildLocator * @param fields * @param body */ public pinMultipleBuilds(buildLocator: string, fields?: string, body?: PinInfo, options?: Configuration): Observable<MultipleOperationResult> { const requestContextPromise = this.requestFactory.pinMultipleBuilds(buildLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.pinMultipleBuilds(rsp))); })); } /** * Remove tags from multiple matching builds. * @param buildLocator * @param fields * @param body */ public removeMultipleBuildTags(buildLocator: string, fields?: string, body?: Tags, options?: Configuration): Observable<MultipleOperationResult> { const requestContextPromise = this.requestFactory.removeMultipleBuildTags(buildLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.removeMultipleBuildTags(rsp))); })); } /** * Remove build parameters from the matching build. * @param buildLocator */ public resetBuildFinishProperties(buildLocator: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.resetBuildFinishProperties(buildLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.resetBuildFinishProperties(rsp))); })); } /** * Update the comment on the matching build. * @param buildLocator * @param body */ public setBuildComment(buildLocator: string, body?: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.setBuildComment(buildLocator, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setBuildComment(rsp))); })); } /** * Marks the running build as finished by passing agent the current time of the build to finish. * @param buildLocator * @param body */ public setBuildFinishDate(buildLocator: string, body?: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.setBuildFinishDate(buildLocator, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setBuildFinishDate(rsp))); })); } /** * Update the number of the matching build. * @param buildLocator * @param body */ public setBuildNumber(buildLocator: string, body?: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.setBuildNumber(buildLocator, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setBuildNumber(rsp))); })); } /** * Update the pin info of the matching build. * @param buildLocator * @param fields * @param body */ public setBuildPinInfo(buildLocator: string, fields?: string, body?: PinInfo, options?: Configuration): Observable<PinInfo> { const requestContextPromise = this.requestFactory.setBuildPinInfo(buildLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setBuildPinInfo(rsp))); })); } /** * Update the build status of the matching build. * @param buildLocator * @param body */ public setBuildStatusText(buildLocator: string, body?: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.setBuildStatusText(buildLocator, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setBuildStatusText(rsp))); })); } /** * Update tags of the matching build. * @param buildLocator * @param locator * @param fields * @param body */ public setBuildTags(buildLocator: string, locator?: string, fields?: string, body?: Tags, options?: Configuration): Observable<Tags> { const requestContextPromise = this.requestFactory.setBuildTags(buildLocator, locator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setBuildTags(rsp))); })); } /** * Marks the running build as finished by passing agent the current time of the build to finish. * @param buildLocator */ public setFinishedTime(buildLocator: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.setFinishedTime(buildLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setFinishedTime(rsp))); })); } /** * Update comments in multiple matching builds. * @param buildLocator * @param fields * @param body */ public setMultipleBuildComments(buildLocator: string, fields?: string, body?: string, options?: Configuration): Observable<MultipleOperationResult> { const requestContextPromise = this.requestFactory.setMultipleBuildComments(buildLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setMultipleBuildComments(rsp))); })); } } import { BuildQueueApiRequestFactory, BuildQueueApiResponseProcessor} from "../apis/BuildQueueApi.ts"; export class ObservableBuildQueueApi { private requestFactory: BuildQueueApiRequestFactory; private responseProcessor: BuildQueueApiResponseProcessor; private configuration: Configuration; public constructor( configuration: Configuration, requestFactory?: BuildQueueApiRequestFactory, responseProcessor?: BuildQueueApiResponseProcessor ) { this.configuration = configuration; this.requestFactory = requestFactory || new BuildQueueApiRequestFactory(configuration); this.responseProcessor = responseProcessor || new BuildQueueApiResponseProcessor(); } /** * Add a new build to the queue. * @param moveToTop * @param body */ public addBuildToQueue(moveToTop?: boolean, body?: Build, options?: Configuration): Observable<Build> { const requestContextPromise = this.requestFactory.addBuildToQueue(moveToTop, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.addBuildToQueue(rsp))); })); } /** * Add tags to the matching build. * @param buildLocator * @param body */ public addTagsToBuildOfBuildQueue(buildLocator: string, body?: Tags, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.addTagsToBuildOfBuildQueue(buildLocator, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.addTagsToBuildOfBuildQueue(rsp))); })); } /** * Cancel a queued matching build. * @param queuedBuildLocator * @param body */ public cancelQueuedBuild(queuedBuildLocator: string, body?: BuildCancelRequest, options?: Configuration): Observable<Build> { const requestContextPromise = this.requestFactory.cancelQueuedBuild(queuedBuildLocator, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.cancelQueuedBuild(rsp))); })); } /** * Delete all queued builds. * @param locator * @param fields */ public deleteAllQueuedBuilds(locator?: string, fields?: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.deleteAllQueuedBuilds(locator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.deleteAllQueuedBuilds(rsp))); })); } /** * Delete a queued matching build. * @param queuedBuildLocator */ public deleteQueuedBuild(queuedBuildLocator: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.deleteQueuedBuild(queuedBuildLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.deleteQueuedBuild(rsp))); })); } /** * Get all queued builds. * @param locator * @param fields */ public getAllQueuedBuilds(locator?: string, fields?: string, options?: Configuration): Observable<Builds> { const requestContextPromise = this.requestFactory.getAllQueuedBuilds(locator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAllQueuedBuilds(rsp))); })); } /** * Get compatible agents for a queued matching build. * @param queuedBuildLocator * @param fields */ public getCompatibleAgentsForBuild(queuedBuildLocator: string, fields?: string, options?: Configuration): Observable<Agents> { const requestContextPromise = this.requestFactory.getCompatibleAgentsForBuild(queuedBuildLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getCompatibleAgentsForBuild(rsp))); })); } /** * Get a queued matching build. * @param queuedBuildLocator * @param fields */ public getQueuedBuild(queuedBuildLocator: string, fields?: string, options?: Configuration): Observable<Build> { const requestContextPromise = this.requestFactory.getQueuedBuild(queuedBuildLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getQueuedBuild(rsp))); })); } /** * Get the queue position of a queued matching build. * @param queuePosition * @param fields */ public getQueuedBuildPosition(queuePosition: string, fields?: string, options?: Configuration): Observable<Build> { const requestContextPromise = this.requestFactory.getQueuedBuildPosition(queuePosition, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getQueuedBuildPosition(rsp))); })); } /** * Get tags of the queued matching build. * @param buildLocator * @param locator * @param fields */ public getQueuedBuildTags(buildLocator: string, locator?: string, fields?: string, options?: Configuration): Observable<Tags> { const requestContextPromise = this.requestFactory.getQueuedBuildTags(buildLocator, locator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getQueuedBuildTags(rsp))); })); } /** * Update the queue position of a queued matching build. * @param queuePosition * @param fields * @param body */ public setQueuedBuildPosition(queuePosition: string, fields?: string, body?: Build, options?: Configuration): Observable<Build> { const requestContextPromise = this.requestFactory.setQueuedBuildPosition(queuePosition, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setQueuedBuildPosition(rsp))); })); } /** * Update the build queue order. * @param fields * @param body */ public setQueuedBuildsOrder(fields?: string, body?: Builds, options?: Configuration): Observable<Builds> { const requestContextPromise = this.requestFactory.setQueuedBuildsOrder(fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setQueuedBuildsOrder(rsp))); })); } } import { BuildTypeApiRequestFactory, BuildTypeApiResponseProcessor} from "../apis/BuildTypeApi.ts"; export class ObservableBuildTypeApi { private requestFactory: BuildTypeApiRequestFactory; private responseProcessor: BuildTypeApiResponseProcessor; private configuration: Configuration; public constructor( configuration: Configuration, requestFactory?: BuildTypeApiRequestFactory, responseProcessor?: BuildTypeApiResponseProcessor ) { this.configuration = configuration; this.requestFactory = requestFactory || new BuildTypeApiRequestFactory(configuration); this.responseProcessor = responseProcessor || new BuildTypeApiResponseProcessor(); } /** * Add an agent requirement to the matching build configuration. * @param btLocator * @param fields * @param body */ public addAgentRequirementToBuildType(btLocator: string, fields?: string, body?: AgentRequirement, options?: Configuration): Observable<AgentRequirement> { const requestContextPromise = this.requestFactory.addAgentRequirementToBuildType(btLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.addAgentRequirementToBuildType(rsp))); })); } /** * Add an artifact dependency to the matching build configuration. * @param btLocator * @param fields * @param body */ public addArtifactDependencyToBuildType(btLocator: string, fields?: string, body?: ArtifactDependency, options?: Configuration): Observable<ArtifactDependency> { const requestContextPromise = this.requestFactory.addArtifactDependencyToBuildType(btLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.addArtifactDependencyToBuildType(rsp))); })); } /** * Add build feature to the matching build configuration. * @param btLocator * @param fields * @param body */ public addBuildFeatureToBuildType(btLocator: string, fields?: string, body?: Feature, options?: Configuration): Observable<Feature> { const requestContextPromise = this.requestFactory.addBuildFeatureToBuildType(btLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.addBuildFeatureToBuildType(rsp))); })); } /** * Add a build step to the matching build configuration. * @param btLocator * @param fields * @param body */ public addBuildStepToBuildType(btLocator: string, fields?: string, body?: Step, options?: Configuration): Observable<Step> { const requestContextPromise = this.requestFactory.addBuildStepToBuildType(btLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.addBuildStepToBuildType(rsp))); })); } /** * Add a build template to the matching build configuration. * @param btLocator * @param optimizeSettings * @param fields * @param body */ public addBuildTemplate(btLocator: string, optimizeSettings?: boolean, fields?: string, body?: BuildType, options?: Configuration): Observable<BuildType> { const requestContextPromise = this.requestFactory.addBuildTemplate(btLocator, optimizeSettings, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.addBuildTemplate(rsp))); })); } /** * Update build feature parameter for the matching build configuration. * @param btLocator * @param featureId * @param parameterName * @param body */ public addParameterToBuildFeature(btLocator: string, featureId: string, parameterName: string, body?: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.addParameterToBuildFeature(btLocator, featureId, parameterName, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.addParameterToBuildFeature(rsp))); })); } /** * Add a parameter to a build step of the matching build configuration. * @param btLocator * @param stepId * @param parameterName * @param body */ public addParameterToBuildStep(btLocator: string, stepId: string, parameterName: string, body?: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.addParameterToBuildStep(btLocator, stepId, parameterName, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.addParameterToBuildStep(rsp))); })); } /** * Add a snapshot dependency to the matching build configuration. * @param btLocator * @param fields * @param body */ public addSnapshotDependencyToBuildType(btLocator: string, fields?: string, body?: SnapshotDependency, options?: Configuration): Observable<SnapshotDependency> { const requestContextPromise = this.requestFactory.addSnapshotDependencyToBuildType(btLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.addSnapshotDependencyToBuildType(rsp))); })); } /** * Add a trigger to the matching build configuration. * @param btLocator * @param fields * @param body */ public addTriggerToBuildType(btLocator: string, fields?: string, body?: Trigger, options?: Configuration): Observable<Trigger> { const requestContextPromise = this.requestFactory.addTriggerToBuildType(btLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.addTriggerToBuildType(rsp))); })); } /** * Add a VCS root to the matching build. * @param btLocator * @param fields * @param body */ public addVcsRootToBuildType(btLocator: string, fields?: string, body?: VcsRootEntry, options?: Configuration): Observable<VcsRootEntry> { const requestContextPromise = this.requestFactory.addVcsRootToBuildType(btLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.addVcsRootToBuildType(rsp))); })); } /** * Create a build parameter. * @param btLocator * @param fields * @param body */ public createBuildParameterOfBuildType(btLocator: string, fields?: string, body?: Property, options?: Configuration): Observable<Property> { const requestContextPromise = this.requestFactory.createBuildParameterOfBuildType(btLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.createBuildParameterOfBuildType(rsp))); })); } /** * Create a new build configuration. * @param fields * @param body */ public createBuildType(fields?: string, body?: BuildType, options?: Configuration): Observable<BuildType> { const requestContextPromise = this.requestFactory.createBuildType(fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.createBuildType(rsp))); })); } /** * Remove an agent requirement of the matching build configuration. * @param btLocator * @param agentRequirementLocator */ public deleteAgentRequirement(btLocator: string, agentRequirementLocator: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.deleteAgentRequirement(btLocator, agentRequirementLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.deleteAgentRequirement(rsp))); })); } /** * Remove an artifact dependency from the matching build configuration. * @param btLocator * @param artifactDepLocator */ public deleteArtifactDependency(btLocator: string, artifactDepLocator: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.deleteArtifactDependency(btLocator, artifactDepLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.deleteArtifactDependency(rsp))); })); } /** * Delete build parameter. * @param name * @param btLocator */ public deleteBuildParameterOfBuildType(name: string, btLocator: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.deleteBuildParameterOfBuildType(name, btLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.deleteBuildParameterOfBuildType(rsp))); })); } /** * Delete all build parameters. * @param btLocator */ public deleteBuildParametersOfBuildType(btLocator: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.deleteBuildParametersOfBuildType(btLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.deleteBuildParametersOfBuildType(rsp))); })); } /** * Delete a build step of the matching build configuration. * @param btLocator * @param stepId */ public deleteBuildStep(btLocator: string, stepId: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.deleteBuildStep(btLocator, stepId, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.deleteBuildStep(rsp))); })); } /** * Update a parameter of a build step of the matching build configuration. * @param btLocator * @param stepId * @param fields * @param body */ public deleteBuildStepParameters(btLocator: string, stepId: string, fields?: string, body?: Properties, options?: Configuration): Observable<Properties> { const requestContextPromise = this.requestFactory.deleteBuildStepParameters(btLocator, stepId, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.deleteBuildStepParameters(rsp))); })); } /** * Delete build configuration matching the locator. * @param btLocator */ public deleteBuildType(btLocator: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.deleteBuildType(btLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.deleteBuildType(rsp))); })); } /** * Remove a build feature of the matching build configuration. * @param btLocator * @param featureId */ public deleteFeatureOfBuildType(btLocator: string, featureId: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.deleteFeatureOfBuildType(btLocator, featureId, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.deleteFeatureOfBuildType(rsp))); })); } /** * Delete a snapshot dependency of the matching build configuration. * @param btLocator * @param snapshotDepLocator */ public deleteSnapshotDependency(btLocator: string, snapshotDepLocator: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.deleteSnapshotDependency(btLocator, snapshotDepLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.deleteSnapshotDependency(rsp))); })); } /** * Delete a trigger of the matching build configuration. * @param btLocator * @param triggerLocator */ public deleteTrigger(btLocator: string, triggerLocator: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.deleteTrigger(btLocator, triggerLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.deleteTrigger(rsp))); })); } /** * Remove a VCS root of the matching build configuration. * @param btLocator * @param vcsRootLocator */ public deleteVcsRootOfBuildType(btLocator: string, vcsRootLocator: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.deleteVcsRootOfBuildType(btLocator, vcsRootLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.deleteVcsRootOfBuildType(rsp))); })); } /** * Download specific file. * @param path * @param btLocator * @param resolveParameters */ public downloadFileOfBuildType(path: string, btLocator: string, resolveParameters?: boolean, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.downloadFileOfBuildType(path, btLocator, resolveParameters, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.downloadFileOfBuildType(rsp))); })); } /** * Get an agent requirement of the matching build configuration. * @param btLocator * @param agentRequirementLocator * @param fields */ public getAgentRequirement(btLocator: string, agentRequirementLocator: string, fields?: string, options?: Configuration): Observable<AgentRequirement> { const requestContextPromise = this.requestFactory.getAgentRequirement(btLocator, agentRequirementLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAgentRequirement(rsp))); })); } /** * Get a setting of an agent requirement of the matching build configuration. * @param btLocator * @param agentRequirementLocator * @param fieldName */ public getAgentRequirementParameter(btLocator: string, agentRequirementLocator: string, fieldName: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.getAgentRequirementParameter(btLocator, agentRequirementLocator, fieldName, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAgentRequirementParameter(rsp))); })); } /** * Get external IDs of the matching build configuration. * @param btLocator * @param field */ public getAliases(btLocator: string, field?: string, options?: Configuration): Observable<Items> { const requestContextPromise = this.requestFactory.getAliases(btLocator, field, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAliases(rsp))); })); } /** * Get all agent requirements of the matching build configuration. * @param btLocator * @param fields */ public getAllAgentRequirements(btLocator: string, fields?: string, options?: Configuration): Observable<AgentRequirements> { const requestContextPromise = this.requestFactory.getAllAgentRequirements(btLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAllAgentRequirements(rsp))); })); } /** * Get all artifact dependencies of the matching build configuration. * @param btLocator * @param fields */ public getAllArtifactDependencies(btLocator: string, fields?: string, options?: Configuration): Observable<ArtifactDependencies> { const requestContextPromise = this.requestFactory.getAllArtifactDependencies(btLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAllArtifactDependencies(rsp))); })); } /** * Get all branches of the matching build configuration. * @param btLocator * @param locator * @param fields */ public getAllBranchesOfBuildType(btLocator: string, locator?: string, fields?: string, options?: Configuration): Observable<Branches> { const requestContextPromise = this.requestFactory.getAllBranchesOfBuildType(btLocator, locator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAllBranchesOfBuildType(rsp))); })); } /** * Get all parameters of a build feature of the matching build configuration. * @param btLocator * @param featureId * @param fields */ public getAllBuildFeatureParameters(btLocator: string, featureId: string, fields?: string, options?: Configuration): Observable<Properties> { const requestContextPromise = this.requestFactory.getAllBuildFeatureParameters(btLocator, featureId, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAllBuildFeatureParameters(rsp))); })); } /** * Get all build features of the matching build configuration. * @param btLocator * @param fields */ public getAllBuildFeatures(btLocator: string, fields?: string, options?: Configuration): Observable<Features> { const requestContextPromise = this.requestFactory.getAllBuildFeatures(btLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAllBuildFeatures(rsp))); })); } /** * Get all parameters of a build step of the matching build configuration. * @param btLocator * @param stepId * @param fields */ public getAllBuildStepParameters(btLocator: string, stepId: string, fields?: string, options?: Configuration): Observable<Properties> { const requestContextPromise = this.requestFactory.getAllBuildStepParameters(btLocator, stepId, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAllBuildStepParameters(rsp))); })); } /** * Get all build steps of the matching build configuration. * @param btLocator * @param fields */ public getAllBuildSteps(btLocator: string, fields?: string, options?: Configuration): Observable<Steps> { const requestContextPromise = this.requestFactory.getAllBuildSteps(btLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAllBuildSteps(rsp))); })); } /** * Get all build templates of the matching build configuration. * @param btLocator * @param fields */ public getAllBuildTemplates(btLocator: string, fields?: string, options?: Configuration): Observable<BuildTypes> { const requestContextPromise = this.requestFactory.getAllBuildTemplates(btLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAllBuildTemplates(rsp))); })); } /** * Get all build configurations. * @param locator * @param fields */ public getAllBuildTypes(locator?: string, fields?: string, options?: Configuration): Observable<BuildTypes> { const requestContextPromise = this.requestFactory.getAllBuildTypes(locator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAllBuildTypes(rsp))); })); } /** * Get all investigations of the matching build configuration. * @param btLocator * @param fields */ public getAllInvestigationsOfBuildType(btLocator: string, fields?: string, options?: Configuration): Observable<Investigations> { const requestContextPromise = this.requestFactory.getAllInvestigationsOfBuildType(btLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAllInvestigationsOfBuildType(rsp))); })); } /** * Get all snapshot dependencies of the matching build configuration. * @param btLocator * @param fields */ public getAllSnapshotDependencies(btLocator: string, fields?: string, options?: Configuration): Observable<SnapshotDependencies> { const requestContextPromise = this.requestFactory.getAllSnapshotDependencies(btLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAllSnapshotDependencies(rsp))); })); } /** * Get all triggers of the matching build configuration. * @param btLocator * @param fields */ public getAllTriggers(btLocator: string, fields?: string, options?: Configuration): Observable<Triggers> { const requestContextPromise = this.requestFactory.getAllTriggers(btLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAllTriggers(rsp))); })); } /** * Get all VCS roots of the matching build configuration. * @param btLocator * @param fields */ public getAllVcsRootsOfBuildType(btLocator: string, fields?: string, options?: Configuration): Observable<VcsRootEntries> { const requestContextPromise = this.requestFactory.getAllVcsRootsOfBuildType(btLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAllVcsRootsOfBuildType(rsp))); })); } /** * Get an artifact dependency of the matching build configuration. * @param btLocator * @param artifactDepLocator * @param fields */ public getArtifactDependency(btLocator: string, artifactDepLocator: string, fields?: string, options?: Configuration): Observable<ArtifactDependency> { const requestContextPromise = this.requestFactory.getArtifactDependency(btLocator, artifactDepLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getArtifactDependency(rsp))); })); } /** * Get a parameter of an artifact dependency of the matching build configuration. * @param btLocator * @param artifactDepLocator * @param fieldName */ public getArtifactDependencyParameter(btLocator: string, artifactDepLocator: string, fieldName: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.getArtifactDependencyParameter(btLocator, artifactDepLocator, fieldName, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getArtifactDependencyParameter(rsp))); })); } /** * Get a build feature of the matching build configuration. * @param btLocator * @param featureId * @param fields */ public getBuildFeature(btLocator: string, featureId: string, fields?: string, options?: Configuration): Observable<Feature> { const requestContextPromise = this.requestFactory.getBuildFeature(btLocator, featureId, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildFeature(rsp))); })); } /** * Get a parameter of a build feature of the matching build configuration. * @param btLocator * @param featureId * @param parameterName */ public getBuildFeatureParameter(btLocator: string, featureId: string, parameterName: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.getBuildFeatureParameter(btLocator, featureId, parameterName, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildFeatureParameter(rsp))); })); } /** * Get the setting of a build feature of the matching build configuration. * @param btLocator * @param featureId * @param name */ public getBuildFeatureSetting(btLocator: string, featureId: string, name: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.getBuildFeatureSetting(btLocator, featureId, name, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildFeatureSetting(rsp))); })); } /** * Get build parameter. * @param name * @param btLocator * @param fields */ public getBuildParameterOfBuildType(name: string, btLocator: string, fields?: string, options?: Configuration): Observable<Property> { const requestContextPromise = this.requestFactory.getBuildParameterOfBuildType(name, btLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildParameterOfBuildType(rsp))); })); } /** * Get build parameter specification. * @param name * @param btLocator */ public getBuildParameterSpecificationOfBuildType(name: string, btLocator: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.getBuildParameterSpecificationOfBuildType(name, btLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildParameterSpecificationOfBuildType(rsp))); })); } /** * Get type of build parameter. * @param name * @param btLocator */ public getBuildParameterTypeOfBuildType(name: string, btLocator: string, options?: Configuration): Observable<Type> { const requestContextPromise = this.requestFactory.getBuildParameterTypeOfBuildType(name, btLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildParameterTypeOfBuildType(rsp))); })); } /** * Get value of build parameter. * @param name * @param btLocator */ public getBuildParameterValueOfBuildType(name: string, btLocator: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.getBuildParameterValueOfBuildType(name, btLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildParameterValueOfBuildType(rsp))); })); } /** * Get build parameters. * @param btLocator * @param locator * @param fields */ public getBuildParametersOfBuildType(btLocator: string, locator?: string, fields?: string, options?: Configuration): Observable<Properties> { const requestContextPromise = this.requestFactory.getBuildParametersOfBuildType(btLocator, locator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildParametersOfBuildType(rsp))); })); } /** * Get a build step of the matching build configuration. * @param btLocator * @param stepId * @param fields */ public getBuildStep(btLocator: string, stepId: string, fields?: string, options?: Configuration): Observable<Step> { const requestContextPromise = this.requestFactory.getBuildStep(btLocator, stepId, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildStep(rsp))); })); } /** * Get a parameter of a build step of the matching build configuration. * @param btLocator * @param stepId * @param parameterName */ public getBuildStepParameter(btLocator: string, stepId: string, parameterName: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.getBuildStepParameter(btLocator, stepId, parameterName, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildStepParameter(rsp))); })); } /** * Get the setting of a build step of the matching build configuration. * @param btLocator * @param stepId * @param fieldName */ public getBuildStepSetting(btLocator: string, stepId: string, fieldName: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.getBuildStepSetting(btLocator, stepId, fieldName, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildStepSetting(rsp))); })); } /** * Get a template of the matching build configuration. * @param btLocator * @param templateLocator * @param fields */ public getBuildTemplate(btLocator: string, templateLocator: string, fields?: string, options?: Configuration): Observable<BuildType> { const requestContextPromise = this.requestFactory.getBuildTemplate(btLocator, templateLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildTemplate(rsp))); })); } /** * Get build configuration matching the locator. * @param btLocator * @param fields */ public getBuildType(btLocator: string, fields?: string, options?: Configuration): Observable<BuildType> { const requestContextPromise = this.requestFactory.getBuildType(btLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildType(rsp))); })); } /** * Get tags of builds of the matching build configuration. * @param btLocator * @param field */ public getBuildTypeBuildTags(btLocator: string, field?: string, options?: Configuration): Observable<Tags> { const requestContextPromise = this.requestFactory.getBuildTypeBuildTags(btLocator, field, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildTypeBuildTags(rsp))); })); } /** * Get builds of the matching build configuration. * @param btLocator * @param fields */ public getBuildTypeBuilds(btLocator: string, fields?: string, options?: Configuration): Observable<Builds> { const requestContextPromise = this.requestFactory.getBuildTypeBuilds(btLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildTypeBuilds(rsp))); })); } /** * Get a field of the matching build configuration. * @param btLocator * @param field */ public getBuildTypeField(btLocator: string, field: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.getBuildTypeField(btLocator, field, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildTypeField(rsp))); })); } /** * Get the settings file of the matching build configuration. * @param btLocator */ public getBuildTypeSettingsFile(btLocator: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.getBuildTypeSettingsFile(btLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildTypeSettingsFile(rsp))); })); } /** * Get metadata of specific file. * @param path * @param btLocator * @param fields * @param resolveParameters */ public getFileMetadataOfBuildType(path: string, btLocator: string, fields?: string, resolveParameters?: boolean, options?: Configuration): Observable<any> { const requestContextPromise = this.requestFactory.getFileMetadataOfBuildType(path, btLocator, fields, resolveParameters, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getFileMetadataOfBuildType(rsp))); })); } /** * List files under this path. * @param path * @param btLocator * @param basePath * @param locator * @param fields * @param resolveParameters */ public getFilesListForSubpathOfBuildType(path: string, btLocator: string, basePath?: string, locator?: string, fields?: string, resolveParameters?: boolean, options?: Configuration): Observable<Files> { const requestContextPromise = this.requestFactory.getFilesListForSubpathOfBuildType(path, btLocator, basePath, locator, fields, resolveParameters, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getFilesListForSubpathOfBuildType(rsp))); })); } /** * List all files. * @param btLocator * @param basePath * @param locator * @param fields * @param resolveParameters */ public getFilesListOfBuildType(btLocator: string, basePath?: string, locator?: string, fields?: string, resolveParameters?: boolean, options?: Configuration): Observable<Files> { const requestContextPromise = this.requestFactory.getFilesListOfBuildType(btLocator, basePath, locator, fields, resolveParameters, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getFilesListOfBuildType(rsp))); })); } /** * Get a snapshot dependency of the matching build configuration. * @param btLocator * @param snapshotDepLocator * @param fields */ public getSnapshotDependency(btLocator: string, snapshotDepLocator: string, fields?: string, options?: Configuration): Observable<SnapshotDependency> { const requestContextPromise = this.requestFactory.getSnapshotDependency(btLocator, snapshotDepLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getSnapshotDependency(rsp))); })); } /** * Get a trigger of the matching build configuration. * @param btLocator * @param triggerLocator * @param fields */ public getTrigger(btLocator: string, triggerLocator: string, fields?: string, options?: Configuration): Observable<Trigger> { const requestContextPromise = this.requestFactory.getTrigger(btLocator, triggerLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getTrigger(rsp))); })); } /** * Get a parameter of a trigger of the matching build configuration. * @param btLocator * @param triggerLocator * @param fieldName */ public getTriggerParameter(btLocator: string, triggerLocator: string, fieldName: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.getTriggerParameter(btLocator, triggerLocator, fieldName, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getTriggerParameter(rsp))); })); } /** * Get a VCS root of the matching build configuration. * @param btLocator * @param vcsRootLocator * @param fields */ public getVcsRoot(btLocator: string, vcsRootLocator: string, fields?: string, options?: Configuration): Observable<VcsRootEntry> { const requestContextPromise = this.requestFactory.getVcsRoot(btLocator, vcsRootLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getVcsRoot(rsp))); })); } /** * Get checkout rules of a VCS root of the matching build configuration. * @param btLocator * @param vcsRootLocator */ public getVcsRootCheckoutRules(btLocator: string, vcsRootLocator: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.getVcsRootCheckoutRules(btLocator, vcsRootLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getVcsRootCheckoutRules(rsp))); })); } /** * Get all VCS root instances of the matching build configuration. * @param btLocator * @param fields */ public getVcsRootInstancesOfBuildType(btLocator: string, fields?: string, options?: Configuration): Observable<VcsRootInstances> { const requestContextPromise = this.requestFactory.getVcsRootInstancesOfBuildType(btLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getVcsRootInstancesOfBuildType(rsp))); })); } /** * Get specific file zipped. * @param path * @param btLocator * @param basePath * @param locator * @param name * @param resolveParameters */ public getZippedFileOfBuildType(path: string, btLocator: string, basePath?: string, locator?: string, name?: string, resolveParameters?: boolean, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.getZippedFileOfBuildType(path, btLocator, basePath, locator, name, resolveParameters, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getZippedFileOfBuildType(rsp))); })); } /** * Detach all templates from the matching build configuration. * @param btLocator * @param inlineSettings */ public removeAllTemplates(btLocator: string, inlineSettings?: boolean, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.removeAllTemplates(btLocator, inlineSettings, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.removeAllTemplates(rsp))); })); } /** * Detach a template from the matching build configuration. * @param btLocator * @param templateLocator * @param inlineSettings */ public removeTemplate(btLocator: string, templateLocator: string, inlineSettings?: boolean, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.removeTemplate(btLocator, templateLocator, inlineSettings, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.removeTemplate(rsp))); })); } /** * Update an agent requirement of the matching build configuration. * @param btLocator * @param agentRequirementLocator * @param fields * @param body */ public replaceAgentRequirement(btLocator: string, agentRequirementLocator: string, fields?: string, body?: AgentRequirement, options?: Configuration): Observable<AgentRequirement> { const requestContextPromise = this.requestFactory.replaceAgentRequirement(btLocator, agentRequirementLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.replaceAgentRequirement(rsp))); })); } /** * Update all agent requirements of the matching build configuration. * @param btLocator * @param fields * @param body */ public replaceAllAgentRequirements(btLocator: string, fields?: string, body?: AgentRequirements, options?: Configuration): Observable<AgentRequirements> { const requestContextPromise = this.requestFactory.replaceAllAgentRequirements(btLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.replaceAllAgentRequirements(rsp))); })); } /** * Update all artifact dependencies of the matching build configuration. * @param btLocator * @param fields * @param body */ public replaceAllArtifactDependencies(btLocator: string, fields?: string, body?: ArtifactDependencies, options?: Configuration): Observable<ArtifactDependencies> { const requestContextPromise = this.requestFactory.replaceAllArtifactDependencies(btLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.replaceAllArtifactDependencies(rsp))); })); } /** * Update all build features of the matching build configuration. * @param btLocator * @param fields * @param body */ public replaceAllBuildFeatures(btLocator: string, fields?: string, body?: Features, options?: Configuration): Observable<Features> { const requestContextPromise = this.requestFactory.replaceAllBuildFeatures(btLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.replaceAllBuildFeatures(rsp))); })); } /** * Update all build steps of the matching build configuration. * @param btLocator * @param fields * @param body */ public replaceAllBuildSteps(btLocator: string, fields?: string, body?: Steps, options?: Configuration): Observable<Steps> { const requestContextPromise = this.requestFactory.replaceAllBuildSteps(btLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.replaceAllBuildSteps(rsp))); })); } /** * Update all snapshot dependencies of the matching build configuration. * @param btLocator * @param fields * @param body */ public replaceAllSnapshotDependencies(btLocator: string, fields?: string, body?: SnapshotDependencies, options?: Configuration): Observable<SnapshotDependencies> { const requestContextPromise = this.requestFactory.replaceAllSnapshotDependencies(btLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.replaceAllSnapshotDependencies(rsp))); })); } /** * Update all triggers of the matching build configuration. * @param btLocator * @param fields * @param body */ public replaceAllTriggers(btLocator: string, fields?: string, body?: Triggers, options?: Configuration): Observable<Triggers> { const requestContextPromise = this.requestFactory.replaceAllTriggers(btLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.replaceAllTriggers(rsp))); })); } /** * Update all VCS roots of the matching build configuration. * @param btLocator * @param fields * @param body */ public replaceAllVcsRoots(btLocator: string, fields?: string, body?: VcsRootEntries, options?: Configuration): Observable<VcsRootEntries> { const requestContextPromise = this.requestFactory.replaceAllVcsRoots(btLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.replaceAllVcsRoots(rsp))); })); } /** * Update an artifact dependency of the matching build configuration. * @param btLocator * @param artifactDepLocator * @param fields * @param body */ public replaceArtifactDependency(btLocator: string, artifactDepLocator: string, fields?: string, body?: ArtifactDependency, options?: Configuration): Observable<ArtifactDependency> { const requestContextPromise = this.requestFactory.replaceArtifactDependency(btLocator, artifactDepLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.replaceArtifactDependency(rsp))); })); } /** * Update a build feature of the matching build configuration. * @param btLocator * @param featureId * @param fields * @param body */ public replaceBuildFeature(btLocator: string, featureId: string, fields?: string, body?: Feature, options?: Configuration): Observable<Feature> { const requestContextPromise = this.requestFactory.replaceBuildFeature(btLocator, featureId, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.replaceBuildFeature(rsp))); })); } /** * Update a parameter of a build feature of the matching build configuration. * @param btLocator * @param featureId * @param fields * @param body */ public replaceBuildFeatureParameters(btLocator: string, featureId: string, fields?: string, body?: Properties, options?: Configuration): Observable<Properties> { const requestContextPromise = this.requestFactory.replaceBuildFeatureParameters(btLocator, featureId, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.replaceBuildFeatureParameters(rsp))); })); } /** * Replace a build step of the matching build configuration. * @param btLocator * @param stepId * @param fields * @param body */ public replaceBuildStep(btLocator: string, stepId: string, fields?: string, body?: Step, options?: Configuration): Observable<Step> { const requestContextPromise = this.requestFactory.replaceBuildStep(btLocator, stepId, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.replaceBuildStep(rsp))); })); } /** * Update a snapshot dependency of the matching build configuration. * @param btLocator * @param snapshotDepLocator * @param fields * @param body */ public replaceSnapshotDependency(btLocator: string, snapshotDepLocator: string, fields?: string, body?: SnapshotDependency, options?: Configuration): Observable<SnapshotDependency> { const requestContextPromise = this.requestFactory.replaceSnapshotDependency(btLocator, snapshotDepLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.replaceSnapshotDependency(rsp))); })); } /** * Update a trigger of the matching build configuration. * @param btLocator * @param triggerLocator * @param fields * @param body */ public replaceTrigger(btLocator: string, triggerLocator: string, fields?: string, body?: Trigger, options?: Configuration): Observable<Trigger> { const requestContextPromise = this.requestFactory.replaceTrigger(btLocator, triggerLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.replaceTrigger(rsp))); })); } /** * Update a parameter of an agent requirement of the matching build configuration. * @param btLocator * @param agentRequirementLocator * @param fieldName * @param body */ public setAgentRequirementParameter(btLocator: string, agentRequirementLocator: string, fieldName: string, body?: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.setAgentRequirementParameter(btLocator, agentRequirementLocator, fieldName, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setAgentRequirementParameter(rsp))); })); } /** * Update a parameter of an artifact dependency of the matching build configuration. * @param btLocator * @param artifactDepLocator * @param fieldName * @param body */ public setArtifactDependencyParameter(btLocator: string, artifactDepLocator: string, fieldName: string, body?: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.setArtifactDependencyParameter(btLocator, artifactDepLocator, fieldName, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setArtifactDependencyParameter(rsp))); })); } /** * Update a parameter of a build feature of the matching build configuration. * @param btLocator * @param featureId * @param name * @param body */ public setBuildFeatureParameter(btLocator: string, featureId: string, name: string, body?: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.setBuildFeatureParameter(btLocator, featureId, name, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setBuildFeatureParameter(rsp))); })); } /** * Update a parameter of a build step of the matching build configuration. * @param btLocator * @param stepId * @param fieldName * @param body */ public setBuildStepParameter(btLocator: string, stepId: string, fieldName: string, body?: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.setBuildStepParameter(btLocator, stepId, fieldName, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setBuildStepParameter(rsp))); })); } /** * Update a field of the matching build configuration. * @param btLocator * @param field * @param body */ public setBuildTypeField(btLocator: string, field: string, body?: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.setBuildTypeField(btLocator, field, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setBuildTypeField(rsp))); })); } /** * Update all templates of the matching build configuration. * @param btLocator * @param optimizeSettings * @param fields * @param body */ public setBuildTypeTemplates(btLocator: string, optimizeSettings?: boolean, fields?: string, body?: BuildTypes, options?: Configuration): Observable<BuildTypes> { const requestContextPromise = this.requestFactory.setBuildTypeTemplates(btLocator, optimizeSettings, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setBuildTypeTemplates(rsp))); })); } /** * Update a parameter of a trigger of the matching build configuration. * @param btLocator * @param triggerLocator * @param fieldName * @param body */ public setTriggerParameter(btLocator: string, triggerLocator: string, fieldName: string, body?: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.setTriggerParameter(btLocator, triggerLocator, fieldName, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setTriggerParameter(rsp))); })); } /** * Update build parameter. * @param name * @param btLocator * @param fields * @param body */ public updateBuildParameterOfBuildType(name: string, btLocator: string, fields?: string, body?: Property, options?: Configuration): Observable<Property> { const requestContextPromise = this.requestFactory.updateBuildParameterOfBuildType(name, btLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.updateBuildParameterOfBuildType(rsp))); })); } /** * Update build parameter specification. * @param name * @param btLocator * @param body */ public updateBuildParameterSpecificationOfBuildType(name: string, btLocator: string, body?: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.updateBuildParameterSpecificationOfBuildType(name, btLocator, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.updateBuildParameterSpecificationOfBuildType(rsp))); })); } /** * Update type of build parameter. * @param name * @param btLocator * @param body */ public updateBuildParameterTypeOfBuildType(name: string, btLocator: string, body?: Type, options?: Configuration): Observable<Type> { const requestContextPromise = this.requestFactory.updateBuildParameterTypeOfBuildType(name, btLocator, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.updateBuildParameterTypeOfBuildType(rsp))); })); } /** * Update value of build parameter. * @param name * @param btLocator * @param body */ public updateBuildParameterValueOfBuildType(name: string, btLocator: string, body?: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.updateBuildParameterValueOfBuildType(name, btLocator, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.updateBuildParameterValueOfBuildType(rsp))); })); } /** * Update build parameters. * @param btLocator * @param fields * @param body */ public updateBuildParametersOfBuildType(btLocator: string, fields?: string, body?: Properties, options?: Configuration): Observable<Properties> { const requestContextPromise = this.requestFactory.updateBuildParametersOfBuildType(btLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.updateBuildParametersOfBuildType(rsp))); })); } /** * Update a VCS root of the matching build configuration. * @param btLocator * @param vcsRootLocator * @param fields * @param body */ public updateBuildTypeVcsRoot(btLocator: string, vcsRootLocator: string, fields?: string, body?: VcsRootEntry, options?: Configuration): Observable<VcsRootEntry> { const requestContextPromise = this.requestFactory.updateBuildTypeVcsRoot(btLocator, vcsRootLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.updateBuildTypeVcsRoot(rsp))); })); } /** * Update checkout rules of a VCS root of the matching build configuration. * @param btLocator * @param vcsRootLocator * @param body */ public updateBuildTypeVcsRootCheckoutRules(btLocator: string, vcsRootLocator: string, body?: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.updateBuildTypeVcsRootCheckoutRules(btLocator, vcsRootLocator, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.updateBuildTypeVcsRootCheckoutRules(rsp))); })); } } import { ChangeApiRequestFactory, ChangeApiResponseProcessor} from "../apis/ChangeApi.ts"; export class ObservableChangeApi { private requestFactory: ChangeApiRequestFactory; private responseProcessor: ChangeApiResponseProcessor; private configuration: Configuration; public constructor( configuration: Configuration, requestFactory?: ChangeApiRequestFactory, responseProcessor?: ChangeApiResponseProcessor ) { this.configuration = configuration; this.requestFactory = requestFactory || new ChangeApiRequestFactory(configuration); this.responseProcessor = responseProcessor || new ChangeApiResponseProcessor(); } /** * Get all changes. * @param locator * @param fields */ public getAllChanges(locator?: string, fields?: string, options?: Configuration): Observable<Changes> { const requestContextPromise = this.requestFactory.getAllChanges(locator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAllChanges(rsp))); })); } /** * Get change matching the locator. * @param changeLocator * @param fields */ public getChange(changeLocator: string, fields?: string, options?: Configuration): Observable<Change> { const requestContextPromise = this.requestFactory.getChange(changeLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getChange(rsp))); })); } /** * Get attributes of the matching change. * @param changeLocator * @param fields */ public getChangeAttributes(changeLocator: string, fields?: string, options?: Configuration): Observable<Entries> { const requestContextPromise = this.requestFactory.getChangeAttributes(changeLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getChangeAttributes(rsp))); })); } /** * Get duplicates of the matching change. * @param changeLocator * @param fields */ public getChangeDuplicates(changeLocator: string, fields?: string, options?: Configuration): Observable<Changes> { const requestContextPromise = this.requestFactory.getChangeDuplicates(changeLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getChangeDuplicates(rsp))); })); } /** * Get a field of the matching change. * @param changeLocator * @param field */ public getChangeField(changeLocator: string, field: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.getChangeField(changeLocator, field, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getChangeField(rsp))); })); } /** * Get first builds of the matching change. * @param changeLocator * @param fields */ public getChangeFirstBuilds(changeLocator: string, fields?: string, options?: Configuration): Observable<Builds> { const requestContextPromise = this.requestFactory.getChangeFirstBuilds(changeLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getChangeFirstBuilds(rsp))); })); } /** * Get issues of the matching change. * @param changeLocator */ public getChangeIssue(changeLocator: string, options?: Configuration): Observable<Issues> { const requestContextPromise = this.requestFactory.getChangeIssue(changeLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getChangeIssue(rsp))); })); } /** * Get parent changes of the matching change. * @param changeLocator * @param fields */ public getChangeParentChanges(changeLocator: string, fields?: string, options?: Configuration): Observable<Changes> { const requestContextPromise = this.requestFactory.getChangeParentChanges(changeLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getChangeParentChanges(rsp))); })); } /** * Get parent revisions of the matching change. * @param changeLocator */ public getChangeParentRevisions(changeLocator: string, options?: Configuration): Observable<Items> { const requestContextPromise = this.requestFactory.getChangeParentRevisions(changeLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getChangeParentRevisions(rsp))); })); } /** * Get build configurations related to the matching change. * @param changeLocator * @param fields */ public getChangeRelatedBuildTypes(changeLocator: string, fields?: string, options?: Configuration): Observable<BuildTypes> { const requestContextPromise = this.requestFactory.getChangeRelatedBuildTypes(changeLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getChangeRelatedBuildTypes(rsp))); })); } /** * Get a VCS root instance of the matching change. * @param changeLocator * @param fields */ public getChangeVcsRoot(changeLocator: string, fields?: string, options?: Configuration): Observable<VcsRootInstance> { const requestContextPromise = this.requestFactory.getChangeVcsRoot(changeLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getChangeVcsRoot(rsp))); })); } } import { CloudInstanceApiRequestFactory, CloudInstanceApiResponseProcessor} from "../apis/CloudInstanceApi.ts"; export class ObservableCloudInstanceApi { private requestFactory: CloudInstanceApiRequestFactory; private responseProcessor: CloudInstanceApiResponseProcessor; private configuration: Configuration; public constructor( configuration: Configuration, requestFactory?: CloudInstanceApiRequestFactory, responseProcessor?: CloudInstanceApiResponseProcessor ) { this.configuration = configuration; this.requestFactory = requestFactory || new CloudInstanceApiRequestFactory(configuration); this.responseProcessor = responseProcessor || new CloudInstanceApiResponseProcessor(); } /** * Get all cloud images. * @param locator * @param fields */ public getAllCloudImages(locator?: string, fields?: string, options?: Configuration): Observable<CloudImages> { const requestContextPromise = this.requestFactory.getAllCloudImages(locator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAllCloudImages(rsp))); })); } /** * Get all cloud instances. * @param locator * @param fields */ public getAllCloudInstances(locator?: string, fields?: string, options?: Configuration): Observable<CloudInstances> { const requestContextPromise = this.requestFactory.getAllCloudInstances(locator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAllCloudInstances(rsp))); })); } /** * Get all cloud profiles. * @param locator * @param fields */ public getAllCloudProfiles(locator?: string, fields?: string, options?: Configuration): Observable<CloudProfiles> { const requestContextPromise = this.requestFactory.getAllCloudProfiles(locator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAllCloudProfiles(rsp))); })); } /** * Get cloud image matching the locator. * @param imageLocator * @param fields */ public getCloudImage(imageLocator: string, fields?: string, options?: Configuration): Observable<CloudImage> { const requestContextPromise = this.requestFactory.getCloudImage(imageLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getCloudImage(rsp))); })); } /** * Get cloud instance matching the locator. * @param instanceLocator * @param fields */ public getCloudInstance(instanceLocator: string, fields?: string, options?: Configuration): Observable<CloudInstance> { const requestContextPromise = this.requestFactory.getCloudInstance(instanceLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getCloudInstance(rsp))); })); } /** * Get cloud profile matching the locator. * @param profileLocator * @param fields */ public getCloudProfile(profileLocator: string, fields?: string, options?: Configuration): Observable<CloudProfile> { const requestContextPromise = this.requestFactory.getCloudProfile(profileLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getCloudProfile(rsp))); })); } /** * Start a new cloud instance. * @param fields * @param body */ public startInstance(fields?: string, body?: CloudInstance, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.startInstance(fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.startInstance(rsp))); })); } /** * Stop cloud instance matching the locator. * @param instanceLocator */ public stopInstance(instanceLocator: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.stopInstance(instanceLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.stopInstance(rsp))); })); } } import { GroupApiRequestFactory, GroupApiResponseProcessor} from "../apis/GroupApi.ts"; export class ObservableGroupApi { private requestFactory: GroupApiRequestFactory; private responseProcessor: GroupApiResponseProcessor; private configuration: Configuration; public constructor( configuration: Configuration, requestFactory?: GroupApiRequestFactory, responseProcessor?: GroupApiResponseProcessor ) { this.configuration = configuration; this.requestFactory = requestFactory || new GroupApiRequestFactory(configuration); this.responseProcessor = responseProcessor || new GroupApiResponseProcessor(); } /** * Add a new user group. * @param fields * @param body */ public addGroup(fields?: string, body?: Group, options?: Configuration): Observable<Group> { const requestContextPromise = this.requestFactory.addGroup(fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.addGroup(rsp))); })); } /** * Add a role with the specific scope to the matching user group. * @param groupLocator * @param roleId * @param scope */ public addRoleAtScopeToGroup(groupLocator: string, roleId: string, scope: string, options?: Configuration): Observable<Role> { const requestContextPromise = this.requestFactory.addRoleAtScopeToGroup(groupLocator, roleId, scope, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.addRoleAtScopeToGroup(rsp))); })); } /** * Add a role to the matching user group. * @param groupLocator * @param body */ public addRoleToGroup(groupLocator: string, body?: Role, options?: Configuration): Observable<Role> { const requestContextPromise = this.requestFactory.addRoleToGroup(groupLocator, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.addRoleToGroup(rsp))); })); } /** * Delete user group matching the locator. * @param groupLocator */ public deleteGroup(groupLocator: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.deleteGroup(groupLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.deleteGroup(rsp))); })); } /** * Get all user groups. * @param fields */ public getAllGroups(fields?: string, options?: Configuration): Observable<Groups> { const requestContextPromise = this.requestFactory.getAllGroups(fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAllGroups(rsp))); })); } /** * Get parent groups of the matching user group. * @param groupLocator * @param fields */ public getGroupParentGroups(groupLocator: string, fields?: string, options?: Configuration): Observable<Groups> { const requestContextPromise = this.requestFactory.getGroupParentGroups(groupLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getGroupParentGroups(rsp))); })); } /** * Get properties of the matching user group. * @param groupLocator * @param fields */ public getGroupProperties(groupLocator: string, fields?: string, options?: Configuration): Observable<Properties> { const requestContextPromise = this.requestFactory.getGroupProperties(groupLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getGroupProperties(rsp))); })); } /** * Get a property of the matching user group. * @param groupLocator * @param name */ public getGroupProperty(groupLocator: string, name: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.getGroupProperty(groupLocator, name, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getGroupProperty(rsp))); })); } /** * Get a role with the specific scope of the matching user group. * @param groupLocator * @param roleId * @param scope */ public getGroupRoleAtScope(groupLocator: string, roleId: string, scope: string, options?: Configuration): Observable<Role> { const requestContextPromise = this.requestFactory.getGroupRoleAtScope(groupLocator, roleId, scope, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getGroupRoleAtScope(rsp))); })); } /** * Get all roles of the matching user group. * @param groupLocator */ public getGroupRoles(groupLocator: string, options?: Configuration): Observable<Roles> { const requestContextPromise = this.requestFactory.getGroupRoles(groupLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getGroupRoles(rsp))); })); } /** * Get user group matching the locator. * @param groupLocator * @param fields */ public getUserGroupOfGroup(groupLocator: string, fields?: string, options?: Configuration): Observable<Group> { const requestContextPromise = this.requestFactory.getUserGroupOfGroup(groupLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getUserGroupOfGroup(rsp))); })); } /** * Remove a property of the matching user group. * @param groupLocator * @param name */ public removeGroupProperty(groupLocator: string, name: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.removeGroupProperty(groupLocator, name, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.removeGroupProperty(rsp))); })); } /** * Remove a role with the specific scope from the matching user group. * @param groupLocator * @param roleId * @param scope */ public removeRoleAtScopeFromGroup(groupLocator: string, roleId: string, scope: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.removeRoleAtScopeFromGroup(groupLocator, roleId, scope, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.removeRoleAtScopeFromGroup(rsp))); })); } /** * Update parent groups of the matching user group. * @param groupLocator * @param fields * @param body */ public setGroupParentGroups(groupLocator: string, fields?: string, body?: Groups, options?: Configuration): Observable<Groups> { const requestContextPromise = this.requestFactory.setGroupParentGroups(groupLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setGroupParentGroups(rsp))); })); } /** * Update a property of the matching user group. * @param groupLocator * @param name * @param body */ public setGroupProperty(groupLocator: string, name: string, body?: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.setGroupProperty(groupLocator, name, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setGroupProperty(rsp))); })); } /** * Update roles of the matching user group. * @param groupLocator * @param body */ public setGroupRoles(groupLocator: string, body?: Roles, options?: Configuration): Observable<Roles> { const requestContextPromise = this.requestFactory.setGroupRoles(groupLocator, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setGroupRoles(rsp))); })); } } import { InvestigationApiRequestFactory, InvestigationApiResponseProcessor} from "../apis/InvestigationApi.ts"; export class ObservableInvestigationApi { private requestFactory: InvestigationApiRequestFactory; private responseProcessor: InvestigationApiResponseProcessor; private configuration: Configuration; public constructor( configuration: Configuration, requestFactory?: InvestigationApiRequestFactory, responseProcessor?: InvestigationApiResponseProcessor ) { this.configuration = configuration; this.requestFactory = requestFactory || new InvestigationApiRequestFactory(configuration); this.responseProcessor = responseProcessor || new InvestigationApiResponseProcessor(); } /** * Create a new investigation. * @param fields * @param body */ public addInvestigation(fields?: string, body?: Investigation, options?: Configuration): Observable<Investigation> { const requestContextPromise = this.requestFactory.addInvestigation(fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.addInvestigation(rsp))); })); } /** * Create multiple new investigations. * @param fields * @param body */ public addMultipleInvestigations(fields?: string, body?: Investigations, options?: Configuration): Observable<Investigations> { const requestContextPromise = this.requestFactory.addMultipleInvestigations(fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.addMultipleInvestigations(rsp))); })); } /** * Delete investigation matching the locator. * @param investigationLocator */ public deleteInvestigation(investigationLocator: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.deleteInvestigation(investigationLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.deleteInvestigation(rsp))); })); } /** * Get all investigations. * @param locator * @param fields */ public getAllInvestigations(locator?: string, fields?: string, options?: Configuration): Observable<Investigations> { const requestContextPromise = this.requestFactory.getAllInvestigations(locator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAllInvestigations(rsp))); })); } /** * Get investigation matching the locator. * @param investigationLocator * @param fields */ public getInvestigation(investigationLocator: string, fields?: string, options?: Configuration): Observable<Investigation> { const requestContextPromise = this.requestFactory.getInvestigation(investigationLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getInvestigation(rsp))); })); } /** * Update investigation matching the locator. * @param investigationLocator * @param fields * @param body */ public replaceInvestigation(investigationLocator: string, fields?: string, body?: Investigation, options?: Configuration): Observable<Investigation> { const requestContextPromise = this.requestFactory.replaceInvestigation(investigationLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.replaceInvestigation(rsp))); })); } } import { MuteApiRequestFactory, MuteApiResponseProcessor} from "../apis/MuteApi.ts"; export class ObservableMuteApi { private requestFactory: MuteApiRequestFactory; private responseProcessor: MuteApiResponseProcessor; private configuration: Configuration; public constructor( configuration: Configuration, requestFactory?: MuteApiRequestFactory, responseProcessor?: MuteApiResponseProcessor ) { this.configuration = configuration; this.requestFactory = requestFactory || new MuteApiRequestFactory(configuration); this.responseProcessor = responseProcessor || new MuteApiResponseProcessor(); } /** * Get all muted tests. * @param locator * @param fields */ public getAllMutedTests(locator?: string, fields?: string, options?: Configuration): Observable<Mutes> { const requestContextPromise = this.requestFactory.getAllMutedTests(locator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAllMutedTests(rsp))); })); } /** * Get a muted test. * @param muteLocator * @param fields */ public getMutedTest(muteLocator: string, fields?: string, options?: Configuration): Observable<Mute> { const requestContextPromise = this.requestFactory.getMutedTest(muteLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getMutedTest(rsp))); })); } /** * Mute multiple tests. * @param fields * @param body */ public muteMultipleTests(fields?: string, body?: Mutes, options?: Configuration): Observable<Mutes> { const requestContextPromise = this.requestFactory.muteMultipleTests(fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.muteMultipleTests(rsp))); })); } /** * Mute a test. * @param fields * @param body */ public muteTest(fields?: string, body?: Mute, options?: Configuration): Observable<Mute> { const requestContextPromise = this.requestFactory.muteTest(fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.muteTest(rsp))); })); } /** * Unmute the matching test. * @param muteLocator * @param body */ public unmuteTest(muteLocator: string, body?: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.unmuteTest(muteLocator, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.unmuteTest(rsp))); })); } } import { ProblemApiRequestFactory, ProblemApiResponseProcessor} from "../apis/ProblemApi.ts"; export class ObservableProblemApi { private requestFactory: ProblemApiRequestFactory; private responseProcessor: ProblemApiResponseProcessor; private configuration: Configuration; public constructor( configuration: Configuration, requestFactory?: ProblemApiRequestFactory, responseProcessor?: ProblemApiResponseProcessor ) { this.configuration = configuration; this.requestFactory = requestFactory || new ProblemApiRequestFactory(configuration); this.responseProcessor = responseProcessor || new ProblemApiResponseProcessor(); } /** * Get all build problems. * @param locator * @param fields */ public getAllBuildProblems(locator?: string, fields?: string, options?: Configuration): Observable<Problems> { const requestContextPromise = this.requestFactory.getAllBuildProblems(locator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAllBuildProblems(rsp))); })); } /** * Get a matching build problem. * @param problemLocator * @param fields */ public getBuildProblem(problemLocator: string, fields?: string, options?: Configuration): Observable<Problem> { const requestContextPromise = this.requestFactory.getBuildProblem(problemLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildProblem(rsp))); })); } } import { ProblemOccurrenceApiRequestFactory, ProblemOccurrenceApiResponseProcessor} from "../apis/ProblemOccurrenceApi.ts"; export class ObservableProblemOccurrenceApi { private requestFactory: ProblemOccurrenceApiRequestFactory; private responseProcessor: ProblemOccurrenceApiResponseProcessor; private configuration: Configuration; public constructor( configuration: Configuration, requestFactory?: ProblemOccurrenceApiRequestFactory, responseProcessor?: ProblemOccurrenceApiResponseProcessor ) { this.configuration = configuration; this.requestFactory = requestFactory || new ProblemOccurrenceApiRequestFactory(configuration); this.responseProcessor = responseProcessor || new ProblemOccurrenceApiResponseProcessor(); } /** * Get all build problem occurrences. * @param locator * @param fields */ public getAllBuildProblemOccurrences(locator?: string, fields?: string, options?: Configuration): Observable<ProblemOccurrences> { const requestContextPromise = this.requestFactory.getAllBuildProblemOccurrences(locator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAllBuildProblemOccurrences(rsp))); })); } /** * Get a matching build problem occurrence. * @param problemLocator * @param fields */ public getBuildProblemOccurrence(problemLocator: string, fields?: string, options?: Configuration): Observable<ProblemOccurrence> { const requestContextPromise = this.requestFactory.getBuildProblemOccurrence(problemLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildProblemOccurrence(rsp))); })); } } import { ProjectApiRequestFactory, ProjectApiResponseProcessor} from "../apis/ProjectApi.ts"; export class ObservableProjectApi { private requestFactory: ProjectApiRequestFactory; private responseProcessor: ProjectApiResponseProcessor; private configuration: Configuration; public constructor( configuration: Configuration, requestFactory?: ProjectApiRequestFactory, responseProcessor?: ProjectApiResponseProcessor ) { this.configuration = configuration; this.requestFactory = requestFactory || new ProjectApiRequestFactory(configuration); this.responseProcessor = responseProcessor || new ProjectApiResponseProcessor(); } /** * Assign the matching project to the agent pool. * @param projectLocator * @param body */ public addAgentPoolsProject(projectLocator: string, body?: AgentPool, options?: Configuration): Observable<AgentPool> { const requestContextPromise = this.requestFactory.addAgentPoolsProject(projectLocator, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.addAgentPoolsProject(rsp))); })); } /** * Add a build configuration to the matching project. * @param projectLocator * @param fields * @param body */ public addBuildType(projectLocator: string, fields?: string, body?: NewBuildTypeDescription, options?: Configuration): Observable<BuildType> { const requestContextPromise = this.requestFactory.addBuildType(projectLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.addBuildType(rsp))); })); } /** * Add a feature. * @param projectLocator * @param fields * @param body */ public addFeature(projectLocator: string, fields?: string, body?: ProjectFeature, options?: Configuration): Observable<any> { const requestContextPromise = this.requestFactory.addFeature(projectLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.addFeature(rsp))); })); } /** * Create a new project. * @param body */ public addProject(body?: NewProjectDescription, options?: Configuration): Observable<Project> { const requestContextPromise = this.requestFactory.addProject(body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.addProject(rsp))); })); } /** * Create a new secure token for the matching project. * @param projectLocator * @param body */ public addSecureToken(projectLocator: string, body?: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.addSecureToken(projectLocator, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.addSecureToken(rsp))); })); } /** * Add a build configuration template to the matching project. * @param projectLocator * @param fields * @param body */ public addTemplate(projectLocator: string, fields?: string, body?: NewBuildTypeDescription, options?: Configuration): Observable<BuildType> { const requestContextPromise = this.requestFactory.addTemplate(projectLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.addTemplate(rsp))); })); } /** * Create a build parameter. * @param projectLocator * @param fields * @param body */ public createBuildParameter(projectLocator: string, fields?: string, body?: Property, options?: Configuration): Observable<Property> { const requestContextPromise = this.requestFactory.createBuildParameter(projectLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.createBuildParameter(rsp))); })); } /** * Delete build parameter. * @param name * @param projectLocator */ public deleteBuildParameter(name: string, projectLocator: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.deleteBuildParameter(name, projectLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.deleteBuildParameter(rsp))); })); } /** * Delete all build parameters. * @param projectLocator */ public deleteBuildParameters(projectLocator: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.deleteBuildParameters(projectLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.deleteBuildParameters(rsp))); })); } /** * Delete a matching feature. * @param featureLocator * @param projectLocator */ public deleteFeature(featureLocator: string, projectLocator: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.deleteFeature(featureLocator, projectLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.deleteFeature(rsp))); })); } /** * Delete project matching the locator. * @param projectLocator */ public deleteProject(projectLocator: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.deleteProject(projectLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.deleteProject(rsp))); })); } /** * Get agent pools appointed to the matching project. * @param projectLocator * @param fields */ public getAgentPoolsProject(projectLocator: string, fields?: string, options?: Configuration): Observable<AgentPools> { const requestContextPromise = this.requestFactory.getAgentPoolsProject(projectLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAgentPoolsProject(rsp))); })); } /** * Get all branches of the matching project. * @param projectLocator * @param locator * @param fields */ public getAllBranches(projectLocator: string, locator?: string, fields?: string, options?: Configuration): Observable<Branches> { const requestContextPromise = this.requestFactory.getAllBranches(projectLocator, locator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAllBranches(rsp))); })); } /** * Get all projects. * @param locator * @param fields */ public getAllProjects(locator?: string, fields?: string, options?: Configuration): Observable<Projects> { const requestContextPromise = this.requestFactory.getAllProjects(locator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAllProjects(rsp))); })); } /** * Get all subprojects ordered of the matching project. * @param projectLocator * @param field */ public getAllSubprojectsOrdered(projectLocator: string, field?: string, options?: Configuration): Observable<Projects> { const requestContextPromise = this.requestFactory.getAllSubprojectsOrdered(projectLocator, field, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAllSubprojectsOrdered(rsp))); })); } /** * Get build parameter. * @param name * @param projectLocator * @param fields */ public getBuildParameter(name: string, projectLocator: string, fields?: string, options?: Configuration): Observable<Property> { const requestContextPromise = this.requestFactory.getBuildParameter(name, projectLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildParameter(rsp))); })); } /** * Get build parameter specification. * @param name * @param projectLocator */ public getBuildParameterSpecification(name: string, projectLocator: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.getBuildParameterSpecification(name, projectLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildParameterSpecification(rsp))); })); } /** * Get type of build parameter. * @param name * @param projectLocator */ public getBuildParameterType(name: string, projectLocator: string, options?: Configuration): Observable<Type> { const requestContextPromise = this.requestFactory.getBuildParameterType(name, projectLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildParameterType(rsp))); })); } /** * Get value of build parameter. * @param name * @param projectLocator */ public getBuildParameterValue(name: string, projectLocator: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.getBuildParameterValue(name, projectLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildParameterValue(rsp))); })); } /** * Get build parameters. * @param projectLocator * @param locator * @param fields */ public getBuildParameters(projectLocator: string, locator?: string, fields?: string, options?: Configuration): Observable<Properties> { const requestContextPromise = this.requestFactory.getBuildParameters(projectLocator, locator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBuildParameters(rsp))); })); } /** * Get the default template of the matching project. * @param projectLocator * @param fields */ public getDefaultTemplate(projectLocator: string, fields?: string, options?: Configuration): Observable<BuildType> { const requestContextPromise = this.requestFactory.getDefaultTemplate(projectLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getDefaultTemplate(rsp))); })); } /** * Get a matching feature. * @param featureLocator * @param projectLocator * @param fields */ public getFeature(featureLocator: string, projectLocator: string, fields?: string, options?: Configuration): Observable<any> { const requestContextPromise = this.requestFactory.getFeature(featureLocator, projectLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getFeature(rsp))); })); } /** * Get all features. * @param projectLocator * @param locator * @param fields */ public getFeatures(projectLocator: string, locator?: string, fields?: string, options?: Configuration): Observable<any> { const requestContextPromise = this.requestFactory.getFeatures(projectLocator, locator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getFeatures(rsp))); })); } /** * Get project matching the locator. * @param projectLocator * @param fields */ public getProject(projectLocator: string, fields?: string, options?: Configuration): Observable<Project> { const requestContextPromise = this.requestFactory.getProject(projectLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getProject(rsp))); })); } /** * Get a field of the matching project. * @param projectLocator * @param field */ public getProjectField(projectLocator: string, field: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.getProjectField(projectLocator, field, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getProjectField(rsp))); })); } /** * Get the parent project of the matching project. * @param projectLocator * @param fields */ public getProjectParentProject(projectLocator: string, fields?: string, options?: Configuration): Observable<Project> { const requestContextPromise = this.requestFactory.getProjectParentProject(projectLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getProjectParentProject(rsp))); })); } /** * Get the settings file of the matching build configuration. * @param projectLocator */ public getProjectSettingsFile(projectLocator: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.getProjectSettingsFile(projectLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getProjectSettingsFile(rsp))); })); } /** * Get all templates of the matching project. * @param projectLocator * @param fields */ public getProjectTemplates(projectLocator: string, fields?: string, options?: Configuration): Observable<BuildTypes> { const requestContextPromise = this.requestFactory.getProjectTemplates(projectLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getProjectTemplates(rsp))); })); } /** * Get a secure token of the matching project. * @param projectLocator * @param token */ public getSecureValue(projectLocator: string, token: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.getSecureValue(projectLocator, token, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getSecureValue(rsp))); })); } /** * Remove the default template from the matching project. * @param projectLocator * @param fields */ public removeDefaultTemplate(projectLocator: string, fields?: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.removeDefaultTemplate(projectLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.removeDefaultTemplate(rsp))); })); } /** * Unassign a project from the matching agent pool. * @param projectLocator * @param agentPoolLocator */ public removeProjectFromAgentPool(projectLocator: string, agentPoolLocator: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.removeProjectFromAgentPool(projectLocator, agentPoolLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.removeProjectFromAgentPool(rsp))); })); } /** * Update agent pools apppointed to the matching project. * @param projectLocator * @param fields * @param body */ public setAgentPoolsProject(projectLocator: string, fields?: string, body?: AgentPools, options?: Configuration): Observable<AgentPools> { const requestContextPromise = this.requestFactory.setAgentPoolsProject(projectLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setAgentPoolsProject(rsp))); })); } /** * Update all build configurations order of the matching project. * @param projectLocator * @param field * @param body */ public setBuildTypesOrder(projectLocator: string, field?: string, body?: BuildTypes, options?: Configuration): Observable<BuildTypes> { const requestContextPromise = this.requestFactory.setBuildTypesOrder(projectLocator, field, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setBuildTypesOrder(rsp))); })); } /** * Update the default template of the matching project. * @param projectLocator * @param fields * @param body */ public setDefaultTemplate(projectLocator: string, fields?: string, body?: BuildType, options?: Configuration): Observable<BuildType> { const requestContextPromise = this.requestFactory.setDefaultTemplate(projectLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setDefaultTemplate(rsp))); })); } /** * Update the parent project of the matching project. * @param projectLocator * @param fields * @param body */ public setParentProject(projectLocator: string, fields?: string, body?: Project, options?: Configuration): Observable<Project> { const requestContextPromise = this.requestFactory.setParentProject(projectLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setParentProject(rsp))); })); } /** * Update a field of the matching project. * @param projectLocator * @param field * @param body */ public setProjectField(projectLocator: string, field: string, body?: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.setProjectField(projectLocator, field, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setProjectField(rsp))); })); } /** * Update all subprojects order of the matching project. * @param projectLocator * @param field * @param body */ public setSubprojectsOrder(projectLocator: string, field?: string, body?: Projects, options?: Configuration): Observable<Projects> { const requestContextPromise = this.requestFactory.setSubprojectsOrder(projectLocator, field, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setSubprojectsOrder(rsp))); })); } /** * Update build parameter. * @param name * @param projectLocator * @param fields * @param body */ public updateBuildParameter(name: string, projectLocator: string, fields?: string, body?: Property, options?: Configuration): Observable<Property> { const requestContextPromise = this.requestFactory.updateBuildParameter(name, projectLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.updateBuildParameter(rsp))); })); } /** * Update build parameter specification. * @param name * @param projectLocator * @param body */ public updateBuildParameterSpecification(name: string, projectLocator: string, body?: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.updateBuildParameterSpecification(name, projectLocator, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.updateBuildParameterSpecification(rsp))); })); } /** * Update type of build parameter. * @param name * @param projectLocator * @param body */ public updateBuildParameterType(name: string, projectLocator: string, body?: Type, options?: Configuration): Observable<Type> { const requestContextPromise = this.requestFactory.updateBuildParameterType(name, projectLocator, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.updateBuildParameterType(rsp))); })); } /** * Update value of build parameter. * @param name * @param projectLocator * @param body */ public updateBuildParameterValue(name: string, projectLocator: string, body?: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.updateBuildParameterValue(name, projectLocator, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.updateBuildParameterValue(rsp))); })); } /** * Update build parameters. * @param projectLocator * @param fields * @param body */ public updateBuildParameters(projectLocator: string, fields?: string, body?: Properties, options?: Configuration): Observable<Properties> { const requestContextPromise = this.requestFactory.updateBuildParameters(projectLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.updateBuildParameters(rsp))); })); } /** * Update a matching feature. * @param featureLocator * @param projectLocator * @param fields * @param body */ public updateFeature(featureLocator: string, projectLocator: string, fields?: string, body?: ProjectFeature, options?: Configuration): Observable<any> { const requestContextPromise = this.requestFactory.updateFeature(featureLocator, projectLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.updateFeature(rsp))); })); } /** * Update all features. * @param projectLocator * @param fields * @param body */ public updateFeatures(projectLocator: string, fields?: string, body?: ProjectFeatures, options?: Configuration): Observable<any> { const requestContextPromise = this.requestFactory.updateFeatures(projectLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.updateFeatures(rsp))); })); } } import { RootApiRequestFactory, RootApiResponseProcessor} from "../apis/RootApi.ts"; export class ObservableRootApi { private requestFactory: RootApiRequestFactory; private responseProcessor: RootApiResponseProcessor; private configuration: Configuration; public constructor( configuration: Configuration, requestFactory?: RootApiRequestFactory, responseProcessor?: RootApiResponseProcessor ) { this.configuration = configuration; this.requestFactory = requestFactory || new RootApiRequestFactory(configuration); this.responseProcessor = responseProcessor || new RootApiResponseProcessor(); } /** * Get the API version. */ public getApiVersion(options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.getApiVersion(options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getApiVersion(rsp))); })); } /** * Get the plugin info. * @param fields */ public getPluginInfo(fields?: string, options?: Configuration): Observable<Plugin> { const requestContextPromise = this.requestFactory.getPluginInfo(fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getPluginInfo(rsp))); })); } /** * Get root endpoints. */ public getRootEndpointsOfRoot(options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.getRootEndpointsOfRoot(options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getRootEndpointsOfRoot(rsp))); })); } /** * Get the TeamCity server version. */ public getVersion(options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.getVersion(options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getVersion(rsp))); })); } } import { ServerApiRequestFactory, ServerApiResponseProcessor} from "../apis/ServerApi.ts"; export class ObservableServerApi { private requestFactory: ServerApiRequestFactory; private responseProcessor: ServerApiResponseProcessor; private configuration: Configuration; public constructor( configuration: Configuration, requestFactory?: ServerApiRequestFactory, responseProcessor?: ServerApiResponseProcessor ) { this.configuration = configuration; this.requestFactory = requestFactory || new ServerApiRequestFactory(configuration); this.responseProcessor = responseProcessor || new ServerApiResponseProcessor(); } /** * Add license keys. * @param fields * @param body */ public addLicenseKeys(fields?: string, body?: string, options?: Configuration): Observable<LicenseKeys> { const requestContextPromise = this.requestFactory.addLicenseKeys(fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.addLicenseKeys(rsp))); })); } /** * Delete a license key. * @param licenseKey */ public deleteLicenseKey(licenseKey: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.deleteLicenseKey(licenseKey, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.deleteLicenseKey(rsp))); })); } /** * Download specific file. * @param path * @param areaId */ public downloadFileOfServer(path: string, areaId: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.downloadFileOfServer(path, areaId, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.downloadFileOfServer(rsp))); })); } /** * Get metrics. * @param fields */ public getAllMetrics(fields?: string, options?: Configuration): Observable<Metrics> { const requestContextPromise = this.requestFactory.getAllMetrics(fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAllMetrics(rsp))); })); } /** * Get all plugins. * @param fields */ public getAllPlugins(fields?: string, options?: Configuration): Observable<Plugins> { const requestContextPromise = this.requestFactory.getAllPlugins(fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAllPlugins(rsp))); })); } /** * Get the latest backup status. */ public getBackupStatus(options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.getBackupStatus(options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getBackupStatus(rsp))); })); } /** * Get metadata of specific file. * @param path * @param areaId * @param fields */ public getFileMetadataOfServer(path: string, areaId: string, fields?: string, options?: Configuration): Observable<any> { const requestContextPromise = this.requestFactory.getFileMetadataOfServer(path, areaId, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getFileMetadataOfServer(rsp))); })); } /** * List files under this path. * @param path * @param areaId * @param basePath * @param locator * @param fields */ public getFilesListForSubpathOfServer(path: string, areaId: string, basePath?: string, locator?: string, fields?: string, options?: Configuration): Observable<Files> { const requestContextPromise = this.requestFactory.getFilesListForSubpathOfServer(path, areaId, basePath, locator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getFilesListForSubpathOfServer(rsp))); })); } /** * List all files. * @param areaId * @param basePath * @param locator * @param fields */ public getFilesListOfServer(areaId: string, basePath?: string, locator?: string, fields?: string, options?: Configuration): Observable<Files> { const requestContextPromise = this.requestFactory.getFilesListOfServer(areaId, basePath, locator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getFilesListOfServer(rsp))); })); } /** * Get a license key. * @param licenseKey * @param fields */ public getLicenseKey(licenseKey: string, fields?: string, options?: Configuration): Observable<LicenseKey> { const requestContextPromise = this.requestFactory.getLicenseKey(licenseKey, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getLicenseKey(rsp))); })); } /** * Get all license keys. * @param fields */ public getLicenseKeys(fields?: string, options?: Configuration): Observable<LicenseKeys> { const requestContextPromise = this.requestFactory.getLicenseKeys(fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getLicenseKeys(rsp))); })); } /** * Get the licensing data. * @param fields */ public getLicensingData(fields?: string, options?: Configuration): Observable<LicensingData> { const requestContextPromise = this.requestFactory.getLicensingData(fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getLicensingData(rsp))); })); } /** * Get a field of the server info. * @param field */ public getServerField(field: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.getServerField(field, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getServerField(rsp))); })); } /** * Get the server info. * @param fields */ public getServerInfo(fields?: string, options?: Configuration): Observable<Server> { const requestContextPromise = this.requestFactory.getServerInfo(fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getServerInfo(rsp))); })); } /** * Get specific file zipped. * @param path * @param areaId * @param basePath * @param locator * @param name */ public getZippedFileOfServer(path: string, areaId: string, basePath?: string, locator?: string, name?: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.getZippedFileOfServer(path, areaId, basePath, locator, name, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getZippedFileOfServer(rsp))); })); } /** * Start a new backup. * @param fileName * @param addTimestamp * @param includeConfigs * @param includeDatabase * @param includeBuildLogs * @param includePersonalChanges * @param includeRunningBuilds * @param includeSupplimentaryData */ public startBackup(fileName?: string, addTimestamp?: boolean, includeConfigs?: boolean, includeDatabase?: boolean, includeBuildLogs?: boolean, includePersonalChanges?: boolean, includeRunningBuilds?: boolean, includeSupplimentaryData?: boolean, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.startBackup(fileName, addTimestamp, includeConfigs, includeDatabase, includeBuildLogs, includePersonalChanges, includeRunningBuilds, includeSupplimentaryData, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.startBackup(rsp))); })); } } import { TestApiRequestFactory, TestApiResponseProcessor} from "../apis/TestApi.ts"; export class ObservableTestApi { private requestFactory: TestApiRequestFactory; private responseProcessor: TestApiResponseProcessor; private configuration: Configuration; public constructor( configuration: Configuration, requestFactory?: TestApiRequestFactory, responseProcessor?: TestApiResponseProcessor ) { this.configuration = configuration; this.requestFactory = requestFactory || new TestApiRequestFactory(configuration); this.responseProcessor = responseProcessor || new TestApiResponseProcessor(); } /** * Get a matching test. * @param testLocator * @param fields */ public getTest(testLocator: string, fields?: string, options?: Configuration): Observable<Test> { const requestContextPromise = this.requestFactory.getTest(testLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getTest(rsp))); })); } /** * Get all tests. * @param locator * @param fields */ public getTests(locator?: string, fields?: string, options?: Configuration): Observable<Tests> { const requestContextPromise = this.requestFactory.getTests(locator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getTests(rsp))); })); } } import { TestOccurrenceApiRequestFactory, TestOccurrenceApiResponseProcessor} from "../apis/TestOccurrenceApi.ts"; export class ObservableTestOccurrenceApi { private requestFactory: TestOccurrenceApiRequestFactory; private responseProcessor: TestOccurrenceApiResponseProcessor; private configuration: Configuration; public constructor( configuration: Configuration, requestFactory?: TestOccurrenceApiRequestFactory, responseProcessor?: TestOccurrenceApiResponseProcessor ) { this.configuration = configuration; this.requestFactory = requestFactory || new TestOccurrenceApiRequestFactory(configuration); this.responseProcessor = responseProcessor || new TestOccurrenceApiResponseProcessor(); } /** * Get all test occurrences. * @param locator * @param fields */ public getAllTestOccurrences(locator?: string, fields?: string, options?: Configuration): Observable<TestOccurrences> { const requestContextPromise = this.requestFactory.getAllTestOccurrences(locator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAllTestOccurrences(rsp))); })); } /** * Get a matching test occurrence. * @param testLocator * @param fields */ public getTestOccurrence(testLocator: string, fields?: string, options?: Configuration): Observable<TestOccurrence> { const requestContextPromise = this.requestFactory.getTestOccurrence(testLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getTestOccurrence(rsp))); })); } } import { UserApiRequestFactory, UserApiResponseProcessor} from "../apis/UserApi.ts"; export class ObservableUserApi { private requestFactory: UserApiRequestFactory; private responseProcessor: UserApiResponseProcessor; private configuration: Configuration; public constructor( configuration: Configuration, requestFactory?: UserApiRequestFactory, responseProcessor?: UserApiResponseProcessor ) { this.configuration = configuration; this.requestFactory = requestFactory || new UserApiRequestFactory(configuration); this.responseProcessor = responseProcessor || new UserApiResponseProcessor(); } /** * Add a role to the matching user. * @param userLocator * @param body */ public addRoleToUser(userLocator: string, body?: Role, options?: Configuration): Observable<Role> { const requestContextPromise = this.requestFactory.addRoleToUser(userLocator, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.addRoleToUser(rsp))); })); } /** * Add a role with the specific scope to the matching user. * @param userLocator * @param roleId * @param scope */ public addRoleToUserAtScope(userLocator: string, roleId: string, scope: string, options?: Configuration): Observable<Role> { const requestContextPromise = this.requestFactory.addRoleToUserAtScope(userLocator, roleId, scope, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.addRoleToUserAtScope(rsp))); })); } /** * Create a new user. * @param fields * @param body */ public addUser(fields?: string, body?: User, options?: Configuration): Observable<User> { const requestContextPromise = this.requestFactory.addUser(fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.addUser(rsp))); })); } /** * Create a new authentication token for the matching user. * @param userLocator * @param fields * @param body */ public addUserToken(userLocator: string, fields?: string, body?: Token, options?: Configuration): Observable<Token> { const requestContextPromise = this.requestFactory.addUserToken(userLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.addUserToken(rsp))); })); } /** * Delete user matching the locator. * @param userLocator */ public deleteUser(userLocator: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.deleteUser(userLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.deleteUser(rsp))); })); } /** * Remove a property of the matching user. * @param userLocator * @param field */ public deleteUserField(userLocator: string, field: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.deleteUserField(userLocator, field, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.deleteUserField(rsp))); })); } /** * Remove an authentication token from the matching user. * @param userLocator * @param name */ public deleteUserToken(userLocator: string, name: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.deleteUserToken(userLocator, name, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.deleteUserToken(rsp))); })); } /** * Get a field of the matching user. * @param userLocator * @param field */ public gerUserField(userLocator: string, field: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.gerUserField(userLocator, field, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.gerUserField(rsp))); })); } /** * Get all groups of the matching user. * @param userLocator * @param fields */ public getAllUserGroups(userLocator: string, fields?: string, options?: Configuration): Observable<Groups> { const requestContextPromise = this.requestFactory.getAllUserGroups(userLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAllUserGroups(rsp))); })); } /** * Get all user roles of the matching user. * @param userLocator */ public getAllUserRoles(userLocator: string, options?: Configuration): Observable<Roles> { const requestContextPromise = this.requestFactory.getAllUserRoles(userLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAllUserRoles(rsp))); })); } /** * Get all users. * @param locator * @param fields */ public getAllUsers(locator?: string, fields?: string, options?: Configuration): Observable<Users> { const requestContextPromise = this.requestFactory.getAllUsers(locator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAllUsers(rsp))); })); } /** * Get user matching the locator. * @param userLocator * @param fields */ public getUser(userLocator: string, fields?: string, options?: Configuration): Observable<User> { const requestContextPromise = this.requestFactory.getUser(userLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getUser(rsp))); })); } /** * Get a user group of the matching user. * @param userLocator * @param groupLocator * @param fields */ public getUserGroup(userLocator: string, groupLocator: string, fields?: string, options?: Configuration): Observable<Group> { const requestContextPromise = this.requestFactory.getUserGroup(userLocator, groupLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getUserGroup(rsp))); })); } /** * Get all permissions effective for the matching user. * @param userLocator * @param locator * @param fields */ public getUserPermissions(userLocator: string, locator?: string, fields?: string, options?: Configuration): Observable<PermissionAssignments> { const requestContextPromise = this.requestFactory.getUserPermissions(userLocator, locator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getUserPermissions(rsp))); })); } /** * Get all properties of the matching user. * @param userLocator * @param fields */ public getUserProperties(userLocator: string, fields?: string, options?: Configuration): Observable<Properties> { const requestContextPromise = this.requestFactory.getUserProperties(userLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getUserProperties(rsp))); })); } /** * Get a property of the matching user. * @param userLocator * @param name */ public getUserProperty(userLocator: string, name: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.getUserProperty(userLocator, name, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getUserProperty(rsp))); })); } /** * Get a user role with the specific scope from the matching user. * @param userLocator * @param roleId * @param scope */ public getUserRolesAtScope(userLocator: string, roleId: string, scope: string, options?: Configuration): Observable<Role> { const requestContextPromise = this.requestFactory.getUserRolesAtScope(userLocator, roleId, scope, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getUserRolesAtScope(rsp))); })); } /** * Get all authentication tokens of the matching user. * @param userLocator * @param fields */ public getUserTokens(userLocator: string, fields?: string, options?: Configuration): Observable<Tokens> { const requestContextPromise = this.requestFactory.getUserTokens(userLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getUserTokens(rsp))); })); } /** * Remove the matching user from the specific group. * @param userLocator * @param groupLocator * @param fields */ public removeUserFromGroup(userLocator: string, groupLocator: string, fields?: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.removeUserFromGroup(userLocator, groupLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.removeUserFromGroup(rsp))); })); } /** * Remove a property of the matching user. * @param userLocator * @param name */ public removeUserProperty(userLocator: string, name: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.removeUserProperty(userLocator, name, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.removeUserProperty(rsp))); })); } /** * Remove the RememberMe data of the matching user. * @param userLocator */ public removeUserRememberMe(userLocator: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.removeUserRememberMe(userLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.removeUserRememberMe(rsp))); })); } /** * Remove a role with the specific scope from the matching user. * @param userLocator * @param roleId * @param scope */ public removeUserRoleAtScope(userLocator: string, roleId: string, scope: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.removeUserRoleAtScope(userLocator, roleId, scope, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.removeUserRoleAtScope(rsp))); })); } /** * Update user matching the locator. * @param userLocator * @param fields * @param body */ public replaceUser(userLocator: string, fields?: string, body?: User, options?: Configuration): Observable<User> { const requestContextPromise = this.requestFactory.replaceUser(userLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.replaceUser(rsp))); })); } /** * Update a field of the matching user. * @param userLocator * @param field * @param body */ public setUserField(userLocator: string, field: string, body?: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.setUserField(userLocator, field, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setUserField(rsp))); })); } /** * Update groups of the matching user. * @param userLocator * @param fields * @param body */ public setUserGroups(userLocator: string, fields?: string, body?: Groups, options?: Configuration): Observable<Groups> { const requestContextPromise = this.requestFactory.setUserGroups(userLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setUserGroups(rsp))); })); } /** * Update a property of the matching user. * @param userLocator * @param name * @param body */ public setUserProperty(userLocator: string, name: string, body?: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.setUserProperty(userLocator, name, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setUserProperty(rsp))); })); } /** * Update user roles of the matching user. * @param userLocator * @param body */ public setUserRoles(userLocator: string, body?: Roles, options?: Configuration): Observable<Roles> { const requestContextPromise = this.requestFactory.setUserRoles(userLocator, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setUserRoles(rsp))); })); } } import { VcsRootApiRequestFactory, VcsRootApiResponseProcessor} from "../apis/VcsRootApi.ts"; export class ObservableVcsRootApi { private requestFactory: VcsRootApiRequestFactory; private responseProcessor: VcsRootApiResponseProcessor; private configuration: Configuration; public constructor( configuration: Configuration, requestFactory?: VcsRootApiRequestFactory, responseProcessor?: VcsRootApiResponseProcessor ) { this.configuration = configuration; this.requestFactory = requestFactory || new VcsRootApiRequestFactory(configuration); this.responseProcessor = responseProcessor || new VcsRootApiResponseProcessor(); } /** * Add a new VCS root. * @param fields * @param body */ public addVcsRoot(fields?: string, body?: VcsRoot, options?: Configuration): Observable<VcsRoot> { const requestContextPromise = this.requestFactory.addVcsRoot(fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.addVcsRoot(rsp))); })); } /** * Delete all properties of the matching VCS root. * @param vcsRootLocator */ public deleteAllVcsRootProperties(vcsRootLocator: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.deleteAllVcsRootProperties(vcsRootLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.deleteAllVcsRootProperties(rsp))); })); } /** * Remove VCS root matching the locator. * @param vcsRootLocator */ public deleteVcsRoot(vcsRootLocator: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.deleteVcsRoot(vcsRootLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.deleteVcsRoot(rsp))); })); } /** * Delete a property of the matching VCS root. * @param vcsRootLocator * @param name */ public deleteVcsRootProperty(vcsRootLocator: string, name: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.deleteVcsRootProperty(vcsRootLocator, name, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.deleteVcsRootProperty(rsp))); })); } /** * Get all properties of the matching VCS root. * @param vcsRootLocator * @param fields */ public getAllVcsRootProperties(vcsRootLocator: string, fields?: string, options?: Configuration): Observable<Properties> { const requestContextPromise = this.requestFactory.getAllVcsRootProperties(vcsRootLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAllVcsRootProperties(rsp))); })); } /** * Get all VCS roots. * @param locator * @param fields */ public getAllVcsRoots(locator?: string, fields?: string, options?: Configuration): Observable<VcsRoots> { const requestContextPromise = this.requestFactory.getAllVcsRoots(locator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAllVcsRoots(rsp))); })); } /** * Get root endpoints. * @param vcsRootLocator * @param fields */ public getRootEndpoints(vcsRootLocator: string, fields?: string, options?: Configuration): Observable<VcsRoot> { const requestContextPromise = this.requestFactory.getRootEndpoints(vcsRootLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getRootEndpoints(rsp))); })); } /** * Get a field of the matching VCS root. * @param vcsRootLocator * @param field */ public getVcsRootField(vcsRootLocator: string, field: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.getVcsRootField(vcsRootLocator, field, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getVcsRootField(rsp))); })); } /** * Get all VCS root instances of the matching VCS root. * @param vcsRootLocator * @param fields */ public getVcsRootInstances(vcsRootLocator: string, fields?: string, options?: Configuration): Observable<VcsRootInstances> { const requestContextPromise = this.requestFactory.getVcsRootInstances(vcsRootLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getVcsRootInstances(rsp))); })); } /** * Get a property on the matching VCS root. * @param vcsRootLocator * @param name */ public getVcsRootProperty(vcsRootLocator: string, name: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.getVcsRootProperty(vcsRootLocator, name, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getVcsRootProperty(rsp))); })); } /** * Get the settings file of the matching VCS root. * @param vcsRootLocator */ public getVcsRootSettingsFile(vcsRootLocator: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.getVcsRootSettingsFile(vcsRootLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getVcsRootSettingsFile(rsp))); })); } /** * Update a field of the matching VCS root. * @param vcsRootLocator * @param field * @param body */ public setVcsRootField(vcsRootLocator: string, field: string, body?: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.setVcsRootField(vcsRootLocator, field, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setVcsRootField(rsp))); })); } /** * Update all properties of the matching VCS root. * @param vcsRootLocator * @param fields * @param body */ public setVcsRootProperties(vcsRootLocator: string, fields?: string, body?: Properties, options?: Configuration): Observable<Properties> { const requestContextPromise = this.requestFactory.setVcsRootProperties(vcsRootLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setVcsRootProperties(rsp))); })); } /** * Update a property of the matching VCS root. * @param vcsRootLocator * @param name * @param body */ public setVcsRootProperty(vcsRootLocator: string, name: string, body?: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.setVcsRootProperty(vcsRootLocator, name, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setVcsRootProperty(rsp))); })); } } import { VcsRootInstanceApiRequestFactory, VcsRootInstanceApiResponseProcessor} from "../apis/VcsRootInstanceApi.ts"; export class ObservableVcsRootInstanceApi { private requestFactory: VcsRootInstanceApiRequestFactory; private responseProcessor: VcsRootInstanceApiResponseProcessor; private configuration: Configuration; public constructor( configuration: Configuration, requestFactory?: VcsRootInstanceApiRequestFactory, responseProcessor?: VcsRootInstanceApiResponseProcessor ) { this.configuration = configuration; this.requestFactory = requestFactory || new VcsRootInstanceApiRequestFactory(configuration); this.responseProcessor = responseProcessor || new VcsRootInstanceApiResponseProcessor(); } /** * Remove a field of the matching VCS root instance. * @param vcsRootInstanceLocator * @param field */ public deleteVcsRootInstanceField(vcsRootInstanceLocator: string, field: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.deleteVcsRootInstanceField(vcsRootInstanceLocator, field, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.deleteVcsRootInstanceField(rsp))); })); } /** * Delete the last repository state of the matching VCS root instance. * @param vcsRootInstanceLocator */ public deleteVcsRootInstanceRepositoryState(vcsRootInstanceLocator: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.deleteVcsRootInstanceRepositoryState(vcsRootInstanceLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.deleteVcsRootInstanceRepositoryState(rsp))); })); } /** * Download specific file. * @param path * @param vcsRootInstanceLocator */ public downloadFile(path: string, vcsRootInstanceLocator: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.downloadFile(path, vcsRootInstanceLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.downloadFile(rsp))); })); } /** * Get all VCS root instances. * @param locator * @param fields */ public getAllVcsRootInstances(locator?: string, fields?: string, options?: Configuration): Observable<VcsRootInstances> { const requestContextPromise = this.requestFactory.getAllVcsRootInstances(locator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getAllVcsRootInstances(rsp))); })); } /** * Get metadata of specific file. * @param path * @param vcsRootInstanceLocator * @param fields */ public getFileMetadata(path: string, vcsRootInstanceLocator: string, fields?: string, options?: Configuration): Observable<any> { const requestContextPromise = this.requestFactory.getFileMetadata(path, vcsRootInstanceLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getFileMetadata(rsp))); })); } /** * List all files. * @param vcsRootInstanceLocator * @param basePath * @param locator * @param fields */ public getFilesList(vcsRootInstanceLocator: string, basePath?: string, locator?: string, fields?: string, options?: Configuration): Observable<Files> { const requestContextPromise = this.requestFactory.getFilesList(vcsRootInstanceLocator, basePath, locator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getFilesList(rsp))); })); } /** * List files under this path. * @param path * @param vcsRootInstanceLocator * @param basePath * @param locator * @param fields */ public getFilesListForSubpath(path: string, vcsRootInstanceLocator: string, basePath?: string, locator?: string, fields?: string, options?: Configuration): Observable<Files> { const requestContextPromise = this.requestFactory.getFilesListForSubpath(path, vcsRootInstanceLocator, basePath, locator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getFilesListForSubpath(rsp))); })); } /** * Get VCS root instance matching the locator. * @param vcsRootInstanceLocator * @param fields */ public getVcsRootInstance(vcsRootInstanceLocator: string, fields?: string, options?: Configuration): Observable<VcsRootInstance> { const requestContextPromise = this.requestFactory.getVcsRootInstance(vcsRootInstanceLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getVcsRootInstance(rsp))); })); } /** * Get the creation date of the matching VCS root instance. * @param vcsRootInstanceLocator */ public getVcsRootInstanceCreationDate(vcsRootInstanceLocator: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.getVcsRootInstanceCreationDate(vcsRootInstanceLocator, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getVcsRootInstanceCreationDate(rsp))); })); } /** * Get a field of the matching VCS root instance. * @param vcsRootInstanceLocator * @param field */ public getVcsRootInstanceField(vcsRootInstanceLocator: string, field: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.getVcsRootInstanceField(vcsRootInstanceLocator, field, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getVcsRootInstanceField(rsp))); })); } /** * Get all properties of the matching VCS root instance. * @param vcsRootInstanceLocator * @param fields */ public getVcsRootInstanceProperties(vcsRootInstanceLocator: string, fields?: string, options?: Configuration): Observable<Properties> { const requestContextPromise = this.requestFactory.getVcsRootInstanceProperties(vcsRootInstanceLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getVcsRootInstanceProperties(rsp))); })); } /** * Get the repository state of the matching VCS root instance. * @param vcsRootInstanceLocator * @param fields */ public getVcsRootInstanceRepositoryState(vcsRootInstanceLocator: string, fields?: string, options?: Configuration): Observable<Entries> { const requestContextPromise = this.requestFactory.getVcsRootInstanceRepositoryState(vcsRootInstanceLocator, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getVcsRootInstanceRepositoryState(rsp))); })); } /** * Get specific file zipped. * @param path * @param vcsRootInstanceLocator * @param basePath * @param locator * @param name */ public getZippedFile(path: string, vcsRootInstanceLocator: string, basePath?: string, locator?: string, name?: string, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.getZippedFile(path, vcsRootInstanceLocator, basePath, locator, name, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getZippedFile(rsp))); })); } /** * Check for the pending changes for all VCS root instances. * @param locator * @param requestor * @param fields */ public requestPendingChangesCheck(locator?: string, requestor?: string, fields?: string, options?: Configuration): Observable<VcsRootInstances> { const requestContextPromise = this.requestFactory.requestPendingChangesCheck(locator, requestor, fields, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.requestPendingChangesCheck(rsp))); })); } /** * Get a field of the matching VCS root instance. * @param vcsRootInstanceLocator * @param field * @param body */ public setVcsRootInstanceField(vcsRootInstanceLocator: string, field: string, body?: string, options?: Configuration): Observable<string> { const requestContextPromise = this.requestFactory.setVcsRootInstanceField(vcsRootInstanceLocator, field, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setVcsRootInstanceField(rsp))); })); } /** * Update the repository state of the matching VCS root instance. * @param vcsRootInstanceLocator * @param fields * @param body */ public setVcsRootInstanceRepositoryState(vcsRootInstanceLocator: string, fields?: string, body?: Entries, options?: Configuration): Observable<Entries> { const requestContextPromise = this.requestFactory.setVcsRootInstanceRepositoryState(vcsRootInstanceLocator, fields, body, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.setVcsRootInstanceRepositoryState(rsp))); })); } /** * Send the commit hook notification. * @param locator * @param okOnNothingFound */ public triggerCommitHookNotification(locator?: string, okOnNothingFound?: boolean, options?: Configuration): Observable<void> { const requestContextPromise = this.requestFactory.triggerCommitHookNotification(locator, okOnNothingFound, options); // build promise chain let middlewarePreObservable = from<RequestContext>(requestContextPromise); for (let middleware of this.configuration.middleware) { middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx))); } return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))). pipe(mergeMap((response: ResponseContext) => { let middlewarePostObservable = of(response); for (let middleware of this.configuration.middleware) { middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp))); } return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.triggerCommitHookNotification(rsp))); })); } } <file_sep>/ts-schema/schema/rest-api/deno/models/FileChange.ts /** * TeamCity REST API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * OpenAPI spec version: 2018.1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { HttpFile } from '../http/http.ts'; export class FileChange { 'beforeRevision'?: string; 'afterRevision'?: string; 'changeType'?: string; 'changeTypeComment'?: string; 'file'?: string; 'relativeFile'?: string; 'directory'?: boolean; static readonly discriminator: string | undefined = undefined; static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [ { "name": "beforeRevision", "baseName": "before-revision", "type": "string", "format": "" }, { "name": "afterRevision", "baseName": "after-revision", "type": "string", "format": "" }, { "name": "changeType", "baseName": "changeType", "type": "string", "format": "" }, { "name": "changeTypeComment", "baseName": "changeTypeComment", "type": "string", "format": "" }, { "name": "file", "baseName": "file", "type": "string", "format": "" }, { "name": "relativeFile", "baseName": "relative-file", "type": "string", "format": "" }, { "name": "directory", "baseName": "directory", "type": "boolean", "format": "" } ]; static getAttributeTypeMap() { return FileChange.attributeTypeMap; } public constructor() { } } <file_sep>/ts-schema/schema/rest-api/deno/models/File.ts /** * TeamCity REST API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * OpenAPI spec version: 2018.1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { Files } from './Files.ts'; import { Href } from './Href.ts'; import { HttpFile } from '../http/http.ts'; export class File { 'name'?: string; 'fullName'?: string; 'size'?: number; 'modificationTime'?: string; 'href'?: string; 'parent'?: any; 'content'?: Href; 'children'?: Files; static readonly discriminator: string | undefined = undefined; static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [ { "name": "name", "baseName": "name", "type": "string", "format": "" }, { "name": "fullName", "baseName": "fullName", "type": "string", "format": "" }, { "name": "size", "baseName": "size", "type": "number", "format": "int64" }, { "name": "modificationTime", "baseName": "modificationTime", "type": "string", "format": "" }, { "name": "href", "baseName": "href", "type": "string", "format": "" }, { "name": "parent", "baseName": "parent", "type": "any", "format": "" }, { "name": "content", "baseName": "content", "type": "Href", "format": "" }, { "name": "children", "baseName": "children", "type": "Files", "format": "" } ]; static getAttributeTypeMap() { return File.attributeTypeMap; } public constructor() { } } <file_sep>/ts-schema/schema/rest-api/deno/apis/ChangeApi.ts // TODO: better import syntax? import { BaseAPIRequestFactory, RequiredError } from './baseapi.ts'; import {Configuration} from '../configuration.ts'; import { RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http.ts'; import {ObjectSerializer} from '../models/ObjectSerializer.ts'; import {ApiException} from './exception.ts'; import {isCodeInRange} from '../util.ts'; import { BuildTypes } from '../models/BuildTypes.ts'; import { Builds } from '../models/Builds.ts'; import { Change } from '../models/Change.ts'; import { Changes } from '../models/Changes.ts'; import { Entries } from '../models/Entries.ts'; import { Issues } from '../models/Issues.ts'; import { Items } from '../models/Items.ts'; import { VcsRootInstance } from '../models/VcsRootInstance.ts'; /** * no description */ export class ChangeApiRequestFactory extends BaseAPIRequestFactory { /** * Get all changes. * @param locator * @param fields */ public async getAllChanges(locator?: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/changes'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "ChangeLocator")); } if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get change matching the locator. * @param changeLocator * @param fields */ public async getChange(changeLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'changeLocator' is not null or undefined if (changeLocator === null || changeLocator === undefined) { throw new RequiredError('Required parameter changeLocator was null or undefined when calling getChange.'); } // Path Params const localVarPath = '/app/rest/changes/{changeLocator}' .replace('{' + 'changeLocator' + '}', encodeURIComponent(String(changeLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get attributes of the matching change. * @param changeLocator * @param fields */ public async getChangeAttributes(changeLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'changeLocator' is not null or undefined if (changeLocator === null || changeLocator === undefined) { throw new RequiredError('Required parameter changeLocator was null or undefined when calling getChangeAttributes.'); } // Path Params const localVarPath = '/app/rest/changes/{changeLocator}/attributes' .replace('{' + 'changeLocator' + '}', encodeURIComponent(String(changeLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get duplicates of the matching change. * @param changeLocator * @param fields */ public async getChangeDuplicates(changeLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'changeLocator' is not null or undefined if (changeLocator === null || changeLocator === undefined) { throw new RequiredError('Required parameter changeLocator was null or undefined when calling getChangeDuplicates.'); } // Path Params const localVarPath = '/app/rest/changes/{changeLocator}/duplicates' .replace('{' + 'changeLocator' + '}', encodeURIComponent(String(changeLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get a field of the matching change. * @param changeLocator * @param field */ public async getChangeField(changeLocator: string, field: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'changeLocator' is not null or undefined if (changeLocator === null || changeLocator === undefined) { throw new RequiredError('Required parameter changeLocator was null or undefined when calling getChangeField.'); } // verify required parameter 'field' is not null or undefined if (field === null || field === undefined) { throw new RequiredError('Required parameter field was null or undefined when calling getChangeField.'); } // Path Params const localVarPath = '/app/rest/changes/{changeLocator}/{field}' .replace('{' + 'changeLocator' + '}', encodeURIComponent(String(changeLocator))) .replace('{' + 'field' + '}', encodeURIComponent(String(field))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get first builds of the matching change. * @param changeLocator * @param fields */ public async getChangeFirstBuilds(changeLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'changeLocator' is not null or undefined if (changeLocator === null || changeLocator === undefined) { throw new RequiredError('Required parameter changeLocator was null or undefined when calling getChangeFirstBuilds.'); } // Path Params const localVarPath = '/app/rest/changes/{changeLocator}/firstBuilds' .replace('{' + 'changeLocator' + '}', encodeURIComponent(String(changeLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get issues of the matching change. * @param changeLocator */ public async getChangeIssue(changeLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'changeLocator' is not null or undefined if (changeLocator === null || changeLocator === undefined) { throw new RequiredError('Required parameter changeLocator was null or undefined when calling getChangeIssue.'); } // Path Params const localVarPath = '/app/rest/changes/{changeLocator}/issues' .replace('{' + 'changeLocator' + '}', encodeURIComponent(String(changeLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get parent changes of the matching change. * @param changeLocator * @param fields */ public async getChangeParentChanges(changeLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'changeLocator' is not null or undefined if (changeLocator === null || changeLocator === undefined) { throw new RequiredError('Required parameter changeLocator was null or undefined when calling getChangeParentChanges.'); } // Path Params const localVarPath = '/app/rest/changes/{changeLocator}/parentChanges' .replace('{' + 'changeLocator' + '}', encodeURIComponent(String(changeLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get parent revisions of the matching change. * @param changeLocator */ public async getChangeParentRevisions(changeLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'changeLocator' is not null or undefined if (changeLocator === null || changeLocator === undefined) { throw new RequiredError('Required parameter changeLocator was null or undefined when calling getChangeParentRevisions.'); } // Path Params const localVarPath = '/app/rest/changes/{changeLocator}/parentRevisions' .replace('{' + 'changeLocator' + '}', encodeURIComponent(String(changeLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get build configurations related to the matching change. * @param changeLocator * @param fields */ public async getChangeRelatedBuildTypes(changeLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'changeLocator' is not null or undefined if (changeLocator === null || changeLocator === undefined) { throw new RequiredError('Required parameter changeLocator was null or undefined when calling getChangeRelatedBuildTypes.'); } // Path Params const localVarPath = '/app/rest/changes/{changeLocator}/buildTypes' .replace('{' + 'changeLocator' + '}', encodeURIComponent(String(changeLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get a VCS root instance of the matching change. * @param changeLocator * @param fields */ public async getChangeVcsRoot(changeLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'changeLocator' is not null or undefined if (changeLocator === null || changeLocator === undefined) { throw new RequiredError('Required parameter changeLocator was null or undefined when calling getChangeVcsRoot.'); } // Path Params const localVarPath = '/app/rest/changes/{changeLocator}/vcsRootInstance' .replace('{' + 'changeLocator' + '}', encodeURIComponent(String(changeLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } } export class ChangeApiResponseProcessor { /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAllChanges * @throws ApiException if the response code was not in [200, 299] */ public async getAllChanges(response: ResponseContext): Promise<Changes > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Changes = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Changes", "" ) as Changes; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Changes = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Changes", "" ) as Changes; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getChange * @throws ApiException if the response code was not in [200, 299] */ public async getChange(response: ResponseContext): Promise<Change > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Change = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Change", "" ) as Change; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Change = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Change", "" ) as Change; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getChangeAttributes * @throws ApiException if the response code was not in [200, 299] */ public async getChangeAttributes(response: ResponseContext): Promise<Entries > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Entries = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Entries", "" ) as Entries; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Entries = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Entries", "" ) as Entries; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getChangeDuplicates * @throws ApiException if the response code was not in [200, 299] */ public async getChangeDuplicates(response: ResponseContext): Promise<Changes > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Changes = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Changes", "" ) as Changes; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Changes = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Changes", "" ) as Changes; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getChangeField * @throws ApiException if the response code was not in [200, 299] */ public async getChangeField(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getChangeFirstBuilds * @throws ApiException if the response code was not in [200, 299] */ public async getChangeFirstBuilds(response: ResponseContext): Promise<Builds > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Builds = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Builds", "" ) as Builds; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Builds = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Builds", "" ) as Builds; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getChangeIssue * @throws ApiException if the response code was not in [200, 299] */ public async getChangeIssue(response: ResponseContext): Promise<Issues > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Issues = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Issues", "" ) as Issues; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Issues = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Issues", "" ) as Issues; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getChangeParentChanges * @throws ApiException if the response code was not in [200, 299] */ public async getChangeParentChanges(response: ResponseContext): Promise<Changes > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Changes = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Changes", "" ) as Changes; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Changes = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Changes", "" ) as Changes; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getChangeParentRevisions * @throws ApiException if the response code was not in [200, 299] */ public async getChangeParentRevisions(response: ResponseContext): Promise<Items > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Items = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Items", "" ) as Items; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Items = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Items", "" ) as Items; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getChangeRelatedBuildTypes * @throws ApiException if the response code was not in [200, 299] */ public async getChangeRelatedBuildTypes(response: ResponseContext): Promise<BuildTypes > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: BuildTypes = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "BuildTypes", "" ) as BuildTypes; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: BuildTypes = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "BuildTypes", "" ) as BuildTypes; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getChangeVcsRoot * @throws ApiException if the response code was not in [200, 299] */ public async getChangeVcsRoot(response: ResponseContext): Promise<VcsRootInstance > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: VcsRootInstance = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "VcsRootInstance", "" ) as VcsRootInstance; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: VcsRootInstance = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "VcsRootInstance", "" ) as VcsRootInstance; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } } <file_sep>/ts-schema/schema/rest-api/deno/types/PromiseAPI.ts import { ResponseContext, RequestContext, HttpFile } from '../http/http.ts'; import * as models from '../models/all.ts'; import { Configuration} from '../configuration.ts' import { Agent } from '../models/Agent.ts'; import { AgentLocator } from '../models/AgentLocator.ts'; import { AgentPool } from '../models/AgentPool.ts'; import { AgentPoolLocator } from '../models/AgentPoolLocator.ts'; import { AgentPools } from '../models/AgentPools.ts'; import { AgentRequirement } from '../models/AgentRequirement.ts'; import { AgentRequirements } from '../models/AgentRequirements.ts'; import { Agents } from '../models/Agents.ts'; import { ArtifactDependencies } from '../models/ArtifactDependencies.ts'; import { ArtifactDependency } from '../models/ArtifactDependency.ts'; import { AuditAction } from '../models/AuditAction.ts'; import { AuditEvent } from '../models/AuditEvent.ts'; import { AuditEvents } from '../models/AuditEvents.ts'; import { AuditLocator } from '../models/AuditLocator.ts'; import { AuthorizedInfo } from '../models/AuthorizedInfo.ts'; import { Branch } from '../models/Branch.ts'; import { BranchLocator } from '../models/BranchLocator.ts'; import { BranchVersion } from '../models/BranchVersion.ts'; import { Branches } from '../models/Branches.ts'; import { Build } from '../models/Build.ts'; import { BuildCancelRequest } from '../models/BuildCancelRequest.ts'; import { BuildChange } from '../models/BuildChange.ts'; import { BuildChanges } from '../models/BuildChanges.ts'; import { BuildLocator } from '../models/BuildLocator.ts'; import { BuildQueueLocator } from '../models/BuildQueueLocator.ts'; import { BuildTriggeringOptions } from '../models/BuildTriggeringOptions.ts'; import { BuildType } from '../models/BuildType.ts'; import { BuildTypeLocator } from '../models/BuildTypeLocator.ts'; import { BuildTypes } from '../models/BuildTypes.ts'; import { Builds } from '../models/Builds.ts'; import { Change } from '../models/Change.ts'; import { ChangeLocator } from '../models/ChangeLocator.ts'; import { Changes } from '../models/Changes.ts'; import { CloudImage } from '../models/CloudImage.ts'; import { CloudImages } from '../models/CloudImages.ts'; import { CloudInstance } from '../models/CloudInstance.ts'; import { CloudInstances } from '../models/CloudInstances.ts'; import { CloudProfile } from '../models/CloudProfile.ts'; import { CloudProfiles } from '../models/CloudProfiles.ts'; import { Comment } from '../models/Comment.ts'; import { Compatibilities } from '../models/Compatibilities.ts'; import { Compatibility } from '../models/Compatibility.ts'; import { CompatibilityPolicy } from '../models/CompatibilityPolicy.ts'; import { Customizations } from '../models/Customizations.ts'; import { Datas } from '../models/Datas.ts'; import { EnabledInfo } from '../models/EnabledInfo.ts'; import { Entries } from '../models/Entries.ts'; import { Entry } from '../models/Entry.ts'; import { Environment } from '../models/Environment.ts'; import { Feature } from '../models/Feature.ts'; import { Features } from '../models/Features.ts'; import { File } from '../models/File.ts'; import { FileChange } from '../models/FileChange.ts'; import { FileChanges } from '../models/FileChanges.ts'; import { Files } from '../models/Files.ts'; import { Group } from '../models/Group.ts'; import { Groups } from '../models/Groups.ts'; import { Href } from '../models/Href.ts'; import { Investigation } from '../models/Investigation.ts'; import { InvestigationLocator } from '../models/InvestigationLocator.ts'; import { Investigations } from '../models/Investigations.ts'; import { Issue } from '../models/Issue.ts'; import { IssueUsage } from '../models/IssueUsage.ts'; import { Issues } from '../models/Issues.ts'; import { IssuesUsages } from '../models/IssuesUsages.ts'; import { Items } from '../models/Items.ts'; import { LicenseKey } from '../models/LicenseKey.ts'; import { LicenseKeys } from '../models/LicenseKeys.ts'; import { LicensingData } from '../models/LicensingData.ts'; import { Link } from '../models/Link.ts'; import { Links } from '../models/Links.ts'; import { MetaData } from '../models/MetaData.ts'; import { Metric } from '../models/Metric.ts'; import { MetricTag } from '../models/MetricTag.ts'; import { MetricTags } from '../models/MetricTags.ts'; import { MetricValue } from '../models/MetricValue.ts'; import { MetricValues } from '../models/MetricValues.ts'; import { Metrics } from '../models/Metrics.ts'; import { MultipleOperationResult } from '../models/MultipleOperationResult.ts'; import { Mute } from '../models/Mute.ts'; import { MuteLocator } from '../models/MuteLocator.ts'; import { Mutes } from '../models/Mutes.ts'; import { NewBuildTypeDescription } from '../models/NewBuildTypeDescription.ts'; import { NewProjectDescription } from '../models/NewProjectDescription.ts'; import { OperationResult } from '../models/OperationResult.ts'; import { ParsedTestName } from '../models/ParsedTestName.ts'; import { Permission } from '../models/Permission.ts'; import { PermissionAssignment } from '../models/PermissionAssignment.ts'; import { PermissionAssignments } from '../models/PermissionAssignments.ts'; import { PermissionRestriction } from '../models/PermissionRestriction.ts'; import { PermissionRestrictions } from '../models/PermissionRestrictions.ts'; import { PinInfo } from '../models/PinInfo.ts'; import { Plugin } from '../models/Plugin.ts'; import { Plugins } from '../models/Plugins.ts'; import { Problem } from '../models/Problem.ts'; import { ProblemLocator } from '../models/ProblemLocator.ts'; import { ProblemOccurrence } from '../models/ProblemOccurrence.ts'; import { ProblemOccurrenceLocator } from '../models/ProblemOccurrenceLocator.ts'; import { ProblemOccurrences } from '../models/ProblemOccurrences.ts'; import { ProblemScope } from '../models/ProblemScope.ts'; import { ProblemTarget } from '../models/ProblemTarget.ts'; import { Problems } from '../models/Problems.ts'; import { ProgressInfo } from '../models/ProgressInfo.ts'; import { Project } from '../models/Project.ts'; import { ProjectFeature } from '../models/ProjectFeature.ts'; import { ProjectFeatures } from '../models/ProjectFeatures.ts'; import { ProjectLocator } from '../models/ProjectLocator.ts'; import { Projects } from '../models/Projects.ts'; import { Properties } from '../models/Properties.ts'; import { Property } from '../models/Property.ts'; import { Related } from '../models/Related.ts'; import { RelatedEntities } from '../models/RelatedEntities.ts'; import { RelatedEntity } from '../models/RelatedEntity.ts'; import { RepositoryState } from '../models/RepositoryState.ts'; import { Requirements } from '../models/Requirements.ts'; import { Resolution } from '../models/Resolution.ts'; import { Revision } from '../models/Revision.ts'; import { Revisions } from '../models/Revisions.ts'; import { Role } from '../models/Role.ts'; import { Roles } from '../models/Roles.ts'; import { Server } from '../models/Server.ts'; import { SnapshotDependencies } from '../models/SnapshotDependencies.ts'; import { SnapshotDependency } from '../models/SnapshotDependency.ts'; import { StateField } from '../models/StateField.ts'; import { Step } from '../models/Step.ts'; import { Steps } from '../models/Steps.ts'; import { Tag } from '../models/Tag.ts'; import { TagLocator } from '../models/TagLocator.ts'; import { Tags } from '../models/Tags.ts'; import { Test } from '../models/Test.ts'; import { TestCounters } from '../models/TestCounters.ts'; import { TestLocator } from '../models/TestLocator.ts'; import { TestOccurrence } from '../models/TestOccurrence.ts'; import { TestOccurrenceLocator } from '../models/TestOccurrenceLocator.ts'; import { TestOccurrences } from '../models/TestOccurrences.ts'; import { TestRunMetadata } from '../models/TestRunMetadata.ts'; import { Tests } from '../models/Tests.ts'; import { Token } from '../models/Token.ts'; import { Tokens } from '../models/Tokens.ts'; import { Trigger } from '../models/Trigger.ts'; import { TriggeredBy } from '../models/TriggeredBy.ts'; import { Triggers } from '../models/Triggers.ts'; import { Type } from '../models/Type.ts'; import { TypedValue } from '../models/TypedValue.ts'; import { User } from '../models/User.ts'; import { UserGroupLocator } from '../models/UserGroupLocator.ts'; import { UserLocator } from '../models/UserLocator.ts'; import { Users } from '../models/Users.ts'; import { VcsCheckStatus } from '../models/VcsCheckStatus.ts'; import { VcsLabel } from '../models/VcsLabel.ts'; import { VcsLabels } from '../models/VcsLabels.ts'; import { VcsRoot } from '../models/VcsRoot.ts'; import { VcsRootEntries } from '../models/VcsRootEntries.ts'; import { VcsRootEntry } from '../models/VcsRootEntry.ts'; import { VcsRootInstance } from '../models/VcsRootInstance.ts'; import { VcsRootInstanceLocator } from '../models/VcsRootInstanceLocator.ts'; import { VcsRootInstances } from '../models/VcsRootInstances.ts'; import { VcsRootLocator } from '../models/VcsRootLocator.ts'; import { VcsRoots } from '../models/VcsRoots.ts'; import { VcsStatus } from '../models/VcsStatus.ts'; import { ObservableAgentApi } from './ObservableAPI.ts'; import { AgentApiRequestFactory, AgentApiResponseProcessor} from "../apis/AgentApi.ts"; export class PromiseAgentApi { private api: ObservableAgentApi public constructor( configuration: Configuration, requestFactory?: AgentApiRequestFactory, responseProcessor?: AgentApiResponseProcessor ) { this.api = new ObservableAgentApi(configuration, requestFactory, responseProcessor); } /** * Delete an inactive agent. * @param agentLocator */ public deleteAgent(agentLocator: string, options?: Configuration): Promise<void> { const result = this.api.deleteAgent(agentLocator, options); return result.toPromise(); } /** * Get agent matching the locator. * @param agentLocator * @param fields */ public getAgent(agentLocator: string, fields?: string, options?: Configuration): Promise<Agent> { const result = this.api.getAgent(agentLocator, fields, options); return result.toPromise(); } /** * Get a field of the matching agent. * @param agentLocator * @param field */ public getAgentField(agentLocator: string, field: string, options?: Configuration): Promise<string> { const result = this.api.getAgentField(agentLocator, field, options); return result.toPromise(); } /** * Get the agent pool of the matching agent. * @param agentLocator * @param fields */ public getAgentPool(agentLocator: string, fields?: string, options?: Configuration): Promise<AgentPool> { const result = this.api.getAgentPool(agentLocator, fields, options); return result.toPromise(); } /** * Get all known agents. * @param locator * @param fields */ public getAllAgents(locator?: string, fields?: string, options?: Configuration): Promise<Agents> { const result = this.api.getAllAgents(locator, fields, options); return result.toPromise(); } /** * Get the authorization info of the matching agent. * @param agentLocator * @param fields */ public getAuthorizedInfo(agentLocator: string, fields?: string, options?: Configuration): Promise<AuthorizedInfo> { const result = this.api.getAuthorizedInfo(agentLocator, fields, options); return result.toPromise(); } /** * Get the build configuration run policy of the matching agent. * @param agentLocator * @param fields */ public getBuildConfigurationRunPolicy(agentLocator: string, fields?: string, options?: Configuration): Promise<CompatibilityPolicy> { const result = this.api.getBuildConfigurationRunPolicy(agentLocator, fields, options); return result.toPromise(); } /** * Get build types compatible with the matching agent. * @param agentLocator * @param fields */ public getCompatibleBuildTypes(agentLocator: string, fields?: string, options?: Configuration): Promise<BuildTypes> { const result = this.api.getCompatibleBuildTypes(agentLocator, fields, options); return result.toPromise(); } /** * Check if the matching agent is enabled. * @param agentLocator * @param fields */ public getEnabledInfo(agentLocator: string, fields?: string, options?: Configuration): Promise<EnabledInfo> { const result = this.api.getEnabledInfo(agentLocator, fields, options); return result.toPromise(); } /** * Get build types incompatible with the matching agent. * @param agentLocator * @param fields */ public getIncompatibleBuildTypes(agentLocator: string, fields?: string, options?: Configuration): Promise<Compatibilities> { const result = this.api.getIncompatibleBuildTypes(agentLocator, fields, options); return result.toPromise(); } /** * Update a field of the matching agent. * @param agentLocator * @param field * @param body */ public setAgentField(agentLocator: string, field: string, body?: string, options?: Configuration): Promise<string> { const result = this.api.setAgentField(agentLocator, field, body, options); return result.toPromise(); } /** * Assign the matching agent to the specified agent pool. * @param agentLocator * @param fields * @param body */ public setAgentPool(agentLocator: string, fields?: string, body?: AgentPool, options?: Configuration): Promise<AgentPool> { const result = this.api.setAgentPool(agentLocator, fields, body, options); return result.toPromise(); } /** * Update the authorization info of the matching agent. * @param agentLocator * @param fields * @param body */ public setAuthorizedInfo(agentLocator: string, fields?: string, body?: AuthorizedInfo, options?: Configuration): Promise<AuthorizedInfo> { const result = this.api.setAuthorizedInfo(agentLocator, fields, body, options); return result.toPromise(); } /** * Update build configuration run policy of agent matching locator. * @param agentLocator * @param fields * @param body */ public setBuildConfigurationRunPolicy(agentLocator: string, fields?: string, body?: CompatibilityPolicy, options?: Configuration): Promise<CompatibilityPolicy> { const result = this.api.setBuildConfigurationRunPolicy(agentLocator, fields, body, options); return result.toPromise(); } /** * Update the enablement status of the matching agent. * @param agentLocator * @param fields * @param body */ public setEnabledInfo(agentLocator: string, fields?: string, body?: EnabledInfo, options?: Configuration): Promise<EnabledInfo> { const result = this.api.setEnabledInfo(agentLocator, fields, body, options); return result.toPromise(); } } import { ObservableAgentPoolApi } from './ObservableAPI.ts'; import { AgentPoolApiRequestFactory, AgentPoolApiResponseProcessor} from "../apis/AgentPoolApi.ts"; export class PromiseAgentPoolApi { private api: ObservableAgentPoolApi public constructor( configuration: Configuration, requestFactory?: AgentPoolApiRequestFactory, responseProcessor?: AgentPoolApiResponseProcessor ) { this.api = new ObservableAgentPoolApi(configuration, requestFactory, responseProcessor); } /** * Assign the agent to the matching agent pool. * @param agentPoolLocator * @param fields * @param body */ public addAgentToAgentPool(agentPoolLocator: string, fields?: string, body?: Agent, options?: Configuration): Promise<Agent> { const result = this.api.addAgentToAgentPool(agentPoolLocator, fields, body, options); return result.toPromise(); } /** * Assign the project to the matching agent pool. * @param agentPoolLocator * @param body */ public addProjectToAgentPool(agentPoolLocator: string, body?: Project, options?: Configuration): Promise<Project> { const result = this.api.addProjectToAgentPool(agentPoolLocator, body, options); return result.toPromise(); } /** * Create a new agent pool. * @param body */ public createAgentPool(body?: AgentPool, options?: Configuration): Promise<AgentPool> { const result = this.api.createAgentPool(body, options); return result.toPromise(); } /** * Delete the agent pool matching the locator. * @param agentPoolLocator */ public deleteAgentPool(agentPoolLocator: string, options?: Configuration): Promise<void> { const result = this.api.deleteAgentPool(agentPoolLocator, options); return result.toPromise(); } /** * Unassign all projects from the matching agent pool. * @param agentPoolLocator */ public deleteAllProjectsFromAgentPool(agentPoolLocator: string, options?: Configuration): Promise<void> { const result = this.api.deleteAllProjectsFromAgentPool(agentPoolLocator, options); return result.toPromise(); } /** * Unassign the project from the matching agent pool. * @param agentPoolLocator * @param projectLocator */ public deleteProjectFromAgentPool(agentPoolLocator: string, projectLocator: string, options?: Configuration): Promise<void> { const result = this.api.deleteProjectFromAgentPool(agentPoolLocator, projectLocator, options); return result.toPromise(); } /** * Get the agent pool matching the locator. * @param agentPoolLocator * @param fields */ public getAgentPoolOfAgentPool(agentPoolLocator: string, fields?: string, options?: Configuration): Promise<AgentPool> { const result = this.api.getAgentPoolOfAgentPool(agentPoolLocator, fields, options); return result.toPromise(); } /** * Get all agent pools. * @param locator * @param fields */ public getAllAgentPools(locator?: string, fields?: string, options?: Configuration): Promise<AgentPools> { const result = this.api.getAllAgentPools(locator, fields, options); return result.toPromise(); } /** * Get the agent of the matching agent pool. * @param agentPoolLocator * @param locator * @param fields */ public getAllAgentsFromAgentPool(agentPoolLocator: string, locator?: string, fields?: string, options?: Configuration): Promise<Agents> { const result = this.api.getAllAgentsFromAgentPool(agentPoolLocator, locator, fields, options); return result.toPromise(); } /** * Get all projects of the matching agent pool. * @param agentPoolLocator * @param fields */ public getAllProjectsFromAgentPool(agentPoolLocator: string, fields?: string, options?: Configuration): Promise<Projects> { const result = this.api.getAllProjectsFromAgentPool(agentPoolLocator, fields, options); return result.toPromise(); } /** * Get a field of the matching agent pool. * @param agentPoolLocator * @param field */ public getFieldFromAgentPool(agentPoolLocator: string, field: string, options?: Configuration): Promise<string> { const result = this.api.getFieldFromAgentPool(agentPoolLocator, field, options); return result.toPromise(); } /** * Update a field of the matching agent pool. * @param agentPoolLocator * @param field * @param body */ public setAgentPoolField(agentPoolLocator: string, field: string, body?: string, options?: Configuration): Promise<string> { const result = this.api.setAgentPoolField(agentPoolLocator, field, body, options); return result.toPromise(); } /** * Update projects of the matching agent pool. * @param agentPoolLocator * @param body */ public setAgentPoolProjects(agentPoolLocator: string, body?: Projects, options?: Configuration): Promise<Projects> { const result = this.api.setAgentPoolProjects(agentPoolLocator, body, options); return result.toPromise(); } } import { ObservableAuditApi } from './ObservableAPI.ts'; import { AuditApiRequestFactory, AuditApiResponseProcessor} from "../apis/AuditApi.ts"; export class PromiseAuditApi { private api: ObservableAuditApi public constructor( configuration: Configuration, requestFactory?: AuditApiRequestFactory, responseProcessor?: AuditApiResponseProcessor ) { this.api = new ObservableAuditApi(configuration, requestFactory, responseProcessor); } /** * Get all audit events. * @param locator * @param fields */ public getAllAuditEvents(locator?: string, fields?: string, options?: Configuration): Promise<AuditEvents> { const result = this.api.getAllAuditEvents(locator, fields, options); return result.toPromise(); } /** * Get audit event matching the locator. * @param auditEventLocator * @param fields */ public getAuditEvent(auditEventLocator: string, fields?: string, options?: Configuration): Promise<AuditEvent> { const result = this.api.getAuditEvent(auditEventLocator, fields, options); return result.toPromise(); } } import { ObservableBuildApi } from './ObservableAPI.ts'; import { BuildApiRequestFactory, BuildApiResponseProcessor} from "../apis/BuildApi.ts"; export class PromiseBuildApi { private api: ObservableBuildApi public constructor( configuration: Configuration, requestFactory?: BuildApiRequestFactory, responseProcessor?: BuildApiResponseProcessor ) { this.api = new ObservableBuildApi(configuration, requestFactory, responseProcessor); } /** * Add a VCS label to the matching build. * @param buildLocator * @param locator * @param fields * @param body */ public addBuildVcsLabel(buildLocator: string, locator?: string, fields?: string, body?: string, options?: Configuration): Promise<VcsLabels> { const result = this.api.addBuildVcsLabel(buildLocator, locator, fields, body, options); return result.toPromise(); } /** * Adds a message to the build log. Service messages are accepted. * @param buildLocator * @param fields * @param body */ public addLogMessageToBuild(buildLocator: string, fields?: string, body?: string, options?: Configuration): Promise<void> { const result = this.api.addLogMessageToBuild(buildLocator, fields, body, options); return result.toPromise(); } /** * Add a build problem to the matching build. * @param buildLocator * @param fields * @param body */ public addProblemToBuild(buildLocator: string, fields?: string, body?: string, options?: Configuration): Promise<ProblemOccurrence> { const result = this.api.addProblemToBuild(buildLocator, fields, body, options); return result.toPromise(); } /** * Add tags to the matching build. * @param buildLocator * @param fields * @param body */ public addTagsToBuild(buildLocator: string, fields?: string, body?: Tags, options?: Configuration): Promise<Tags> { const result = this.api.addTagsToBuild(buildLocator, fields, body, options); return result.toPromise(); } /** * Add tags to multiple matching builds. * @param buildLocator * @param fields * @param body */ public addTagsToMultipleBuilds(buildLocator: string, fields?: string, body?: Tags, options?: Configuration): Promise<MultipleOperationResult> { const result = this.api.addTagsToMultipleBuilds(buildLocator, fields, body, options); return result.toPromise(); } /** * Delete build matching the locator. * @param buildLocator */ public deleteBuild(buildLocator: string, options?: Configuration): Promise<void> { const result = this.api.deleteBuild(buildLocator, options); return result.toPromise(); } /** * Remove the build comment matching the locator. * @param buildLocator */ public deleteBuildComment(buildLocator: string, options?: Configuration): Promise<void> { const result = this.api.deleteBuildComment(buildLocator, options); return result.toPromise(); } /** * Delete comments of multiple matching builds. * @param buildLocator * @param fields */ public deleteMultipleBuildComments(buildLocator: string, fields?: string, options?: Configuration): Promise<MultipleOperationResult> { const result = this.api.deleteMultipleBuildComments(buildLocator, fields, options); return result.toPromise(); } /** * Delete multiple builds matching the locator. * @param buildLocator * @param fields */ public deleteMultipleBuilds(buildLocator: string, fields?: string, options?: Configuration): Promise<MultipleOperationResult> { const result = this.api.deleteMultipleBuilds(buildLocator, fields, options); return result.toPromise(); } /** * Download specific file. * @param path * @param buildLocator * @param resolveParameters * @param logBuildUsage */ public downloadFileOfBuild(path: string, buildLocator: string, resolveParameters?: boolean, logBuildUsage?: boolean, options?: Configuration): Promise<void> { const result = this.api.downloadFileOfBuild(path, buildLocator, resolveParameters, logBuildUsage, options); return result.toPromise(); } /** * Get the build status of aggregated matching builds. * @param buildLocator */ public getAggregatedBuildStatus(buildLocator: string, options?: Configuration): Promise<string> { const result = this.api.getAggregatedBuildStatus(buildLocator, options); return result.toPromise(); } /** * Get the status icon (in specified format) of aggregated matching builds. * @param buildLocator * @param suffix */ public getAggregatedBuildStatusIcon(buildLocator: string, suffix: string, options?: Configuration): Promise<void> { const result = this.api.getAggregatedBuildStatusIcon(buildLocator, suffix, options); return result.toPromise(); } /** * Get all builds. * @param locator * @param fields */ public getAllBuilds(locator?: string, fields?: string, options?: Configuration): Promise<Builds> { const result = this.api.getAllBuilds(locator, fields, options); return result.toPromise(); } /** * Get artifact dependency changes of the matching build. * @param buildLocator * @param fields */ public getArtifactDependencyChanges(buildLocator: string, fields?: string, options?: Configuration): Promise<BuildChanges> { const result = this.api.getArtifactDependencyChanges(buildLocator, fields, options); return result.toPromise(); } /** * Get the artifacts' directory of the matching build. * @param buildLocator */ public getArtifactsDirectory(buildLocator: string, options?: Configuration): Promise<string> { const result = this.api.getArtifactsDirectory(buildLocator, options); return result.toPromise(); } /** * Get build matching the locator. * @param buildLocator * @param fields */ public getBuild(buildLocator: string, fields?: string, options?: Configuration): Promise<Build> { const result = this.api.getBuild(buildLocator, fields, options); return result.toPromise(); } /** * Get actual build parameters of the matching build. * @param buildLocator * @param fields */ public getBuildActualParameters(buildLocator: string, fields?: string, options?: Configuration): Promise<Properties> { const result = this.api.getBuildActualParameters(buildLocator, fields, options); return result.toPromise(); } /** * Get a field of the matching build. * @param buildLocator * @param field */ public getBuildField(buildLocator: string, field: string, options?: Configuration): Promise<string> { const result = this.api.getBuildField(buildLocator, field, options); return result.toPromise(); } /** * Get the finish date of the matching build. * @param buildLocator */ public getBuildFinishDate(buildLocator: string, options?: Configuration): Promise<string> { const result = this.api.getBuildFinishDate(buildLocator, options); return result.toPromise(); } /** * Get the number of the matching build. * @param buildLocator */ public getBuildNumber(buildLocator: string, options?: Configuration): Promise<string> { const result = this.api.getBuildNumber(buildLocator, options); return result.toPromise(); } /** * Check if the matching build is pinned. * @param buildLocator * @param fields */ public getBuildPinInfo(buildLocator: string, fields?: string, options?: Configuration): Promise<PinInfo> { const result = this.api.getBuildPinInfo(buildLocator, fields, options); return result.toPromise(); } /** * Get build problems of the matching build. * @param buildLocator * @param fields */ public getBuildProblems(buildLocator: string, fields?: string, options?: Configuration): Promise<ProblemOccurrences> { const result = this.api.getBuildProblems(buildLocator, fields, options); return result.toPromise(); } /** * Get related issues of the matching build. * @param buildLocator * @param fields */ public getBuildRelatedIssues(buildLocator: string, fields?: string, options?: Configuration): Promise<IssuesUsages> { const result = this.api.getBuildRelatedIssues(buildLocator, fields, options); return result.toPromise(); } /** * Get the resolvement status of the matching build. * @param buildLocator * @param value */ public getBuildResolved(buildLocator: string, value: string, options?: Configuration): Promise<string> { const result = this.api.getBuildResolved(buildLocator, value, options); return result.toPromise(); } /** * Update a build parameter of the matching build. * @param buildLocator * @param propertyName */ public getBuildResultingProperties(buildLocator: string, propertyName: string, options?: Configuration): Promise<string> { const result = this.api.getBuildResultingProperties(buildLocator, propertyName, options); return result.toPromise(); } /** * Get a source file of the matching build. * @param buildLocator * @param fileName */ public getBuildSourceFile(buildLocator: string, fileName: string, options?: Configuration): Promise<void> { const result = this.api.getBuildSourceFile(buildLocator, fileName, options); return result.toPromise(); } /** * Get a statistical value of the matching build. * @param buildLocator * @param name */ public getBuildStatisticValue(buildLocator: string, name: string, options?: Configuration): Promise<string> { const result = this.api.getBuildStatisticValue(buildLocator, name, options); return result.toPromise(); } /** * Get all statistical values of the matching build. * @param buildLocator * @param fields */ public getBuildStatisticValues(buildLocator: string, fields?: string, options?: Configuration): Promise<Properties> { const result = this.api.getBuildStatisticValues(buildLocator, fields, options); return result.toPromise(); } /** * Get the status icon (in specified format) of the matching build. * @param buildLocator * @param suffix */ public getBuildStatusIcon(buildLocator: string, suffix: string, options?: Configuration): Promise<void> { const result = this.api.getBuildStatusIcon(buildLocator, suffix, options); return result.toPromise(); } /** * Get the build status text of the matching build. * @param buildLocator */ public getBuildStatusText(buildLocator: string, options?: Configuration): Promise<string> { const result = this.api.getBuildStatusText(buildLocator, options); return result.toPromise(); } /** * Get tags of the matching build. * @param buildLocator * @param locator * @param fields */ public getBuildTags(buildLocator: string, locator?: string, fields?: string, options?: Configuration): Promise<Tags> { const result = this.api.getBuildTags(buildLocator, locator, fields, options); return result.toPromise(); } /** * Get test occurrences of the matching build. * @param buildLocator * @param fields */ public getBuildTestOccurrences(buildLocator: string, fields?: string, options?: Configuration): Promise<TestOccurrences> { const result = this.api.getBuildTestOccurrences(buildLocator, fields, options); return result.toPromise(); } /** * Get VCS labels of the matching build. * @param buildLocator * @param fields */ public getBuildVcsLabels(buildLocator: string, fields?: string, options?: Configuration): Promise<VcsLabels> { const result = this.api.getBuildVcsLabels(buildLocator, fields, options); return result.toPromise(); } /** * Check if the matching build is canceled. * @param buildLocator * @param fields */ public getCanceledInfo(buildLocator: string, fields?: string, options?: Configuration): Promise<Comment> { const result = this.api.getCanceledInfo(buildLocator, fields, options); return result.toPromise(); } /** * Get metadata of specific file. * @param path * @param buildLocator * @param fields * @param resolveParameters * @param logBuildUsage */ public getFileMetadataOfBuild(path: string, buildLocator: string, fields?: string, resolveParameters?: boolean, logBuildUsage?: boolean, options?: Configuration): Promise<any> { const result = this.api.getFileMetadataOfBuild(path, buildLocator, fields, resolveParameters, logBuildUsage, options); return result.toPromise(); } /** * List files under this path. * @param path * @param buildLocator * @param basePath * @param locator * @param fields * @param resolveParameters * @param logBuildUsage */ public getFilesListForSubpathOfBuild(path: string, buildLocator: string, basePath?: string, locator?: string, fields?: string, resolveParameters?: boolean, logBuildUsage?: boolean, options?: Configuration): Promise<Files> { const result = this.api.getFilesListForSubpathOfBuild(path, buildLocator, basePath, locator, fields, resolveParameters, logBuildUsage, options); return result.toPromise(); } /** * List all files. * @param buildLocator * @param basePath * @param locator * @param fields * @param resolveParameters * @param logBuildUsage */ public getFilesListOfBuild(buildLocator: string, basePath?: string, locator?: string, fields?: string, resolveParameters?: boolean, logBuildUsage?: boolean, options?: Configuration): Promise<Files> { const result = this.api.getFilesListOfBuild(buildLocator, basePath, locator, fields, resolveParameters, logBuildUsage, options); return result.toPromise(); } /** * Get multiple builds matching the locator. * @param buildLocator * @param fields */ public getMultipleBuilds(buildLocator: string, fields?: string, options?: Configuration): Promise<Builds> { const result = this.api.getMultipleBuilds(buildLocator, fields, options); return result.toPromise(); } /** * Get specific file zipped. * @param path * @param buildLocator * @param basePath * @param locator * @param name * @param resolveParameters * @param logBuildUsage */ public getZippedFileOfBuild(path: string, buildLocator: string, basePath?: string, locator?: string, name?: string, resolveParameters?: boolean, logBuildUsage?: boolean, options?: Configuration): Promise<void> { const result = this.api.getZippedFileOfBuild(path, buildLocator, basePath, locator, name, resolveParameters, logBuildUsage, options); return result.toPromise(); } /** * Starts the queued build as an agent-less build and returns the corresponding running build. * @param buildLocator * @param fields * @param body */ public markBuildAsRunning(buildLocator: string, fields?: string, body?: string, options?: Configuration): Promise<Build> { const result = this.api.markBuildAsRunning(buildLocator, fields, body, options); return result.toPromise(); } /** * Pin multiple matching builds. * @param buildLocator * @param fields * @param body */ public pinMultipleBuilds(buildLocator: string, fields?: string, body?: PinInfo, options?: Configuration): Promise<MultipleOperationResult> { const result = this.api.pinMultipleBuilds(buildLocator, fields, body, options); return result.toPromise(); } /** * Remove tags from multiple matching builds. * @param buildLocator * @param fields * @param body */ public removeMultipleBuildTags(buildLocator: string, fields?: string, body?: Tags, options?: Configuration): Promise<MultipleOperationResult> { const result = this.api.removeMultipleBuildTags(buildLocator, fields, body, options); return result.toPromise(); } /** * Remove build parameters from the matching build. * @param buildLocator */ public resetBuildFinishProperties(buildLocator: string, options?: Configuration): Promise<void> { const result = this.api.resetBuildFinishProperties(buildLocator, options); return result.toPromise(); } /** * Update the comment on the matching build. * @param buildLocator * @param body */ public setBuildComment(buildLocator: string, body?: string, options?: Configuration): Promise<void> { const result = this.api.setBuildComment(buildLocator, body, options); return result.toPromise(); } /** * Marks the running build as finished by passing agent the current time of the build to finish. * @param buildLocator * @param body */ public setBuildFinishDate(buildLocator: string, body?: string, options?: Configuration): Promise<string> { const result = this.api.setBuildFinishDate(buildLocator, body, options); return result.toPromise(); } /** * Update the number of the matching build. * @param buildLocator * @param body */ public setBuildNumber(buildLocator: string, body?: string, options?: Configuration): Promise<string> { const result = this.api.setBuildNumber(buildLocator, body, options); return result.toPromise(); } /** * Update the pin info of the matching build. * @param buildLocator * @param fields * @param body */ public setBuildPinInfo(buildLocator: string, fields?: string, body?: PinInfo, options?: Configuration): Promise<PinInfo> { const result = this.api.setBuildPinInfo(buildLocator, fields, body, options); return result.toPromise(); } /** * Update the build status of the matching build. * @param buildLocator * @param body */ public setBuildStatusText(buildLocator: string, body?: string, options?: Configuration): Promise<string> { const result = this.api.setBuildStatusText(buildLocator, body, options); return result.toPromise(); } /** * Update tags of the matching build. * @param buildLocator * @param locator * @param fields * @param body */ public setBuildTags(buildLocator: string, locator?: string, fields?: string, body?: Tags, options?: Configuration): Promise<Tags> { const result = this.api.setBuildTags(buildLocator, locator, fields, body, options); return result.toPromise(); } /** * Marks the running build as finished by passing agent the current time of the build to finish. * @param buildLocator */ public setFinishedTime(buildLocator: string, options?: Configuration): Promise<string> { const result = this.api.setFinishedTime(buildLocator, options); return result.toPromise(); } /** * Update comments in multiple matching builds. * @param buildLocator * @param fields * @param body */ public setMultipleBuildComments(buildLocator: string, fields?: string, body?: string, options?: Configuration): Promise<MultipleOperationResult> { const result = this.api.setMultipleBuildComments(buildLocator, fields, body, options); return result.toPromise(); } } import { ObservableBuildQueueApi } from './ObservableAPI.ts'; import { BuildQueueApiRequestFactory, BuildQueueApiResponseProcessor} from "../apis/BuildQueueApi.ts"; export class PromiseBuildQueueApi { private api: ObservableBuildQueueApi public constructor( configuration: Configuration, requestFactory?: BuildQueueApiRequestFactory, responseProcessor?: BuildQueueApiResponseProcessor ) { this.api = new ObservableBuildQueueApi(configuration, requestFactory, responseProcessor); } /** * Add a new build to the queue. * @param moveToTop * @param body */ public addBuildToQueue(moveToTop?: boolean, body?: Build, options?: Configuration): Promise<Build> { const result = this.api.addBuildToQueue(moveToTop, body, options); return result.toPromise(); } /** * Add tags to the matching build. * @param buildLocator * @param body */ public addTagsToBuildOfBuildQueue(buildLocator: string, body?: Tags, options?: Configuration): Promise<void> { const result = this.api.addTagsToBuildOfBuildQueue(buildLocator, body, options); return result.toPromise(); } /** * Cancel a queued matching build. * @param queuedBuildLocator * @param body */ public cancelQueuedBuild(queuedBuildLocator: string, body?: BuildCancelRequest, options?: Configuration): Promise<Build> { const result = this.api.cancelQueuedBuild(queuedBuildLocator, body, options); return result.toPromise(); } /** * Delete all queued builds. * @param locator * @param fields */ public deleteAllQueuedBuilds(locator?: string, fields?: string, options?: Configuration): Promise<void> { const result = this.api.deleteAllQueuedBuilds(locator, fields, options); return result.toPromise(); } /** * Delete a queued matching build. * @param queuedBuildLocator */ public deleteQueuedBuild(queuedBuildLocator: string, options?: Configuration): Promise<void> { const result = this.api.deleteQueuedBuild(queuedBuildLocator, options); return result.toPromise(); } /** * Get all queued builds. * @param locator * @param fields */ public getAllQueuedBuilds(locator?: string, fields?: string, options?: Configuration): Promise<Builds> { const result = this.api.getAllQueuedBuilds(locator, fields, options); return result.toPromise(); } /** * Get compatible agents for a queued matching build. * @param queuedBuildLocator * @param fields */ public getCompatibleAgentsForBuild(queuedBuildLocator: string, fields?: string, options?: Configuration): Promise<Agents> { const result = this.api.getCompatibleAgentsForBuild(queuedBuildLocator, fields, options); return result.toPromise(); } /** * Get a queued matching build. * @param queuedBuildLocator * @param fields */ public getQueuedBuild(queuedBuildLocator: string, fields?: string, options?: Configuration): Promise<Build> { const result = this.api.getQueuedBuild(queuedBuildLocator, fields, options); return result.toPromise(); } /** * Get the queue position of a queued matching build. * @param queuePosition * @param fields */ public getQueuedBuildPosition(queuePosition: string, fields?: string, options?: Configuration): Promise<Build> { const result = this.api.getQueuedBuildPosition(queuePosition, fields, options); return result.toPromise(); } /** * Get tags of the queued matching build. * @param buildLocator * @param locator * @param fields */ public getQueuedBuildTags(buildLocator: string, locator?: string, fields?: string, options?: Configuration): Promise<Tags> { const result = this.api.getQueuedBuildTags(buildLocator, locator, fields, options); return result.toPromise(); } /** * Update the queue position of a queued matching build. * @param queuePosition * @param fields * @param body */ public setQueuedBuildPosition(queuePosition: string, fields?: string, body?: Build, options?: Configuration): Promise<Build> { const result = this.api.setQueuedBuildPosition(queuePosition, fields, body, options); return result.toPromise(); } /** * Update the build queue order. * @param fields * @param body */ public setQueuedBuildsOrder(fields?: string, body?: Builds, options?: Configuration): Promise<Builds> { const result = this.api.setQueuedBuildsOrder(fields, body, options); return result.toPromise(); } } import { ObservableBuildTypeApi } from './ObservableAPI.ts'; import { BuildTypeApiRequestFactory, BuildTypeApiResponseProcessor} from "../apis/BuildTypeApi.ts"; export class PromiseBuildTypeApi { private api: ObservableBuildTypeApi public constructor( configuration: Configuration, requestFactory?: BuildTypeApiRequestFactory, responseProcessor?: BuildTypeApiResponseProcessor ) { this.api = new ObservableBuildTypeApi(configuration, requestFactory, responseProcessor); } /** * Add an agent requirement to the matching build configuration. * @param btLocator * @param fields * @param body */ public addAgentRequirementToBuildType(btLocator: string, fields?: string, body?: AgentRequirement, options?: Configuration): Promise<AgentRequirement> { const result = this.api.addAgentRequirementToBuildType(btLocator, fields, body, options); return result.toPromise(); } /** * Add an artifact dependency to the matching build configuration. * @param btLocator * @param fields * @param body */ public addArtifactDependencyToBuildType(btLocator: string, fields?: string, body?: ArtifactDependency, options?: Configuration): Promise<ArtifactDependency> { const result = this.api.addArtifactDependencyToBuildType(btLocator, fields, body, options); return result.toPromise(); } /** * Add build feature to the matching build configuration. * @param btLocator * @param fields * @param body */ public addBuildFeatureToBuildType(btLocator: string, fields?: string, body?: Feature, options?: Configuration): Promise<Feature> { const result = this.api.addBuildFeatureToBuildType(btLocator, fields, body, options); return result.toPromise(); } /** * Add a build step to the matching build configuration. * @param btLocator * @param fields * @param body */ public addBuildStepToBuildType(btLocator: string, fields?: string, body?: Step, options?: Configuration): Promise<Step> { const result = this.api.addBuildStepToBuildType(btLocator, fields, body, options); return result.toPromise(); } /** * Add a build template to the matching build configuration. * @param btLocator * @param optimizeSettings * @param fields * @param body */ public addBuildTemplate(btLocator: string, optimizeSettings?: boolean, fields?: string, body?: BuildType, options?: Configuration): Promise<BuildType> { const result = this.api.addBuildTemplate(btLocator, optimizeSettings, fields, body, options); return result.toPromise(); } /** * Update build feature parameter for the matching build configuration. * @param btLocator * @param featureId * @param parameterName * @param body */ public addParameterToBuildFeature(btLocator: string, featureId: string, parameterName: string, body?: string, options?: Configuration): Promise<string> { const result = this.api.addParameterToBuildFeature(btLocator, featureId, parameterName, body, options); return result.toPromise(); } /** * Add a parameter to a build step of the matching build configuration. * @param btLocator * @param stepId * @param parameterName * @param body */ public addParameterToBuildStep(btLocator: string, stepId: string, parameterName: string, body?: string, options?: Configuration): Promise<string> { const result = this.api.addParameterToBuildStep(btLocator, stepId, parameterName, body, options); return result.toPromise(); } /** * Add a snapshot dependency to the matching build configuration. * @param btLocator * @param fields * @param body */ public addSnapshotDependencyToBuildType(btLocator: string, fields?: string, body?: SnapshotDependency, options?: Configuration): Promise<SnapshotDependency> { const result = this.api.addSnapshotDependencyToBuildType(btLocator, fields, body, options); return result.toPromise(); } /** * Add a trigger to the matching build configuration. * @param btLocator * @param fields * @param body */ public addTriggerToBuildType(btLocator: string, fields?: string, body?: Trigger, options?: Configuration): Promise<Trigger> { const result = this.api.addTriggerToBuildType(btLocator, fields, body, options); return result.toPromise(); } /** * Add a VCS root to the matching build. * @param btLocator * @param fields * @param body */ public addVcsRootToBuildType(btLocator: string, fields?: string, body?: VcsRootEntry, options?: Configuration): Promise<VcsRootEntry> { const result = this.api.addVcsRootToBuildType(btLocator, fields, body, options); return result.toPromise(); } /** * Create a build parameter. * @param btLocator * @param fields * @param body */ public createBuildParameterOfBuildType(btLocator: string, fields?: string, body?: Property, options?: Configuration): Promise<Property> { const result = this.api.createBuildParameterOfBuildType(btLocator, fields, body, options); return result.toPromise(); } /** * Create a new build configuration. * @param fields * @param body */ public createBuildType(fields?: string, body?: BuildType, options?: Configuration): Promise<BuildType> { const result = this.api.createBuildType(fields, body, options); return result.toPromise(); } /** * Remove an agent requirement of the matching build configuration. * @param btLocator * @param agentRequirementLocator */ public deleteAgentRequirement(btLocator: string, agentRequirementLocator: string, options?: Configuration): Promise<void> { const result = this.api.deleteAgentRequirement(btLocator, agentRequirementLocator, options); return result.toPromise(); } /** * Remove an artifact dependency from the matching build configuration. * @param btLocator * @param artifactDepLocator */ public deleteArtifactDependency(btLocator: string, artifactDepLocator: string, options?: Configuration): Promise<void> { const result = this.api.deleteArtifactDependency(btLocator, artifactDepLocator, options); return result.toPromise(); } /** * Delete build parameter. * @param name * @param btLocator */ public deleteBuildParameterOfBuildType(name: string, btLocator: string, options?: Configuration): Promise<void> { const result = this.api.deleteBuildParameterOfBuildType(name, btLocator, options); return result.toPromise(); } /** * Delete all build parameters. * @param btLocator */ public deleteBuildParametersOfBuildType(btLocator: string, options?: Configuration): Promise<void> { const result = this.api.deleteBuildParametersOfBuildType(btLocator, options); return result.toPromise(); } /** * Delete a build step of the matching build configuration. * @param btLocator * @param stepId */ public deleteBuildStep(btLocator: string, stepId: string, options?: Configuration): Promise<void> { const result = this.api.deleteBuildStep(btLocator, stepId, options); return result.toPromise(); } /** * Update a parameter of a build step of the matching build configuration. * @param btLocator * @param stepId * @param fields * @param body */ public deleteBuildStepParameters(btLocator: string, stepId: string, fields?: string, body?: Properties, options?: Configuration): Promise<Properties> { const result = this.api.deleteBuildStepParameters(btLocator, stepId, fields, body, options); return result.toPromise(); } /** * Delete build configuration matching the locator. * @param btLocator */ public deleteBuildType(btLocator: string, options?: Configuration): Promise<void> { const result = this.api.deleteBuildType(btLocator, options); return result.toPromise(); } /** * Remove a build feature of the matching build configuration. * @param btLocator * @param featureId */ public deleteFeatureOfBuildType(btLocator: string, featureId: string, options?: Configuration): Promise<void> { const result = this.api.deleteFeatureOfBuildType(btLocator, featureId, options); return result.toPromise(); } /** * Delete a snapshot dependency of the matching build configuration. * @param btLocator * @param snapshotDepLocator */ public deleteSnapshotDependency(btLocator: string, snapshotDepLocator: string, options?: Configuration): Promise<void> { const result = this.api.deleteSnapshotDependency(btLocator, snapshotDepLocator, options); return result.toPromise(); } /** * Delete a trigger of the matching build configuration. * @param btLocator * @param triggerLocator */ public deleteTrigger(btLocator: string, triggerLocator: string, options?: Configuration): Promise<void> { const result = this.api.deleteTrigger(btLocator, triggerLocator, options); return result.toPromise(); } /** * Remove a VCS root of the matching build configuration. * @param btLocator * @param vcsRootLocator */ public deleteVcsRootOfBuildType(btLocator: string, vcsRootLocator: string, options?: Configuration): Promise<void> { const result = this.api.deleteVcsRootOfBuildType(btLocator, vcsRootLocator, options); return result.toPromise(); } /** * Download specific file. * @param path * @param btLocator * @param resolveParameters */ public downloadFileOfBuildType(path: string, btLocator: string, resolveParameters?: boolean, options?: Configuration): Promise<void> { const result = this.api.downloadFileOfBuildType(path, btLocator, resolveParameters, options); return result.toPromise(); } /** * Get an agent requirement of the matching build configuration. * @param btLocator * @param agentRequirementLocator * @param fields */ public getAgentRequirement(btLocator: string, agentRequirementLocator: string, fields?: string, options?: Configuration): Promise<AgentRequirement> { const result = this.api.getAgentRequirement(btLocator, agentRequirementLocator, fields, options); return result.toPromise(); } /** * Get a setting of an agent requirement of the matching build configuration. * @param btLocator * @param agentRequirementLocator * @param fieldName */ public getAgentRequirementParameter(btLocator: string, agentRequirementLocator: string, fieldName: string, options?: Configuration): Promise<string> { const result = this.api.getAgentRequirementParameter(btLocator, agentRequirementLocator, fieldName, options); return result.toPromise(); } /** * Get external IDs of the matching build configuration. * @param btLocator * @param field */ public getAliases(btLocator: string, field?: string, options?: Configuration): Promise<Items> { const result = this.api.getAliases(btLocator, field, options); return result.toPromise(); } /** * Get all agent requirements of the matching build configuration. * @param btLocator * @param fields */ public getAllAgentRequirements(btLocator: string, fields?: string, options?: Configuration): Promise<AgentRequirements> { const result = this.api.getAllAgentRequirements(btLocator, fields, options); return result.toPromise(); } /** * Get all artifact dependencies of the matching build configuration. * @param btLocator * @param fields */ public getAllArtifactDependencies(btLocator: string, fields?: string, options?: Configuration): Promise<ArtifactDependencies> { const result = this.api.getAllArtifactDependencies(btLocator, fields, options); return result.toPromise(); } /** * Get all branches of the matching build configuration. * @param btLocator * @param locator * @param fields */ public getAllBranchesOfBuildType(btLocator: string, locator?: string, fields?: string, options?: Configuration): Promise<Branches> { const result = this.api.getAllBranchesOfBuildType(btLocator, locator, fields, options); return result.toPromise(); } /** * Get all parameters of a build feature of the matching build configuration. * @param btLocator * @param featureId * @param fields */ public getAllBuildFeatureParameters(btLocator: string, featureId: string, fields?: string, options?: Configuration): Promise<Properties> { const result = this.api.getAllBuildFeatureParameters(btLocator, featureId, fields, options); return result.toPromise(); } /** * Get all build features of the matching build configuration. * @param btLocator * @param fields */ public getAllBuildFeatures(btLocator: string, fields?: string, options?: Configuration): Promise<Features> { const result = this.api.getAllBuildFeatures(btLocator, fields, options); return result.toPromise(); } /** * Get all parameters of a build step of the matching build configuration. * @param btLocator * @param stepId * @param fields */ public getAllBuildStepParameters(btLocator: string, stepId: string, fields?: string, options?: Configuration): Promise<Properties> { const result = this.api.getAllBuildStepParameters(btLocator, stepId, fields, options); return result.toPromise(); } /** * Get all build steps of the matching build configuration. * @param btLocator * @param fields */ public getAllBuildSteps(btLocator: string, fields?: string, options?: Configuration): Promise<Steps> { const result = this.api.getAllBuildSteps(btLocator, fields, options); return result.toPromise(); } /** * Get all build templates of the matching build configuration. * @param btLocator * @param fields */ public getAllBuildTemplates(btLocator: string, fields?: string, options?: Configuration): Promise<BuildTypes> { const result = this.api.getAllBuildTemplates(btLocator, fields, options); return result.toPromise(); } /** * Get all build configurations. * @param locator * @param fields */ public getAllBuildTypes(locator?: string, fields?: string, options?: Configuration): Promise<BuildTypes> { const result = this.api.getAllBuildTypes(locator, fields, options); return result.toPromise(); } /** * Get all investigations of the matching build configuration. * @param btLocator * @param fields */ public getAllInvestigationsOfBuildType(btLocator: string, fields?: string, options?: Configuration): Promise<Investigations> { const result = this.api.getAllInvestigationsOfBuildType(btLocator, fields, options); return result.toPromise(); } /** * Get all snapshot dependencies of the matching build configuration. * @param btLocator * @param fields */ public getAllSnapshotDependencies(btLocator: string, fields?: string, options?: Configuration): Promise<SnapshotDependencies> { const result = this.api.getAllSnapshotDependencies(btLocator, fields, options); return result.toPromise(); } /** * Get all triggers of the matching build configuration. * @param btLocator * @param fields */ public getAllTriggers(btLocator: string, fields?: string, options?: Configuration): Promise<Triggers> { const result = this.api.getAllTriggers(btLocator, fields, options); return result.toPromise(); } /** * Get all VCS roots of the matching build configuration. * @param btLocator * @param fields */ public getAllVcsRootsOfBuildType(btLocator: string, fields?: string, options?: Configuration): Promise<VcsRootEntries> { const result = this.api.getAllVcsRootsOfBuildType(btLocator, fields, options); return result.toPromise(); } /** * Get an artifact dependency of the matching build configuration. * @param btLocator * @param artifactDepLocator * @param fields */ public getArtifactDependency(btLocator: string, artifactDepLocator: string, fields?: string, options?: Configuration): Promise<ArtifactDependency> { const result = this.api.getArtifactDependency(btLocator, artifactDepLocator, fields, options); return result.toPromise(); } /** * Get a parameter of an artifact dependency of the matching build configuration. * @param btLocator * @param artifactDepLocator * @param fieldName */ public getArtifactDependencyParameter(btLocator: string, artifactDepLocator: string, fieldName: string, options?: Configuration): Promise<string> { const result = this.api.getArtifactDependencyParameter(btLocator, artifactDepLocator, fieldName, options); return result.toPromise(); } /** * Get a build feature of the matching build configuration. * @param btLocator * @param featureId * @param fields */ public getBuildFeature(btLocator: string, featureId: string, fields?: string, options?: Configuration): Promise<Feature> { const result = this.api.getBuildFeature(btLocator, featureId, fields, options); return result.toPromise(); } /** * Get a parameter of a build feature of the matching build configuration. * @param btLocator * @param featureId * @param parameterName */ public getBuildFeatureParameter(btLocator: string, featureId: string, parameterName: string, options?: Configuration): Promise<string> { const result = this.api.getBuildFeatureParameter(btLocator, featureId, parameterName, options); return result.toPromise(); } /** * Get the setting of a build feature of the matching build configuration. * @param btLocator * @param featureId * @param name */ public getBuildFeatureSetting(btLocator: string, featureId: string, name: string, options?: Configuration): Promise<string> { const result = this.api.getBuildFeatureSetting(btLocator, featureId, name, options); return result.toPromise(); } /** * Get build parameter. * @param name * @param btLocator * @param fields */ public getBuildParameterOfBuildType(name: string, btLocator: string, fields?: string, options?: Configuration): Promise<Property> { const result = this.api.getBuildParameterOfBuildType(name, btLocator, fields, options); return result.toPromise(); } /** * Get build parameter specification. * @param name * @param btLocator */ public getBuildParameterSpecificationOfBuildType(name: string, btLocator: string, options?: Configuration): Promise<string> { const result = this.api.getBuildParameterSpecificationOfBuildType(name, btLocator, options); return result.toPromise(); } /** * Get type of build parameter. * @param name * @param btLocator */ public getBuildParameterTypeOfBuildType(name: string, btLocator: string, options?: Configuration): Promise<Type> { const result = this.api.getBuildParameterTypeOfBuildType(name, btLocator, options); return result.toPromise(); } /** * Get value of build parameter. * @param name * @param btLocator */ public getBuildParameterValueOfBuildType(name: string, btLocator: string, options?: Configuration): Promise<string> { const result = this.api.getBuildParameterValueOfBuildType(name, btLocator, options); return result.toPromise(); } /** * Get build parameters. * @param btLocator * @param locator * @param fields */ public getBuildParametersOfBuildType(btLocator: string, locator?: string, fields?: string, options?: Configuration): Promise<Properties> { const result = this.api.getBuildParametersOfBuildType(btLocator, locator, fields, options); return result.toPromise(); } /** * Get a build step of the matching build configuration. * @param btLocator * @param stepId * @param fields */ public getBuildStep(btLocator: string, stepId: string, fields?: string, options?: Configuration): Promise<Step> { const result = this.api.getBuildStep(btLocator, stepId, fields, options); return result.toPromise(); } /** * Get a parameter of a build step of the matching build configuration. * @param btLocator * @param stepId * @param parameterName */ public getBuildStepParameter(btLocator: string, stepId: string, parameterName: string, options?: Configuration): Promise<string> { const result = this.api.getBuildStepParameter(btLocator, stepId, parameterName, options); return result.toPromise(); } /** * Get the setting of a build step of the matching build configuration. * @param btLocator * @param stepId * @param fieldName */ public getBuildStepSetting(btLocator: string, stepId: string, fieldName: string, options?: Configuration): Promise<string> { const result = this.api.getBuildStepSetting(btLocator, stepId, fieldName, options); return result.toPromise(); } /** * Get a template of the matching build configuration. * @param btLocator * @param templateLocator * @param fields */ public getBuildTemplate(btLocator: string, templateLocator: string, fields?: string, options?: Configuration): Promise<BuildType> { const result = this.api.getBuildTemplate(btLocator, templateLocator, fields, options); return result.toPromise(); } /** * Get build configuration matching the locator. * @param btLocator * @param fields */ public getBuildType(btLocator: string, fields?: string, options?: Configuration): Promise<BuildType> { const result = this.api.getBuildType(btLocator, fields, options); return result.toPromise(); } /** * Get tags of builds of the matching build configuration. * @param btLocator * @param field */ public getBuildTypeBuildTags(btLocator: string, field?: string, options?: Configuration): Promise<Tags> { const result = this.api.getBuildTypeBuildTags(btLocator, field, options); return result.toPromise(); } /** * Get builds of the matching build configuration. * @param btLocator * @param fields */ public getBuildTypeBuilds(btLocator: string, fields?: string, options?: Configuration): Promise<Builds> { const result = this.api.getBuildTypeBuilds(btLocator, fields, options); return result.toPromise(); } /** * Get a field of the matching build configuration. * @param btLocator * @param field */ public getBuildTypeField(btLocator: string, field: string, options?: Configuration): Promise<string> { const result = this.api.getBuildTypeField(btLocator, field, options); return result.toPromise(); } /** * Get the settings file of the matching build configuration. * @param btLocator */ public getBuildTypeSettingsFile(btLocator: string, options?: Configuration): Promise<string> { const result = this.api.getBuildTypeSettingsFile(btLocator, options); return result.toPromise(); } /** * Get metadata of specific file. * @param path * @param btLocator * @param fields * @param resolveParameters */ public getFileMetadataOfBuildType(path: string, btLocator: string, fields?: string, resolveParameters?: boolean, options?: Configuration): Promise<any> { const result = this.api.getFileMetadataOfBuildType(path, btLocator, fields, resolveParameters, options); return result.toPromise(); } /** * List files under this path. * @param path * @param btLocator * @param basePath * @param locator * @param fields * @param resolveParameters */ public getFilesListForSubpathOfBuildType(path: string, btLocator: string, basePath?: string, locator?: string, fields?: string, resolveParameters?: boolean, options?: Configuration): Promise<Files> { const result = this.api.getFilesListForSubpathOfBuildType(path, btLocator, basePath, locator, fields, resolveParameters, options); return result.toPromise(); } /** * List all files. * @param btLocator * @param basePath * @param locator * @param fields * @param resolveParameters */ public getFilesListOfBuildType(btLocator: string, basePath?: string, locator?: string, fields?: string, resolveParameters?: boolean, options?: Configuration): Promise<Files> { const result = this.api.getFilesListOfBuildType(btLocator, basePath, locator, fields, resolveParameters, options); return result.toPromise(); } /** * Get a snapshot dependency of the matching build configuration. * @param btLocator * @param snapshotDepLocator * @param fields */ public getSnapshotDependency(btLocator: string, snapshotDepLocator: string, fields?: string, options?: Configuration): Promise<SnapshotDependency> { const result = this.api.getSnapshotDependency(btLocator, snapshotDepLocator, fields, options); return result.toPromise(); } /** * Get a trigger of the matching build configuration. * @param btLocator * @param triggerLocator * @param fields */ public getTrigger(btLocator: string, triggerLocator: string, fields?: string, options?: Configuration): Promise<Trigger> { const result = this.api.getTrigger(btLocator, triggerLocator, fields, options); return result.toPromise(); } /** * Get a parameter of a trigger of the matching build configuration. * @param btLocator * @param triggerLocator * @param fieldName */ public getTriggerParameter(btLocator: string, triggerLocator: string, fieldName: string, options?: Configuration): Promise<string> { const result = this.api.getTriggerParameter(btLocator, triggerLocator, fieldName, options); return result.toPromise(); } /** * Get a VCS root of the matching build configuration. * @param btLocator * @param vcsRootLocator * @param fields */ public getVcsRoot(btLocator: string, vcsRootLocator: string, fields?: string, options?: Configuration): Promise<VcsRootEntry> { const result = this.api.getVcsRoot(btLocator, vcsRootLocator, fields, options); return result.toPromise(); } /** * Get checkout rules of a VCS root of the matching build configuration. * @param btLocator * @param vcsRootLocator */ public getVcsRootCheckoutRules(btLocator: string, vcsRootLocator: string, options?: Configuration): Promise<string> { const result = this.api.getVcsRootCheckoutRules(btLocator, vcsRootLocator, options); return result.toPromise(); } /** * Get all VCS root instances of the matching build configuration. * @param btLocator * @param fields */ public getVcsRootInstancesOfBuildType(btLocator: string, fields?: string, options?: Configuration): Promise<VcsRootInstances> { const result = this.api.getVcsRootInstancesOfBuildType(btLocator, fields, options); return result.toPromise(); } /** * Get specific file zipped. * @param path * @param btLocator * @param basePath * @param locator * @param name * @param resolveParameters */ public getZippedFileOfBuildType(path: string, btLocator: string, basePath?: string, locator?: string, name?: string, resolveParameters?: boolean, options?: Configuration): Promise<void> { const result = this.api.getZippedFileOfBuildType(path, btLocator, basePath, locator, name, resolveParameters, options); return result.toPromise(); } /** * Detach all templates from the matching build configuration. * @param btLocator * @param inlineSettings */ public removeAllTemplates(btLocator: string, inlineSettings?: boolean, options?: Configuration): Promise<void> { const result = this.api.removeAllTemplates(btLocator, inlineSettings, options); return result.toPromise(); } /** * Detach a template from the matching build configuration. * @param btLocator * @param templateLocator * @param inlineSettings */ public removeTemplate(btLocator: string, templateLocator: string, inlineSettings?: boolean, options?: Configuration): Promise<void> { const result = this.api.removeTemplate(btLocator, templateLocator, inlineSettings, options); return result.toPromise(); } /** * Update an agent requirement of the matching build configuration. * @param btLocator * @param agentRequirementLocator * @param fields * @param body */ public replaceAgentRequirement(btLocator: string, agentRequirementLocator: string, fields?: string, body?: AgentRequirement, options?: Configuration): Promise<AgentRequirement> { const result = this.api.replaceAgentRequirement(btLocator, agentRequirementLocator, fields, body, options); return result.toPromise(); } /** * Update all agent requirements of the matching build configuration. * @param btLocator * @param fields * @param body */ public replaceAllAgentRequirements(btLocator: string, fields?: string, body?: AgentRequirements, options?: Configuration): Promise<AgentRequirements> { const result = this.api.replaceAllAgentRequirements(btLocator, fields, body, options); return result.toPromise(); } /** * Update all artifact dependencies of the matching build configuration. * @param btLocator * @param fields * @param body */ public replaceAllArtifactDependencies(btLocator: string, fields?: string, body?: ArtifactDependencies, options?: Configuration): Promise<ArtifactDependencies> { const result = this.api.replaceAllArtifactDependencies(btLocator, fields, body, options); return result.toPromise(); } /** * Update all build features of the matching build configuration. * @param btLocator * @param fields * @param body */ public replaceAllBuildFeatures(btLocator: string, fields?: string, body?: Features, options?: Configuration): Promise<Features> { const result = this.api.replaceAllBuildFeatures(btLocator, fields, body, options); return result.toPromise(); } /** * Update all build steps of the matching build configuration. * @param btLocator * @param fields * @param body */ public replaceAllBuildSteps(btLocator: string, fields?: string, body?: Steps, options?: Configuration): Promise<Steps> { const result = this.api.replaceAllBuildSteps(btLocator, fields, body, options); return result.toPromise(); } /** * Update all snapshot dependencies of the matching build configuration. * @param btLocator * @param fields * @param body */ public replaceAllSnapshotDependencies(btLocator: string, fields?: string, body?: SnapshotDependencies, options?: Configuration): Promise<SnapshotDependencies> { const result = this.api.replaceAllSnapshotDependencies(btLocator, fields, body, options); return result.toPromise(); } /** * Update all triggers of the matching build configuration. * @param btLocator * @param fields * @param body */ public replaceAllTriggers(btLocator: string, fields?: string, body?: Triggers, options?: Configuration): Promise<Triggers> { const result = this.api.replaceAllTriggers(btLocator, fields, body, options); return result.toPromise(); } /** * Update all VCS roots of the matching build configuration. * @param btLocator * @param fields * @param body */ public replaceAllVcsRoots(btLocator: string, fields?: string, body?: VcsRootEntries, options?: Configuration): Promise<VcsRootEntries> { const result = this.api.replaceAllVcsRoots(btLocator, fields, body, options); return result.toPromise(); } /** * Update an artifact dependency of the matching build configuration. * @param btLocator * @param artifactDepLocator * @param fields * @param body */ public replaceArtifactDependency(btLocator: string, artifactDepLocator: string, fields?: string, body?: ArtifactDependency, options?: Configuration): Promise<ArtifactDependency> { const result = this.api.replaceArtifactDependency(btLocator, artifactDepLocator, fields, body, options); return result.toPromise(); } /** * Update a build feature of the matching build configuration. * @param btLocator * @param featureId * @param fields * @param body */ public replaceBuildFeature(btLocator: string, featureId: string, fields?: string, body?: Feature, options?: Configuration): Promise<Feature> { const result = this.api.replaceBuildFeature(btLocator, featureId, fields, body, options); return result.toPromise(); } /** * Update a parameter of a build feature of the matching build configuration. * @param btLocator * @param featureId * @param fields * @param body */ public replaceBuildFeatureParameters(btLocator: string, featureId: string, fields?: string, body?: Properties, options?: Configuration): Promise<Properties> { const result = this.api.replaceBuildFeatureParameters(btLocator, featureId, fields, body, options); return result.toPromise(); } /** * Replace a build step of the matching build configuration. * @param btLocator * @param stepId * @param fields * @param body */ public replaceBuildStep(btLocator: string, stepId: string, fields?: string, body?: Step, options?: Configuration): Promise<Step> { const result = this.api.replaceBuildStep(btLocator, stepId, fields, body, options); return result.toPromise(); } /** * Update a snapshot dependency of the matching build configuration. * @param btLocator * @param snapshotDepLocator * @param fields * @param body */ public replaceSnapshotDependency(btLocator: string, snapshotDepLocator: string, fields?: string, body?: SnapshotDependency, options?: Configuration): Promise<SnapshotDependency> { const result = this.api.replaceSnapshotDependency(btLocator, snapshotDepLocator, fields, body, options); return result.toPromise(); } /** * Update a trigger of the matching build configuration. * @param btLocator * @param triggerLocator * @param fields * @param body */ public replaceTrigger(btLocator: string, triggerLocator: string, fields?: string, body?: Trigger, options?: Configuration): Promise<Trigger> { const result = this.api.replaceTrigger(btLocator, triggerLocator, fields, body, options); return result.toPromise(); } /** * Update a parameter of an agent requirement of the matching build configuration. * @param btLocator * @param agentRequirementLocator * @param fieldName * @param body */ public setAgentRequirementParameter(btLocator: string, agentRequirementLocator: string, fieldName: string, body?: string, options?: Configuration): Promise<string> { const result = this.api.setAgentRequirementParameter(btLocator, agentRequirementLocator, fieldName, body, options); return result.toPromise(); } /** * Update a parameter of an artifact dependency of the matching build configuration. * @param btLocator * @param artifactDepLocator * @param fieldName * @param body */ public setArtifactDependencyParameter(btLocator: string, artifactDepLocator: string, fieldName: string, body?: string, options?: Configuration): Promise<string> { const result = this.api.setArtifactDependencyParameter(btLocator, artifactDepLocator, fieldName, body, options); return result.toPromise(); } /** * Update a parameter of a build feature of the matching build configuration. * @param btLocator * @param featureId * @param name * @param body */ public setBuildFeatureParameter(btLocator: string, featureId: string, name: string, body?: string, options?: Configuration): Promise<string> { const result = this.api.setBuildFeatureParameter(btLocator, featureId, name, body, options); return result.toPromise(); } /** * Update a parameter of a build step of the matching build configuration. * @param btLocator * @param stepId * @param fieldName * @param body */ public setBuildStepParameter(btLocator: string, stepId: string, fieldName: string, body?: string, options?: Configuration): Promise<string> { const result = this.api.setBuildStepParameter(btLocator, stepId, fieldName, body, options); return result.toPromise(); } /** * Update a field of the matching build configuration. * @param btLocator * @param field * @param body */ public setBuildTypeField(btLocator: string, field: string, body?: string, options?: Configuration): Promise<string> { const result = this.api.setBuildTypeField(btLocator, field, body, options); return result.toPromise(); } /** * Update all templates of the matching build configuration. * @param btLocator * @param optimizeSettings * @param fields * @param body */ public setBuildTypeTemplates(btLocator: string, optimizeSettings?: boolean, fields?: string, body?: BuildTypes, options?: Configuration): Promise<BuildTypes> { const result = this.api.setBuildTypeTemplates(btLocator, optimizeSettings, fields, body, options); return result.toPromise(); } /** * Update a parameter of a trigger of the matching build configuration. * @param btLocator * @param triggerLocator * @param fieldName * @param body */ public setTriggerParameter(btLocator: string, triggerLocator: string, fieldName: string, body?: string, options?: Configuration): Promise<string> { const result = this.api.setTriggerParameter(btLocator, triggerLocator, fieldName, body, options); return result.toPromise(); } /** * Update build parameter. * @param name * @param btLocator * @param fields * @param body */ public updateBuildParameterOfBuildType(name: string, btLocator: string, fields?: string, body?: Property, options?: Configuration): Promise<Property> { const result = this.api.updateBuildParameterOfBuildType(name, btLocator, fields, body, options); return result.toPromise(); } /** * Update build parameter specification. * @param name * @param btLocator * @param body */ public updateBuildParameterSpecificationOfBuildType(name: string, btLocator: string, body?: string, options?: Configuration): Promise<string> { const result = this.api.updateBuildParameterSpecificationOfBuildType(name, btLocator, body, options); return result.toPromise(); } /** * Update type of build parameter. * @param name * @param btLocator * @param body */ public updateBuildParameterTypeOfBuildType(name: string, btLocator: string, body?: Type, options?: Configuration): Promise<Type> { const result = this.api.updateBuildParameterTypeOfBuildType(name, btLocator, body, options); return result.toPromise(); } /** * Update value of build parameter. * @param name * @param btLocator * @param body */ public updateBuildParameterValueOfBuildType(name: string, btLocator: string, body?: string, options?: Configuration): Promise<string> { const result = this.api.updateBuildParameterValueOfBuildType(name, btLocator, body, options); return result.toPromise(); } /** * Update build parameters. * @param btLocator * @param fields * @param body */ public updateBuildParametersOfBuildType(btLocator: string, fields?: string, body?: Properties, options?: Configuration): Promise<Properties> { const result = this.api.updateBuildParametersOfBuildType(btLocator, fields, body, options); return result.toPromise(); } /** * Update a VCS root of the matching build configuration. * @param btLocator * @param vcsRootLocator * @param fields * @param body */ public updateBuildTypeVcsRoot(btLocator: string, vcsRootLocator: string, fields?: string, body?: VcsRootEntry, options?: Configuration): Promise<VcsRootEntry> { const result = this.api.updateBuildTypeVcsRoot(btLocator, vcsRootLocator, fields, body, options); return result.toPromise(); } /** * Update checkout rules of a VCS root of the matching build configuration. * @param btLocator * @param vcsRootLocator * @param body */ public updateBuildTypeVcsRootCheckoutRules(btLocator: string, vcsRootLocator: string, body?: string, options?: Configuration): Promise<string> { const result = this.api.updateBuildTypeVcsRootCheckoutRules(btLocator, vcsRootLocator, body, options); return result.toPromise(); } } import { ObservableChangeApi } from './ObservableAPI.ts'; import { ChangeApiRequestFactory, ChangeApiResponseProcessor} from "../apis/ChangeApi.ts"; export class PromiseChangeApi { private api: ObservableChangeApi public constructor( configuration: Configuration, requestFactory?: ChangeApiRequestFactory, responseProcessor?: ChangeApiResponseProcessor ) { this.api = new ObservableChangeApi(configuration, requestFactory, responseProcessor); } /** * Get all changes. * @param locator * @param fields */ public getAllChanges(locator?: string, fields?: string, options?: Configuration): Promise<Changes> { const result = this.api.getAllChanges(locator, fields, options); return result.toPromise(); } /** * Get change matching the locator. * @param changeLocator * @param fields */ public getChange(changeLocator: string, fields?: string, options?: Configuration): Promise<Change> { const result = this.api.getChange(changeLocator, fields, options); return result.toPromise(); } /** * Get attributes of the matching change. * @param changeLocator * @param fields */ public getChangeAttributes(changeLocator: string, fields?: string, options?: Configuration): Promise<Entries> { const result = this.api.getChangeAttributes(changeLocator, fields, options); return result.toPromise(); } /** * Get duplicates of the matching change. * @param changeLocator * @param fields */ public getChangeDuplicates(changeLocator: string, fields?: string, options?: Configuration): Promise<Changes> { const result = this.api.getChangeDuplicates(changeLocator, fields, options); return result.toPromise(); } /** * Get a field of the matching change. * @param changeLocator * @param field */ public getChangeField(changeLocator: string, field: string, options?: Configuration): Promise<string> { const result = this.api.getChangeField(changeLocator, field, options); return result.toPromise(); } /** * Get first builds of the matching change. * @param changeLocator * @param fields */ public getChangeFirstBuilds(changeLocator: string, fields?: string, options?: Configuration): Promise<Builds> { const result = this.api.getChangeFirstBuilds(changeLocator, fields, options); return result.toPromise(); } /** * Get issues of the matching change. * @param changeLocator */ public getChangeIssue(changeLocator: string, options?: Configuration): Promise<Issues> { const result = this.api.getChangeIssue(changeLocator, options); return result.toPromise(); } /** * Get parent changes of the matching change. * @param changeLocator * @param fields */ public getChangeParentChanges(changeLocator: string, fields?: string, options?: Configuration): Promise<Changes> { const result = this.api.getChangeParentChanges(changeLocator, fields, options); return result.toPromise(); } /** * Get parent revisions of the matching change. * @param changeLocator */ public getChangeParentRevisions(changeLocator: string, options?: Configuration): Promise<Items> { const result = this.api.getChangeParentRevisions(changeLocator, options); return result.toPromise(); } /** * Get build configurations related to the matching change. * @param changeLocator * @param fields */ public getChangeRelatedBuildTypes(changeLocator: string, fields?: string, options?: Configuration): Promise<BuildTypes> { const result = this.api.getChangeRelatedBuildTypes(changeLocator, fields, options); return result.toPromise(); } /** * Get a VCS root instance of the matching change. * @param changeLocator * @param fields */ public getChangeVcsRoot(changeLocator: string, fields?: string, options?: Configuration): Promise<VcsRootInstance> { const result = this.api.getChangeVcsRoot(changeLocator, fields, options); return result.toPromise(); } } import { ObservableCloudInstanceApi } from './ObservableAPI.ts'; import { CloudInstanceApiRequestFactory, CloudInstanceApiResponseProcessor} from "../apis/CloudInstanceApi.ts"; export class PromiseCloudInstanceApi { private api: ObservableCloudInstanceApi public constructor( configuration: Configuration, requestFactory?: CloudInstanceApiRequestFactory, responseProcessor?: CloudInstanceApiResponseProcessor ) { this.api = new ObservableCloudInstanceApi(configuration, requestFactory, responseProcessor); } /** * Get all cloud images. * @param locator * @param fields */ public getAllCloudImages(locator?: string, fields?: string, options?: Configuration): Promise<CloudImages> { const result = this.api.getAllCloudImages(locator, fields, options); return result.toPromise(); } /** * Get all cloud instances. * @param locator * @param fields */ public getAllCloudInstances(locator?: string, fields?: string, options?: Configuration): Promise<CloudInstances> { const result = this.api.getAllCloudInstances(locator, fields, options); return result.toPromise(); } /** * Get all cloud profiles. * @param locator * @param fields */ public getAllCloudProfiles(locator?: string, fields?: string, options?: Configuration): Promise<CloudProfiles> { const result = this.api.getAllCloudProfiles(locator, fields, options); return result.toPromise(); } /** * Get cloud image matching the locator. * @param imageLocator * @param fields */ public getCloudImage(imageLocator: string, fields?: string, options?: Configuration): Promise<CloudImage> { const result = this.api.getCloudImage(imageLocator, fields, options); return result.toPromise(); } /** * Get cloud instance matching the locator. * @param instanceLocator * @param fields */ public getCloudInstance(instanceLocator: string, fields?: string, options?: Configuration): Promise<CloudInstance> { const result = this.api.getCloudInstance(instanceLocator, fields, options); return result.toPromise(); } /** * Get cloud profile matching the locator. * @param profileLocator * @param fields */ public getCloudProfile(profileLocator: string, fields?: string, options?: Configuration): Promise<CloudProfile> { const result = this.api.getCloudProfile(profileLocator, fields, options); return result.toPromise(); } /** * Start a new cloud instance. * @param fields * @param body */ public startInstance(fields?: string, body?: CloudInstance, options?: Configuration): Promise<void> { const result = this.api.startInstance(fields, body, options); return result.toPromise(); } /** * Stop cloud instance matching the locator. * @param instanceLocator */ public stopInstance(instanceLocator: string, options?: Configuration): Promise<void> { const result = this.api.stopInstance(instanceLocator, options); return result.toPromise(); } } import { ObservableGroupApi } from './ObservableAPI.ts'; import { GroupApiRequestFactory, GroupApiResponseProcessor} from "../apis/GroupApi.ts"; export class PromiseGroupApi { private api: ObservableGroupApi public constructor( configuration: Configuration, requestFactory?: GroupApiRequestFactory, responseProcessor?: GroupApiResponseProcessor ) { this.api = new ObservableGroupApi(configuration, requestFactory, responseProcessor); } /** * Add a new user group. * @param fields * @param body */ public addGroup(fields?: string, body?: Group, options?: Configuration): Promise<Group> { const result = this.api.addGroup(fields, body, options); return result.toPromise(); } /** * Add a role with the specific scope to the matching user group. * @param groupLocator * @param roleId * @param scope */ public addRoleAtScopeToGroup(groupLocator: string, roleId: string, scope: string, options?: Configuration): Promise<Role> { const result = this.api.addRoleAtScopeToGroup(groupLocator, roleId, scope, options); return result.toPromise(); } /** * Add a role to the matching user group. * @param groupLocator * @param body */ public addRoleToGroup(groupLocator: string, body?: Role, options?: Configuration): Promise<Role> { const result = this.api.addRoleToGroup(groupLocator, body, options); return result.toPromise(); } /** * Delete user group matching the locator. * @param groupLocator */ public deleteGroup(groupLocator: string, options?: Configuration): Promise<void> { const result = this.api.deleteGroup(groupLocator, options); return result.toPromise(); } /** * Get all user groups. * @param fields */ public getAllGroups(fields?: string, options?: Configuration): Promise<Groups> { const result = this.api.getAllGroups(fields, options); return result.toPromise(); } /** * Get parent groups of the matching user group. * @param groupLocator * @param fields */ public getGroupParentGroups(groupLocator: string, fields?: string, options?: Configuration): Promise<Groups> { const result = this.api.getGroupParentGroups(groupLocator, fields, options); return result.toPromise(); } /** * Get properties of the matching user group. * @param groupLocator * @param fields */ public getGroupProperties(groupLocator: string, fields?: string, options?: Configuration): Promise<Properties> { const result = this.api.getGroupProperties(groupLocator, fields, options); return result.toPromise(); } /** * Get a property of the matching user group. * @param groupLocator * @param name */ public getGroupProperty(groupLocator: string, name: string, options?: Configuration): Promise<string> { const result = this.api.getGroupProperty(groupLocator, name, options); return result.toPromise(); } /** * Get a role with the specific scope of the matching user group. * @param groupLocator * @param roleId * @param scope */ public getGroupRoleAtScope(groupLocator: string, roleId: string, scope: string, options?: Configuration): Promise<Role> { const result = this.api.getGroupRoleAtScope(groupLocator, roleId, scope, options); return result.toPromise(); } /** * Get all roles of the matching user group. * @param groupLocator */ public getGroupRoles(groupLocator: string, options?: Configuration): Promise<Roles> { const result = this.api.getGroupRoles(groupLocator, options); return result.toPromise(); } /** * Get user group matching the locator. * @param groupLocator * @param fields */ public getUserGroupOfGroup(groupLocator: string, fields?: string, options?: Configuration): Promise<Group> { const result = this.api.getUserGroupOfGroup(groupLocator, fields, options); return result.toPromise(); } /** * Remove a property of the matching user group. * @param groupLocator * @param name */ public removeGroupProperty(groupLocator: string, name: string, options?: Configuration): Promise<void> { const result = this.api.removeGroupProperty(groupLocator, name, options); return result.toPromise(); } /** * Remove a role with the specific scope from the matching user group. * @param groupLocator * @param roleId * @param scope */ public removeRoleAtScopeFromGroup(groupLocator: string, roleId: string, scope: string, options?: Configuration): Promise<void> { const result = this.api.removeRoleAtScopeFromGroup(groupLocator, roleId, scope, options); return result.toPromise(); } /** * Update parent groups of the matching user group. * @param groupLocator * @param fields * @param body */ public setGroupParentGroups(groupLocator: string, fields?: string, body?: Groups, options?: Configuration): Promise<Groups> { const result = this.api.setGroupParentGroups(groupLocator, fields, body, options); return result.toPromise(); } /** * Update a property of the matching user group. * @param groupLocator * @param name * @param body */ public setGroupProperty(groupLocator: string, name: string, body?: string, options?: Configuration): Promise<string> { const result = this.api.setGroupProperty(groupLocator, name, body, options); return result.toPromise(); } /** * Update roles of the matching user group. * @param groupLocator * @param body */ public setGroupRoles(groupLocator: string, body?: Roles, options?: Configuration): Promise<Roles> { const result = this.api.setGroupRoles(groupLocator, body, options); return result.toPromise(); } } import { ObservableInvestigationApi } from './ObservableAPI.ts'; import { InvestigationApiRequestFactory, InvestigationApiResponseProcessor} from "../apis/InvestigationApi.ts"; export class PromiseInvestigationApi { private api: ObservableInvestigationApi public constructor( configuration: Configuration, requestFactory?: InvestigationApiRequestFactory, responseProcessor?: InvestigationApiResponseProcessor ) { this.api = new ObservableInvestigationApi(configuration, requestFactory, responseProcessor); } /** * Create a new investigation. * @param fields * @param body */ public addInvestigation(fields?: string, body?: Investigation, options?: Configuration): Promise<Investigation> { const result = this.api.addInvestigation(fields, body, options); return result.toPromise(); } /** * Create multiple new investigations. * @param fields * @param body */ public addMultipleInvestigations(fields?: string, body?: Investigations, options?: Configuration): Promise<Investigations> { const result = this.api.addMultipleInvestigations(fields, body, options); return result.toPromise(); } /** * Delete investigation matching the locator. * @param investigationLocator */ public deleteInvestigation(investigationLocator: string, options?: Configuration): Promise<void> { const result = this.api.deleteInvestigation(investigationLocator, options); return result.toPromise(); } /** * Get all investigations. * @param locator * @param fields */ public getAllInvestigations(locator?: string, fields?: string, options?: Configuration): Promise<Investigations> { const result = this.api.getAllInvestigations(locator, fields, options); return result.toPromise(); } /** * Get investigation matching the locator. * @param investigationLocator * @param fields */ public getInvestigation(investigationLocator: string, fields?: string, options?: Configuration): Promise<Investigation> { const result = this.api.getInvestigation(investigationLocator, fields, options); return result.toPromise(); } /** * Update investigation matching the locator. * @param investigationLocator * @param fields * @param body */ public replaceInvestigation(investigationLocator: string, fields?: string, body?: Investigation, options?: Configuration): Promise<Investigation> { const result = this.api.replaceInvestigation(investigationLocator, fields, body, options); return result.toPromise(); } } import { ObservableMuteApi } from './ObservableAPI.ts'; import { MuteApiRequestFactory, MuteApiResponseProcessor} from "../apis/MuteApi.ts"; export class PromiseMuteApi { private api: ObservableMuteApi public constructor( configuration: Configuration, requestFactory?: MuteApiRequestFactory, responseProcessor?: MuteApiResponseProcessor ) { this.api = new ObservableMuteApi(configuration, requestFactory, responseProcessor); } /** * Get all muted tests. * @param locator * @param fields */ public getAllMutedTests(locator?: string, fields?: string, options?: Configuration): Promise<Mutes> { const result = this.api.getAllMutedTests(locator, fields, options); return result.toPromise(); } /** * Get a muted test. * @param muteLocator * @param fields */ public getMutedTest(muteLocator: string, fields?: string, options?: Configuration): Promise<Mute> { const result = this.api.getMutedTest(muteLocator, fields, options); return result.toPromise(); } /** * Mute multiple tests. * @param fields * @param body */ public muteMultipleTests(fields?: string, body?: Mutes, options?: Configuration): Promise<Mutes> { const result = this.api.muteMultipleTests(fields, body, options); return result.toPromise(); } /** * Mute a test. * @param fields * @param body */ public muteTest(fields?: string, body?: Mute, options?: Configuration): Promise<Mute> { const result = this.api.muteTest(fields, body, options); return result.toPromise(); } /** * Unmute the matching test. * @param muteLocator * @param body */ public unmuteTest(muteLocator: string, body?: string, options?: Configuration): Promise<void> { const result = this.api.unmuteTest(muteLocator, body, options); return result.toPromise(); } } import { ObservableProblemApi } from './ObservableAPI.ts'; import { ProblemApiRequestFactory, ProblemApiResponseProcessor} from "../apis/ProblemApi.ts"; export class PromiseProblemApi { private api: ObservableProblemApi public constructor( configuration: Configuration, requestFactory?: ProblemApiRequestFactory, responseProcessor?: ProblemApiResponseProcessor ) { this.api = new ObservableProblemApi(configuration, requestFactory, responseProcessor); } /** * Get all build problems. * @param locator * @param fields */ public getAllBuildProblems(locator?: string, fields?: string, options?: Configuration): Promise<Problems> { const result = this.api.getAllBuildProblems(locator, fields, options); return result.toPromise(); } /** * Get a matching build problem. * @param problemLocator * @param fields */ public getBuildProblem(problemLocator: string, fields?: string, options?: Configuration): Promise<Problem> { const result = this.api.getBuildProblem(problemLocator, fields, options); return result.toPromise(); } } import { ObservableProblemOccurrenceApi } from './ObservableAPI.ts'; import { ProblemOccurrenceApiRequestFactory, ProblemOccurrenceApiResponseProcessor} from "../apis/ProblemOccurrenceApi.ts"; export class PromiseProblemOccurrenceApi { private api: ObservableProblemOccurrenceApi public constructor( configuration: Configuration, requestFactory?: ProblemOccurrenceApiRequestFactory, responseProcessor?: ProblemOccurrenceApiResponseProcessor ) { this.api = new ObservableProblemOccurrenceApi(configuration, requestFactory, responseProcessor); } /** * Get all build problem occurrences. * @param locator * @param fields */ public getAllBuildProblemOccurrences(locator?: string, fields?: string, options?: Configuration): Promise<ProblemOccurrences> { const result = this.api.getAllBuildProblemOccurrences(locator, fields, options); return result.toPromise(); } /** * Get a matching build problem occurrence. * @param problemLocator * @param fields */ public getBuildProblemOccurrence(problemLocator: string, fields?: string, options?: Configuration): Promise<ProblemOccurrence> { const result = this.api.getBuildProblemOccurrence(problemLocator, fields, options); return result.toPromise(); } } import { ObservableProjectApi } from './ObservableAPI.ts'; import { ProjectApiRequestFactory, ProjectApiResponseProcessor} from "../apis/ProjectApi.ts"; export class PromiseProjectApi { private api: ObservableProjectApi public constructor( configuration: Configuration, requestFactory?: ProjectApiRequestFactory, responseProcessor?: ProjectApiResponseProcessor ) { this.api = new ObservableProjectApi(configuration, requestFactory, responseProcessor); } /** * Assign the matching project to the agent pool. * @param projectLocator * @param body */ public addAgentPoolsProject(projectLocator: string, body?: AgentPool, options?: Configuration): Promise<AgentPool> { const result = this.api.addAgentPoolsProject(projectLocator, body, options); return result.toPromise(); } /** * Add a build configuration to the matching project. * @param projectLocator * @param fields * @param body */ public addBuildType(projectLocator: string, fields?: string, body?: NewBuildTypeDescription, options?: Configuration): Promise<BuildType> { const result = this.api.addBuildType(projectLocator, fields, body, options); return result.toPromise(); } /** * Add a feature. * @param projectLocator * @param fields * @param body */ public addFeature(projectLocator: string, fields?: string, body?: ProjectFeature, options?: Configuration): Promise<any> { const result = this.api.addFeature(projectLocator, fields, body, options); return result.toPromise(); } /** * Create a new project. * @param body */ public addProject(body?: NewProjectDescription, options?: Configuration): Promise<Project> { const result = this.api.addProject(body, options); return result.toPromise(); } /** * Create a new secure token for the matching project. * @param projectLocator * @param body */ public addSecureToken(projectLocator: string, body?: string, options?: Configuration): Promise<string> { const result = this.api.addSecureToken(projectLocator, body, options); return result.toPromise(); } /** * Add a build configuration template to the matching project. * @param projectLocator * @param fields * @param body */ public addTemplate(projectLocator: string, fields?: string, body?: NewBuildTypeDescription, options?: Configuration): Promise<BuildType> { const result = this.api.addTemplate(projectLocator, fields, body, options); return result.toPromise(); } /** * Create a build parameter. * @param projectLocator * @param fields * @param body */ public createBuildParameter(projectLocator: string, fields?: string, body?: Property, options?: Configuration): Promise<Property> { const result = this.api.createBuildParameter(projectLocator, fields, body, options); return result.toPromise(); } /** * Delete build parameter. * @param name * @param projectLocator */ public deleteBuildParameter(name: string, projectLocator: string, options?: Configuration): Promise<void> { const result = this.api.deleteBuildParameter(name, projectLocator, options); return result.toPromise(); } /** * Delete all build parameters. * @param projectLocator */ public deleteBuildParameters(projectLocator: string, options?: Configuration): Promise<void> { const result = this.api.deleteBuildParameters(projectLocator, options); return result.toPromise(); } /** * Delete a matching feature. * @param featureLocator * @param projectLocator */ public deleteFeature(featureLocator: string, projectLocator: string, options?: Configuration): Promise<void> { const result = this.api.deleteFeature(featureLocator, projectLocator, options); return result.toPromise(); } /** * Delete project matching the locator. * @param projectLocator */ public deleteProject(projectLocator: string, options?: Configuration): Promise<void> { const result = this.api.deleteProject(projectLocator, options); return result.toPromise(); } /** * Get agent pools appointed to the matching project. * @param projectLocator * @param fields */ public getAgentPoolsProject(projectLocator: string, fields?: string, options?: Configuration): Promise<AgentPools> { const result = this.api.getAgentPoolsProject(projectLocator, fields, options); return result.toPromise(); } /** * Get all branches of the matching project. * @param projectLocator * @param locator * @param fields */ public getAllBranches(projectLocator: string, locator?: string, fields?: string, options?: Configuration): Promise<Branches> { const result = this.api.getAllBranches(projectLocator, locator, fields, options); return result.toPromise(); } /** * Get all projects. * @param locator * @param fields */ public getAllProjects(locator?: string, fields?: string, options?: Configuration): Promise<Projects> { const result = this.api.getAllProjects(locator, fields, options); return result.toPromise(); } /** * Get all subprojects ordered of the matching project. * @param projectLocator * @param field */ public getAllSubprojectsOrdered(projectLocator: string, field?: string, options?: Configuration): Promise<Projects> { const result = this.api.getAllSubprojectsOrdered(projectLocator, field, options); return result.toPromise(); } /** * Get build parameter. * @param name * @param projectLocator * @param fields */ public getBuildParameter(name: string, projectLocator: string, fields?: string, options?: Configuration): Promise<Property> { const result = this.api.getBuildParameter(name, projectLocator, fields, options); return result.toPromise(); } /** * Get build parameter specification. * @param name * @param projectLocator */ public getBuildParameterSpecification(name: string, projectLocator: string, options?: Configuration): Promise<string> { const result = this.api.getBuildParameterSpecification(name, projectLocator, options); return result.toPromise(); } /** * Get type of build parameter. * @param name * @param projectLocator */ public getBuildParameterType(name: string, projectLocator: string, options?: Configuration): Promise<Type> { const result = this.api.getBuildParameterType(name, projectLocator, options); return result.toPromise(); } /** * Get value of build parameter. * @param name * @param projectLocator */ public getBuildParameterValue(name: string, projectLocator: string, options?: Configuration): Promise<string> { const result = this.api.getBuildParameterValue(name, projectLocator, options); return result.toPromise(); } /** * Get build parameters. * @param projectLocator * @param locator * @param fields */ public getBuildParameters(projectLocator: string, locator?: string, fields?: string, options?: Configuration): Promise<Properties> { const result = this.api.getBuildParameters(projectLocator, locator, fields, options); return result.toPromise(); } /** * Get the default template of the matching project. * @param projectLocator * @param fields */ public getDefaultTemplate(projectLocator: string, fields?: string, options?: Configuration): Promise<BuildType> { const result = this.api.getDefaultTemplate(projectLocator, fields, options); return result.toPromise(); } /** * Get a matching feature. * @param featureLocator * @param projectLocator * @param fields */ public getFeature(featureLocator: string, projectLocator: string, fields?: string, options?: Configuration): Promise<any> { const result = this.api.getFeature(featureLocator, projectLocator, fields, options); return result.toPromise(); } /** * Get all features. * @param projectLocator * @param locator * @param fields */ public getFeatures(projectLocator: string, locator?: string, fields?: string, options?: Configuration): Promise<any> { const result = this.api.getFeatures(projectLocator, locator, fields, options); return result.toPromise(); } /** * Get project matching the locator. * @param projectLocator * @param fields */ public getProject(projectLocator: string, fields?: string, options?: Configuration): Promise<Project> { const result = this.api.getProject(projectLocator, fields, options); return result.toPromise(); } /** * Get a field of the matching project. * @param projectLocator * @param field */ public getProjectField(projectLocator: string, field: string, options?: Configuration): Promise<string> { const result = this.api.getProjectField(projectLocator, field, options); return result.toPromise(); } /** * Get the parent project of the matching project. * @param projectLocator * @param fields */ public getProjectParentProject(projectLocator: string, fields?: string, options?: Configuration): Promise<Project> { const result = this.api.getProjectParentProject(projectLocator, fields, options); return result.toPromise(); } /** * Get the settings file of the matching build configuration. * @param projectLocator */ public getProjectSettingsFile(projectLocator: string, options?: Configuration): Promise<string> { const result = this.api.getProjectSettingsFile(projectLocator, options); return result.toPromise(); } /** * Get all templates of the matching project. * @param projectLocator * @param fields */ public getProjectTemplates(projectLocator: string, fields?: string, options?: Configuration): Promise<BuildTypes> { const result = this.api.getProjectTemplates(projectLocator, fields, options); return result.toPromise(); } /** * Get a secure token of the matching project. * @param projectLocator * @param token */ public getSecureValue(projectLocator: string, token: string, options?: Configuration): Promise<string> { const result = this.api.getSecureValue(projectLocator, token, options); return result.toPromise(); } /** * Remove the default template from the matching project. * @param projectLocator * @param fields */ public removeDefaultTemplate(projectLocator: string, fields?: string, options?: Configuration): Promise<void> { const result = this.api.removeDefaultTemplate(projectLocator, fields, options); return result.toPromise(); } /** * Unassign a project from the matching agent pool. * @param projectLocator * @param agentPoolLocator */ public removeProjectFromAgentPool(projectLocator: string, agentPoolLocator: string, options?: Configuration): Promise<void> { const result = this.api.removeProjectFromAgentPool(projectLocator, agentPoolLocator, options); return result.toPromise(); } /** * Update agent pools apppointed to the matching project. * @param projectLocator * @param fields * @param body */ public setAgentPoolsProject(projectLocator: string, fields?: string, body?: AgentPools, options?: Configuration): Promise<AgentPools> { const result = this.api.setAgentPoolsProject(projectLocator, fields, body, options); return result.toPromise(); } /** * Update all build configurations order of the matching project. * @param projectLocator * @param field * @param body */ public setBuildTypesOrder(projectLocator: string, field?: string, body?: BuildTypes, options?: Configuration): Promise<BuildTypes> { const result = this.api.setBuildTypesOrder(projectLocator, field, body, options); return result.toPromise(); } /** * Update the default template of the matching project. * @param projectLocator * @param fields * @param body */ public setDefaultTemplate(projectLocator: string, fields?: string, body?: BuildType, options?: Configuration): Promise<BuildType> { const result = this.api.setDefaultTemplate(projectLocator, fields, body, options); return result.toPromise(); } /** * Update the parent project of the matching project. * @param projectLocator * @param fields * @param body */ public setParentProject(projectLocator: string, fields?: string, body?: Project, options?: Configuration): Promise<Project> { const result = this.api.setParentProject(projectLocator, fields, body, options); return result.toPromise(); } /** * Update a field of the matching project. * @param projectLocator * @param field * @param body */ public setProjectField(projectLocator: string, field: string, body?: string, options?: Configuration): Promise<string> { const result = this.api.setProjectField(projectLocator, field, body, options); return result.toPromise(); } /** * Update all subprojects order of the matching project. * @param projectLocator * @param field * @param body */ public setSubprojectsOrder(projectLocator: string, field?: string, body?: Projects, options?: Configuration): Promise<Projects> { const result = this.api.setSubprojectsOrder(projectLocator, field, body, options); return result.toPromise(); } /** * Update build parameter. * @param name * @param projectLocator * @param fields * @param body */ public updateBuildParameter(name: string, projectLocator: string, fields?: string, body?: Property, options?: Configuration): Promise<Property> { const result = this.api.updateBuildParameter(name, projectLocator, fields, body, options); return result.toPromise(); } /** * Update build parameter specification. * @param name * @param projectLocator * @param body */ public updateBuildParameterSpecification(name: string, projectLocator: string, body?: string, options?: Configuration): Promise<string> { const result = this.api.updateBuildParameterSpecification(name, projectLocator, body, options); return result.toPromise(); } /** * Update type of build parameter. * @param name * @param projectLocator * @param body */ public updateBuildParameterType(name: string, projectLocator: string, body?: Type, options?: Configuration): Promise<Type> { const result = this.api.updateBuildParameterType(name, projectLocator, body, options); return result.toPromise(); } /** * Update value of build parameter. * @param name * @param projectLocator * @param body */ public updateBuildParameterValue(name: string, projectLocator: string, body?: string, options?: Configuration): Promise<string> { const result = this.api.updateBuildParameterValue(name, projectLocator, body, options); return result.toPromise(); } /** * Update build parameters. * @param projectLocator * @param fields * @param body */ public updateBuildParameters(projectLocator: string, fields?: string, body?: Properties, options?: Configuration): Promise<Properties> { const result = this.api.updateBuildParameters(projectLocator, fields, body, options); return result.toPromise(); } /** * Update a matching feature. * @param featureLocator * @param projectLocator * @param fields * @param body */ public updateFeature(featureLocator: string, projectLocator: string, fields?: string, body?: ProjectFeature, options?: Configuration): Promise<any> { const result = this.api.updateFeature(featureLocator, projectLocator, fields, body, options); return result.toPromise(); } /** * Update all features. * @param projectLocator * @param fields * @param body */ public updateFeatures(projectLocator: string, fields?: string, body?: ProjectFeatures, options?: Configuration): Promise<any> { const result = this.api.updateFeatures(projectLocator, fields, body, options); return result.toPromise(); } } import { ObservableRootApi } from './ObservableAPI.ts'; import { RootApiRequestFactory, RootApiResponseProcessor} from "../apis/RootApi.ts"; export class PromiseRootApi { private api: ObservableRootApi public constructor( configuration: Configuration, requestFactory?: RootApiRequestFactory, responseProcessor?: RootApiResponseProcessor ) { this.api = new ObservableRootApi(configuration, requestFactory, responseProcessor); } /** * Get the API version. */ public getApiVersion(options?: Configuration): Promise<string> { const result = this.api.getApiVersion(options); return result.toPromise(); } /** * Get the plugin info. * @param fields */ public getPluginInfo(fields?: string, options?: Configuration): Promise<Plugin> { const result = this.api.getPluginInfo(fields, options); return result.toPromise(); } /** * Get root endpoints. */ public getRootEndpointsOfRoot(options?: Configuration): Promise<string> { const result = this.api.getRootEndpointsOfRoot(options); return result.toPromise(); } /** * Get the TeamCity server version. */ public getVersion(options?: Configuration): Promise<string> { const result = this.api.getVersion(options); return result.toPromise(); } } import { ObservableServerApi } from './ObservableAPI.ts'; import { ServerApiRequestFactory, ServerApiResponseProcessor} from "../apis/ServerApi.ts"; export class PromiseServerApi { private api: ObservableServerApi public constructor( configuration: Configuration, requestFactory?: ServerApiRequestFactory, responseProcessor?: ServerApiResponseProcessor ) { this.api = new ObservableServerApi(configuration, requestFactory, responseProcessor); } /** * Add license keys. * @param fields * @param body */ public addLicenseKeys(fields?: string, body?: string, options?: Configuration): Promise<LicenseKeys> { const result = this.api.addLicenseKeys(fields, body, options); return result.toPromise(); } /** * Delete a license key. * @param licenseKey */ public deleteLicenseKey(licenseKey: string, options?: Configuration): Promise<void> { const result = this.api.deleteLicenseKey(licenseKey, options); return result.toPromise(); } /** * Download specific file. * @param path * @param areaId */ public downloadFileOfServer(path: string, areaId: string, options?: Configuration): Promise<void> { const result = this.api.downloadFileOfServer(path, areaId, options); return result.toPromise(); } /** * Get metrics. * @param fields */ public getAllMetrics(fields?: string, options?: Configuration): Promise<Metrics> { const result = this.api.getAllMetrics(fields, options); return result.toPromise(); } /** * Get all plugins. * @param fields */ public getAllPlugins(fields?: string, options?: Configuration): Promise<Plugins> { const result = this.api.getAllPlugins(fields, options); return result.toPromise(); } /** * Get the latest backup status. */ public getBackupStatus(options?: Configuration): Promise<string> { const result = this.api.getBackupStatus(options); return result.toPromise(); } /** * Get metadata of specific file. * @param path * @param areaId * @param fields */ public getFileMetadataOfServer(path: string, areaId: string, fields?: string, options?: Configuration): Promise<any> { const result = this.api.getFileMetadataOfServer(path, areaId, fields, options); return result.toPromise(); } /** * List files under this path. * @param path * @param areaId * @param basePath * @param locator * @param fields */ public getFilesListForSubpathOfServer(path: string, areaId: string, basePath?: string, locator?: string, fields?: string, options?: Configuration): Promise<Files> { const result = this.api.getFilesListForSubpathOfServer(path, areaId, basePath, locator, fields, options); return result.toPromise(); } /** * List all files. * @param areaId * @param basePath * @param locator * @param fields */ public getFilesListOfServer(areaId: string, basePath?: string, locator?: string, fields?: string, options?: Configuration): Promise<Files> { const result = this.api.getFilesListOfServer(areaId, basePath, locator, fields, options); return result.toPromise(); } /** * Get a license key. * @param licenseKey * @param fields */ public getLicenseKey(licenseKey: string, fields?: string, options?: Configuration): Promise<LicenseKey> { const result = this.api.getLicenseKey(licenseKey, fields, options); return result.toPromise(); } /** * Get all license keys. * @param fields */ public getLicenseKeys(fields?: string, options?: Configuration): Promise<LicenseKeys> { const result = this.api.getLicenseKeys(fields, options); return result.toPromise(); } /** * Get the licensing data. * @param fields */ public getLicensingData(fields?: string, options?: Configuration): Promise<LicensingData> { const result = this.api.getLicensingData(fields, options); return result.toPromise(); } /** * Get a field of the server info. * @param field */ public getServerField(field: string, options?: Configuration): Promise<string> { const result = this.api.getServerField(field, options); return result.toPromise(); } /** * Get the server info. * @param fields */ public getServerInfo(fields?: string, options?: Configuration): Promise<Server> { const result = this.api.getServerInfo(fields, options); return result.toPromise(); } /** * Get specific file zipped. * @param path * @param areaId * @param basePath * @param locator * @param name */ public getZippedFileOfServer(path: string, areaId: string, basePath?: string, locator?: string, name?: string, options?: Configuration): Promise<void> { const result = this.api.getZippedFileOfServer(path, areaId, basePath, locator, name, options); return result.toPromise(); } /** * Start a new backup. * @param fileName * @param addTimestamp * @param includeConfigs * @param includeDatabase * @param includeBuildLogs * @param includePersonalChanges * @param includeRunningBuilds * @param includeSupplimentaryData */ public startBackup(fileName?: string, addTimestamp?: boolean, includeConfigs?: boolean, includeDatabase?: boolean, includeBuildLogs?: boolean, includePersonalChanges?: boolean, includeRunningBuilds?: boolean, includeSupplimentaryData?: boolean, options?: Configuration): Promise<string> { const result = this.api.startBackup(fileName, addTimestamp, includeConfigs, includeDatabase, includeBuildLogs, includePersonalChanges, includeRunningBuilds, includeSupplimentaryData, options); return result.toPromise(); } } import { ObservableTestApi } from './ObservableAPI.ts'; import { TestApiRequestFactory, TestApiResponseProcessor} from "../apis/TestApi.ts"; export class PromiseTestApi { private api: ObservableTestApi public constructor( configuration: Configuration, requestFactory?: TestApiRequestFactory, responseProcessor?: TestApiResponseProcessor ) { this.api = new ObservableTestApi(configuration, requestFactory, responseProcessor); } /** * Get a matching test. * @param testLocator * @param fields */ public getTest(testLocator: string, fields?: string, options?: Configuration): Promise<Test> { const result = this.api.getTest(testLocator, fields, options); return result.toPromise(); } /** * Get all tests. * @param locator * @param fields */ public getTests(locator?: string, fields?: string, options?: Configuration): Promise<Tests> { const result = this.api.getTests(locator, fields, options); return result.toPromise(); } } import { ObservableTestOccurrenceApi } from './ObservableAPI.ts'; import { TestOccurrenceApiRequestFactory, TestOccurrenceApiResponseProcessor} from "../apis/TestOccurrenceApi.ts"; export class PromiseTestOccurrenceApi { private api: ObservableTestOccurrenceApi public constructor( configuration: Configuration, requestFactory?: TestOccurrenceApiRequestFactory, responseProcessor?: TestOccurrenceApiResponseProcessor ) { this.api = new ObservableTestOccurrenceApi(configuration, requestFactory, responseProcessor); } /** * Get all test occurrences. * @param locator * @param fields */ public getAllTestOccurrences(locator?: string, fields?: string, options?: Configuration): Promise<TestOccurrences> { const result = this.api.getAllTestOccurrences(locator, fields, options); return result.toPromise(); } /** * Get a matching test occurrence. * @param testLocator * @param fields */ public getTestOccurrence(testLocator: string, fields?: string, options?: Configuration): Promise<TestOccurrence> { const result = this.api.getTestOccurrence(testLocator, fields, options); return result.toPromise(); } } import { ObservableUserApi } from './ObservableAPI.ts'; import { UserApiRequestFactory, UserApiResponseProcessor} from "../apis/UserApi.ts"; export class PromiseUserApi { private api: ObservableUserApi public constructor( configuration: Configuration, requestFactory?: UserApiRequestFactory, responseProcessor?: UserApiResponseProcessor ) { this.api = new ObservableUserApi(configuration, requestFactory, responseProcessor); } /** * Add a role to the matching user. * @param userLocator * @param body */ public addRoleToUser(userLocator: string, body?: Role, options?: Configuration): Promise<Role> { const result = this.api.addRoleToUser(userLocator, body, options); return result.toPromise(); } /** * Add a role with the specific scope to the matching user. * @param userLocator * @param roleId * @param scope */ public addRoleToUserAtScope(userLocator: string, roleId: string, scope: string, options?: Configuration): Promise<Role> { const result = this.api.addRoleToUserAtScope(userLocator, roleId, scope, options); return result.toPromise(); } /** * Create a new user. * @param fields * @param body */ public addUser(fields?: string, body?: User, options?: Configuration): Promise<User> { const result = this.api.addUser(fields, body, options); return result.toPromise(); } /** * Create a new authentication token for the matching user. * @param userLocator * @param fields * @param body */ public addUserToken(userLocator: string, fields?: string, body?: Token, options?: Configuration): Promise<Token> { const result = this.api.addUserToken(userLocator, fields, body, options); return result.toPromise(); } /** * Delete user matching the locator. * @param userLocator */ public deleteUser(userLocator: string, options?: Configuration): Promise<void> { const result = this.api.deleteUser(userLocator, options); return result.toPromise(); } /** * Remove a property of the matching user. * @param userLocator * @param field */ public deleteUserField(userLocator: string, field: string, options?: Configuration): Promise<void> { const result = this.api.deleteUserField(userLocator, field, options); return result.toPromise(); } /** * Remove an authentication token from the matching user. * @param userLocator * @param name */ public deleteUserToken(userLocator: string, name: string, options?: Configuration): Promise<void> { const result = this.api.deleteUserToken(userLocator, name, options); return result.toPromise(); } /** * Get a field of the matching user. * @param userLocator * @param field */ public gerUserField(userLocator: string, field: string, options?: Configuration): Promise<string> { const result = this.api.gerUserField(userLocator, field, options); return result.toPromise(); } /** * Get all groups of the matching user. * @param userLocator * @param fields */ public getAllUserGroups(userLocator: string, fields?: string, options?: Configuration): Promise<Groups> { const result = this.api.getAllUserGroups(userLocator, fields, options); return result.toPromise(); } /** * Get all user roles of the matching user. * @param userLocator */ public getAllUserRoles(userLocator: string, options?: Configuration): Promise<Roles> { const result = this.api.getAllUserRoles(userLocator, options); return result.toPromise(); } /** * Get all users. * @param locator * @param fields */ public getAllUsers(locator?: string, fields?: string, options?: Configuration): Promise<Users> { const result = this.api.getAllUsers(locator, fields, options); return result.toPromise(); } /** * Get user matching the locator. * @param userLocator * @param fields */ public getUser(userLocator: string, fields?: string, options?: Configuration): Promise<User> { const result = this.api.getUser(userLocator, fields, options); return result.toPromise(); } /** * Get a user group of the matching user. * @param userLocator * @param groupLocator * @param fields */ public getUserGroup(userLocator: string, groupLocator: string, fields?: string, options?: Configuration): Promise<Group> { const result = this.api.getUserGroup(userLocator, groupLocator, fields, options); return result.toPromise(); } /** * Get all permissions effective for the matching user. * @param userLocator * @param locator * @param fields */ public getUserPermissions(userLocator: string, locator?: string, fields?: string, options?: Configuration): Promise<PermissionAssignments> { const result = this.api.getUserPermissions(userLocator, locator, fields, options); return result.toPromise(); } /** * Get all properties of the matching user. * @param userLocator * @param fields */ public getUserProperties(userLocator: string, fields?: string, options?: Configuration): Promise<Properties> { const result = this.api.getUserProperties(userLocator, fields, options); return result.toPromise(); } /** * Get a property of the matching user. * @param userLocator * @param name */ public getUserProperty(userLocator: string, name: string, options?: Configuration): Promise<string> { const result = this.api.getUserProperty(userLocator, name, options); return result.toPromise(); } /** * Get a user role with the specific scope from the matching user. * @param userLocator * @param roleId * @param scope */ public getUserRolesAtScope(userLocator: string, roleId: string, scope: string, options?: Configuration): Promise<Role> { const result = this.api.getUserRolesAtScope(userLocator, roleId, scope, options); return result.toPromise(); } /** * Get all authentication tokens of the matching user. * @param userLocator * @param fields */ public getUserTokens(userLocator: string, fields?: string, options?: Configuration): Promise<Tokens> { const result = this.api.getUserTokens(userLocator, fields, options); return result.toPromise(); } /** * Remove the matching user from the specific group. * @param userLocator * @param groupLocator * @param fields */ public removeUserFromGroup(userLocator: string, groupLocator: string, fields?: string, options?: Configuration): Promise<void> { const result = this.api.removeUserFromGroup(userLocator, groupLocator, fields, options); return result.toPromise(); } /** * Remove a property of the matching user. * @param userLocator * @param name */ public removeUserProperty(userLocator: string, name: string, options?: Configuration): Promise<void> { const result = this.api.removeUserProperty(userLocator, name, options); return result.toPromise(); } /** * Remove the RememberMe data of the matching user. * @param userLocator */ public removeUserRememberMe(userLocator: string, options?: Configuration): Promise<void> { const result = this.api.removeUserRememberMe(userLocator, options); return result.toPromise(); } /** * Remove a role with the specific scope from the matching user. * @param userLocator * @param roleId * @param scope */ public removeUserRoleAtScope(userLocator: string, roleId: string, scope: string, options?: Configuration): Promise<void> { const result = this.api.removeUserRoleAtScope(userLocator, roleId, scope, options); return result.toPromise(); } /** * Update user matching the locator. * @param userLocator * @param fields * @param body */ public replaceUser(userLocator: string, fields?: string, body?: User, options?: Configuration): Promise<User> { const result = this.api.replaceUser(userLocator, fields, body, options); return result.toPromise(); } /** * Update a field of the matching user. * @param userLocator * @param field * @param body */ public setUserField(userLocator: string, field: string, body?: string, options?: Configuration): Promise<string> { const result = this.api.setUserField(userLocator, field, body, options); return result.toPromise(); } /** * Update groups of the matching user. * @param userLocator * @param fields * @param body */ public setUserGroups(userLocator: string, fields?: string, body?: Groups, options?: Configuration): Promise<Groups> { const result = this.api.setUserGroups(userLocator, fields, body, options); return result.toPromise(); } /** * Update a property of the matching user. * @param userLocator * @param name * @param body */ public setUserProperty(userLocator: string, name: string, body?: string, options?: Configuration): Promise<string> { const result = this.api.setUserProperty(userLocator, name, body, options); return result.toPromise(); } /** * Update user roles of the matching user. * @param userLocator * @param body */ public setUserRoles(userLocator: string, body?: Roles, options?: Configuration): Promise<Roles> { const result = this.api.setUserRoles(userLocator, body, options); return result.toPromise(); } } import { ObservableVcsRootApi } from './ObservableAPI.ts'; import { VcsRootApiRequestFactory, VcsRootApiResponseProcessor} from "../apis/VcsRootApi.ts"; export class PromiseVcsRootApi { private api: ObservableVcsRootApi public constructor( configuration: Configuration, requestFactory?: VcsRootApiRequestFactory, responseProcessor?: VcsRootApiResponseProcessor ) { this.api = new ObservableVcsRootApi(configuration, requestFactory, responseProcessor); } /** * Add a new VCS root. * @param fields * @param body */ public addVcsRoot(fields?: string, body?: VcsRoot, options?: Configuration): Promise<VcsRoot> { const result = this.api.addVcsRoot(fields, body, options); return result.toPromise(); } /** * Delete all properties of the matching VCS root. * @param vcsRootLocator */ public deleteAllVcsRootProperties(vcsRootLocator: string, options?: Configuration): Promise<void> { const result = this.api.deleteAllVcsRootProperties(vcsRootLocator, options); return result.toPromise(); } /** * Remove VCS root matching the locator. * @param vcsRootLocator */ public deleteVcsRoot(vcsRootLocator: string, options?: Configuration): Promise<void> { const result = this.api.deleteVcsRoot(vcsRootLocator, options); return result.toPromise(); } /** * Delete a property of the matching VCS root. * @param vcsRootLocator * @param name */ public deleteVcsRootProperty(vcsRootLocator: string, name: string, options?: Configuration): Promise<void> { const result = this.api.deleteVcsRootProperty(vcsRootLocator, name, options); return result.toPromise(); } /** * Get all properties of the matching VCS root. * @param vcsRootLocator * @param fields */ public getAllVcsRootProperties(vcsRootLocator: string, fields?: string, options?: Configuration): Promise<Properties> { const result = this.api.getAllVcsRootProperties(vcsRootLocator, fields, options); return result.toPromise(); } /** * Get all VCS roots. * @param locator * @param fields */ public getAllVcsRoots(locator?: string, fields?: string, options?: Configuration): Promise<VcsRoots> { const result = this.api.getAllVcsRoots(locator, fields, options); return result.toPromise(); } /** * Get root endpoints. * @param vcsRootLocator * @param fields */ public getRootEndpoints(vcsRootLocator: string, fields?: string, options?: Configuration): Promise<VcsRoot> { const result = this.api.getRootEndpoints(vcsRootLocator, fields, options); return result.toPromise(); } /** * Get a field of the matching VCS root. * @param vcsRootLocator * @param field */ public getVcsRootField(vcsRootLocator: string, field: string, options?: Configuration): Promise<string> { const result = this.api.getVcsRootField(vcsRootLocator, field, options); return result.toPromise(); } /** * Get all VCS root instances of the matching VCS root. * @param vcsRootLocator * @param fields */ public getVcsRootInstances(vcsRootLocator: string, fields?: string, options?: Configuration): Promise<VcsRootInstances> { const result = this.api.getVcsRootInstances(vcsRootLocator, fields, options); return result.toPromise(); } /** * Get a property on the matching VCS root. * @param vcsRootLocator * @param name */ public getVcsRootProperty(vcsRootLocator: string, name: string, options?: Configuration): Promise<string> { const result = this.api.getVcsRootProperty(vcsRootLocator, name, options); return result.toPromise(); } /** * Get the settings file of the matching VCS root. * @param vcsRootLocator */ public getVcsRootSettingsFile(vcsRootLocator: string, options?: Configuration): Promise<string> { const result = this.api.getVcsRootSettingsFile(vcsRootLocator, options); return result.toPromise(); } /** * Update a field of the matching VCS root. * @param vcsRootLocator * @param field * @param body */ public setVcsRootField(vcsRootLocator: string, field: string, body?: string, options?: Configuration): Promise<string> { const result = this.api.setVcsRootField(vcsRootLocator, field, body, options); return result.toPromise(); } /** * Update all properties of the matching VCS root. * @param vcsRootLocator * @param fields * @param body */ public setVcsRootProperties(vcsRootLocator: string, fields?: string, body?: Properties, options?: Configuration): Promise<Properties> { const result = this.api.setVcsRootProperties(vcsRootLocator, fields, body, options); return result.toPromise(); } /** * Update a property of the matching VCS root. * @param vcsRootLocator * @param name * @param body */ public setVcsRootProperty(vcsRootLocator: string, name: string, body?: string, options?: Configuration): Promise<string> { const result = this.api.setVcsRootProperty(vcsRootLocator, name, body, options); return result.toPromise(); } } import { ObservableVcsRootInstanceApi } from './ObservableAPI.ts'; import { VcsRootInstanceApiRequestFactory, VcsRootInstanceApiResponseProcessor} from "../apis/VcsRootInstanceApi.ts"; export class PromiseVcsRootInstanceApi { private api: ObservableVcsRootInstanceApi public constructor( configuration: Configuration, requestFactory?: VcsRootInstanceApiRequestFactory, responseProcessor?: VcsRootInstanceApiResponseProcessor ) { this.api = new ObservableVcsRootInstanceApi(configuration, requestFactory, responseProcessor); } /** * Remove a field of the matching VCS root instance. * @param vcsRootInstanceLocator * @param field */ public deleteVcsRootInstanceField(vcsRootInstanceLocator: string, field: string, options?: Configuration): Promise<void> { const result = this.api.deleteVcsRootInstanceField(vcsRootInstanceLocator, field, options); return result.toPromise(); } /** * Delete the last repository state of the matching VCS root instance. * @param vcsRootInstanceLocator */ public deleteVcsRootInstanceRepositoryState(vcsRootInstanceLocator: string, options?: Configuration): Promise<void> { const result = this.api.deleteVcsRootInstanceRepositoryState(vcsRootInstanceLocator, options); return result.toPromise(); } /** * Download specific file. * @param path * @param vcsRootInstanceLocator */ public downloadFile(path: string, vcsRootInstanceLocator: string, options?: Configuration): Promise<void> { const result = this.api.downloadFile(path, vcsRootInstanceLocator, options); return result.toPromise(); } /** * Get all VCS root instances. * @param locator * @param fields */ public getAllVcsRootInstances(locator?: string, fields?: string, options?: Configuration): Promise<VcsRootInstances> { const result = this.api.getAllVcsRootInstances(locator, fields, options); return result.toPromise(); } /** * Get metadata of specific file. * @param path * @param vcsRootInstanceLocator * @param fields */ public getFileMetadata(path: string, vcsRootInstanceLocator: string, fields?: string, options?: Configuration): Promise<any> { const result = this.api.getFileMetadata(path, vcsRootInstanceLocator, fields, options); return result.toPromise(); } /** * List all files. * @param vcsRootInstanceLocator * @param basePath * @param locator * @param fields */ public getFilesList(vcsRootInstanceLocator: string, basePath?: string, locator?: string, fields?: string, options?: Configuration): Promise<Files> { const result = this.api.getFilesList(vcsRootInstanceLocator, basePath, locator, fields, options); return result.toPromise(); } /** * List files under this path. * @param path * @param vcsRootInstanceLocator * @param basePath * @param locator * @param fields */ public getFilesListForSubpath(path: string, vcsRootInstanceLocator: string, basePath?: string, locator?: string, fields?: string, options?: Configuration): Promise<Files> { const result = this.api.getFilesListForSubpath(path, vcsRootInstanceLocator, basePath, locator, fields, options); return result.toPromise(); } /** * Get VCS root instance matching the locator. * @param vcsRootInstanceLocator * @param fields */ public getVcsRootInstance(vcsRootInstanceLocator: string, fields?: string, options?: Configuration): Promise<VcsRootInstance> { const result = this.api.getVcsRootInstance(vcsRootInstanceLocator, fields, options); return result.toPromise(); } /** * Get the creation date of the matching VCS root instance. * @param vcsRootInstanceLocator */ public getVcsRootInstanceCreationDate(vcsRootInstanceLocator: string, options?: Configuration): Promise<string> { const result = this.api.getVcsRootInstanceCreationDate(vcsRootInstanceLocator, options); return result.toPromise(); } /** * Get a field of the matching VCS root instance. * @param vcsRootInstanceLocator * @param field */ public getVcsRootInstanceField(vcsRootInstanceLocator: string, field: string, options?: Configuration): Promise<string> { const result = this.api.getVcsRootInstanceField(vcsRootInstanceLocator, field, options); return result.toPromise(); } /** * Get all properties of the matching VCS root instance. * @param vcsRootInstanceLocator * @param fields */ public getVcsRootInstanceProperties(vcsRootInstanceLocator: string, fields?: string, options?: Configuration): Promise<Properties> { const result = this.api.getVcsRootInstanceProperties(vcsRootInstanceLocator, fields, options); return result.toPromise(); } /** * Get the repository state of the matching VCS root instance. * @param vcsRootInstanceLocator * @param fields */ public getVcsRootInstanceRepositoryState(vcsRootInstanceLocator: string, fields?: string, options?: Configuration): Promise<Entries> { const result = this.api.getVcsRootInstanceRepositoryState(vcsRootInstanceLocator, fields, options); return result.toPromise(); } /** * Get specific file zipped. * @param path * @param vcsRootInstanceLocator * @param basePath * @param locator * @param name */ public getZippedFile(path: string, vcsRootInstanceLocator: string, basePath?: string, locator?: string, name?: string, options?: Configuration): Promise<void> { const result = this.api.getZippedFile(path, vcsRootInstanceLocator, basePath, locator, name, options); return result.toPromise(); } /** * Check for the pending changes for all VCS root instances. * @param locator * @param requestor * @param fields */ public requestPendingChangesCheck(locator?: string, requestor?: string, fields?: string, options?: Configuration): Promise<VcsRootInstances> { const result = this.api.requestPendingChangesCheck(locator, requestor, fields, options); return result.toPromise(); } /** * Get a field of the matching VCS root instance. * @param vcsRootInstanceLocator * @param field * @param body */ public setVcsRootInstanceField(vcsRootInstanceLocator: string, field: string, body?: string, options?: Configuration): Promise<string> { const result = this.api.setVcsRootInstanceField(vcsRootInstanceLocator, field, body, options); return result.toPromise(); } /** * Update the repository state of the matching VCS root instance. * @param vcsRootInstanceLocator * @param fields * @param body */ public setVcsRootInstanceRepositoryState(vcsRootInstanceLocator: string, fields?: string, body?: Entries, options?: Configuration): Promise<Entries> { const result = this.api.setVcsRootInstanceRepositoryState(vcsRootInstanceLocator, fields, body, options); return result.toPromise(); } /** * Send the commit hook notification. * @param locator * @param okOnNothingFound */ public triggerCommitHookNotification(locator?: string, okOnNothingFound?: boolean, options?: Configuration): Promise<void> { const result = this.api.triggerCommitHookNotification(locator, okOnNothingFound, options); return result.toPromise(); } } <file_sep>/ts-schema/schema/rest-api/deno/models/ObjectSerializer.ts export * from './Agent.ts'; export * from './AgentLocator.ts'; export * from './AgentPool.ts'; export * from './AgentPoolLocator.ts'; export * from './AgentPools.ts'; export * from './AgentRequirement.ts'; export * from './AgentRequirements.ts'; export * from './Agents.ts'; export * from './ArtifactDependencies.ts'; export * from './ArtifactDependency.ts'; export * from './AuditAction.ts'; export * from './AuditEvent.ts'; export * from './AuditEvents.ts'; export * from './AuditLocator.ts'; export * from './AuthorizedInfo.ts'; export * from './Branch.ts'; export * from './BranchLocator.ts'; export * from './BranchVersion.ts'; export * from './Branches.ts'; export * from './Build.ts'; export * from './BuildCancelRequest.ts'; export * from './BuildChange.ts'; export * from './BuildChanges.ts'; export * from './BuildLocator.ts'; export * from './BuildQueueLocator.ts'; export * from './BuildTriggeringOptions.ts'; export * from './BuildType.ts'; export * from './BuildTypeLocator.ts'; export * from './BuildTypes.ts'; export * from './Builds.ts'; export * from './Change.ts'; export * from './ChangeLocator.ts'; export * from './Changes.ts'; export * from './CloudImage.ts'; export * from './CloudImages.ts'; export * from './CloudInstance.ts'; export * from './CloudInstances.ts'; export * from './CloudProfile.ts'; export * from './CloudProfiles.ts'; export * from './Comment.ts'; export * from './Compatibilities.ts'; export * from './Compatibility.ts'; export * from './CompatibilityPolicy.ts'; export * from './Customizations.ts'; export * from './Datas.ts'; export * from './EnabledInfo.ts'; export * from './Entries.ts'; export * from './Entry.ts'; export * from './Environment.ts'; export * from './Feature.ts'; export * from './Features.ts'; export * from './File.ts'; export * from './FileChange.ts'; export * from './FileChanges.ts'; export * from './Files.ts'; export * from './Group.ts'; export * from './Groups.ts'; export * from './Href.ts'; export * from './Investigation.ts'; export * from './InvestigationLocator.ts'; export * from './Investigations.ts'; export * from './Issue.ts'; export * from './IssueUsage.ts'; export * from './Issues.ts'; export * from './IssuesUsages.ts'; export * from './Items.ts'; export * from './LicenseKey.ts'; export * from './LicenseKeys.ts'; export * from './LicensingData.ts'; export * from './Link.ts'; export * from './Links.ts'; export * from './MetaData.ts'; export * from './Metric.ts'; export * from './MetricTag.ts'; export * from './MetricTags.ts'; export * from './MetricValue.ts'; export * from './MetricValues.ts'; export * from './Metrics.ts'; export * from './MultipleOperationResult.ts'; export * from './Mute.ts'; export * from './MuteLocator.ts'; export * from './Mutes.ts'; export * from './NewBuildTypeDescription.ts'; export * from './NewProjectDescription.ts'; export * from './OperationResult.ts'; export * from './ParsedTestName.ts'; export * from './Permission.ts'; export * from './PermissionAssignment.ts'; export * from './PermissionAssignments.ts'; export * from './PermissionRestriction.ts'; export * from './PermissionRestrictions.ts'; export * from './PinInfo.ts'; export * from './Plugin.ts'; export * from './Plugins.ts'; export * from './Problem.ts'; export * from './ProblemLocator.ts'; export * from './ProblemOccurrence.ts'; export * from './ProblemOccurrenceLocator.ts'; export * from './ProblemOccurrences.ts'; export * from './ProblemScope.ts'; export * from './ProblemTarget.ts'; export * from './Problems.ts'; export * from './ProgressInfo.ts'; export * from './Project.ts'; export * from './ProjectFeature.ts'; export * from './ProjectFeatures.ts'; export * from './ProjectLocator.ts'; export * from './Projects.ts'; export * from './Properties.ts'; export * from './Property.ts'; export * from './Related.ts'; export * from './RelatedEntities.ts'; export * from './RelatedEntity.ts'; export * from './RepositoryState.ts'; export * from './Requirements.ts'; export * from './Resolution.ts'; export * from './Revision.ts'; export * from './Revisions.ts'; export * from './Role.ts'; export * from './Roles.ts'; export * from './Server.ts'; export * from './SnapshotDependencies.ts'; export * from './SnapshotDependency.ts'; export * from './StateField.ts'; export * from './Step.ts'; export * from './Steps.ts'; export * from './Tag.ts'; export * from './TagLocator.ts'; export * from './Tags.ts'; export * from './Test.ts'; export * from './TestCounters.ts'; export * from './TestLocator.ts'; export * from './TestOccurrence.ts'; export * from './TestOccurrenceLocator.ts'; export * from './TestOccurrences.ts'; export * from './TestRunMetadata.ts'; export * from './Tests.ts'; export * from './Token.ts'; export * from './Tokens.ts'; export * from './Trigger.ts'; export * from './TriggeredBy.ts'; export * from './Triggers.ts'; export * from './Type.ts'; export * from './TypedValue.ts'; export * from './User.ts'; export * from './UserGroupLocator.ts'; export * from './UserLocator.ts'; export * from './Users.ts'; export * from './VcsCheckStatus.ts'; export * from './VcsLabel.ts'; export * from './VcsLabels.ts'; export * from './VcsRoot.ts'; export * from './VcsRootEntries.ts'; export * from './VcsRootEntry.ts'; export * from './VcsRootInstance.ts'; export * from './VcsRootInstanceLocator.ts'; export * from './VcsRootInstances.ts'; export * from './VcsRootLocator.ts'; export * from './VcsRoots.ts'; export * from './VcsStatus.ts'; import { Agent } from './Agent.ts'; import { AgentLocator } from './AgentLocator.ts'; import { AgentPool } from './AgentPool.ts'; import { AgentPoolLocator } from './AgentPoolLocator.ts'; import { AgentPools } from './AgentPools.ts'; import { AgentRequirement } from './AgentRequirement.ts'; import { AgentRequirements } from './AgentRequirements.ts'; import { Agents } from './Agents.ts'; import { ArtifactDependencies } from './ArtifactDependencies.ts'; import { ArtifactDependency } from './ArtifactDependency.ts'; import { AuditAction } from './AuditAction.ts'; import { AuditEvent } from './AuditEvent.ts'; import { AuditEvents } from './AuditEvents.ts'; import { AuditLocator } from './AuditLocator.ts'; import { AuthorizedInfo } from './AuthorizedInfo.ts'; import { Branch } from './Branch.ts'; import { BranchLocator } from './BranchLocator.ts'; import { BranchVersion } from './BranchVersion.ts'; import { Branches } from './Branches.ts'; import { Build } from './Build.ts'; import { BuildCancelRequest } from './BuildCancelRequest.ts'; import { BuildChange } from './BuildChange.ts'; import { BuildChanges } from './BuildChanges.ts'; import { BuildLocator } from './BuildLocator.ts'; import { BuildQueueLocator } from './BuildQueueLocator.ts'; import { BuildTriggeringOptions } from './BuildTriggeringOptions.ts'; import { BuildType } from './BuildType.ts'; import { BuildTypeLocator } from './BuildTypeLocator.ts'; import { BuildTypes } from './BuildTypes.ts'; import { Builds } from './Builds.ts'; import { Change } from './Change.ts'; import { ChangeLocator } from './ChangeLocator.ts'; import { Changes } from './Changes.ts'; import { CloudImage } from './CloudImage.ts'; import { CloudImages } from './CloudImages.ts'; import { CloudInstance } from './CloudInstance.ts'; import { CloudInstances } from './CloudInstances.ts'; import { CloudProfile } from './CloudProfile.ts'; import { CloudProfiles } from './CloudProfiles.ts'; import { Comment } from './Comment.ts'; import { Compatibilities } from './Compatibilities.ts'; import { Compatibility } from './Compatibility.ts'; import { CompatibilityPolicy } from './CompatibilityPolicy.ts'; import { Customizations } from './Customizations.ts'; import { Datas } from './Datas.ts'; import { EnabledInfo } from './EnabledInfo.ts'; import { Entries } from './Entries.ts'; import { Entry } from './Entry.ts'; import { Environment } from './Environment.ts'; import { Feature } from './Feature.ts'; import { Features } from './Features.ts'; import { File } from './File.ts'; import { FileChange } from './FileChange.ts'; import { FileChanges } from './FileChanges.ts'; import { Files } from './Files.ts'; import { Group } from './Group.ts'; import { Groups } from './Groups.ts'; import { Href } from './Href.ts'; import { Investigation } from './Investigation.ts'; import { InvestigationLocator } from './InvestigationLocator.ts'; import { Investigations } from './Investigations.ts'; import { Issue } from './Issue.ts'; import { IssueUsage } from './IssueUsage.ts'; import { Issues } from './Issues.ts'; import { IssuesUsages } from './IssuesUsages.ts'; import { Items } from './Items.ts'; import { LicenseKey } from './LicenseKey.ts'; import { LicenseKeys } from './LicenseKeys.ts'; import { LicensingData } from './LicensingData.ts'; import { Link } from './Link.ts'; import { Links } from './Links.ts'; import { MetaData } from './MetaData.ts'; import { Metric } from './Metric.ts'; import { MetricTag } from './MetricTag.ts'; import { MetricTags } from './MetricTags.ts'; import { MetricValue } from './MetricValue.ts'; import { MetricValues } from './MetricValues.ts'; import { Metrics } from './Metrics.ts'; import { MultipleOperationResult } from './MultipleOperationResult.ts'; import { Mute } from './Mute.ts'; import { MuteLocator } from './MuteLocator.ts'; import { Mutes } from './Mutes.ts'; import { NewBuildTypeDescription } from './NewBuildTypeDescription.ts'; import { NewProjectDescription } from './NewProjectDescription.ts'; import { OperationResult } from './OperationResult.ts'; import { ParsedTestName } from './ParsedTestName.ts'; import { Permission } from './Permission.ts'; import { PermissionAssignment } from './PermissionAssignment.ts'; import { PermissionAssignments } from './PermissionAssignments.ts'; import { PermissionRestriction } from './PermissionRestriction.ts'; import { PermissionRestrictions } from './PermissionRestrictions.ts'; import { PinInfo } from './PinInfo.ts'; import { Plugin } from './Plugin.ts'; import { Plugins } from './Plugins.ts'; import { Problem } from './Problem.ts'; import { ProblemLocator } from './ProblemLocator.ts'; import { ProblemOccurrence } from './ProblemOccurrence.ts'; import { ProblemOccurrenceLocator } from './ProblemOccurrenceLocator.ts'; import { ProblemOccurrences } from './ProblemOccurrences.ts'; import { ProblemScope } from './ProblemScope.ts'; import { ProblemTarget } from './ProblemTarget.ts'; import { Problems } from './Problems.ts'; import { ProgressInfo } from './ProgressInfo.ts'; import { Project } from './Project.ts'; import { ProjectFeature } from './ProjectFeature.ts'; import { ProjectFeatures } from './ProjectFeatures.ts'; import { ProjectLocator } from './ProjectLocator.ts'; import { Projects } from './Projects.ts'; import { Properties } from './Properties.ts'; import { Property } from './Property.ts'; import { Related } from './Related.ts'; import { RelatedEntities } from './RelatedEntities.ts'; import { RelatedEntity } from './RelatedEntity.ts'; import { RepositoryState } from './RepositoryState.ts'; import { Requirements } from './Requirements.ts'; import { Resolution } from './Resolution.ts'; import { Revision } from './Revision.ts'; import { Revisions } from './Revisions.ts'; import { Role } from './Role.ts'; import { Roles } from './Roles.ts'; import { Server } from './Server.ts'; import { SnapshotDependencies } from './SnapshotDependencies.ts'; import { SnapshotDependency } from './SnapshotDependency.ts'; import { StateField } from './StateField.ts'; import { Step } from './Step.ts'; import { Steps } from './Steps.ts'; import { Tag } from './Tag.ts'; import { TagLocator } from './TagLocator.ts'; import { Tags } from './Tags.ts'; import { Test } from './Test.ts'; import { TestCounters } from './TestCounters.ts'; import { TestLocator } from './TestLocator.ts'; import { TestOccurrence } from './TestOccurrence.ts'; import { TestOccurrenceLocator } from './TestOccurrenceLocator.ts'; import { TestOccurrences } from './TestOccurrences.ts'; import { TestRunMetadata } from './TestRunMetadata.ts'; import { Tests } from './Tests.ts'; import { Token } from './Token.ts'; import { Tokens } from './Tokens.ts'; import { Trigger } from './Trigger.ts'; import { TriggeredBy } from './TriggeredBy.ts'; import { Triggers } from './Triggers.ts'; import { Type } from './Type.ts'; import { TypedValue } from './TypedValue.ts'; import { User } from './User.ts'; import { UserGroupLocator } from './UserGroupLocator.ts'; import { UserLocator } from './UserLocator.ts'; import { Users } from './Users.ts'; import { VcsCheckStatus } from './VcsCheckStatus.ts'; import { VcsLabel } from './VcsLabel.ts'; import { VcsLabels } from './VcsLabels.ts'; import { VcsRoot } from './VcsRoot.ts'; import { VcsRootEntries } from './VcsRootEntries.ts'; import { VcsRootEntry } from './VcsRootEntry.ts'; import { VcsRootInstance } from './VcsRootInstance.ts'; import { VcsRootInstanceLocator } from './VcsRootInstanceLocator.ts'; import { VcsRootInstances } from './VcsRootInstances.ts'; import { VcsRootLocator } from './VcsRootLocator.ts'; import { VcsRoots } from './VcsRoots.ts'; import { VcsStatus } from './VcsStatus.ts'; /* tslint:disable:no-unused-variable */ let primitives = [ "string", "boolean", "double", "integer", "long", "float", "number", "any" ]; const supportedMediaTypes: { [mediaType: string]: number } = { "application/json": Infinity, "application/octet-stream": 0 } let enumsMap: Set<string> = new Set<string>([ ]); let typeMap: {[index: string]: any} = { "Agent": Agent, "AgentLocator": AgentLocator, "AgentPool": AgentPool, "AgentPoolLocator": AgentPoolLocator, "AgentPools": AgentPools, "AgentRequirement": AgentRequirement, "AgentRequirements": AgentRequirements, "Agents": Agents, "ArtifactDependencies": ArtifactDependencies, "ArtifactDependency": ArtifactDependency, "AuditAction": AuditAction, "AuditEvent": AuditEvent, "AuditEvents": AuditEvents, "AuditLocator": AuditLocator, "AuthorizedInfo": AuthorizedInfo, "Branch": Branch, "BranchLocator": BranchLocator, "BranchVersion": BranchVersion, "Branches": Branches, "Build": Build, "BuildCancelRequest": BuildCancelRequest, "BuildChange": BuildChange, "BuildChanges": BuildChanges, "BuildLocator": BuildLocator, "BuildQueueLocator": BuildQueueLocator, "BuildTriggeringOptions": BuildTriggeringOptions, "BuildType": BuildType, "BuildTypeLocator": BuildTypeLocator, "BuildTypes": BuildTypes, "Builds": Builds, "Change": Change, "ChangeLocator": ChangeLocator, "Changes": Changes, "CloudImage": CloudImage, "CloudImages": CloudImages, "CloudInstance": CloudInstance, "CloudInstances": CloudInstances, "CloudProfile": CloudProfile, "CloudProfiles": CloudProfiles, "Comment": Comment, "Compatibilities": Compatibilities, "Compatibility": Compatibility, "CompatibilityPolicy": CompatibilityPolicy, "Customizations": Customizations, "Datas": Datas, "EnabledInfo": EnabledInfo, "Entries": Entries, "Entry": Entry, "Environment": Environment, "Feature": Feature, "Features": Features, "File": File, "FileChange": FileChange, "FileChanges": FileChanges, "Files": Files, "Group": Group, "Groups": Groups, "Href": Href, "Investigation": Investigation, "InvestigationLocator": InvestigationLocator, "Investigations": Investigations, "Issue": Issue, "IssueUsage": IssueUsage, "Issues": Issues, "IssuesUsages": IssuesUsages, "Items": Items, "LicenseKey": LicenseKey, "LicenseKeys": LicenseKeys, "LicensingData": LicensingData, "Link": Link, "Links": Links, "MetaData": MetaData, "Metric": Metric, "MetricTag": MetricTag, "MetricTags": MetricTags, "MetricValue": MetricValue, "MetricValues": MetricValues, "Metrics": Metrics, "MultipleOperationResult": MultipleOperationResult, "Mute": Mute, "MuteLocator": MuteLocator, "Mutes": Mutes, "NewBuildTypeDescription": NewBuildTypeDescription, "NewProjectDescription": NewProjectDescription, "OperationResult": OperationResult, "ParsedTestName": ParsedTestName, "Permission": Permission, "PermissionAssignment": PermissionAssignment, "PermissionAssignments": PermissionAssignments, "PermissionRestriction": PermissionRestriction, "PermissionRestrictions": PermissionRestrictions, "PinInfo": PinInfo, "Plugin": Plugin, "Plugins": Plugins, "Problem": Problem, "ProblemLocator": ProblemLocator, "ProblemOccurrence": ProblemOccurrence, "ProblemOccurrenceLocator": ProblemOccurrenceLocator, "ProblemOccurrences": ProblemOccurrences, "ProblemScope": ProblemScope, "ProblemTarget": ProblemTarget, "Problems": Problems, "ProgressInfo": ProgressInfo, "Project": Project, "ProjectFeature": ProjectFeature, "ProjectFeatures": ProjectFeatures, "ProjectLocator": ProjectLocator, "Projects": Projects, "Properties": Properties, "Property": Property, "Related": Related, "RelatedEntities": RelatedEntities, "RelatedEntity": RelatedEntity, "RepositoryState": RepositoryState, "Requirements": Requirements, "Resolution": Resolution, "Revision": Revision, "Revisions": Revisions, "Role": Role, "Roles": Roles, "Server": Server, "SnapshotDependencies": SnapshotDependencies, "SnapshotDependency": SnapshotDependency, "StateField": StateField, "Step": Step, "Steps": Steps, "Tag": Tag, "TagLocator": TagLocator, "Tags": Tags, "Test": Test, "TestCounters": TestCounters, "TestLocator": TestLocator, "TestOccurrence": TestOccurrence, "TestOccurrenceLocator": TestOccurrenceLocator, "TestOccurrences": TestOccurrences, "TestRunMetadata": TestRunMetadata, "Tests": Tests, "Token": Token, "Tokens": Tokens, "Trigger": Trigger, "TriggeredBy": TriggeredBy, "Triggers": Triggers, "Type": Type, "TypedValue": TypedValue, "User": User, "UserGroupLocator": UserGroupLocator, "UserLocator": UserLocator, "Users": Users, "VcsCheckStatus": VcsCheckStatus, "VcsLabel": VcsLabel, "VcsLabels": VcsLabels, "VcsRoot": VcsRoot, "VcsRootEntries": VcsRootEntries, "VcsRootEntry": VcsRootEntry, "VcsRootInstance": VcsRootInstance, "VcsRootInstanceLocator": VcsRootInstanceLocator, "VcsRootInstances": VcsRootInstances, "VcsRootLocator": VcsRootLocator, "VcsRoots": VcsRoots, "VcsStatus": VcsStatus, } export class ObjectSerializer { public static findCorrectType(data: any, expectedType: string) { if (data == undefined) { return expectedType; } else if (primitives.indexOf(expectedType.toLowerCase()) !== -1) { return expectedType; } else if (expectedType === "Date") { return expectedType; } else { if (enumsMap.has(expectedType)) { return expectedType; } if (!typeMap[expectedType]) { return expectedType; // w/e we don't know the type } // Check the discriminator let discriminatorProperty = typeMap[expectedType].discriminator; if (discriminatorProperty == null) { return expectedType; // the type does not have a discriminator. use it. } else { if (data[discriminatorProperty]) { var discriminatorType = data[discriminatorProperty]; if(typeMap[discriminatorType]){ return discriminatorType; // use the type given in the discriminator } else { return expectedType; // discriminator did not map to a type } } else { return expectedType; // discriminator was not present (or an empty string) } } } } public static serialize(data: any, type: string, format: string) { if (data == undefined) { return data; } else if (primitives.indexOf(type.toLowerCase()) !== -1) { return data; } else if (type.lastIndexOf("Array<", 0) === 0) { // string.startsWith pre es6 let subType: string = type.replace("Array<", ""); // Array<Type> => Type> subType = subType.substring(0, subType.length - 1); // Type> => Type let transformedData: any[] = []; for (let index in data) { let date = data[index]; transformedData.push(ObjectSerializer.serialize(date, subType, format)); } return transformedData; } else if (type === "Date") { if (format == "date") { let month = data.getMonth()+1 month = month < 10 ? "0" + month.toString() : month.toString() let day = data.getDate(); day = day < 10 ? "0" + day.toString() : day.toString(); return data.getFullYear() + "-" + month + "-" + day; } else { return data.toISOString(); } } else { if (enumsMap.has(type)) { return data; } if (!typeMap[type]) { // in case we dont know the type return data; } // Get the actual type of this object type = this.findCorrectType(data, type); // get the map for the correct type. let attributeTypes = typeMap[type].getAttributeTypeMap(); let instance: {[index: string]: any} = {}; for (let index in attributeTypes) { let attributeType = attributeTypes[index]; instance[attributeType.baseName] = ObjectSerializer.serialize(data[attributeType.name], attributeType.type, attributeType.format); } return instance; } } public static deserialize(data: any, type: string, format: string) { // polymorphism may change the actual type. type = ObjectSerializer.findCorrectType(data, type); if (data == undefined) { return data; } else if (primitives.indexOf(type.toLowerCase()) !== -1) { return data; } else if (type.lastIndexOf("Array<", 0) === 0) { // string.startsWith pre es6 let subType: string = type.replace("Array<", ""); // Array<Type> => Type> subType = subType.substring(0, subType.length - 1); // Type> => Type let transformedData: any[] = []; for (let index in data) { let date = data[index]; transformedData.push(ObjectSerializer.deserialize(date, subType, format)); } return transformedData; } else if (type === "Date") { return new Date(data); } else { if (enumsMap.has(type)) {// is Enum return data; } if (!typeMap[type]) { // dont know the type return data; } let instance = new typeMap[type](); let attributeTypes = typeMap[type].getAttributeTypeMap(); for (let index in attributeTypes) { let attributeType = attributeTypes[index]; instance[attributeType.name] = ObjectSerializer.deserialize(data[attributeType.baseName], attributeType.type, attributeType.format); } return instance; } } /** * Normalize media type * * We currently do not handle any media types attributes, i.e. anything * after a semicolon. All content is assumed to be UTF-8 compatible. */ public static normalizeMediaType(mediaType: string | undefined): string | undefined { if (mediaType === undefined) { return undefined; } return mediaType.split(";")[0].trim().toLowerCase(); } /** * From a list of possible media types, choose the one we can handle best. * * The order of the given media types does not have any impact on the choice * made. */ public static getPreferredMediaType(mediaTypes: Array<string>): string { /** According to OAS 3 we should default to json */ if (!mediaTypes) { return "application/json"; } const normalMediaTypes = mediaTypes.map(this.normalizeMediaType); let selectedMediaType: string | undefined = undefined; let selectedRank: number = -Infinity; for (const mediaType of normalMediaTypes) { if (supportedMediaTypes[mediaType!] > selectedRank) { selectedMediaType = mediaType; selectedRank = supportedMediaTypes[mediaType!]; } } if (selectedMediaType === undefined) { throw new Error("None of the given media types are supported: " + mediaTypes.join(", ")); } return selectedMediaType!; } /** * Convert data to a string according the given media type */ public static stringify(data: any, mediaType: string): string { if (mediaType === "application/json") { return JSON.stringify(data); } throw new Error("The mediaType " + mediaType + " is not supported by ObjectSerializer.stringify."); } /** * Parse data from a string according to the given media type */ public static parse(rawData: string, mediaType: string | undefined) { if (mediaType === undefined) { throw new Error("Cannot parse content. No Content-Type defined."); } if (mediaType === "application/json") { return JSON.parse(rawData); } throw new Error("The mediaType " + mediaType + " is not supported by ObjectSerializer.parse."); } } <file_sep>/ts-schema/schema/rest-api/deno/apis/BuildApi.ts // TODO: better import syntax? import { BaseAPIRequestFactory, RequiredError } from './baseapi.ts'; import {Configuration} from '../configuration.ts'; import { RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http.ts'; import {ObjectSerializer} from '../models/ObjectSerializer.ts'; import {ApiException} from './exception.ts'; import {isCodeInRange} from '../util.ts'; import { Build } from '../models/Build.ts'; import { BuildChanges } from '../models/BuildChanges.ts'; import { Builds } from '../models/Builds.ts'; import { Comment } from '../models/Comment.ts'; import { Files } from '../models/Files.ts'; import { IssuesUsages } from '../models/IssuesUsages.ts'; import { MultipleOperationResult } from '../models/MultipleOperationResult.ts'; import { PinInfo } from '../models/PinInfo.ts'; import { ProblemOccurrence } from '../models/ProblemOccurrence.ts'; import { ProblemOccurrences } from '../models/ProblemOccurrences.ts'; import { Properties } from '../models/Properties.ts'; import { Tags } from '../models/Tags.ts'; import { TestOccurrences } from '../models/TestOccurrences.ts'; import { VcsLabels } from '../models/VcsLabels.ts'; /** * no description */ export class BuildApiRequestFactory extends BaseAPIRequestFactory { /** * Add a VCS label to the matching build. * @param buildLocator * @param locator * @param fields * @param body */ public async addBuildVcsLabel(buildLocator: string, locator?: string, fields?: string, body?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling addBuildVcsLabel.'); } // Path Params const localVarPath = '/app/rest/builds/{buildLocator}/vcsLabels' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "VcsRootInstanceLocator")); } if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "text/plain" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "string", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Adds a message to the build log. Service messages are accepted. * @param buildLocator * @param fields * @param body */ public async addLogMessageToBuild(buildLocator: string, fields?: string, body?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling addLogMessageToBuild.'); } // Path Params const localVarPath = '/app/rest/builds/{buildLocator}/log' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "text/plain" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "string", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Add a build problem to the matching build. * @param buildLocator * @param fields * @param body */ public async addProblemToBuild(buildLocator: string, fields?: string, body?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling addProblemToBuild.'); } // Path Params const localVarPath = '/app/rest/builds/{buildLocator}/problemOccurrences' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "text/plain" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "string", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Add tags to the matching build. * @param buildLocator * @param fields * @param body */ public async addTagsToBuild(buildLocator: string, fields?: string, body?: Tags, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling addTagsToBuild.'); } // Path Params const localVarPath = '/app/rest/builds/{buildLocator}/tags' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Tags", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Add tags to multiple matching builds. * @param buildLocator * @param fields * @param body */ public async addTagsToMultipleBuilds(buildLocator: string, fields?: string, body?: Tags, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling addTagsToMultipleBuilds.'); } // Path Params const localVarPath = '/app/rest/builds/multiple/{buildLocator}/tags' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Tags", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Delete build matching the locator. * @param buildLocator */ public async deleteBuild(buildLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling deleteBuild.'); } // Path Params const localVarPath = '/app/rest/builds/{buildLocator}' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Remove the build comment matching the locator. * @param buildLocator */ public async deleteBuildComment(buildLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling deleteBuildComment.'); } // Path Params const localVarPath = '/app/rest/builds/{buildLocator}/comment' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Delete comments of multiple matching builds. * @param buildLocator * @param fields */ public async deleteMultipleBuildComments(buildLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling deleteMultipleBuildComments.'); } // Path Params const localVarPath = '/app/rest/builds/multiple/{buildLocator}/comment' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Delete multiple builds matching the locator. * @param buildLocator * @param fields */ public async deleteMultipleBuilds(buildLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling deleteMultipleBuilds.'); } // Path Params const localVarPath = '/app/rest/builds/multiple/{buildLocator}' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Download specific file. * @param path * @param buildLocator * @param resolveParameters * @param logBuildUsage */ public async downloadFileOfBuild(path: string, buildLocator: string, resolveParameters?: boolean, logBuildUsage?: boolean, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'path' is not null or undefined if (path === null || path === undefined) { throw new RequiredError('Required parameter path was null or undefined when calling downloadFileOfBuild.'); } // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling downloadFileOfBuild.'); } // Path Params const localVarPath = '/app/rest/builds/{buildLocator}/artifacts/files{path}' .replace('{' + 'path' + '}', encodeURIComponent(String(path))) .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (resolveParameters !== undefined) { requestContext.setQueryParam("resolveParameters", ObjectSerializer.serialize(resolveParameters, "boolean", "")); } if (logBuildUsage !== undefined) { requestContext.setQueryParam("logBuildUsage", ObjectSerializer.serialize(logBuildUsage, "boolean", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get the build status of aggregated matching builds. * @param buildLocator */ public async getAggregatedBuildStatus(buildLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling getAggregatedBuildStatus.'); } // Path Params const localVarPath = '/app/rest/builds/aggregated/{buildLocator}/status' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get the status icon (in specified format) of aggregated matching builds. * @param buildLocator * @param suffix */ public async getAggregatedBuildStatusIcon(buildLocator: string, suffix: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling getAggregatedBuildStatusIcon.'); } // verify required parameter 'suffix' is not null or undefined if (suffix === null || suffix === undefined) { throw new RequiredError('Required parameter suffix was null or undefined when calling getAggregatedBuildStatusIcon.'); } // Path Params const localVarPath = '/app/rest/builds/aggregated/{buildLocator}/statusIcon{suffix}' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))) .replace('{' + 'suffix' + '}', encodeURIComponent(String(suffix))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all builds. * @param locator * @param fields */ public async getAllBuilds(locator?: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/builds'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "BuildLocator")); } if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get artifact dependency changes of the matching build. * @param buildLocator * @param fields */ public async getArtifactDependencyChanges(buildLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling getArtifactDependencyChanges.'); } // Path Params const localVarPath = '/app/rest/builds/{buildLocator}/artifactDependencyChanges' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get the artifacts' directory of the matching build. * @param buildLocator */ public async getArtifactsDirectory(buildLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling getArtifactsDirectory.'); } // Path Params const localVarPath = '/app/rest/builds/{buildLocator}/artifactsDirectory' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get build matching the locator. * @param buildLocator * @param fields */ public async getBuild(buildLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling getBuild.'); } // Path Params const localVarPath = '/app/rest/builds/{buildLocator}' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get actual build parameters of the matching build. * @param buildLocator * @param fields */ public async getBuildActualParameters(buildLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling getBuildActualParameters.'); } // Path Params const localVarPath = '/app/rest/builds/{buildLocator}/resulting-properties' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get a field of the matching build. * @param buildLocator * @param field */ public async getBuildField(buildLocator: string, field: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling getBuildField.'); } // verify required parameter 'field' is not null or undefined if (field === null || field === undefined) { throw new RequiredError('Required parameter field was null or undefined when calling getBuildField.'); } // Path Params const localVarPath = '/app/rest/builds/{buildLocator}/{field}' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))) .replace('{' + 'field' + '}', encodeURIComponent(String(field))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get the finish date of the matching build. * @param buildLocator */ public async getBuildFinishDate(buildLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling getBuildFinishDate.'); } // Path Params const localVarPath = '/app/rest/builds/{buildLocator}/finishDate' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get the number of the matching build. * @param buildLocator */ public async getBuildNumber(buildLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling getBuildNumber.'); } // Path Params const localVarPath = '/app/rest/builds/{buildLocator}/number' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Check if the matching build is pinned. * @param buildLocator * @param fields */ public async getBuildPinInfo(buildLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling getBuildPinInfo.'); } // Path Params const localVarPath = '/app/rest/builds/{buildLocator}/pinInfo' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get build problems of the matching build. * @param buildLocator * @param fields */ public async getBuildProblems(buildLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling getBuildProblems.'); } // Path Params const localVarPath = '/app/rest/builds/{buildLocator}/problemOccurrences' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get related issues of the matching build. * @param buildLocator * @param fields */ public async getBuildRelatedIssues(buildLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling getBuildRelatedIssues.'); } // Path Params const localVarPath = '/app/rest/builds/{buildLocator}/relatedIssues' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get the resolvement status of the matching build. * @param buildLocator * @param value */ public async getBuildResolved(buildLocator: string, value: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling getBuildResolved.'); } // verify required parameter 'value' is not null or undefined if (value === null || value === undefined) { throw new RequiredError('Required parameter value was null or undefined when calling getBuildResolved.'); } // Path Params const localVarPath = '/app/rest/builds/{buildLocator}/resolved/{value}' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))) .replace('{' + 'value' + '}', encodeURIComponent(String(value))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update a build parameter of the matching build. * @param buildLocator * @param propertyName */ public async getBuildResultingProperties(buildLocator: string, propertyName: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling getBuildResultingProperties.'); } // verify required parameter 'propertyName' is not null or undefined if (propertyName === null || propertyName === undefined) { throw new RequiredError('Required parameter propertyName was null or undefined when calling getBuildResultingProperties.'); } // Path Params const localVarPath = '/app/rest/builds/{buildLocator}/resulting-properties/{propertyName}' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))) .replace('{' + 'propertyName' + '}', encodeURIComponent(String(propertyName))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get a source file of the matching build. * @param buildLocator * @param fileName */ public async getBuildSourceFile(buildLocator: string, fileName: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling getBuildSourceFile.'); } // verify required parameter 'fileName' is not null or undefined if (fileName === null || fileName === undefined) { throw new RequiredError('Required parameter fileName was null or undefined when calling getBuildSourceFile.'); } // Path Params const localVarPath = '/app/rest/builds/{buildLocator}/sources/files/{fileName}' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))) .replace('{' + 'fileName' + '}', encodeURIComponent(String(fileName))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get a statistical value of the matching build. * @param buildLocator * @param name */ public async getBuildStatisticValue(buildLocator: string, name: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling getBuildStatisticValue.'); } // verify required parameter 'name' is not null or undefined if (name === null || name === undefined) { throw new RequiredError('Required parameter name was null or undefined when calling getBuildStatisticValue.'); } // Path Params const localVarPath = '/app/rest/builds/{buildLocator}/statistics/{name}' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))) .replace('{' + 'name' + '}', encodeURIComponent(String(name))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all statistical values of the matching build. * @param buildLocator * @param fields */ public async getBuildStatisticValues(buildLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling getBuildStatisticValues.'); } // Path Params const localVarPath = '/app/rest/builds/{buildLocator}/statistics' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get the status icon (in specified format) of the matching build. * @param buildLocator * @param suffix */ public async getBuildStatusIcon(buildLocator: string, suffix: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling getBuildStatusIcon.'); } // verify required parameter 'suffix' is not null or undefined if (suffix === null || suffix === undefined) { throw new RequiredError('Required parameter suffix was null or undefined when calling getBuildStatusIcon.'); } // Path Params const localVarPath = '/app/rest/builds/{buildLocator}/statusIcon{suffix}' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))) .replace('{' + 'suffix' + '}', encodeURIComponent(String(suffix))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get the build status text of the matching build. * @param buildLocator */ public async getBuildStatusText(buildLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling getBuildStatusText.'); } // Path Params const localVarPath = '/app/rest/builds/{buildLocator}/statusText' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get tags of the matching build. * @param buildLocator * @param locator * @param fields */ public async getBuildTags(buildLocator: string, locator?: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling getBuildTags.'); } // Path Params const localVarPath = '/app/rest/builds/{buildLocator}/tags' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "TagLocator")); } if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get test occurrences of the matching build. * @param buildLocator * @param fields */ public async getBuildTestOccurrences(buildLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling getBuildTestOccurrences.'); } // Path Params const localVarPath = '/app/rest/builds/{buildLocator}/testOccurrences' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get VCS labels of the matching build. * @param buildLocator * @param fields */ public async getBuildVcsLabels(buildLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling getBuildVcsLabels.'); } // Path Params const localVarPath = '/app/rest/builds/{buildLocator}/vcsLabels' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Check if the matching build is canceled. * @param buildLocator * @param fields */ public async getCanceledInfo(buildLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling getCanceledInfo.'); } // Path Params const localVarPath = '/app/rest/builds/{buildLocator}/canceledInfo' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get metadata of specific file. * @param path * @param buildLocator * @param fields * @param resolveParameters * @param logBuildUsage */ public async getFileMetadataOfBuild(path: string, buildLocator: string, fields?: string, resolveParameters?: boolean, logBuildUsage?: boolean, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'path' is not null or undefined if (path === null || path === undefined) { throw new RequiredError('Required parameter path was null or undefined when calling getFileMetadataOfBuild.'); } // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling getFileMetadataOfBuild.'); } // Path Params const localVarPath = '/app/rest/builds/{buildLocator}/artifacts/metadata{path}' .replace('{' + 'path' + '}', encodeURIComponent(String(path))) .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } if (resolveParameters !== undefined) { requestContext.setQueryParam("resolveParameters", ObjectSerializer.serialize(resolveParameters, "boolean", "")); } if (logBuildUsage !== undefined) { requestContext.setQueryParam("logBuildUsage", ObjectSerializer.serialize(logBuildUsage, "boolean", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * List files under this path. * @param path * @param buildLocator * @param basePath * @param locator * @param fields * @param resolveParameters * @param logBuildUsage */ public async getFilesListForSubpathOfBuild(path: string, buildLocator: string, basePath?: string, locator?: string, fields?: string, resolveParameters?: boolean, logBuildUsage?: boolean, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'path' is not null or undefined if (path === null || path === undefined) { throw new RequiredError('Required parameter path was null or undefined when calling getFilesListForSubpathOfBuild.'); } // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling getFilesListForSubpathOfBuild.'); } // Path Params const localVarPath = '/app/rest/builds/{buildLocator}/artifacts/{path}' .replace('{' + 'path' + '}', encodeURIComponent(String(path))) .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (basePath !== undefined) { requestContext.setQueryParam("basePath", ObjectSerializer.serialize(basePath, "string", "")); } if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "")); } if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } if (resolveParameters !== undefined) { requestContext.setQueryParam("resolveParameters", ObjectSerializer.serialize(resolveParameters, "boolean", "")); } if (logBuildUsage !== undefined) { requestContext.setQueryParam("logBuildUsage", ObjectSerializer.serialize(logBuildUsage, "boolean", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * List all files. * @param buildLocator * @param basePath * @param locator * @param fields * @param resolveParameters * @param logBuildUsage */ public async getFilesListOfBuild(buildLocator: string, basePath?: string, locator?: string, fields?: string, resolveParameters?: boolean, logBuildUsage?: boolean, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling getFilesListOfBuild.'); } // Path Params const localVarPath = '/app/rest/builds/{buildLocator}/artifacts' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (basePath !== undefined) { requestContext.setQueryParam("basePath", ObjectSerializer.serialize(basePath, "string", "")); } if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "")); } if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } if (resolveParameters !== undefined) { requestContext.setQueryParam("resolveParameters", ObjectSerializer.serialize(resolveParameters, "boolean", "")); } if (logBuildUsage !== undefined) { requestContext.setQueryParam("logBuildUsage", ObjectSerializer.serialize(logBuildUsage, "boolean", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get multiple builds matching the locator. * @param buildLocator * @param fields */ public async getMultipleBuilds(buildLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling getMultipleBuilds.'); } // Path Params const localVarPath = '/app/rest/builds/multiple/{buildLocator}' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get specific file zipped. * @param path * @param buildLocator * @param basePath * @param locator * @param name * @param resolveParameters * @param logBuildUsage */ public async getZippedFileOfBuild(path: string, buildLocator: string, basePath?: string, locator?: string, name?: string, resolveParameters?: boolean, logBuildUsage?: boolean, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'path' is not null or undefined if (path === null || path === undefined) { throw new RequiredError('Required parameter path was null or undefined when calling getZippedFileOfBuild.'); } // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling getZippedFileOfBuild.'); } // Path Params const localVarPath = '/app/rest/builds/{buildLocator}/artifacts/archived{path}' .replace('{' + 'path' + '}', encodeURIComponent(String(path))) .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (basePath !== undefined) { requestContext.setQueryParam("basePath", ObjectSerializer.serialize(basePath, "string", "")); } if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "")); } if (name !== undefined) { requestContext.setQueryParam("name", ObjectSerializer.serialize(name, "string", "")); } if (resolveParameters !== undefined) { requestContext.setQueryParam("resolveParameters", ObjectSerializer.serialize(resolveParameters, "boolean", "")); } if (logBuildUsage !== undefined) { requestContext.setQueryParam("logBuildUsage", ObjectSerializer.serialize(logBuildUsage, "boolean", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Starts the queued build as an agent-less build and returns the corresponding running build. * @param buildLocator * @param fields * @param body */ public async markBuildAsRunning(buildLocator: string, fields?: string, body?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling markBuildAsRunning.'); } // Path Params const localVarPath = '/app/rest/builds/{buildLocator}/runningData' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "text/plain" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "string", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Pin multiple matching builds. * @param buildLocator * @param fields * @param body */ public async pinMultipleBuilds(buildLocator: string, fields?: string, body?: PinInfo, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling pinMultipleBuilds.'); } // Path Params const localVarPath = '/app/rest/builds/multiple/{buildLocator}/pinInfo' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "PinInfo", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Remove tags from multiple matching builds. * @param buildLocator * @param fields * @param body */ public async removeMultipleBuildTags(buildLocator: string, fields?: string, body?: Tags, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling removeMultipleBuildTags.'); } // Path Params const localVarPath = '/app/rest/builds/multiple/{buildLocator}/tags' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Tags", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Remove build parameters from the matching build. * @param buildLocator */ public async resetBuildFinishProperties(buildLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling resetBuildFinishProperties.'); } // Path Params const localVarPath = '/app/rest/builds/{buildLocator}/caches/finishProperties' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update the comment on the matching build. * @param buildLocator * @param body */ public async setBuildComment(buildLocator: string, body?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling setBuildComment.'); } // Path Params const localVarPath = '/app/rest/builds/{buildLocator}/comment' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "text/plain" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "string", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Marks the running build as finished by passing agent the current time of the build to finish. * @param buildLocator * @param body */ public async setBuildFinishDate(buildLocator: string, body?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling setBuildFinishDate.'); } // Path Params const localVarPath = '/app/rest/builds/{buildLocator}/finishDate' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "text/plain" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "string", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update the number of the matching build. * @param buildLocator * @param body */ public async setBuildNumber(buildLocator: string, body?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling setBuildNumber.'); } // Path Params const localVarPath = '/app/rest/builds/{buildLocator}/number' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "text/plain" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "string", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update the pin info of the matching build. * @param buildLocator * @param fields * @param body */ public async setBuildPinInfo(buildLocator: string, fields?: string, body?: PinInfo, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling setBuildPinInfo.'); } // Path Params const localVarPath = '/app/rest/builds/{buildLocator}/pinInfo' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "PinInfo", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update the build status of the matching build. * @param buildLocator * @param body */ public async setBuildStatusText(buildLocator: string, body?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling setBuildStatusText.'); } // Path Params const localVarPath = '/app/rest/builds/{buildLocator}/statusText' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "text/plain" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "string", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update tags of the matching build. * @param buildLocator * @param locator * @param fields * @param body */ public async setBuildTags(buildLocator: string, locator?: string, fields?: string, body?: Tags, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling setBuildTags.'); } // Path Params const localVarPath = '/app/rest/builds/{buildLocator}/tags' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "TagLocator")); } if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Tags", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Marks the running build as finished by passing agent the current time of the build to finish. * @param buildLocator */ public async setFinishedTime(buildLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling setFinishedTime.'); } // Path Params const localVarPath = '/app/rest/builds/{buildLocator}/finish' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update comments in multiple matching builds. * @param buildLocator * @param fields * @param body */ public async setMultipleBuildComments(buildLocator: string, fields?: string, body?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling setMultipleBuildComments.'); } // Path Params const localVarPath = '/app/rest/builds/multiple/{buildLocator}/comment' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "text/plain" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "string", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } } export class BuildApiResponseProcessor { /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to addBuildVcsLabel * @throws ApiException if the response code was not in [200, 299] */ public async addBuildVcsLabel(response: ResponseContext): Promise<VcsLabels > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: VcsLabels = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "VcsLabels", "" ) as VcsLabels; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: VcsLabels = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "VcsLabels", "" ) as VcsLabels; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to addLogMessageToBuild * @throws ApiException if the response code was not in [200, 299] */ public async addLogMessageToBuild(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to addProblemToBuild * @throws ApiException if the response code was not in [200, 299] */ public async addProblemToBuild(response: ResponseContext): Promise<ProblemOccurrence > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: ProblemOccurrence = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "ProblemOccurrence", "" ) as ProblemOccurrence; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: ProblemOccurrence = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "ProblemOccurrence", "" ) as ProblemOccurrence; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to addTagsToBuild * @throws ApiException if the response code was not in [200, 299] */ public async addTagsToBuild(response: ResponseContext): Promise<Tags > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Tags = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Tags", "" ) as Tags; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Tags = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Tags", "" ) as Tags; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to addTagsToMultipleBuilds * @throws ApiException if the response code was not in [200, 299] */ public async addTagsToMultipleBuilds(response: ResponseContext): Promise<MultipleOperationResult > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: MultipleOperationResult = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "MultipleOperationResult", "" ) as MultipleOperationResult; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: MultipleOperationResult = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "MultipleOperationResult", "" ) as MultipleOperationResult; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to deleteBuild * @throws ApiException if the response code was not in [200, 299] */ public async deleteBuild(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to deleteBuildComment * @throws ApiException if the response code was not in [200, 299] */ public async deleteBuildComment(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to deleteMultipleBuildComments * @throws ApiException if the response code was not in [200, 299] */ public async deleteMultipleBuildComments(response: ResponseContext): Promise<MultipleOperationResult > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: MultipleOperationResult = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "MultipleOperationResult", "" ) as MultipleOperationResult; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: MultipleOperationResult = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "MultipleOperationResult", "" ) as MultipleOperationResult; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to deleteMultipleBuilds * @throws ApiException if the response code was not in [200, 299] */ public async deleteMultipleBuilds(response: ResponseContext): Promise<MultipleOperationResult > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: MultipleOperationResult = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "MultipleOperationResult", "" ) as MultipleOperationResult; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: MultipleOperationResult = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "MultipleOperationResult", "" ) as MultipleOperationResult; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to downloadFileOfBuild * @throws ApiException if the response code was not in [200, 299] */ public async downloadFileOfBuild(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAggregatedBuildStatus * @throws ApiException if the response code was not in [200, 299] */ public async getAggregatedBuildStatus(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAggregatedBuildStatusIcon * @throws ApiException if the response code was not in [200, 299] */ public async getAggregatedBuildStatusIcon(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAllBuilds * @throws ApiException if the response code was not in [200, 299] */ public async getAllBuilds(response: ResponseContext): Promise<Builds > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Builds = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Builds", "" ) as Builds; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Builds = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Builds", "" ) as Builds; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getArtifactDependencyChanges * @throws ApiException if the response code was not in [200, 299] */ public async getArtifactDependencyChanges(response: ResponseContext): Promise<BuildChanges > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: BuildChanges = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "BuildChanges", "" ) as BuildChanges; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: BuildChanges = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "BuildChanges", "" ) as BuildChanges; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getArtifactsDirectory * @throws ApiException if the response code was not in [200, 299] */ public async getArtifactsDirectory(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuild * @throws ApiException if the response code was not in [200, 299] */ public async getBuild(response: ResponseContext): Promise<Build > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Build = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Build", "" ) as Build; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Build = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Build", "" ) as Build; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuildActualParameters * @throws ApiException if the response code was not in [200, 299] */ public async getBuildActualParameters(response: ResponseContext): Promise<Properties > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Properties = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Properties", "" ) as Properties; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Properties = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Properties", "" ) as Properties; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuildField * @throws ApiException if the response code was not in [200, 299] */ public async getBuildField(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuildFinishDate * @throws ApiException if the response code was not in [200, 299] */ public async getBuildFinishDate(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuildNumber * @throws ApiException if the response code was not in [200, 299] */ public async getBuildNumber(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuildPinInfo * @throws ApiException if the response code was not in [200, 299] */ public async getBuildPinInfo(response: ResponseContext): Promise<PinInfo > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: PinInfo = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "PinInfo", "" ) as PinInfo; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: PinInfo = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "PinInfo", "" ) as PinInfo; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuildProblems * @throws ApiException if the response code was not in [200, 299] */ public async getBuildProblems(response: ResponseContext): Promise<ProblemOccurrences > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: ProblemOccurrences = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "ProblemOccurrences", "" ) as ProblemOccurrences; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: ProblemOccurrences = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "ProblemOccurrences", "" ) as ProblemOccurrences; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuildRelatedIssues * @throws ApiException if the response code was not in [200, 299] */ public async getBuildRelatedIssues(response: ResponseContext): Promise<IssuesUsages > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: IssuesUsages = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "IssuesUsages", "" ) as IssuesUsages; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: IssuesUsages = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "IssuesUsages", "" ) as IssuesUsages; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuildResolved * @throws ApiException if the response code was not in [200, 299] */ public async getBuildResolved(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuildResultingProperties * @throws ApiException if the response code was not in [200, 299] */ public async getBuildResultingProperties(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuildSourceFile * @throws ApiException if the response code was not in [200, 299] */ public async getBuildSourceFile(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuildStatisticValue * @throws ApiException if the response code was not in [200, 299] */ public async getBuildStatisticValue(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuildStatisticValues * @throws ApiException if the response code was not in [200, 299] */ public async getBuildStatisticValues(response: ResponseContext): Promise<Properties > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Properties = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Properties", "" ) as Properties; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Properties = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Properties", "" ) as Properties; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuildStatusIcon * @throws ApiException if the response code was not in [200, 299] */ public async getBuildStatusIcon(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuildStatusText * @throws ApiException if the response code was not in [200, 299] */ public async getBuildStatusText(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuildTags * @throws ApiException if the response code was not in [200, 299] */ public async getBuildTags(response: ResponseContext): Promise<Tags > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Tags = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Tags", "" ) as Tags; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Tags = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Tags", "" ) as Tags; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuildTestOccurrences * @throws ApiException if the response code was not in [200, 299] */ public async getBuildTestOccurrences(response: ResponseContext): Promise<TestOccurrences > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: TestOccurrences = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "TestOccurrences", "" ) as TestOccurrences; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: TestOccurrences = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "TestOccurrences", "" ) as TestOccurrences; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuildVcsLabels * @throws ApiException if the response code was not in [200, 299] */ public async getBuildVcsLabels(response: ResponseContext): Promise<VcsLabels > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: VcsLabels = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "VcsLabels", "" ) as VcsLabels; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: VcsLabels = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "VcsLabels", "" ) as VcsLabels; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getCanceledInfo * @throws ApiException if the response code was not in [200, 299] */ public async getCanceledInfo(response: ResponseContext): Promise<Comment > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Comment = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Comment", "" ) as Comment; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Comment = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Comment", "" ) as Comment; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getFileMetadataOfBuild * @throws ApiException if the response code was not in [200, 299] */ public async getFileMetadataOfBuild(response: ResponseContext): Promise<any > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: any = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "any", "" ) as any; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: any = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "any", "" ) as any; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getFilesListForSubpathOfBuild * @throws ApiException if the response code was not in [200, 299] */ public async getFilesListForSubpathOfBuild(response: ResponseContext): Promise<Files > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Files = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Files", "" ) as Files; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Files = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Files", "" ) as Files; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getFilesListOfBuild * @throws ApiException if the response code was not in [200, 299] */ public async getFilesListOfBuild(response: ResponseContext): Promise<Files > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Files = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Files", "" ) as Files; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Files = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Files", "" ) as Files; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getMultipleBuilds * @throws ApiException if the response code was not in [200, 299] */ public async getMultipleBuilds(response: ResponseContext): Promise<Builds > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Builds = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Builds", "" ) as Builds; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Builds = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Builds", "" ) as Builds; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getZippedFileOfBuild * @throws ApiException if the response code was not in [200, 299] */ public async getZippedFileOfBuild(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to markBuildAsRunning * @throws ApiException if the response code was not in [200, 299] */ public async markBuildAsRunning(response: ResponseContext): Promise<Build > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Build = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Build", "" ) as Build; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Build = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Build", "" ) as Build; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to pinMultipleBuilds * @throws ApiException if the response code was not in [200, 299] */ public async pinMultipleBuilds(response: ResponseContext): Promise<MultipleOperationResult > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: MultipleOperationResult = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "MultipleOperationResult", "" ) as MultipleOperationResult; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: MultipleOperationResult = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "MultipleOperationResult", "" ) as MultipleOperationResult; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to removeMultipleBuildTags * @throws ApiException if the response code was not in [200, 299] */ public async removeMultipleBuildTags(response: ResponseContext): Promise<MultipleOperationResult > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: MultipleOperationResult = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "MultipleOperationResult", "" ) as MultipleOperationResult; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: MultipleOperationResult = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "MultipleOperationResult", "" ) as MultipleOperationResult; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to resetBuildFinishProperties * @throws ApiException if the response code was not in [200, 299] */ public async resetBuildFinishProperties(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setBuildComment * @throws ApiException if the response code was not in [200, 299] */ public async setBuildComment(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setBuildFinishDate * @throws ApiException if the response code was not in [200, 299] */ public async setBuildFinishDate(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setBuildNumber * @throws ApiException if the response code was not in [200, 299] */ public async setBuildNumber(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setBuildPinInfo * @throws ApiException if the response code was not in [200, 299] */ public async setBuildPinInfo(response: ResponseContext): Promise<PinInfo > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: PinInfo = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "PinInfo", "" ) as PinInfo; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: PinInfo = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "PinInfo", "" ) as PinInfo; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setBuildStatusText * @throws ApiException if the response code was not in [200, 299] */ public async setBuildStatusText(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setBuildTags * @throws ApiException if the response code was not in [200, 299] */ public async setBuildTags(response: ResponseContext): Promise<Tags > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Tags = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Tags", "" ) as Tags; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Tags = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Tags", "" ) as Tags; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setFinishedTime * @throws ApiException if the response code was not in [200, 299] */ public async setFinishedTime(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setMultipleBuildComments * @throws ApiException if the response code was not in [200, 299] */ public async setMultipleBuildComments(response: ResponseContext): Promise<MultipleOperationResult > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: MultipleOperationResult = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "MultipleOperationResult", "" ) as MultipleOperationResult; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: MultipleOperationResult = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "MultipleOperationResult", "" ) as MultipleOperationResult; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } } <file_sep>/ts-schema/schema/rest-api/deno/models/Change.ts /** * TeamCity REST API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * OpenAPI spec version: 2018.1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { Changes } from './Changes.ts'; import { FileChanges } from './FileChanges.ts'; import { Items } from './Items.ts'; import { Properties } from './Properties.ts'; import { User } from './User.ts'; import { VcsRootInstance } from './VcsRootInstance.ts'; import { HttpFile } from '../http/http.ts'; export class Change { 'id'?: number; 'version'?: string; 'internalVersion'?: string; 'username'?: string; 'date'?: string; 'registrationDate'?: string; 'personal'?: boolean; 'href'?: string; 'webUrl'?: string; 'comment'?: string; 'user'?: User; 'files'?: FileChanges; 'vcsRootInstance'?: VcsRootInstance; 'parentChanges'?: Changes; 'parentRevisions'?: Items; 'attributes'?: Properties; 'storesProjectSettings'?: boolean; 'locator'?: string; static readonly discriminator: string | undefined = undefined; static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [ { "name": "id", "baseName": "id", "type": "number", "format": "int64" }, { "name": "version", "baseName": "version", "type": "string", "format": "" }, { "name": "internalVersion", "baseName": "internalVersion", "type": "string", "format": "" }, { "name": "username", "baseName": "username", "type": "string", "format": "" }, { "name": "date", "baseName": "date", "type": "string", "format": "" }, { "name": "registrationDate", "baseName": "registrationDate", "type": "string", "format": "" }, { "name": "personal", "baseName": "personal", "type": "boolean", "format": "" }, { "name": "href", "baseName": "href", "type": "string", "format": "" }, { "name": "webUrl", "baseName": "webUrl", "type": "string", "format": "" }, { "name": "comment", "baseName": "comment", "type": "string", "format": "" }, { "name": "user", "baseName": "user", "type": "User", "format": "" }, { "name": "files", "baseName": "files", "type": "FileChanges", "format": "" }, { "name": "vcsRootInstance", "baseName": "vcsRootInstance", "type": "VcsRootInstance", "format": "" }, { "name": "parentChanges", "baseName": "parentChanges", "type": "Changes", "format": "" }, { "name": "parentRevisions", "baseName": "parentRevisions", "type": "Items", "format": "" }, { "name": "attributes", "baseName": "attributes", "type": "Properties", "format": "" }, { "name": "storesProjectSettings", "baseName": "storesProjectSettings", "type": "boolean", "format": "" }, { "name": "locator", "baseName": "locator", "type": "string", "format": "" } ]; static getAttributeTypeMap() { return Change.attributeTypeMap; } public constructor() { } } <file_sep>/ts-schema/schema/json/mod.ts export * from "./build_type.ts"; export * from "./parameter.ts"; export * from "./project_cleanup.ts"; export * from "./project_extension.ts"; export * from "./project.ts"; export * from "./vcs_root.ts"; <file_sep>/ts-schema/schema/rest-api/deno/apis/AgentPoolApi.ts // TODO: better import syntax? import { BaseAPIRequestFactory, RequiredError } from './baseapi.ts'; import {Configuration} from '../configuration.ts'; import { RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http.ts'; import {ObjectSerializer} from '../models/ObjectSerializer.ts'; import {ApiException} from './exception.ts'; import {isCodeInRange} from '../util.ts'; import { Agent } from '../models/Agent.ts'; import { AgentPool } from '../models/AgentPool.ts'; import { AgentPools } from '../models/AgentPools.ts'; import { Agents } from '../models/Agents.ts'; import { Project } from '../models/Project.ts'; import { Projects } from '../models/Projects.ts'; /** * no description */ export class AgentPoolApiRequestFactory extends BaseAPIRequestFactory { /** * Assign the agent to the matching agent pool. * @param agentPoolLocator * @param fields * @param body */ public async addAgentToAgentPool(agentPoolLocator: string, fields?: string, body?: Agent, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'agentPoolLocator' is not null or undefined if (agentPoolLocator === null || agentPoolLocator === undefined) { throw new RequiredError('Required parameter agentPoolLocator was null or undefined when calling addAgentToAgentPool.'); } // Path Params const localVarPath = '/app/rest/agentPools/{agentPoolLocator}/agents' .replace('{' + 'agentPoolLocator' + '}', encodeURIComponent(String(agentPoolLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Agent", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Assign the project to the matching agent pool. * @param agentPoolLocator * @param body */ public async addProjectToAgentPool(agentPoolLocator: string, body?: Project, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'agentPoolLocator' is not null or undefined if (agentPoolLocator === null || agentPoolLocator === undefined) { throw new RequiredError('Required parameter agentPoolLocator was null or undefined when calling addProjectToAgentPool.'); } // Path Params const localVarPath = '/app/rest/agentPools/{agentPoolLocator}/projects' .replace('{' + 'agentPoolLocator' + '}', encodeURIComponent(String(agentPoolLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Project", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Create a new agent pool. * @param body */ public async createAgentPool(body?: AgentPool, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/agentPools'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "AgentPool", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Delete the agent pool matching the locator. * @param agentPoolLocator */ public async deleteAgentPool(agentPoolLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'agentPoolLocator' is not null or undefined if (agentPoolLocator === null || agentPoolLocator === undefined) { throw new RequiredError('Required parameter agentPoolLocator was null or undefined when calling deleteAgentPool.'); } // Path Params const localVarPath = '/app/rest/agentPools/{agentPoolLocator}' .replace('{' + 'agentPoolLocator' + '}', encodeURIComponent(String(agentPoolLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Unassign all projects from the matching agent pool. * @param agentPoolLocator */ public async deleteAllProjectsFromAgentPool(agentPoolLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'agentPoolLocator' is not null or undefined if (agentPoolLocator === null || agentPoolLocator === undefined) { throw new RequiredError('Required parameter agentPoolLocator was null or undefined when calling deleteAllProjectsFromAgentPool.'); } // Path Params const localVarPath = '/app/rest/agentPools/{agentPoolLocator}/projects' .replace('{' + 'agentPoolLocator' + '}', encodeURIComponent(String(agentPoolLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Unassign the project from the matching agent pool. * @param agentPoolLocator * @param projectLocator */ public async deleteProjectFromAgentPool(agentPoolLocator: string, projectLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'agentPoolLocator' is not null or undefined if (agentPoolLocator === null || agentPoolLocator === undefined) { throw new RequiredError('Required parameter agentPoolLocator was null or undefined when calling deleteProjectFromAgentPool.'); } // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling deleteProjectFromAgentPool.'); } // Path Params const localVarPath = '/app/rest/agentPools/{agentPoolLocator}/projects/{projectLocator}' .replace('{' + 'agentPoolLocator' + '}', encodeURIComponent(String(agentPoolLocator))) .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get the agent pool matching the locator. * @param agentPoolLocator * @param fields */ public async getAgentPoolOfAgentPool(agentPoolLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'agentPoolLocator' is not null or undefined if (agentPoolLocator === null || agentPoolLocator === undefined) { throw new RequiredError('Required parameter agentPoolLocator was null or undefined when calling getAgentPoolOfAgentPool.'); } // Path Params const localVarPath = '/app/rest/agentPools/{agentPoolLocator}' .replace('{' + 'agentPoolLocator' + '}', encodeURIComponent(String(agentPoolLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all agent pools. * @param locator * @param fields */ public async getAllAgentPools(locator?: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/agentPools'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "AgentPoolLocator")); } if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get the agent of the matching agent pool. * @param agentPoolLocator * @param locator * @param fields */ public async getAllAgentsFromAgentPool(agentPoolLocator: string, locator?: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'agentPoolLocator' is not null or undefined if (agentPoolLocator === null || agentPoolLocator === undefined) { throw new RequiredError('Required parameter agentPoolLocator was null or undefined when calling getAllAgentsFromAgentPool.'); } // Path Params const localVarPath = '/app/rest/agentPools/{agentPoolLocator}/agents' .replace('{' + 'agentPoolLocator' + '}', encodeURIComponent(String(agentPoolLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "AgentLocator")); } if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all projects of the matching agent pool. * @param agentPoolLocator * @param fields */ public async getAllProjectsFromAgentPool(agentPoolLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'agentPoolLocator' is not null or undefined if (agentPoolLocator === null || agentPoolLocator === undefined) { throw new RequiredError('Required parameter agentPoolLocator was null or undefined when calling getAllProjectsFromAgentPool.'); } // Path Params const localVarPath = '/app/rest/agentPools/{agentPoolLocator}/projects' .replace('{' + 'agentPoolLocator' + '}', encodeURIComponent(String(agentPoolLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get a field of the matching agent pool. * @param agentPoolLocator * @param field */ public async getFieldFromAgentPool(agentPoolLocator: string, field: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'agentPoolLocator' is not null or undefined if (agentPoolLocator === null || agentPoolLocator === undefined) { throw new RequiredError('Required parameter agentPoolLocator was null or undefined when calling getFieldFromAgentPool.'); } // verify required parameter 'field' is not null or undefined if (field === null || field === undefined) { throw new RequiredError('Required parameter field was null or undefined when calling getFieldFromAgentPool.'); } // Path Params const localVarPath = '/app/rest/agentPools/{agentPoolLocator}/{field}' .replace('{' + 'agentPoolLocator' + '}', encodeURIComponent(String(agentPoolLocator))) .replace('{' + 'field' + '}', encodeURIComponent(String(field))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update a field of the matching agent pool. * @param agentPoolLocator * @param field * @param body */ public async setAgentPoolField(agentPoolLocator: string, field: string, body?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'agentPoolLocator' is not null or undefined if (agentPoolLocator === null || agentPoolLocator === undefined) { throw new RequiredError('Required parameter agentPoolLocator was null or undefined when calling setAgentPoolField.'); } // verify required parameter 'field' is not null or undefined if (field === null || field === undefined) { throw new RequiredError('Required parameter field was null or undefined when calling setAgentPoolField.'); } // Path Params const localVarPath = '/app/rest/agentPools/{agentPoolLocator}/{field}' .replace('{' + 'agentPoolLocator' + '}', encodeURIComponent(String(agentPoolLocator))) .replace('{' + 'field' + '}', encodeURIComponent(String(field))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "text/plain" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "string", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update projects of the matching agent pool. * @param agentPoolLocator * @param body */ public async setAgentPoolProjects(agentPoolLocator: string, body?: Projects, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'agentPoolLocator' is not null or undefined if (agentPoolLocator === null || agentPoolLocator === undefined) { throw new RequiredError('Required parameter agentPoolLocator was null or undefined when calling setAgentPoolProjects.'); } // Path Params const localVarPath = '/app/rest/agentPools/{agentPoolLocator}/projects' .replace('{' + 'agentPoolLocator' + '}', encodeURIComponent(String(agentPoolLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Projects", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } } export class AgentPoolApiResponseProcessor { /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to addAgentToAgentPool * @throws ApiException if the response code was not in [200, 299] */ public async addAgentToAgentPool(response: ResponseContext): Promise<Agent > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Agent = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Agent", "" ) as Agent; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Agent = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Agent", "" ) as Agent; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to addProjectToAgentPool * @throws ApiException if the response code was not in [200, 299] */ public async addProjectToAgentPool(response: ResponseContext): Promise<Project > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Project = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Project", "" ) as Project; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Project = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Project", "" ) as Project; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to createAgentPool * @throws ApiException if the response code was not in [200, 299] */ public async createAgentPool(response: ResponseContext): Promise<AgentPool > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: AgentPool = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "AgentPool", "" ) as AgentPool; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: AgentPool = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "AgentPool", "" ) as AgentPool; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to deleteAgentPool * @throws ApiException if the response code was not in [200, 299] */ public async deleteAgentPool(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to deleteAllProjectsFromAgentPool * @throws ApiException if the response code was not in [200, 299] */ public async deleteAllProjectsFromAgentPool(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to deleteProjectFromAgentPool * @throws ApiException if the response code was not in [200, 299] */ public async deleteProjectFromAgentPool(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAgentPoolOfAgentPool * @throws ApiException if the response code was not in [200, 299] */ public async getAgentPoolOfAgentPool(response: ResponseContext): Promise<AgentPool > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: AgentPool = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "AgentPool", "" ) as AgentPool; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: AgentPool = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "AgentPool", "" ) as AgentPool; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAllAgentPools * @throws ApiException if the response code was not in [200, 299] */ public async getAllAgentPools(response: ResponseContext): Promise<AgentPools > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: AgentPools = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "AgentPools", "" ) as AgentPools; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: AgentPools = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "AgentPools", "" ) as AgentPools; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAllAgentsFromAgentPool * @throws ApiException if the response code was not in [200, 299] */ public async getAllAgentsFromAgentPool(response: ResponseContext): Promise<Agents > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Agents = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Agents", "" ) as Agents; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Agents = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Agents", "" ) as Agents; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAllProjectsFromAgentPool * @throws ApiException if the response code was not in [200, 299] */ public async getAllProjectsFromAgentPool(response: ResponseContext): Promise<Projects > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Projects = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Projects", "" ) as Projects; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Projects = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Projects", "" ) as Projects; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getFieldFromAgentPool * @throws ApiException if the response code was not in [200, 299] */ public async getFieldFromAgentPool(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setAgentPoolField * @throws ApiException if the response code was not in [200, 299] */ public async setAgentPoolField(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setAgentPoolProjects * @throws ApiException if the response code was not in [200, 299] */ public async setAgentPoolProjects(response: ResponseContext): Promise<Projects > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Projects = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Projects", "" ) as Projects; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Projects = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Projects", "" ) as Projects; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } } <file_sep>/ts-schema/schema/rest-api/deno/apis/AgentApi.ts // TODO: better import syntax? import { BaseAPIRequestFactory, RequiredError } from './baseapi.ts'; import {Configuration} from '../configuration.ts'; import { RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http.ts'; import {ObjectSerializer} from '../models/ObjectSerializer.ts'; import {ApiException} from './exception.ts'; import {isCodeInRange} from '../util.ts'; import { Agent } from '../models/Agent.ts'; import { AgentPool } from '../models/AgentPool.ts'; import { Agents } from '../models/Agents.ts'; import { AuthorizedInfo } from '../models/AuthorizedInfo.ts'; import { BuildTypes } from '../models/BuildTypes.ts'; import { Compatibilities } from '../models/Compatibilities.ts'; import { CompatibilityPolicy } from '../models/CompatibilityPolicy.ts'; import { EnabledInfo } from '../models/EnabledInfo.ts'; /** * no description */ export class AgentApiRequestFactory extends BaseAPIRequestFactory { /** * Delete an inactive agent. * @param agentLocator */ public async deleteAgent(agentLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'agentLocator' is not null or undefined if (agentLocator === null || agentLocator === undefined) { throw new RequiredError('Required parameter agentLocator was null or undefined when calling deleteAgent.'); } // Path Params const localVarPath = '/app/rest/agents/{agentLocator}' .replace('{' + 'agentLocator' + '}', encodeURIComponent(String(agentLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get agent matching the locator. * @param agentLocator * @param fields */ public async getAgent(agentLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'agentLocator' is not null or undefined if (agentLocator === null || agentLocator === undefined) { throw new RequiredError('Required parameter agentLocator was null or undefined when calling getAgent.'); } // Path Params const localVarPath = '/app/rest/agents/{agentLocator}' .replace('{' + 'agentLocator' + '}', encodeURIComponent(String(agentLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get a field of the matching agent. * @param agentLocator * @param field */ public async getAgentField(agentLocator: string, field: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'agentLocator' is not null or undefined if (agentLocator === null || agentLocator === undefined) { throw new RequiredError('Required parameter agentLocator was null or undefined when calling getAgentField.'); } // verify required parameter 'field' is not null or undefined if (field === null || field === undefined) { throw new RequiredError('Required parameter field was null or undefined when calling getAgentField.'); } // Path Params const localVarPath = '/app/rest/agents/{agentLocator}/{field}' .replace('{' + 'agentLocator' + '}', encodeURIComponent(String(agentLocator))) .replace('{' + 'field' + '}', encodeURIComponent(String(field))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get the agent pool of the matching agent. * @param agentLocator * @param fields */ public async getAgentPool(agentLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'agentLocator' is not null or undefined if (agentLocator === null || agentLocator === undefined) { throw new RequiredError('Required parameter agentLocator was null or undefined when calling getAgentPool.'); } // Path Params const localVarPath = '/app/rest/agents/{agentLocator}/pool' .replace('{' + 'agentLocator' + '}', encodeURIComponent(String(agentLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all known agents. * @param locator * @param fields */ public async getAllAgents(locator?: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/agents'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "AgentLocator")); } if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get the authorization info of the matching agent. * @param agentLocator * @param fields */ public async getAuthorizedInfo(agentLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'agentLocator' is not null or undefined if (agentLocator === null || agentLocator === undefined) { throw new RequiredError('Required parameter agentLocator was null or undefined when calling getAuthorizedInfo.'); } // Path Params const localVarPath = '/app/rest/agents/{agentLocator}/authorizedInfo' .replace('{' + 'agentLocator' + '}', encodeURIComponent(String(agentLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get the build configuration run policy of the matching agent. * @param agentLocator * @param fields */ public async getBuildConfigurationRunPolicy(agentLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'agentLocator' is not null or undefined if (agentLocator === null || agentLocator === undefined) { throw new RequiredError('Required parameter agentLocator was null or undefined when calling getBuildConfigurationRunPolicy.'); } // Path Params const localVarPath = '/app/rest/agents/{agentLocator}/compatibilityPolicy' .replace('{' + 'agentLocator' + '}', encodeURIComponent(String(agentLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get build types compatible with the matching agent. * @param agentLocator * @param fields */ public async getCompatibleBuildTypes(agentLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'agentLocator' is not null or undefined if (agentLocator === null || agentLocator === undefined) { throw new RequiredError('Required parameter agentLocator was null or undefined when calling getCompatibleBuildTypes.'); } // Path Params const localVarPath = '/app/rest/agents/{agentLocator}/compatibleBuildTypes' .replace('{' + 'agentLocator' + '}', encodeURIComponent(String(agentLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Check if the matching agent is enabled. * @param agentLocator * @param fields */ public async getEnabledInfo(agentLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'agentLocator' is not null or undefined if (agentLocator === null || agentLocator === undefined) { throw new RequiredError('Required parameter agentLocator was null or undefined when calling getEnabledInfo.'); } // Path Params const localVarPath = '/app/rest/agents/{agentLocator}/enabledInfo' .replace('{' + 'agentLocator' + '}', encodeURIComponent(String(agentLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get build types incompatible with the matching agent. * @param agentLocator * @param fields */ public async getIncompatibleBuildTypes(agentLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'agentLocator' is not null or undefined if (agentLocator === null || agentLocator === undefined) { throw new RequiredError('Required parameter agentLocator was null or undefined when calling getIncompatibleBuildTypes.'); } // Path Params const localVarPath = '/app/rest/agents/{agentLocator}/incompatibleBuildTypes' .replace('{' + 'agentLocator' + '}', encodeURIComponent(String(agentLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update a field of the matching agent. * @param agentLocator * @param field * @param body */ public async setAgentField(agentLocator: string, field: string, body?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'agentLocator' is not null or undefined if (agentLocator === null || agentLocator === undefined) { throw new RequiredError('Required parameter agentLocator was null or undefined when calling setAgentField.'); } // verify required parameter 'field' is not null or undefined if (field === null || field === undefined) { throw new RequiredError('Required parameter field was null or undefined when calling setAgentField.'); } // Path Params const localVarPath = '/app/rest/agents/{agentLocator}/{field}' .replace('{' + 'agentLocator' + '}', encodeURIComponent(String(agentLocator))) .replace('{' + 'field' + '}', encodeURIComponent(String(field))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "text/plain" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "string", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Assign the matching agent to the specified agent pool. * @param agentLocator * @param fields * @param body */ public async setAgentPool(agentLocator: string, fields?: string, body?: AgentPool, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'agentLocator' is not null or undefined if (agentLocator === null || agentLocator === undefined) { throw new RequiredError('Required parameter agentLocator was null or undefined when calling setAgentPool.'); } // Path Params const localVarPath = '/app/rest/agents/{agentLocator}/pool' .replace('{' + 'agentLocator' + '}', encodeURIComponent(String(agentLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "AgentPool", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update the authorization info of the matching agent. * @param agentLocator * @param fields * @param body */ public async setAuthorizedInfo(agentLocator: string, fields?: string, body?: AuthorizedInfo, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'agentLocator' is not null or undefined if (agentLocator === null || agentLocator === undefined) { throw new RequiredError('Required parameter agentLocator was null or undefined when calling setAuthorizedInfo.'); } // Path Params const localVarPath = '/app/rest/agents/{agentLocator}/authorizedInfo' .replace('{' + 'agentLocator' + '}', encodeURIComponent(String(agentLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "AuthorizedInfo", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update build configuration run policy of agent matching locator. * @param agentLocator * @param fields * @param body */ public async setBuildConfigurationRunPolicy(agentLocator: string, fields?: string, body?: CompatibilityPolicy, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'agentLocator' is not null or undefined if (agentLocator === null || agentLocator === undefined) { throw new RequiredError('Required parameter agentLocator was null or undefined when calling setBuildConfigurationRunPolicy.'); } // Path Params const localVarPath = '/app/rest/agents/{agentLocator}/compatibilityPolicy' .replace('{' + 'agentLocator' + '}', encodeURIComponent(String(agentLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "CompatibilityPolicy", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update the enablement status of the matching agent. * @param agentLocator * @param fields * @param body */ public async setEnabledInfo(agentLocator: string, fields?: string, body?: EnabledInfo, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'agentLocator' is not null or undefined if (agentLocator === null || agentLocator === undefined) { throw new RequiredError('Required parameter agentLocator was null or undefined when calling setEnabledInfo.'); } // Path Params const localVarPath = '/app/rest/agents/{agentLocator}/enabledInfo' .replace('{' + 'agentLocator' + '}', encodeURIComponent(String(agentLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "EnabledInfo", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } } export class AgentApiResponseProcessor { /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to deleteAgent * @throws ApiException if the response code was not in [200, 299] */ public async deleteAgent(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAgent * @throws ApiException if the response code was not in [200, 299] */ public async getAgent(response: ResponseContext): Promise<Agent > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Agent = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Agent", "" ) as Agent; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Agent = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Agent", "" ) as Agent; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAgentField * @throws ApiException if the response code was not in [200, 299] */ public async getAgentField(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAgentPool * @throws ApiException if the response code was not in [200, 299] */ public async getAgentPool(response: ResponseContext): Promise<AgentPool > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: AgentPool = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "AgentPool", "" ) as AgentPool; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: AgentPool = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "AgentPool", "" ) as AgentPool; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAllAgents * @throws ApiException if the response code was not in [200, 299] */ public async getAllAgents(response: ResponseContext): Promise<Agents > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Agents = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Agents", "" ) as Agents; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Agents = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Agents", "" ) as Agents; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAuthorizedInfo * @throws ApiException if the response code was not in [200, 299] */ public async getAuthorizedInfo(response: ResponseContext): Promise<AuthorizedInfo > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: AuthorizedInfo = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "AuthorizedInfo", "" ) as AuthorizedInfo; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: AuthorizedInfo = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "AuthorizedInfo", "" ) as AuthorizedInfo; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuildConfigurationRunPolicy * @throws ApiException if the response code was not in [200, 299] */ public async getBuildConfigurationRunPolicy(response: ResponseContext): Promise<CompatibilityPolicy > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: CompatibilityPolicy = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "CompatibilityPolicy", "" ) as CompatibilityPolicy; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: CompatibilityPolicy = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "CompatibilityPolicy", "" ) as CompatibilityPolicy; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getCompatibleBuildTypes * @throws ApiException if the response code was not in [200, 299] */ public async getCompatibleBuildTypes(response: ResponseContext): Promise<BuildTypes > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: BuildTypes = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "BuildTypes", "" ) as BuildTypes; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: BuildTypes = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "BuildTypes", "" ) as BuildTypes; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getEnabledInfo * @throws ApiException if the response code was not in [200, 299] */ public async getEnabledInfo(response: ResponseContext): Promise<EnabledInfo > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: EnabledInfo = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "EnabledInfo", "" ) as EnabledInfo; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: EnabledInfo = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "EnabledInfo", "" ) as EnabledInfo; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getIncompatibleBuildTypes * @throws ApiException if the response code was not in [200, 299] */ public async getIncompatibleBuildTypes(response: ResponseContext): Promise<Compatibilities > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Compatibilities = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Compatibilities", "" ) as Compatibilities; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Compatibilities = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Compatibilities", "" ) as Compatibilities; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setAgentField * @throws ApiException if the response code was not in [200, 299] */ public async setAgentField(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setAgentPool * @throws ApiException if the response code was not in [200, 299] */ public async setAgentPool(response: ResponseContext): Promise<AgentPool > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: AgentPool = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "AgentPool", "" ) as AgentPool; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: AgentPool = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "AgentPool", "" ) as AgentPool; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setAuthorizedInfo * @throws ApiException if the response code was not in [200, 299] */ public async setAuthorizedInfo(response: ResponseContext): Promise<AuthorizedInfo > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: AuthorizedInfo = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "AuthorizedInfo", "" ) as AuthorizedInfo; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: AuthorizedInfo = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "AuthorizedInfo", "" ) as AuthorizedInfo; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setBuildConfigurationRunPolicy * @throws ApiException if the response code was not in [200, 299] */ public async setBuildConfigurationRunPolicy(response: ResponseContext): Promise<CompatibilityPolicy > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: CompatibilityPolicy = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "CompatibilityPolicy", "" ) as CompatibilityPolicy; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: CompatibilityPolicy = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "CompatibilityPolicy", "" ) as CompatibilityPolicy; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setEnabledInfo * @throws ApiException if the response code was not in [200, 299] */ public async setEnabledInfo(response: ResponseContext): Promise<EnabledInfo > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: EnabledInfo = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "EnabledInfo", "" ) as EnabledInfo; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: EnabledInfo = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "EnabledInfo", "" ) as EnabledInfo; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } } <file_sep>/ts-schema/schema/rest-api/deno/apis/RootApi.ts // TODO: better import syntax? import { BaseAPIRequestFactory, RequiredError } from './baseapi.ts'; import {Configuration} from '../configuration.ts'; import { RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http.ts'; import {ObjectSerializer} from '../models/ObjectSerializer.ts'; import {ApiException} from './exception.ts'; import {isCodeInRange} from '../util.ts'; import { Plugin } from '../models/Plugin.ts'; /** * no description */ export class RootApiRequestFactory extends BaseAPIRequestFactory { /** * Get the API version. */ public async getApiVersion(options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/apiVersion'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get the plugin info. * @param fields */ public async getPluginInfo(fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/info'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get root endpoints. */ public async getRootEndpointsOfRoot(options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get the TeamCity server version. */ public async getVersion(options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/version'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } } export class RootApiResponseProcessor { /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getApiVersion * @throws ApiException if the response code was not in [200, 299] */ public async getApiVersion(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getPluginInfo * @throws ApiException if the response code was not in [200, 299] */ public async getPluginInfo(response: ResponseContext): Promise<Plugin > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Plugin = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Plugin", "" ) as Plugin; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Plugin = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Plugin", "" ) as Plugin; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getRootEndpointsOfRoot * @throws ApiException if the response code was not in [200, 299] */ public async getRootEndpointsOfRoot(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getVersion * @throws ApiException if the response code was not in [200, 299] */ public async getVersion(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } } <file_sep>/ts-schema/schema/xml/vcs_root.ts import { Parameter } from "./parameter.ts"; export interface VcsRoot { "?xml": { "@version": string; "@encoding": string }; "vcs-root": { "@xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance"; "@xsi:noNamespaceSchemaLocation": "https://www.jetbrains.com/teamcity/schemas/2020.1/project-config.xsd"; "@uuid": string; "@type": string; "modification-check-interval"?: number; name: string; param: Parameter[]; }; } <file_sep>/ts-schema/schema/rest-api/deno/models/LicenseKey.ts /** * TeamCity REST API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * OpenAPI spec version: 2018.1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { HttpFile } from '../http/http.ts'; export class LicenseKey { 'valid'?: boolean; 'active'?: boolean; 'expired'?: boolean; 'obsolete'?: boolean; 'expirationDate'?: string; 'maintenanceEndDate'?: string; 'type'?: string; 'servers'?: number; 'agents'?: number; 'unlimitedAgents'?: boolean; 'buildTypes'?: number; 'unlimitedBuildTypes'?: boolean; 'errorDetails'?: string; 'key'?: string; 'rawType'?: string; static readonly discriminator: string | undefined = undefined; static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [ { "name": "valid", "baseName": "valid", "type": "boolean", "format": "" }, { "name": "active", "baseName": "active", "type": "boolean", "format": "" }, { "name": "expired", "baseName": "expired", "type": "boolean", "format": "" }, { "name": "obsolete", "baseName": "obsolete", "type": "boolean", "format": "" }, { "name": "expirationDate", "baseName": "expirationDate", "type": "string", "format": "" }, { "name": "maintenanceEndDate", "baseName": "maintenanceEndDate", "type": "string", "format": "" }, { "name": "type", "baseName": "type", "type": "string", "format": "" }, { "name": "servers", "baseName": "servers", "type": "number", "format": "int32" }, { "name": "agents", "baseName": "agents", "type": "number", "format": "int32" }, { "name": "unlimitedAgents", "baseName": "unlimitedAgents", "type": "boolean", "format": "" }, { "name": "buildTypes", "baseName": "buildTypes", "type": "number", "format": "int32" }, { "name": "unlimitedBuildTypes", "baseName": "unlimitedBuildTypes", "type": "boolean", "format": "" }, { "name": "errorDetails", "baseName": "errorDetails", "type": "string", "format": "" }, { "name": "key", "baseName": "key", "type": "string", "format": "" }, { "name": "rawType", "baseName": "rawType", "type": "string", "format": "" } ]; static getAttributeTypeMap() { return LicenseKey.attributeTypeMap; } public constructor() { } } <file_sep>/ts-schema/schema/rest-api/deno/models/Build.ts /** * TeamCity REST API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * OpenAPI spec version: 2018.1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { Agent } from './Agent.ts'; import { Agents } from './Agents.ts'; import { ArtifactDependencies } from './ArtifactDependencies.ts'; import { BuildChanges } from './BuildChanges.ts'; import { BuildTriggeringOptions } from './BuildTriggeringOptions.ts'; import { BuildType } from './BuildType.ts'; import { Builds } from './Builds.ts'; import { Changes } from './Changes.ts'; import { Comment } from './Comment.ts'; import { Customizations } from './Customizations.ts'; import { Datas } from './Datas.ts'; import { Entries } from './Entries.ts'; import { Files } from './Files.ts'; import { IssuesUsages } from './IssuesUsages.ts'; import { Items } from './Items.ts'; import { Links } from './Links.ts'; import { ProblemOccurrences } from './ProblemOccurrences.ts'; import { ProgressInfo } from './ProgressInfo.ts'; import { Properties } from './Properties.ts'; import { Related } from './Related.ts'; import { Revision } from './Revision.ts'; import { Revisions } from './Revisions.ts'; import { Tags } from './Tags.ts'; import { TestOccurrences } from './TestOccurrences.ts'; import { TriggeredBy } from './TriggeredBy.ts'; import { User } from './User.ts'; import { VcsLabel } from './VcsLabel.ts'; import { HttpFile } from '../http/http.ts'; export class Build { 'id'?: number; 'taskId'?: number; 'buildTypeId'?: string; 'buildTypeInternalId'?: string; 'number'?: string; 'status'?: string; 'state'?: string; 'running'?: boolean; 'composite'?: boolean; 'failedToStart'?: boolean; 'personal'?: boolean; 'percentageComplete'?: number; 'branchName'?: string; 'defaultBranch'?: boolean; 'unspecifiedBranch'?: boolean; 'history'?: boolean; 'pinned'?: boolean; 'href'?: string; 'webUrl'?: string; 'queuePosition'?: number; 'limitedChangesCount'?: number; 'artifactsDirectory'?: string; 'links'?: Links; 'statusText'?: string; 'buildType'?: BuildType; 'comment'?: Comment; 'tags'?: Tags; 'pinInfo'?: Comment; 'user'?: User; 'startEstimate'?: string; 'waitReason'?: string; 'finishEstimate'?: string; 'runningInfo'?: ProgressInfo; 'canceledInfo'?: Comment; 'queuedDate'?: string; 'startDate'?: string; 'finishDate'?: string; 'triggered'?: TriggeredBy; 'lastChanges'?: Changes; 'changes'?: Changes; 'revisions'?: Revisions; 'versionedSettingsRevision'?: Revision; 'artifactDependencyChanges'?: BuildChanges; 'agent'?: Agent; 'compatibleAgents'?: Agents; 'testOccurrences'?: TestOccurrences; 'problemOccurrences'?: ProblemOccurrences; 'artifacts'?: Files; 'relatedIssues'?: IssuesUsages; 'properties'?: Properties; 'resultingProperties'?: Properties; 'attributes'?: Entries; 'statistics'?: Properties; 'metadata'?: Datas; 'snapshotDependencies'?: Builds; 'artifactDependencies'?: Builds; 'customArtifactDependencies'?: ArtifactDependencies; 'settingsHash'?: string; 'currentSettingsHash'?: string; 'modificationId'?: string; 'chainModificationId'?: string; 'replacementIds'?: Items; 'related'?: Related; 'triggeringOptions'?: BuildTriggeringOptions; 'usedByOtherBuilds'?: boolean; 'statusChangeComment'?: Comment; 'vcsLabels'?: Array<VcsLabel>; 'detachedFromAgent'?: boolean; 'finishOnAgentDate'?: string; 'customized'?: boolean; 'customization'?: Customizations; 'locator'?: string; static readonly discriminator: string | undefined = undefined; static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [ { "name": "id", "baseName": "id", "type": "number", "format": "int64" }, { "name": "taskId", "baseName": "taskId", "type": "number", "format": "int64" }, { "name": "buildTypeId", "baseName": "buildTypeId", "type": "string", "format": "" }, { "name": "buildTypeInternalId", "baseName": "buildTypeInternalId", "type": "string", "format": "" }, { "name": "number", "baseName": "number", "type": "string", "format": "" }, { "name": "status", "baseName": "status", "type": "string", "format": "" }, { "name": "state", "baseName": "state", "type": "string", "format": "" }, { "name": "running", "baseName": "running", "type": "boolean", "format": "" }, { "name": "composite", "baseName": "composite", "type": "boolean", "format": "" }, { "name": "failedToStart", "baseName": "failedToStart", "type": "boolean", "format": "" }, { "name": "personal", "baseName": "personal", "type": "boolean", "format": "" }, { "name": "percentageComplete", "baseName": "percentageComplete", "type": "number", "format": "int32" }, { "name": "branchName", "baseName": "branchName", "type": "string", "format": "" }, { "name": "defaultBranch", "baseName": "defaultBranch", "type": "boolean", "format": "" }, { "name": "unspecifiedBranch", "baseName": "unspecifiedBranch", "type": "boolean", "format": "" }, { "name": "history", "baseName": "history", "type": "boolean", "format": "" }, { "name": "pinned", "baseName": "pinned", "type": "boolean", "format": "" }, { "name": "href", "baseName": "href", "type": "string", "format": "" }, { "name": "webUrl", "baseName": "webUrl", "type": "string", "format": "" }, { "name": "queuePosition", "baseName": "queuePosition", "type": "number", "format": "int32" }, { "name": "limitedChangesCount", "baseName": "limitedChangesCount", "type": "number", "format": "int32" }, { "name": "artifactsDirectory", "baseName": "artifactsDirectory", "type": "string", "format": "" }, { "name": "links", "baseName": "links", "type": "Links", "format": "" }, { "name": "statusText", "baseName": "statusText", "type": "string", "format": "" }, { "name": "buildType", "baseName": "buildType", "type": "BuildType", "format": "" }, { "name": "comment", "baseName": "comment", "type": "Comment", "format": "" }, { "name": "tags", "baseName": "tags", "type": "Tags", "format": "" }, { "name": "pinInfo", "baseName": "pinInfo", "type": "Comment", "format": "" }, { "name": "user", "baseName": "user", "type": "User", "format": "" }, { "name": "startEstimate", "baseName": "startEstimate", "type": "string", "format": "" }, { "name": "waitReason", "baseName": "waitReason", "type": "string", "format": "" }, { "name": "finishEstimate", "baseName": "finishEstimate", "type": "string", "format": "" }, { "name": "runningInfo", "baseName": "running-info", "type": "ProgressInfo", "format": "" }, { "name": "canceledInfo", "baseName": "canceledInfo", "type": "Comment", "format": "" }, { "name": "queuedDate", "baseName": "queuedDate", "type": "string", "format": "" }, { "name": "startDate", "baseName": "startDate", "type": "string", "format": "" }, { "name": "finishDate", "baseName": "finishDate", "type": "string", "format": "" }, { "name": "triggered", "baseName": "triggered", "type": "TriggeredBy", "format": "" }, { "name": "lastChanges", "baseName": "lastChanges", "type": "Changes", "format": "" }, { "name": "changes", "baseName": "changes", "type": "Changes", "format": "" }, { "name": "revisions", "baseName": "revisions", "type": "Revisions", "format": "" }, { "name": "versionedSettingsRevision", "baseName": "versionedSettingsRevision", "type": "Revision", "format": "" }, { "name": "artifactDependencyChanges", "baseName": "artifactDependencyChanges", "type": "BuildChanges", "format": "" }, { "name": "agent", "baseName": "agent", "type": "Agent", "format": "" }, { "name": "compatibleAgents", "baseName": "compatibleAgents", "type": "Agents", "format": "" }, { "name": "testOccurrences", "baseName": "testOccurrences", "type": "TestOccurrences", "format": "" }, { "name": "problemOccurrences", "baseName": "problemOccurrences", "type": "ProblemOccurrences", "format": "" }, { "name": "artifacts", "baseName": "artifacts", "type": "Files", "format": "" }, { "name": "relatedIssues", "baseName": "relatedIssues", "type": "IssuesUsages", "format": "" }, { "name": "properties", "baseName": "properties", "type": "Properties", "format": "" }, { "name": "resultingProperties", "baseName": "resultingProperties", "type": "Properties", "format": "" }, { "name": "attributes", "baseName": "attributes", "type": "Entries", "format": "" }, { "name": "statistics", "baseName": "statistics", "type": "Properties", "format": "" }, { "name": "metadata", "baseName": "metadata", "type": "Datas", "format": "" }, { "name": "snapshotDependencies", "baseName": "snapshot-dependencies", "type": "Builds", "format": "" }, { "name": "artifactDependencies", "baseName": "artifact-dependencies", "type": "Builds", "format": "" }, { "name": "customArtifactDependencies", "baseName": "custom-artifact-dependencies", "type": "ArtifactDependencies", "format": "" }, { "name": "settingsHash", "baseName": "settingsHash", "type": "string", "format": "" }, { "name": "currentSettingsHash", "baseName": "currentSettingsHash", "type": "string", "format": "" }, { "name": "modificationId", "baseName": "modificationId", "type": "string", "format": "" }, { "name": "chainModificationId", "baseName": "chainModificationId", "type": "string", "format": "" }, { "name": "replacementIds", "baseName": "replacementIds", "type": "Items", "format": "" }, { "name": "related", "baseName": "related", "type": "Related", "format": "" }, { "name": "triggeringOptions", "baseName": "triggeringOptions", "type": "BuildTriggeringOptions", "format": "" }, { "name": "usedByOtherBuilds", "baseName": "usedByOtherBuilds", "type": "boolean", "format": "" }, { "name": "statusChangeComment", "baseName": "statusChangeComment", "type": "Comment", "format": "" }, { "name": "vcsLabels", "baseName": "vcsLabels", "type": "Array<VcsLabel>", "format": "" }, { "name": "detachedFromAgent", "baseName": "detachedFromAgent", "type": "boolean", "format": "" }, { "name": "finishOnAgentDate", "baseName": "finishOnAgentDate", "type": "string", "format": "" }, { "name": "customized", "baseName": "customized", "type": "boolean", "format": "" }, { "name": "customization", "baseName": "customization", "type": "Customizations", "format": "" }, { "name": "locator", "baseName": "locator", "type": "string", "format": "" } ]; static getAttributeTypeMap() { return Build.attributeTypeMap; } public constructor() { } } <file_sep>/ts-schema/schema/rest-api/deno/models/ProblemOccurrence.ts /** * TeamCity REST API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * OpenAPI spec version: 2018.1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { Build } from './Build.ts'; import { Mute } from './Mute.ts'; import { Problem } from './Problem.ts'; import { HttpFile } from '../http/http.ts'; export class ProblemOccurrence { 'id'?: string; 'type'?: string; 'identity'?: string; 'href'?: string; 'muted'?: boolean; 'currentlyInvestigated'?: boolean; 'currentlyMuted'?: boolean; 'logAnchor'?: string; 'newFailure'?: boolean; 'details'?: string; 'additionalData'?: string; 'problem'?: Problem; 'mute'?: Mute; 'build'?: Build; static readonly discriminator: string | undefined = undefined; static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [ { "name": "id", "baseName": "id", "type": "string", "format": "" }, { "name": "type", "baseName": "type", "type": "string", "format": "" }, { "name": "identity", "baseName": "identity", "type": "string", "format": "" }, { "name": "href", "baseName": "href", "type": "string", "format": "" }, { "name": "muted", "baseName": "muted", "type": "boolean", "format": "" }, { "name": "currentlyInvestigated", "baseName": "currentlyInvestigated", "type": "boolean", "format": "" }, { "name": "currentlyMuted", "baseName": "currentlyMuted", "type": "boolean", "format": "" }, { "name": "logAnchor", "baseName": "logAnchor", "type": "string", "format": "" }, { "name": "newFailure", "baseName": "newFailure", "type": "boolean", "format": "" }, { "name": "details", "baseName": "details", "type": "string", "format": "" }, { "name": "additionalData", "baseName": "additionalData", "type": "string", "format": "" }, { "name": "problem", "baseName": "problem", "type": "Problem", "format": "" }, { "name": "mute", "baseName": "mute", "type": "Mute", "format": "" }, { "name": "build", "baseName": "build", "type": "Build", "format": "" } ]; static getAttributeTypeMap() { return ProblemOccurrence.attributeTypeMap; } public constructor() { } } <file_sep>/ts-schema/schema/rest-api/deno/apis/GroupApi.ts // TODO: better import syntax? import { BaseAPIRequestFactory, RequiredError } from './baseapi.ts'; import {Configuration} from '../configuration.ts'; import { RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http.ts'; import {ObjectSerializer} from '../models/ObjectSerializer.ts'; import {ApiException} from './exception.ts'; import {isCodeInRange} from '../util.ts'; import { Group } from '../models/Group.ts'; import { Groups } from '../models/Groups.ts'; import { Properties } from '../models/Properties.ts'; import { Role } from '../models/Role.ts'; import { Roles } from '../models/Roles.ts'; /** * no description */ export class GroupApiRequestFactory extends BaseAPIRequestFactory { /** * Add a new user group. * @param fields * @param body */ public async addGroup(fields?: string, body?: Group, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/userGroups'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Group", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Add a role with the specific scope to the matching user group. * @param groupLocator * @param roleId * @param scope */ public async addRoleAtScopeToGroup(groupLocator: string, roleId: string, scope: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'groupLocator' is not null or undefined if (groupLocator === null || groupLocator === undefined) { throw new RequiredError('Required parameter groupLocator was null or undefined when calling addRoleAtScopeToGroup.'); } // verify required parameter 'roleId' is not null or undefined if (roleId === null || roleId === undefined) { throw new RequiredError('Required parameter roleId was null or undefined when calling addRoleAtScopeToGroup.'); } // verify required parameter 'scope' is not null or undefined if (scope === null || scope === undefined) { throw new RequiredError('Required parameter scope was null or undefined when calling addRoleAtScopeToGroup.'); } // Path Params const localVarPath = '/app/rest/userGroups/{groupLocator}/roles/{roleId}/{scope}' .replace('{' + 'groupLocator' + '}', encodeURIComponent(String(groupLocator))) .replace('{' + 'roleId' + '}', encodeURIComponent(String(roleId))) .replace('{' + 'scope' + '}', encodeURIComponent(String(scope))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Add a role to the matching user group. * @param groupLocator * @param body */ public async addRoleToGroup(groupLocator: string, body?: Role, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'groupLocator' is not null or undefined if (groupLocator === null || groupLocator === undefined) { throw new RequiredError('Required parameter groupLocator was null or undefined when calling addRoleToGroup.'); } // Path Params const localVarPath = '/app/rest/userGroups/{groupLocator}/roles' .replace('{' + 'groupLocator' + '}', encodeURIComponent(String(groupLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Role", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Delete user group matching the locator. * @param groupLocator */ public async deleteGroup(groupLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'groupLocator' is not null or undefined if (groupLocator === null || groupLocator === undefined) { throw new RequiredError('Required parameter groupLocator was null or undefined when calling deleteGroup.'); } // Path Params const localVarPath = '/app/rest/userGroups/{groupLocator}' .replace('{' + 'groupLocator' + '}', encodeURIComponent(String(groupLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all user groups. * @param fields */ public async getAllGroups(fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/userGroups'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get parent groups of the matching user group. * @param groupLocator * @param fields */ public async getGroupParentGroups(groupLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'groupLocator' is not null or undefined if (groupLocator === null || groupLocator === undefined) { throw new RequiredError('Required parameter groupLocator was null or undefined when calling getGroupParentGroups.'); } // Path Params const localVarPath = '/app/rest/userGroups/{groupLocator}/parent-groups' .replace('{' + 'groupLocator' + '}', encodeURIComponent(String(groupLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get properties of the matching user group. * @param groupLocator * @param fields */ public async getGroupProperties(groupLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'groupLocator' is not null or undefined if (groupLocator === null || groupLocator === undefined) { throw new RequiredError('Required parameter groupLocator was null or undefined when calling getGroupProperties.'); } // Path Params const localVarPath = '/app/rest/userGroups/{groupLocator}/properties' .replace('{' + 'groupLocator' + '}', encodeURIComponent(String(groupLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get a property of the matching user group. * @param groupLocator * @param name */ public async getGroupProperty(groupLocator: string, name: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'groupLocator' is not null or undefined if (groupLocator === null || groupLocator === undefined) { throw new RequiredError('Required parameter groupLocator was null or undefined when calling getGroupProperty.'); } // verify required parameter 'name' is not null or undefined if (name === null || name === undefined) { throw new RequiredError('Required parameter name was null or undefined when calling getGroupProperty.'); } // Path Params const localVarPath = '/app/rest/userGroups/{groupLocator}/properties/{name}' .replace('{' + 'groupLocator' + '}', encodeURIComponent(String(groupLocator))) .replace('{' + 'name' + '}', encodeURIComponent(String(name))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get a role with the specific scope of the matching user group. * @param groupLocator * @param roleId * @param scope */ public async getGroupRoleAtScope(groupLocator: string, roleId: string, scope: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'groupLocator' is not null or undefined if (groupLocator === null || groupLocator === undefined) { throw new RequiredError('Required parameter groupLocator was null or undefined when calling getGroupRoleAtScope.'); } // verify required parameter 'roleId' is not null or undefined if (roleId === null || roleId === undefined) { throw new RequiredError('Required parameter roleId was null or undefined when calling getGroupRoleAtScope.'); } // verify required parameter 'scope' is not null or undefined if (scope === null || scope === undefined) { throw new RequiredError('Required parameter scope was null or undefined when calling getGroupRoleAtScope.'); } // Path Params const localVarPath = '/app/rest/userGroups/{groupLocator}/roles/{roleId}/{scope}' .replace('{' + 'groupLocator' + '}', encodeURIComponent(String(groupLocator))) .replace('{' + 'roleId' + '}', encodeURIComponent(String(roleId))) .replace('{' + 'scope' + '}', encodeURIComponent(String(scope))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all roles of the matching user group. * @param groupLocator */ public async getGroupRoles(groupLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'groupLocator' is not null or undefined if (groupLocator === null || groupLocator === undefined) { throw new RequiredError('Required parameter groupLocator was null or undefined when calling getGroupRoles.'); } // Path Params const localVarPath = '/app/rest/userGroups/{groupLocator}/roles' .replace('{' + 'groupLocator' + '}', encodeURIComponent(String(groupLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get user group matching the locator. * @param groupLocator * @param fields */ public async getUserGroupOfGroup(groupLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'groupLocator' is not null or undefined if (groupLocator === null || groupLocator === undefined) { throw new RequiredError('Required parameter groupLocator was null or undefined when calling getUserGroupOfGroup.'); } // Path Params const localVarPath = '/app/rest/userGroups/{groupLocator}' .replace('{' + 'groupLocator' + '}', encodeURIComponent(String(groupLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Remove a property of the matching user group. * @param groupLocator * @param name */ public async removeGroupProperty(groupLocator: string, name: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'groupLocator' is not null or undefined if (groupLocator === null || groupLocator === undefined) { throw new RequiredError('Required parameter groupLocator was null or undefined when calling removeGroupProperty.'); } // verify required parameter 'name' is not null or undefined if (name === null || name === undefined) { throw new RequiredError('Required parameter name was null or undefined when calling removeGroupProperty.'); } // Path Params const localVarPath = '/app/rest/userGroups/{groupLocator}/properties/{name}' .replace('{' + 'groupLocator' + '}', encodeURIComponent(String(groupLocator))) .replace('{' + 'name' + '}', encodeURIComponent(String(name))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Remove a role with the specific scope from the matching user group. * @param groupLocator * @param roleId * @param scope */ public async removeRoleAtScopeFromGroup(groupLocator: string, roleId: string, scope: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'groupLocator' is not null or undefined if (groupLocator === null || groupLocator === undefined) { throw new RequiredError('Required parameter groupLocator was null or undefined when calling removeRoleAtScopeFromGroup.'); } // verify required parameter 'roleId' is not null or undefined if (roleId === null || roleId === undefined) { throw new RequiredError('Required parameter roleId was null or undefined when calling removeRoleAtScopeFromGroup.'); } // verify required parameter 'scope' is not null or undefined if (scope === null || scope === undefined) { throw new RequiredError('Required parameter scope was null or undefined when calling removeRoleAtScopeFromGroup.'); } // Path Params const localVarPath = '/app/rest/userGroups/{groupLocator}/roles/{roleId}/{scope}' .replace('{' + 'groupLocator' + '}', encodeURIComponent(String(groupLocator))) .replace('{' + 'roleId' + '}', encodeURIComponent(String(roleId))) .replace('{' + 'scope' + '}', encodeURIComponent(String(scope))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update parent groups of the matching user group. * @param groupLocator * @param fields * @param body */ public async setGroupParentGroups(groupLocator: string, fields?: string, body?: Groups, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'groupLocator' is not null or undefined if (groupLocator === null || groupLocator === undefined) { throw new RequiredError('Required parameter groupLocator was null or undefined when calling setGroupParentGroups.'); } // Path Params const localVarPath = '/app/rest/userGroups/{groupLocator}/parent-groups' .replace('{' + 'groupLocator' + '}', encodeURIComponent(String(groupLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Groups", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update a property of the matching user group. * @param groupLocator * @param name * @param body */ public async setGroupProperty(groupLocator: string, name: string, body?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'groupLocator' is not null or undefined if (groupLocator === null || groupLocator === undefined) { throw new RequiredError('Required parameter groupLocator was null or undefined when calling setGroupProperty.'); } // verify required parameter 'name' is not null or undefined if (name === null || name === undefined) { throw new RequiredError('Required parameter name was null or undefined when calling setGroupProperty.'); } // Path Params const localVarPath = '/app/rest/userGroups/{groupLocator}/properties/{name}' .replace('{' + 'groupLocator' + '}', encodeURIComponent(String(groupLocator))) .replace('{' + 'name' + '}', encodeURIComponent(String(name))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "text/plain" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "string", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update roles of the matching user group. * @param groupLocator * @param body */ public async setGroupRoles(groupLocator: string, body?: Roles, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'groupLocator' is not null or undefined if (groupLocator === null || groupLocator === undefined) { throw new RequiredError('Required parameter groupLocator was null or undefined when calling setGroupRoles.'); } // Path Params const localVarPath = '/app/rest/userGroups/{groupLocator}/roles' .replace('{' + 'groupLocator' + '}', encodeURIComponent(String(groupLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Roles", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } } export class GroupApiResponseProcessor { /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to addGroup * @throws ApiException if the response code was not in [200, 299] */ public async addGroup(response: ResponseContext): Promise<Group > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Group = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Group", "" ) as Group; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Group = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Group", "" ) as Group; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to addRoleAtScopeToGroup * @throws ApiException if the response code was not in [200, 299] */ public async addRoleAtScopeToGroup(response: ResponseContext): Promise<Role > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Role = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Role", "" ) as Role; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Role = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Role", "" ) as Role; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to addRoleToGroup * @throws ApiException if the response code was not in [200, 299] */ public async addRoleToGroup(response: ResponseContext): Promise<Role > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Role = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Role", "" ) as Role; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Role = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Role", "" ) as Role; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to deleteGroup * @throws ApiException if the response code was not in [200, 299] */ public async deleteGroup(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAllGroups * @throws ApiException if the response code was not in [200, 299] */ public async getAllGroups(response: ResponseContext): Promise<Groups > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Groups = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Groups", "" ) as Groups; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Groups = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Groups", "" ) as Groups; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getGroupParentGroups * @throws ApiException if the response code was not in [200, 299] */ public async getGroupParentGroups(response: ResponseContext): Promise<Groups > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Groups = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Groups", "" ) as Groups; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Groups = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Groups", "" ) as Groups; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getGroupProperties * @throws ApiException if the response code was not in [200, 299] */ public async getGroupProperties(response: ResponseContext): Promise<Properties > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Properties = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Properties", "" ) as Properties; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Properties = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Properties", "" ) as Properties; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getGroupProperty * @throws ApiException if the response code was not in [200, 299] */ public async getGroupProperty(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getGroupRoleAtScope * @throws ApiException if the response code was not in [200, 299] */ public async getGroupRoleAtScope(response: ResponseContext): Promise<Role > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Role = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Role", "" ) as Role; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Role = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Role", "" ) as Role; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getGroupRoles * @throws ApiException if the response code was not in [200, 299] */ public async getGroupRoles(response: ResponseContext): Promise<Roles > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Roles = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Roles", "" ) as Roles; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Roles = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Roles", "" ) as Roles; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getUserGroupOfGroup * @throws ApiException if the response code was not in [200, 299] */ public async getUserGroupOfGroup(response: ResponseContext): Promise<Group > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Group = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Group", "" ) as Group; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Group = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Group", "" ) as Group; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to removeGroupProperty * @throws ApiException if the response code was not in [200, 299] */ public async removeGroupProperty(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to removeRoleAtScopeFromGroup * @throws ApiException if the response code was not in [200, 299] */ public async removeRoleAtScopeFromGroup(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setGroupParentGroups * @throws ApiException if the response code was not in [200, 299] */ public async setGroupParentGroups(response: ResponseContext): Promise<Groups > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Groups = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Groups", "" ) as Groups; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Groups = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Groups", "" ) as Groups; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setGroupProperty * @throws ApiException if the response code was not in [200, 299] */ public async setGroupProperty(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setGroupRoles * @throws ApiException if the response code was not in [200, 299] */ public async setGroupRoles(response: ResponseContext): Promise<Roles > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Roles = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Roles", "" ) as Roles; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Roles = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Roles", "" ) as Roles; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } } <file_sep>/ts-schema/schema/rest-api/deno/models/Server.ts /** * TeamCity REST API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * OpenAPI spec version: 2018.1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { Href } from './Href.ts'; import { HttpFile } from '../http/http.ts'; export class Server { 'version'?: string; 'versionMajor'?: number; 'versionMinor'?: number; 'startTime'?: string; 'currentTime'?: string; 'buildNumber'?: string; 'buildDate'?: string; 'internalId'?: string; 'role'?: string; 'webUrl'?: string; 'projects'?: Href; 'vcsRoots'?: Href; 'builds'?: Href; 'users'?: Href; 'userGroups'?: Href; 'agents'?: Href; 'buildQueue'?: Href; 'agentPools'?: Href; 'investigations'?: Href; 'mutes'?: Href; static readonly discriminator: string | undefined = undefined; static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [ { "name": "version", "baseName": "version", "type": "string", "format": "" }, { "name": "versionMajor", "baseName": "versionMajor", "type": "number", "format": "int32" }, { "name": "versionMinor", "baseName": "versionMinor", "type": "number", "format": "int32" }, { "name": "startTime", "baseName": "startTime", "type": "string", "format": "" }, { "name": "currentTime", "baseName": "currentTime", "type": "string", "format": "" }, { "name": "buildNumber", "baseName": "buildNumber", "type": "string", "format": "" }, { "name": "buildDate", "baseName": "buildDate", "type": "string", "format": "" }, { "name": "internalId", "baseName": "internalId", "type": "string", "format": "" }, { "name": "role", "baseName": "role", "type": "string", "format": "" }, { "name": "webUrl", "baseName": "webUrl", "type": "string", "format": "" }, { "name": "projects", "baseName": "projects", "type": "Href", "format": "" }, { "name": "vcsRoots", "baseName": "vcsRoots", "type": "Href", "format": "" }, { "name": "builds", "baseName": "builds", "type": "Href", "format": "" }, { "name": "users", "baseName": "users", "type": "Href", "format": "" }, { "name": "userGroups", "baseName": "userGroups", "type": "Href", "format": "" }, { "name": "agents", "baseName": "agents", "type": "Href", "format": "" }, { "name": "buildQueue", "baseName": "buildQueue", "type": "Href", "format": "" }, { "name": "agentPools", "baseName": "agentPools", "type": "Href", "format": "" }, { "name": "investigations", "baseName": "investigations", "type": "Href", "format": "" }, { "name": "mutes", "baseName": "mutes", "type": "Href", "format": "" } ]; static getAttributeTypeMap() { return Server.attributeTypeMap; } public constructor() { } } <file_sep>/ts-schema/schema/rest-api/deno/models/Agent.ts /** * TeamCity REST API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * OpenAPI spec version: 2018.1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { AgentPool } from './AgentPool.ts'; import { AuthorizedInfo } from './AuthorizedInfo.ts'; import { Build } from './Build.ts'; import { BuildTypes } from './BuildTypes.ts'; import { Builds } from './Builds.ts'; import { CloudImage } from './CloudImage.ts'; import { CloudInstance } from './CloudInstance.ts'; import { Compatibilities } from './Compatibilities.ts'; import { CompatibilityPolicy } from './CompatibilityPolicy.ts'; import { EnabledInfo } from './EnabledInfo.ts'; import { Environment } from './Environment.ts'; import { Links } from './Links.ts'; import { Properties } from './Properties.ts'; import { HttpFile } from '../http/http.ts'; export class Agent { 'id'?: number; 'name'?: string; 'typeId'?: number; 'connected'?: boolean; 'enabled'?: boolean; 'authorized'?: boolean; 'uptodate'?: boolean; 'outdated'?: boolean; 'pluginsOutdated'?: boolean; 'javaOutdated'?: boolean; 'ip'?: string; 'protocol'?: string; 'version'?: string; 'currentAgentVersion'?: string; 'lastActivityTime'?: string; 'idleSinceTime'?: string; 'disconnectionComment'?: string; 'registrationTimestamp'?: string; 'host'?: string; 'cpuRank'?: number; 'port'?: number; 'href'?: string; 'webUrl'?: string; 'build'?: Build; 'links'?: Links; 'enabledInfo'?: EnabledInfo; 'authorizedInfo'?: AuthorizedInfo; 'properties'?: Properties; 'cloudInstance'?: CloudInstance; 'cloudImage'?: CloudImage; 'environment'?: Environment; 'pool'?: AgentPool; 'compatibilityPolicy'?: CompatibilityPolicy; 'compatibleBuildTypes'?: BuildTypes; 'incompatibleBuildTypes'?: Compatibilities; 'builds'?: Builds; 'locator'?: string; static readonly discriminator: string | undefined = undefined; static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [ { "name": "id", "baseName": "id", "type": "number", "format": "int32" }, { "name": "name", "baseName": "name", "type": "string", "format": "" }, { "name": "typeId", "baseName": "typeId", "type": "number", "format": "int32" }, { "name": "connected", "baseName": "connected", "type": "boolean", "format": "" }, { "name": "enabled", "baseName": "enabled", "type": "boolean", "format": "" }, { "name": "authorized", "baseName": "authorized", "type": "boolean", "format": "" }, { "name": "uptodate", "baseName": "uptodate", "type": "boolean", "format": "" }, { "name": "outdated", "baseName": "outdated", "type": "boolean", "format": "" }, { "name": "pluginsOutdated", "baseName": "pluginsOutdated", "type": "boolean", "format": "" }, { "name": "javaOutdated", "baseName": "javaOutdated", "type": "boolean", "format": "" }, { "name": "ip", "baseName": "ip", "type": "string", "format": "" }, { "name": "protocol", "baseName": "protocol", "type": "string", "format": "" }, { "name": "version", "baseName": "version", "type": "string", "format": "" }, { "name": "currentAgentVersion", "baseName": "currentAgentVersion", "type": "string", "format": "" }, { "name": "lastActivityTime", "baseName": "lastActivityTime", "type": "string", "format": "" }, { "name": "idleSinceTime", "baseName": "idleSinceTime", "type": "string", "format": "" }, { "name": "disconnectionComment", "baseName": "disconnectionComment", "type": "string", "format": "" }, { "name": "registrationTimestamp", "baseName": "registrationTimestamp", "type": "string", "format": "" }, { "name": "host", "baseName": "host", "type": "string", "format": "" }, { "name": "cpuRank", "baseName": "cpuRank", "type": "number", "format": "int32" }, { "name": "port", "baseName": "port", "type": "number", "format": "int32" }, { "name": "href", "baseName": "href", "type": "string", "format": "" }, { "name": "webUrl", "baseName": "webUrl", "type": "string", "format": "" }, { "name": "build", "baseName": "build", "type": "Build", "format": "" }, { "name": "links", "baseName": "links", "type": "Links", "format": "" }, { "name": "enabledInfo", "baseName": "enabledInfo", "type": "EnabledInfo", "format": "" }, { "name": "authorizedInfo", "baseName": "authorizedInfo", "type": "AuthorizedInfo", "format": "" }, { "name": "properties", "baseName": "properties", "type": "Properties", "format": "" }, { "name": "cloudInstance", "baseName": "cloudInstance", "type": "CloudInstance", "format": "" }, { "name": "cloudImage", "baseName": "cloudImage", "type": "CloudImage", "format": "" }, { "name": "environment", "baseName": "environment", "type": "Environment", "format": "" }, { "name": "pool", "baseName": "pool", "type": "AgentPool", "format": "" }, { "name": "compatibilityPolicy", "baseName": "compatibilityPolicy", "type": "CompatibilityPolicy", "format": "" }, { "name": "compatibleBuildTypes", "baseName": "compatibleBuildTypes", "type": "BuildTypes", "format": "" }, { "name": "incompatibleBuildTypes", "baseName": "incompatibleBuildTypes", "type": "Compatibilities", "format": "" }, { "name": "builds", "baseName": "builds", "type": "Builds", "format": "" }, { "name": "locator", "baseName": "locator", "type": "string", "format": "" } ]; static getAttributeTypeMap() { return Agent.attributeTypeMap; } public constructor() { } } <file_sep>/ts-schema/schema/rest-api/deno/models/Mute.ts /** * TeamCity REST API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * OpenAPI spec version: 2018.1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { Comment } from './Comment.ts'; import { ProblemScope } from './ProblemScope.ts'; import { ProblemTarget } from './ProblemTarget.ts'; import { Resolution } from './Resolution.ts'; import { HttpFile } from '../http/http.ts'; export class Mute { 'id'?: number; 'href'?: string; 'assignment'?: Comment; 'scope'?: ProblemScope; 'target'?: ProblemTarget; 'resolution'?: Resolution; static readonly discriminator: string | undefined = undefined; static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [ { "name": "id", "baseName": "id", "type": "number", "format": "int32" }, { "name": "href", "baseName": "href", "type": "string", "format": "" }, { "name": "assignment", "baseName": "assignment", "type": "Comment", "format": "" }, { "name": "scope", "baseName": "scope", "type": "ProblemScope", "format": "" }, { "name": "target", "baseName": "target", "type": "ProblemTarget", "format": "" }, { "name": "resolution", "baseName": "resolution", "type": "Resolution", "format": "" } ]; static getAttributeTypeMap() { return Mute.attributeTypeMap; } public constructor() { } } <file_sep>/ts-schema/schema/xml/project_cleanup.ts import { Parameter } from "./parameter.ts"; export interface ProjectCleanup { policy?: ProjectCleanupPolicy[]; options?: { option: Parameter[]; }; } export interface ProjectCleanupPolicy { "@type": string; "@cleanup-level": string; parameters: { param: Parameter[]; }; } <file_sep>/ts-schema/schema/rest-api/deno/apis/VcsRootInstanceApi.ts // TODO: better import syntax? import { BaseAPIRequestFactory, RequiredError } from './baseapi.ts'; import {Configuration} from '../configuration.ts'; import { RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http.ts'; import {ObjectSerializer} from '../models/ObjectSerializer.ts'; import {ApiException} from './exception.ts'; import {isCodeInRange} from '../util.ts'; import { Entries } from '../models/Entries.ts'; import { Files } from '../models/Files.ts'; import { Properties } from '../models/Properties.ts'; import { VcsRootInstance } from '../models/VcsRootInstance.ts'; import { VcsRootInstances } from '../models/VcsRootInstances.ts'; /** * no description */ export class VcsRootInstanceApiRequestFactory extends BaseAPIRequestFactory { /** * Remove a field of the matching VCS root instance. * @param vcsRootInstanceLocator * @param field */ public async deleteVcsRootInstanceField(vcsRootInstanceLocator: string, field: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'vcsRootInstanceLocator' is not null or undefined if (vcsRootInstanceLocator === null || vcsRootInstanceLocator === undefined) { throw new RequiredError('Required parameter vcsRootInstanceLocator was null or undefined when calling deleteVcsRootInstanceField.'); } // verify required parameter 'field' is not null or undefined if (field === null || field === undefined) { throw new RequiredError('Required parameter field was null or undefined when calling deleteVcsRootInstanceField.'); } // Path Params const localVarPath = '/app/rest/vcs-root-instances/{vcsRootInstanceLocator}/{field}' .replace('{' + 'vcsRootInstanceLocator' + '}', encodeURIComponent(String(vcsRootInstanceLocator))) .replace('{' + 'field' + '}', encodeURIComponent(String(field))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Delete the last repository state of the matching VCS root instance. * @param vcsRootInstanceLocator */ public async deleteVcsRootInstanceRepositoryState(vcsRootInstanceLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'vcsRootInstanceLocator' is not null or undefined if (vcsRootInstanceLocator === null || vcsRootInstanceLocator === undefined) { throw new RequiredError('Required parameter vcsRootInstanceLocator was null or undefined when calling deleteVcsRootInstanceRepositoryState.'); } // Path Params const localVarPath = '/app/rest/vcs-root-instances/{vcsRootInstanceLocator}/repositoryState' .replace('{' + 'vcsRootInstanceLocator' + '}', encodeURIComponent(String(vcsRootInstanceLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Download specific file. * @param path * @param vcsRootInstanceLocator */ public async downloadFile(path: string, vcsRootInstanceLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'path' is not null or undefined if (path === null || path === undefined) { throw new RequiredError('Required parameter path was null or undefined when calling downloadFile.'); } // verify required parameter 'vcsRootInstanceLocator' is not null or undefined if (vcsRootInstanceLocator === null || vcsRootInstanceLocator === undefined) { throw new RequiredError('Required parameter vcsRootInstanceLocator was null or undefined when calling downloadFile.'); } // Path Params const localVarPath = '/app/rest/vcs-root-instances/{vcsRootInstanceLocator}/files/latest/files{path}' .replace('{' + 'path' + '}', encodeURIComponent(String(path))) .replace('{' + 'vcsRootInstanceLocator' + '}', encodeURIComponent(String(vcsRootInstanceLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all VCS root instances. * @param locator * @param fields */ public async getAllVcsRootInstances(locator?: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/vcs-root-instances'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "VcsRootInstanceLocator")); } if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get metadata of specific file. * @param path * @param vcsRootInstanceLocator * @param fields */ public async getFileMetadata(path: string, vcsRootInstanceLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'path' is not null or undefined if (path === null || path === undefined) { throw new RequiredError('Required parameter path was null or undefined when calling getFileMetadata.'); } // verify required parameter 'vcsRootInstanceLocator' is not null or undefined if (vcsRootInstanceLocator === null || vcsRootInstanceLocator === undefined) { throw new RequiredError('Required parameter vcsRootInstanceLocator was null or undefined when calling getFileMetadata.'); } // Path Params const localVarPath = '/app/rest/vcs-root-instances/{vcsRootInstanceLocator}/files/latest/metadata{path}' .replace('{' + 'path' + '}', encodeURIComponent(String(path))) .replace('{' + 'vcsRootInstanceLocator' + '}', encodeURIComponent(String(vcsRootInstanceLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * List all files. * @param vcsRootInstanceLocator * @param basePath * @param locator * @param fields */ public async getFilesList(vcsRootInstanceLocator: string, basePath?: string, locator?: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'vcsRootInstanceLocator' is not null or undefined if (vcsRootInstanceLocator === null || vcsRootInstanceLocator === undefined) { throw new RequiredError('Required parameter vcsRootInstanceLocator was null or undefined when calling getFilesList.'); } // Path Params const localVarPath = '/app/rest/vcs-root-instances/{vcsRootInstanceLocator}/files/latest' .replace('{' + 'vcsRootInstanceLocator' + '}', encodeURIComponent(String(vcsRootInstanceLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (basePath !== undefined) { requestContext.setQueryParam("basePath", ObjectSerializer.serialize(basePath, "string", "")); } if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "")); } if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * List files under this path. * @param path * @param vcsRootInstanceLocator * @param basePath * @param locator * @param fields */ public async getFilesListForSubpath(path: string, vcsRootInstanceLocator: string, basePath?: string, locator?: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'path' is not null or undefined if (path === null || path === undefined) { throw new RequiredError('Required parameter path was null or undefined when calling getFilesListForSubpath.'); } // verify required parameter 'vcsRootInstanceLocator' is not null or undefined if (vcsRootInstanceLocator === null || vcsRootInstanceLocator === undefined) { throw new RequiredError('Required parameter vcsRootInstanceLocator was null or undefined when calling getFilesListForSubpath.'); } // Path Params const localVarPath = '/app/rest/vcs-root-instances/{vcsRootInstanceLocator}/files/latest/{path}' .replace('{' + 'path' + '}', encodeURIComponent(String(path))) .replace('{' + 'vcsRootInstanceLocator' + '}', encodeURIComponent(String(vcsRootInstanceLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (basePath !== undefined) { requestContext.setQueryParam("basePath", ObjectSerializer.serialize(basePath, "string", "")); } if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "")); } if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get VCS root instance matching the locator. * @param vcsRootInstanceLocator * @param fields */ public async getVcsRootInstance(vcsRootInstanceLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'vcsRootInstanceLocator' is not null or undefined if (vcsRootInstanceLocator === null || vcsRootInstanceLocator === undefined) { throw new RequiredError('Required parameter vcsRootInstanceLocator was null or undefined when calling getVcsRootInstance.'); } // Path Params const localVarPath = '/app/rest/vcs-root-instances/{vcsRootInstanceLocator}' .replace('{' + 'vcsRootInstanceLocator' + '}', encodeURIComponent(String(vcsRootInstanceLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get the creation date of the matching VCS root instance. * @param vcsRootInstanceLocator */ public async getVcsRootInstanceCreationDate(vcsRootInstanceLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'vcsRootInstanceLocator' is not null or undefined if (vcsRootInstanceLocator === null || vcsRootInstanceLocator === undefined) { throw new RequiredError('Required parameter vcsRootInstanceLocator was null or undefined when calling getVcsRootInstanceCreationDate.'); } // Path Params const localVarPath = '/app/rest/vcs-root-instances/{vcsRootInstanceLocator}/repositoryState/creationDate' .replace('{' + 'vcsRootInstanceLocator' + '}', encodeURIComponent(String(vcsRootInstanceLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get a field of the matching VCS root instance. * @param vcsRootInstanceLocator * @param field */ public async getVcsRootInstanceField(vcsRootInstanceLocator: string, field: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'vcsRootInstanceLocator' is not null or undefined if (vcsRootInstanceLocator === null || vcsRootInstanceLocator === undefined) { throw new RequiredError('Required parameter vcsRootInstanceLocator was null or undefined when calling getVcsRootInstanceField.'); } // verify required parameter 'field' is not null or undefined if (field === null || field === undefined) { throw new RequiredError('Required parameter field was null or undefined when calling getVcsRootInstanceField.'); } // Path Params const localVarPath = '/app/rest/vcs-root-instances/{vcsRootInstanceLocator}/{field}' .replace('{' + 'vcsRootInstanceLocator' + '}', encodeURIComponent(String(vcsRootInstanceLocator))) .replace('{' + 'field' + '}', encodeURIComponent(String(field))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all properties of the matching VCS root instance. * @param vcsRootInstanceLocator * @param fields */ public async getVcsRootInstanceProperties(vcsRootInstanceLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'vcsRootInstanceLocator' is not null or undefined if (vcsRootInstanceLocator === null || vcsRootInstanceLocator === undefined) { throw new RequiredError('Required parameter vcsRootInstanceLocator was null or undefined when calling getVcsRootInstanceProperties.'); } // Path Params const localVarPath = '/app/rest/vcs-root-instances/{vcsRootInstanceLocator}/properties' .replace('{' + 'vcsRootInstanceLocator' + '}', encodeURIComponent(String(vcsRootInstanceLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get the repository state of the matching VCS root instance. * @param vcsRootInstanceLocator * @param fields */ public async getVcsRootInstanceRepositoryState(vcsRootInstanceLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'vcsRootInstanceLocator' is not null or undefined if (vcsRootInstanceLocator === null || vcsRootInstanceLocator === undefined) { throw new RequiredError('Required parameter vcsRootInstanceLocator was null or undefined when calling getVcsRootInstanceRepositoryState.'); } // Path Params const localVarPath = '/app/rest/vcs-root-instances/{vcsRootInstanceLocator}/repositoryState' .replace('{' + 'vcsRootInstanceLocator' + '}', encodeURIComponent(String(vcsRootInstanceLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get specific file zipped. * @param path * @param vcsRootInstanceLocator * @param basePath * @param locator * @param name */ public async getZippedFile(path: string, vcsRootInstanceLocator: string, basePath?: string, locator?: string, name?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'path' is not null or undefined if (path === null || path === undefined) { throw new RequiredError('Required parameter path was null or undefined when calling getZippedFile.'); } // verify required parameter 'vcsRootInstanceLocator' is not null or undefined if (vcsRootInstanceLocator === null || vcsRootInstanceLocator === undefined) { throw new RequiredError('Required parameter vcsRootInstanceLocator was null or undefined when calling getZippedFile.'); } // Path Params const localVarPath = '/app/rest/vcs-root-instances/{vcsRootInstanceLocator}/files/latest/archived{path}' .replace('{' + 'path' + '}', encodeURIComponent(String(path))) .replace('{' + 'vcsRootInstanceLocator' + '}', encodeURIComponent(String(vcsRootInstanceLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (basePath !== undefined) { requestContext.setQueryParam("basePath", ObjectSerializer.serialize(basePath, "string", "")); } if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "")); } if (name !== undefined) { requestContext.setQueryParam("name", ObjectSerializer.serialize(name, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Check for the pending changes for all VCS root instances. * @param locator * @param requestor * @param fields */ public async requestPendingChangesCheck(locator?: string, requestor?: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/vcs-root-instances/checkingForChangesQueue'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "VcsRootInstanceLocator")); } if (requestor !== undefined) { requestContext.setQueryParam("requestor", ObjectSerializer.serialize(requestor, "string", "")); } if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get a field of the matching VCS root instance. * @param vcsRootInstanceLocator * @param field * @param body */ public async setVcsRootInstanceField(vcsRootInstanceLocator: string, field: string, body?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'vcsRootInstanceLocator' is not null or undefined if (vcsRootInstanceLocator === null || vcsRootInstanceLocator === undefined) { throw new RequiredError('Required parameter vcsRootInstanceLocator was null or undefined when calling setVcsRootInstanceField.'); } // verify required parameter 'field' is not null or undefined if (field === null || field === undefined) { throw new RequiredError('Required parameter field was null or undefined when calling setVcsRootInstanceField.'); } // Path Params const localVarPath = '/app/rest/vcs-root-instances/{vcsRootInstanceLocator}/{field}' .replace('{' + 'vcsRootInstanceLocator' + '}', encodeURIComponent(String(vcsRootInstanceLocator))) .replace('{' + 'field' + '}', encodeURIComponent(String(field))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "text/plain" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "string", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update the repository state of the matching VCS root instance. * @param vcsRootInstanceLocator * @param fields * @param body */ public async setVcsRootInstanceRepositoryState(vcsRootInstanceLocator: string, fields?: string, body?: Entries, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'vcsRootInstanceLocator' is not null or undefined if (vcsRootInstanceLocator === null || vcsRootInstanceLocator === undefined) { throw new RequiredError('Required parameter vcsRootInstanceLocator was null or undefined when calling setVcsRootInstanceRepositoryState.'); } // Path Params const localVarPath = '/app/rest/vcs-root-instances/{vcsRootInstanceLocator}/repositoryState' .replace('{' + 'vcsRootInstanceLocator' + '}', encodeURIComponent(String(vcsRootInstanceLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Entries", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Send the commit hook notification. * @param locator * @param okOnNothingFound */ public async triggerCommitHookNotification(locator?: string, okOnNothingFound?: boolean, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/vcs-root-instances/commitHookNotification'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "VcsRootInstanceLocator")); } if (okOnNothingFound !== undefined) { requestContext.setQueryParam("okOnNothingFound", ObjectSerializer.serialize(okOnNothingFound, "boolean", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } } export class VcsRootInstanceApiResponseProcessor { /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to deleteVcsRootInstanceField * @throws ApiException if the response code was not in [200, 299] */ public async deleteVcsRootInstanceField(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to deleteVcsRootInstanceRepositoryState * @throws ApiException if the response code was not in [200, 299] */ public async deleteVcsRootInstanceRepositoryState(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to downloadFile * @throws ApiException if the response code was not in [200, 299] */ public async downloadFile(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAllVcsRootInstances * @throws ApiException if the response code was not in [200, 299] */ public async getAllVcsRootInstances(response: ResponseContext): Promise<VcsRootInstances > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: VcsRootInstances = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "VcsRootInstances", "" ) as VcsRootInstances; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: VcsRootInstances = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "VcsRootInstances", "" ) as VcsRootInstances; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getFileMetadata * @throws ApiException if the response code was not in [200, 299] */ public async getFileMetadata(response: ResponseContext): Promise<any > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: any = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "any", "" ) as any; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: any = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "any", "" ) as any; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getFilesList * @throws ApiException if the response code was not in [200, 299] */ public async getFilesList(response: ResponseContext): Promise<Files > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Files = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Files", "" ) as Files; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Files = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Files", "" ) as Files; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getFilesListForSubpath * @throws ApiException if the response code was not in [200, 299] */ public async getFilesListForSubpath(response: ResponseContext): Promise<Files > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Files = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Files", "" ) as Files; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Files = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Files", "" ) as Files; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getVcsRootInstance * @throws ApiException if the response code was not in [200, 299] */ public async getVcsRootInstance(response: ResponseContext): Promise<VcsRootInstance > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: VcsRootInstance = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "VcsRootInstance", "" ) as VcsRootInstance; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: VcsRootInstance = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "VcsRootInstance", "" ) as VcsRootInstance; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getVcsRootInstanceCreationDate * @throws ApiException if the response code was not in [200, 299] */ public async getVcsRootInstanceCreationDate(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getVcsRootInstanceField * @throws ApiException if the response code was not in [200, 299] */ public async getVcsRootInstanceField(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getVcsRootInstanceProperties * @throws ApiException if the response code was not in [200, 299] */ public async getVcsRootInstanceProperties(response: ResponseContext): Promise<Properties > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Properties = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Properties", "" ) as Properties; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Properties = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Properties", "" ) as Properties; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getVcsRootInstanceRepositoryState * @throws ApiException if the response code was not in [200, 299] */ public async getVcsRootInstanceRepositoryState(response: ResponseContext): Promise<Entries > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Entries = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Entries", "" ) as Entries; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Entries = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Entries", "" ) as Entries; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getZippedFile * @throws ApiException if the response code was not in [200, 299] */ public async getZippedFile(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to requestPendingChangesCheck * @throws ApiException if the response code was not in [200, 299] */ public async requestPendingChangesCheck(response: ResponseContext): Promise<VcsRootInstances > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: VcsRootInstances = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "VcsRootInstances", "" ) as VcsRootInstances; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: VcsRootInstances = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "VcsRootInstances", "" ) as VcsRootInstances; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setVcsRootInstanceField * @throws ApiException if the response code was not in [200, 299] */ public async setVcsRootInstanceField(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setVcsRootInstanceRepositoryState * @throws ApiException if the response code was not in [200, 299] */ public async setVcsRootInstanceRepositoryState(response: ResponseContext): Promise<Entries > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Entries = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Entries", "" ) as Entries; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Entries = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Entries", "" ) as Entries; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to triggerCommitHookNotification * @throws ApiException if the response code was not in [200, 299] */ public async triggerCommitHookNotification(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } } <file_sep>/ts-schema/schema/rest-api/deno/models/BuildLocator.ts /** * TeamCity REST API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * OpenAPI spec version: 2018.1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { HttpFile } from '../http/http.ts'; export class BuildLocator { 'affectedProject'?: string; 'agent'?: string; 'agentTypeId'?: number; 'any'?: boolean; 'artifactDependency'?: string; 'branch'?: string; 'buildType'?: string; 'canceled'?: boolean; 'compatibleAgent'?: string; 'composite'?: boolean; 'count'?: number; 'defaultFilter'?: boolean; 'failedToStart'?: boolean; 'finishDate'?: string; 'finished'?: boolean; 'hanging'?: boolean; 'history'?: boolean; 'id'?: number; 'item'?: string; 'lookupLimit'?: number; 'number'?: string; 'personal'?: boolean; 'pinned'?: boolean; 'project'?: string; 'property'?: string; 'queued'?: boolean; 'queuedDate'?: string; 'running'?: boolean; 'snapshotDependency'?: string; 'start'?: number; 'startDate'?: string; 'state'?: string; 'status'?: string; 'tag'?: string; 'taskId'?: number; 'user'?: string; static readonly discriminator: string | undefined = undefined; static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [ { "name": "affectedProject", "baseName": "affectedProject", "type": "string", "format": "ProjectLocator" }, { "name": "agent", "baseName": "agent", "type": "string", "format": "AgentLocator" }, { "name": "agentTypeId", "baseName": "agentTypeId", "type": "number", "format": "int32" }, { "name": "any", "baseName": "any", "type": "boolean", "format": "" }, { "name": "artifactDependency", "baseName": "artifactDependency", "type": "string", "format": "" }, { "name": "branch", "baseName": "branch", "type": "string", "format": "BranchLocator" }, { "name": "buildType", "baseName": "buildType", "type": "string", "format": "BuildTypeLocator" }, { "name": "canceled", "baseName": "canceled", "type": "boolean", "format": "" }, { "name": "compatibleAgent", "baseName": "compatibleAgent", "type": "string", "format": "AgentLocator" }, { "name": "composite", "baseName": "composite", "type": "boolean", "format": "" }, { "name": "count", "baseName": "count", "type": "number", "format": "int32" }, { "name": "defaultFilter", "baseName": "defaultFilter", "type": "boolean", "format": "" }, { "name": "failedToStart", "baseName": "failedToStart", "type": "boolean", "format": "" }, { "name": "finishDate", "baseName": "finishDate", "type": "string", "format": "date:&lt;yyyyMMddTHHmmss+ZZZZ&gt;,build:&lt;build locator&gt;,condition:&lt;before/after&gt;" }, { "name": "finished", "baseName": "finished", "type": "boolean", "format": "" }, { "name": "hanging", "baseName": "hanging", "type": "boolean", "format": "" }, { "name": "history", "baseName": "history", "type": "boolean", "format": "" }, { "name": "id", "baseName": "id", "type": "number", "format": "int32" }, { "name": "item", "baseName": "item", "type": "string", "format": "item:(&lt;locator1&gt;),item:(&lt;locator2&gt;...)" }, { "name": "lookupLimit", "baseName": "lookupLimit", "type": "number", "format": "int32" }, { "name": "number", "baseName": "number", "type": "string", "format": "" }, { "name": "personal", "baseName": "personal", "type": "boolean", "format": "" }, { "name": "pinned", "baseName": "pinned", "type": "boolean", "format": "" }, { "name": "project", "baseName": "project", "type": "string", "format": "ProjectLocator" }, { "name": "property", "baseName": "property", "type": "string", "format": "property:(name:&lt;name&gt;,value:&lt;value&gt;,matchType:&lt;matchType&gt;)" }, { "name": "queued", "baseName": "queued", "type": "boolean", "format": "" }, { "name": "queuedDate", "baseName": "queuedDate", "type": "string", "format": "date:&lt;yyyyMMddTHHmmss+ZZZZ&gt;,build:&lt;build locator&gt;,condition:&lt;before/after&gt;" }, { "name": "running", "baseName": "running", "type": "boolean", "format": "" }, { "name": "snapshotDependency", "baseName": "snapshotDependency", "type": "string", "format": "" }, { "name": "start", "baseName": "start", "type": "number", "format": "int32" }, { "name": "startDate", "baseName": "startDate", "type": "string", "format": "date:&lt;yyyyMMddTHHmmss+ZZZZ&gt;,build:&lt;build locator&gt;,condition:&lt;before/after&gt;" }, { "name": "state", "baseName": "state", "type": "string", "format": "" }, { "name": "status", "baseName": "status", "type": "string", "format": "" }, { "name": "tag", "baseName": "tag", "type": "string", "format": "TagLocator" }, { "name": "taskId", "baseName": "taskId", "type": "number", "format": "int32" }, { "name": "user", "baseName": "user", "type": "string", "format": "UserLocator" } ]; static getAttributeTypeMap() { return BuildLocator.attributeTypeMap; } public constructor() { } } <file_sep>/ts-schema/schema/rest-api/deno/models/UserLocator.ts /** * TeamCity REST API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * OpenAPI spec version: 2018.1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { HttpFile } from '../http/http.ts'; export class UserLocator { 'affectedGroup'?: string; 'email'?: string; 'group'?: string; 'id'?: string; 'item'?: string; 'lastLogin'?: Date; 'name'?: string; 'property'?: string; 'role'?: string; 'username'?: string; static readonly discriminator: string | undefined = undefined; static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [ { "name": "affectedGroup", "baseName": "affectedGroup", "type": "string", "format": "UserGroupLocator" }, { "name": "email", "baseName": "email", "type": "string", "format": "" }, { "name": "group", "baseName": "group", "type": "string", "format": "UserGroupLocator" }, { "name": "id", "baseName": "id", "type": "string", "format": "" }, { "name": "item", "baseName": "item", "type": "string", "format": "item:(&lt;locator1&gt;),item:(&lt;locator2&gt;...)" }, { "name": "lastLogin", "baseName": "lastLogin", "type": "Date", "format": "date-time" }, { "name": "name", "baseName": "name", "type": "string", "format": "" }, { "name": "property", "baseName": "property", "type": "string", "format": "property:(name:&lt;name&gt;,value:&lt;value&gt;,matchType:&lt;matchType&gt;)" }, { "name": "role", "baseName": "role", "type": "string", "format": "RoleLocator" }, { "name": "username", "baseName": "username", "type": "string", "format": "" } ]; static getAttributeTypeMap() { return UserLocator.attributeTypeMap; } public constructor() { } } <file_sep>/ts-schema/schema/rest-api/deno/models/Revision.ts /** * TeamCity REST API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * OpenAPI spec version: 2018.1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { VcsRootInstance } from './VcsRootInstance.ts'; import { HttpFile } from '../http/http.ts'; export class Revision { 'version'?: string; 'internalVersion'?: string; 'vcsBranchName'?: string; 'vcsRootInstance'?: VcsRootInstance; 'checkoutRules'?: string; static readonly discriminator: string | undefined = undefined; static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [ { "name": "version", "baseName": "version", "type": "string", "format": "" }, { "name": "internalVersion", "baseName": "internalVersion", "type": "string", "format": "" }, { "name": "vcsBranchName", "baseName": "vcsBranchName", "type": "string", "format": "" }, { "name": "vcsRootInstance", "baseName": "vcs-root-instance", "type": "VcsRootInstance", "format": "" }, { "name": "checkoutRules", "baseName": "checkout-rules", "type": "string", "format": "" } ]; static getAttributeTypeMap() { return Revision.attributeTypeMap; } public constructor() { } } <file_sep>/ts-schema/schema/rest-api/deno/models/VcsRootInstanceLocator.ts /** * TeamCity REST API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * OpenAPI spec version: 2018.1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { HttpFile } from '../http/http.ts'; export class VcsRootInstanceLocator { 'affectedProject'?: string; 'build'?: string; 'buildType'?: string; 'count'?: number; 'id'?: number; 'item'?: string; 'lookupLimit'?: number; 'project'?: string; 'property'?: string; 'start'?: number; 'type'?: string; 'vcsRoot'?: string; 'versionedSettings'?: boolean; static readonly discriminator: string | undefined = undefined; static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [ { "name": "affectedProject", "baseName": "affectedProject", "type": "string", "format": "ProjectLocator" }, { "name": "build", "baseName": "build", "type": "string", "format": "BuildLocator" }, { "name": "buildType", "baseName": "buildType", "type": "string", "format": "BuildTypeLocator" }, { "name": "count", "baseName": "count", "type": "number", "format": "int32" }, { "name": "id", "baseName": "id", "type": "number", "format": "int32" }, { "name": "item", "baseName": "item", "type": "string", "format": "item:(&lt;locator1&gt;),item:(&lt;locator2&gt;...)" }, { "name": "lookupLimit", "baseName": "lookupLimit", "type": "number", "format": "int32" }, { "name": "project", "baseName": "project", "type": "string", "format": "ProjectLocator" }, { "name": "property", "baseName": "property", "type": "string", "format": "property:(name:&lt;name&gt;,value:&lt;value&gt;,matchType:&lt;matchType&gt;)" }, { "name": "start", "baseName": "start", "type": "number", "format": "int32" }, { "name": "type", "baseName": "type", "type": "string", "format": "" }, { "name": "vcsRoot", "baseName": "vcsRoot", "type": "string", "format": "VcsRootLocator" }, { "name": "versionedSettings", "baseName": "versionedSettings", "type": "boolean", "format": "" } ]; static getAttributeTypeMap() { return VcsRootInstanceLocator.attributeTypeMap; } public constructor() { } } <file_sep>/ts-schema/schema/rest-api/deno/apis/BuildQueueApi.ts // TODO: better import syntax? import { BaseAPIRequestFactory, RequiredError } from './baseapi.ts'; import {Configuration} from '../configuration.ts'; import { RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http.ts'; import {ObjectSerializer} from '../models/ObjectSerializer.ts'; import {ApiException} from './exception.ts'; import {isCodeInRange} from '../util.ts'; import { Agents } from '../models/Agents.ts'; import { Build } from '../models/Build.ts'; import { BuildCancelRequest } from '../models/BuildCancelRequest.ts'; import { Builds } from '../models/Builds.ts'; import { Tags } from '../models/Tags.ts'; /** * no description */ export class BuildQueueApiRequestFactory extends BaseAPIRequestFactory { /** * Add a new build to the queue. * @param moveToTop * @param body */ public async addBuildToQueue(moveToTop?: boolean, body?: Build, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/buildQueue'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (moveToTop !== undefined) { requestContext.setQueryParam("moveToTop", ObjectSerializer.serialize(moveToTop, "boolean", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Build", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Add tags to the matching build. * @param buildLocator * @param body */ public async addTagsToBuildOfBuildQueue(buildLocator: string, body?: Tags, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling addTagsToBuildOfBuildQueue.'); } // Path Params const localVarPath = '/app/rest/buildQueue/{buildLocator}/tags' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Tags", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Cancel a queued matching build. * @param queuedBuildLocator * @param body */ public async cancelQueuedBuild(queuedBuildLocator: string, body?: BuildCancelRequest, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'queuedBuildLocator' is not null or undefined if (queuedBuildLocator === null || queuedBuildLocator === undefined) { throw new RequiredError('Required parameter queuedBuildLocator was null or undefined when calling cancelQueuedBuild.'); } // Path Params const localVarPath = '/app/rest/buildQueue/{queuedBuildLocator}' .replace('{' + 'queuedBuildLocator' + '}', encodeURIComponent(String(queuedBuildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "BuildCancelRequest", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Delete all queued builds. * @param locator * @param fields */ public async deleteAllQueuedBuilds(locator?: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/buildQueue'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "BuildQueueLocator")); } if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Delete a queued matching build. * @param queuedBuildLocator */ public async deleteQueuedBuild(queuedBuildLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'queuedBuildLocator' is not null or undefined if (queuedBuildLocator === null || queuedBuildLocator === undefined) { throw new RequiredError('Required parameter queuedBuildLocator was null or undefined when calling deleteQueuedBuild.'); } // Path Params const localVarPath = '/app/rest/buildQueue/{queuedBuildLocator}' .replace('{' + 'queuedBuildLocator' + '}', encodeURIComponent(String(queuedBuildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all queued builds. * @param locator * @param fields */ public async getAllQueuedBuilds(locator?: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/buildQueue'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "BuildQueueLocator")); } if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get compatible agents for a queued matching build. * @param queuedBuildLocator * @param fields */ public async getCompatibleAgentsForBuild(queuedBuildLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'queuedBuildLocator' is not null or undefined if (queuedBuildLocator === null || queuedBuildLocator === undefined) { throw new RequiredError('Required parameter queuedBuildLocator was null or undefined when calling getCompatibleAgentsForBuild.'); } // Path Params const localVarPath = '/app/rest/buildQueue/{queuedBuildLocator}/compatibleAgents' .replace('{' + 'queuedBuildLocator' + '}', encodeURIComponent(String(queuedBuildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get a queued matching build. * @param queuedBuildLocator * @param fields */ public async getQueuedBuild(queuedBuildLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'queuedBuildLocator' is not null or undefined if (queuedBuildLocator === null || queuedBuildLocator === undefined) { throw new RequiredError('Required parameter queuedBuildLocator was null or undefined when calling getQueuedBuild.'); } // Path Params const localVarPath = '/app/rest/buildQueue/{queuedBuildLocator}' .replace('{' + 'queuedBuildLocator' + '}', encodeURIComponent(String(queuedBuildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get the queue position of a queued matching build. * @param queuePosition * @param fields */ public async getQueuedBuildPosition(queuePosition: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'queuePosition' is not null or undefined if (queuePosition === null || queuePosition === undefined) { throw new RequiredError('Required parameter queuePosition was null or undefined when calling getQueuedBuildPosition.'); } // Path Params const localVarPath = '/app/rest/buildQueue/order/{queuePosition}' .replace('{' + 'queuePosition' + '}', encodeURIComponent(String(queuePosition))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get tags of the queued matching build. * @param buildLocator * @param locator * @param fields */ public async getQueuedBuildTags(buildLocator: string, locator?: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'buildLocator' is not null or undefined if (buildLocator === null || buildLocator === undefined) { throw new RequiredError('Required parameter buildLocator was null or undefined when calling getQueuedBuildTags.'); } // Path Params const localVarPath = '/app/rest/buildQueue/{buildLocator}/tags' .replace('{' + 'buildLocator' + '}', encodeURIComponent(String(buildLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "")); } if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update the queue position of a queued matching build. * @param queuePosition * @param fields * @param body */ public async setQueuedBuildPosition(queuePosition: string, fields?: string, body?: Build, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'queuePosition' is not null or undefined if (queuePosition === null || queuePosition === undefined) { throw new RequiredError('Required parameter queuePosition was null or undefined when calling setQueuedBuildPosition.'); } // Path Params const localVarPath = '/app/rest/buildQueue/order/{queuePosition}' .replace('{' + 'queuePosition' + '}', encodeURIComponent(String(queuePosition))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Build", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update the build queue order. * @param fields * @param body */ public async setQueuedBuildsOrder(fields?: string, body?: Builds, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/buildQueue/order'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Builds", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } } export class BuildQueueApiResponseProcessor { /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to addBuildToQueue * @throws ApiException if the response code was not in [200, 299] */ public async addBuildToQueue(response: ResponseContext): Promise<Build > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Build = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Build", "" ) as Build; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Build = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Build", "" ) as Build; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to addTagsToBuildOfBuildQueue * @throws ApiException if the response code was not in [200, 299] */ public async addTagsToBuildOfBuildQueue(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to cancelQueuedBuild * @throws ApiException if the response code was not in [200, 299] */ public async cancelQueuedBuild(response: ResponseContext): Promise<Build > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Build = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Build", "" ) as Build; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Build = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Build", "" ) as Build; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to deleteAllQueuedBuilds * @throws ApiException if the response code was not in [200, 299] */ public async deleteAllQueuedBuilds(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to deleteQueuedBuild * @throws ApiException if the response code was not in [200, 299] */ public async deleteQueuedBuild(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAllQueuedBuilds * @throws ApiException if the response code was not in [200, 299] */ public async getAllQueuedBuilds(response: ResponseContext): Promise<Builds > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Builds = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Builds", "" ) as Builds; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Builds = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Builds", "" ) as Builds; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getCompatibleAgentsForBuild * @throws ApiException if the response code was not in [200, 299] */ public async getCompatibleAgentsForBuild(response: ResponseContext): Promise<Agents > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Agents = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Agents", "" ) as Agents; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Agents = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Agents", "" ) as Agents; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getQueuedBuild * @throws ApiException if the response code was not in [200, 299] */ public async getQueuedBuild(response: ResponseContext): Promise<Build > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Build = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Build", "" ) as Build; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Build = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Build", "" ) as Build; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getQueuedBuildPosition * @throws ApiException if the response code was not in [200, 299] */ public async getQueuedBuildPosition(response: ResponseContext): Promise<Build > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Build = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Build", "" ) as Build; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Build = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Build", "" ) as Build; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getQueuedBuildTags * @throws ApiException if the response code was not in [200, 299] */ public async getQueuedBuildTags(response: ResponseContext): Promise<Tags > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Tags = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Tags", "" ) as Tags; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Tags = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Tags", "" ) as Tags; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setQueuedBuildPosition * @throws ApiException if the response code was not in [200, 299] */ public async setQueuedBuildPosition(response: ResponseContext): Promise<Build > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Build = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Build", "" ) as Build; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Build = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Build", "" ) as Build; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setQueuedBuildsOrder * @throws ApiException if the response code was not in [200, 299] */ public async setQueuedBuildsOrder(response: ResponseContext): Promise<Builds > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Builds = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Builds", "" ) as Builds; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Builds = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Builds", "" ) as Builds; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } } <file_sep>/ts-schema/schema/xml/build_type.ts import { Parameter, Parameters } from "./parameter.ts"; import { ProjectCleanup, ProjectCleanupPolicy } from "./project_cleanup.ts"; import { ProjectExtension, ProjectExtensions } from "./project_extension.ts"; export interface BuildType { "?xml": { "@version": string; "@encoding": string }; "build-type": { "@xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance"; "@xsi:noNamespaceSchemaLocation": "https://www.jetbrains.com/teamcity/schemas/2020.1/project-config.xsd"; "@uuid": string; name: string; description?: string; settings: { options?: BuildOptions; parameters?: Parameters; "vcs-settings"?: VcsSettings; requirements?: BuildRequirements; "build-triggers"?: BuildTriggers; "build-runners"?: BuildRunners; "build-extensions"?: BuildExtensions; cleanup?: BuildCleanup; }; }; } export interface BuildOptions { option: Parameter[]; } export interface VcsSettings { "vcs-entry-ref": { "@root-id": string; "checkout-rule": { "@rule": string; }[]; }[]; } export interface BuildRequirements { [k: string]: BuildRequirement[]; } export interface BuildRequirement { "@id": string; "@name": string; "@value"?: string; } export interface BuildTriggers { "build-trigger": BuildTrigger[]; } export interface BuildTrigger { "@id": string; "@type": string; parameters: { param: Parameter[]; }; } export interface BuildRunners { "runner": BuildRunner[]; } export interface BuildRunner { "@id": string; "@name": string; "@type": string; conditions?: BuildConditions; parameters?: Parameters; } export interface BuildConditions { [k: string]: BuildCondition[]; } export interface BuildCondition { "@name": string; "@value"?: string; } export type BuildExtensions = ProjectExtensions; export type BuildExtension = ProjectExtension; export type BuildCleanup = ProjectCleanup; export type BuildCleanupPolicy = ProjectCleanupPolicy; <file_sep>/ts-schema/schema/rest-api/deno/apis/BuildTypeApi.ts // TODO: better import syntax? import { BaseAPIRequestFactory, RequiredError } from './baseapi.ts'; import {Configuration} from '../configuration.ts'; import { RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http.ts'; import {ObjectSerializer} from '../models/ObjectSerializer.ts'; import {ApiException} from './exception.ts'; import {isCodeInRange} from '../util.ts'; import { AgentRequirement } from '../models/AgentRequirement.ts'; import { AgentRequirements } from '../models/AgentRequirements.ts'; import { ArtifactDependencies } from '../models/ArtifactDependencies.ts'; import { ArtifactDependency } from '../models/ArtifactDependency.ts'; import { Branches } from '../models/Branches.ts'; import { BuildType } from '../models/BuildType.ts'; import { BuildTypes } from '../models/BuildTypes.ts'; import { Builds } from '../models/Builds.ts'; import { Feature } from '../models/Feature.ts'; import { Features } from '../models/Features.ts'; import { Files } from '../models/Files.ts'; import { Investigations } from '../models/Investigations.ts'; import { Items } from '../models/Items.ts'; import { Properties } from '../models/Properties.ts'; import { Property } from '../models/Property.ts'; import { SnapshotDependencies } from '../models/SnapshotDependencies.ts'; import { SnapshotDependency } from '../models/SnapshotDependency.ts'; import { Step } from '../models/Step.ts'; import { Steps } from '../models/Steps.ts'; import { Tags } from '../models/Tags.ts'; import { Trigger } from '../models/Trigger.ts'; import { Triggers } from '../models/Triggers.ts'; import { Type } from '../models/Type.ts'; import { VcsRootEntries } from '../models/VcsRootEntries.ts'; import { VcsRootEntry } from '../models/VcsRootEntry.ts'; import { VcsRootInstances } from '../models/VcsRootInstances.ts'; /** * no description */ export class BuildTypeApiRequestFactory extends BaseAPIRequestFactory { /** * Add an agent requirement to the matching build configuration. * @param btLocator * @param fields * @param body */ public async addAgentRequirementToBuildType(btLocator: string, fields?: string, body?: AgentRequirement, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling addAgentRequirementToBuildType.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/agent-requirements' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "AgentRequirement", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Add an artifact dependency to the matching build configuration. * @param btLocator * @param fields * @param body */ public async addArtifactDependencyToBuildType(btLocator: string, fields?: string, body?: ArtifactDependency, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling addArtifactDependencyToBuildType.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/artifact-dependencies' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "ArtifactDependency", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Add build feature to the matching build configuration. * @param btLocator * @param fields * @param body */ public async addBuildFeatureToBuildType(btLocator: string, fields?: string, body?: Feature, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling addBuildFeatureToBuildType.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/features' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Feature", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Add a build step to the matching build configuration. * @param btLocator * @param fields * @param body */ public async addBuildStepToBuildType(btLocator: string, fields?: string, body?: Step, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling addBuildStepToBuildType.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/steps' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Step", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Add a build template to the matching build configuration. * @param btLocator * @param optimizeSettings * @param fields * @param body */ public async addBuildTemplate(btLocator: string, optimizeSettings?: boolean, fields?: string, body?: BuildType, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling addBuildTemplate.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/templates' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (optimizeSettings !== undefined) { requestContext.setQueryParam("optimizeSettings", ObjectSerializer.serialize(optimizeSettings, "boolean", "")); } if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "BuildType", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update build feature parameter for the matching build configuration. * @param btLocator * @param featureId * @param parameterName * @param body */ public async addParameterToBuildFeature(btLocator: string, featureId: string, parameterName: string, body?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling addParameterToBuildFeature.'); } // verify required parameter 'featureId' is not null or undefined if (featureId === null || featureId === undefined) { throw new RequiredError('Required parameter featureId was null or undefined when calling addParameterToBuildFeature.'); } // verify required parameter 'parameterName' is not null or undefined if (parameterName === null || parameterName === undefined) { throw new RequiredError('Required parameter parameterName was null or undefined when calling addParameterToBuildFeature.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/features/{featureId}/parameters/{parameterName}' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'featureId' + '}', encodeURIComponent(String(featureId))) .replace('{' + 'parameterName' + '}', encodeURIComponent(String(parameterName))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "text/plain" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "string", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Add a parameter to a build step of the matching build configuration. * @param btLocator * @param stepId * @param parameterName * @param body */ public async addParameterToBuildStep(btLocator: string, stepId: string, parameterName: string, body?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling addParameterToBuildStep.'); } // verify required parameter 'stepId' is not null or undefined if (stepId === null || stepId === undefined) { throw new RequiredError('Required parameter stepId was null or undefined when calling addParameterToBuildStep.'); } // verify required parameter 'parameterName' is not null or undefined if (parameterName === null || parameterName === undefined) { throw new RequiredError('Required parameter parameterName was null or undefined when calling addParameterToBuildStep.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/steps/{stepId}/parameters/{parameterName}' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'stepId' + '}', encodeURIComponent(String(stepId))) .replace('{' + 'parameterName' + '}', encodeURIComponent(String(parameterName))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "text/plain" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "string", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Add a snapshot dependency to the matching build configuration. * @param btLocator * @param fields * @param body */ public async addSnapshotDependencyToBuildType(btLocator: string, fields?: string, body?: SnapshotDependency, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling addSnapshotDependencyToBuildType.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/snapshot-dependencies' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "SnapshotDependency", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Add a trigger to the matching build configuration. * @param btLocator * @param fields * @param body */ public async addTriggerToBuildType(btLocator: string, fields?: string, body?: Trigger, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling addTriggerToBuildType.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/triggers' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Trigger", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Add a VCS root to the matching build. * @param btLocator * @param fields * @param body */ public async addVcsRootToBuildType(btLocator: string, fields?: string, body?: VcsRootEntry, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling addVcsRootToBuildType.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/vcs-root-entries' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "VcsRootEntry", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Create a build parameter. * @param btLocator * @param fields * @param body */ public async createBuildParameterOfBuildType(btLocator: string, fields?: string, body?: Property, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling createBuildParameterOfBuildType.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/parameters' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Property", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Create a new build configuration. * @param fields * @param body */ public async createBuildType(fields?: string, body?: BuildType, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/buildTypes'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "BuildType", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Remove an agent requirement of the matching build configuration. * @param btLocator * @param agentRequirementLocator */ public async deleteAgentRequirement(btLocator: string, agentRequirementLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling deleteAgentRequirement.'); } // verify required parameter 'agentRequirementLocator' is not null or undefined if (agentRequirementLocator === null || agentRequirementLocator === undefined) { throw new RequiredError('Required parameter agentRequirementLocator was null or undefined when calling deleteAgentRequirement.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/agent-requirements/{agentRequirementLocator}' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'agentRequirementLocator' + '}', encodeURIComponent(String(agentRequirementLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Remove an artifact dependency from the matching build configuration. * @param btLocator * @param artifactDepLocator */ public async deleteArtifactDependency(btLocator: string, artifactDepLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling deleteArtifactDependency.'); } // verify required parameter 'artifactDepLocator' is not null or undefined if (artifactDepLocator === null || artifactDepLocator === undefined) { throw new RequiredError('Required parameter artifactDepLocator was null or undefined when calling deleteArtifactDependency.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/artifact-dependencies/{artifactDepLocator}' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'artifactDepLocator' + '}', encodeURIComponent(String(artifactDepLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Delete build parameter. * @param name * @param btLocator */ public async deleteBuildParameterOfBuildType(name: string, btLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'name' is not null or undefined if (name === null || name === undefined) { throw new RequiredError('Required parameter name was null or undefined when calling deleteBuildParameterOfBuildType.'); } // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling deleteBuildParameterOfBuildType.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/parameters/{name}' .replace('{' + 'name' + '}', encodeURIComponent(String(name))) .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Delete all build parameters. * @param btLocator */ public async deleteBuildParametersOfBuildType(btLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling deleteBuildParametersOfBuildType.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/parameters' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Delete a build step of the matching build configuration. * @param btLocator * @param stepId */ public async deleteBuildStep(btLocator: string, stepId: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling deleteBuildStep.'); } // verify required parameter 'stepId' is not null or undefined if (stepId === null || stepId === undefined) { throw new RequiredError('Required parameter stepId was null or undefined when calling deleteBuildStep.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/steps/{stepId}' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'stepId' + '}', encodeURIComponent(String(stepId))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update a parameter of a build step of the matching build configuration. * @param btLocator * @param stepId * @param fields * @param body */ public async deleteBuildStepParameters(btLocator: string, stepId: string, fields?: string, body?: Properties, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling deleteBuildStepParameters.'); } // verify required parameter 'stepId' is not null or undefined if (stepId === null || stepId === undefined) { throw new RequiredError('Required parameter stepId was null or undefined when calling deleteBuildStepParameters.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/steps/{stepId}/parameters' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'stepId' + '}', encodeURIComponent(String(stepId))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Properties", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Delete build configuration matching the locator. * @param btLocator */ public async deleteBuildType(btLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling deleteBuildType.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Remove a build feature of the matching build configuration. * @param btLocator * @param featureId */ public async deleteFeatureOfBuildType(btLocator: string, featureId: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling deleteFeatureOfBuildType.'); } // verify required parameter 'featureId' is not null or undefined if (featureId === null || featureId === undefined) { throw new RequiredError('Required parameter featureId was null or undefined when calling deleteFeatureOfBuildType.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/features/{featureId}' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'featureId' + '}', encodeURIComponent(String(featureId))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Delete a snapshot dependency of the matching build configuration. * @param btLocator * @param snapshotDepLocator */ public async deleteSnapshotDependency(btLocator: string, snapshotDepLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling deleteSnapshotDependency.'); } // verify required parameter 'snapshotDepLocator' is not null or undefined if (snapshotDepLocator === null || snapshotDepLocator === undefined) { throw new RequiredError('Required parameter snapshotDepLocator was null or undefined when calling deleteSnapshotDependency.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/snapshot-dependencies/{snapshotDepLocator}' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'snapshotDepLocator' + '}', encodeURIComponent(String(snapshotDepLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Delete a trigger of the matching build configuration. * @param btLocator * @param triggerLocator */ public async deleteTrigger(btLocator: string, triggerLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling deleteTrigger.'); } // verify required parameter 'triggerLocator' is not null or undefined if (triggerLocator === null || triggerLocator === undefined) { throw new RequiredError('Required parameter triggerLocator was null or undefined when calling deleteTrigger.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/triggers/{triggerLocator}' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'triggerLocator' + '}', encodeURIComponent(String(triggerLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Remove a VCS root of the matching build configuration. * @param btLocator * @param vcsRootLocator */ public async deleteVcsRootOfBuildType(btLocator: string, vcsRootLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling deleteVcsRootOfBuildType.'); } // verify required parameter 'vcsRootLocator' is not null or undefined if (vcsRootLocator === null || vcsRootLocator === undefined) { throw new RequiredError('Required parameter vcsRootLocator was null or undefined when calling deleteVcsRootOfBuildType.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/vcs-root-entries/{vcsRootLocator}' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'vcsRootLocator' + '}', encodeURIComponent(String(vcsRootLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Download specific file. * @param path * @param btLocator * @param resolveParameters */ public async downloadFileOfBuildType(path: string, btLocator: string, resolveParameters?: boolean, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'path' is not null or undefined if (path === null || path === undefined) { throw new RequiredError('Required parameter path was null or undefined when calling downloadFileOfBuildType.'); } // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling downloadFileOfBuildType.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/vcs/files/latest/files{path}' .replace('{' + 'path' + '}', encodeURIComponent(String(path))) .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (resolveParameters !== undefined) { requestContext.setQueryParam("resolveParameters", ObjectSerializer.serialize(resolveParameters, "boolean", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get an agent requirement of the matching build configuration. * @param btLocator * @param agentRequirementLocator * @param fields */ public async getAgentRequirement(btLocator: string, agentRequirementLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getAgentRequirement.'); } // verify required parameter 'agentRequirementLocator' is not null or undefined if (agentRequirementLocator === null || agentRequirementLocator === undefined) { throw new RequiredError('Required parameter agentRequirementLocator was null or undefined when calling getAgentRequirement.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/agent-requirements/{agentRequirementLocator}' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'agentRequirementLocator' + '}', encodeURIComponent(String(agentRequirementLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get a setting of an agent requirement of the matching build configuration. * @param btLocator * @param agentRequirementLocator * @param fieldName */ public async getAgentRequirementParameter(btLocator: string, agentRequirementLocator: string, fieldName: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getAgentRequirementParameter.'); } // verify required parameter 'agentRequirementLocator' is not null or undefined if (agentRequirementLocator === null || agentRequirementLocator === undefined) { throw new RequiredError('Required parameter agentRequirementLocator was null or undefined when calling getAgentRequirementParameter.'); } // verify required parameter 'fieldName' is not null or undefined if (fieldName === null || fieldName === undefined) { throw new RequiredError('Required parameter fieldName was null or undefined when calling getAgentRequirementParameter.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/agent-requirements/{agentRequirementLocator}/{fieldName}' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'agentRequirementLocator' + '}', encodeURIComponent(String(agentRequirementLocator))) .replace('{' + 'fieldName' + '}', encodeURIComponent(String(fieldName))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get external IDs of the matching build configuration. * @param btLocator * @param field */ public async getAliases(btLocator: string, field?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getAliases.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/aliases' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (field !== undefined) { requestContext.setQueryParam("field", ObjectSerializer.serialize(field, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all agent requirements of the matching build configuration. * @param btLocator * @param fields */ public async getAllAgentRequirements(btLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getAllAgentRequirements.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/agent-requirements' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all artifact dependencies of the matching build configuration. * @param btLocator * @param fields */ public async getAllArtifactDependencies(btLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getAllArtifactDependencies.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/artifact-dependencies' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all branches of the matching build configuration. * @param btLocator * @param locator * @param fields */ public async getAllBranchesOfBuildType(btLocator: string, locator?: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getAllBranchesOfBuildType.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/branches' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "")); } if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all parameters of a build feature of the matching build configuration. * @param btLocator * @param featureId * @param fields */ public async getAllBuildFeatureParameters(btLocator: string, featureId: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getAllBuildFeatureParameters.'); } // verify required parameter 'featureId' is not null or undefined if (featureId === null || featureId === undefined) { throw new RequiredError('Required parameter featureId was null or undefined when calling getAllBuildFeatureParameters.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/features/{featureId}/parameters' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'featureId' + '}', encodeURIComponent(String(featureId))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all build features of the matching build configuration. * @param btLocator * @param fields */ public async getAllBuildFeatures(btLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getAllBuildFeatures.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/features' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all parameters of a build step of the matching build configuration. * @param btLocator * @param stepId * @param fields */ public async getAllBuildStepParameters(btLocator: string, stepId: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getAllBuildStepParameters.'); } // verify required parameter 'stepId' is not null or undefined if (stepId === null || stepId === undefined) { throw new RequiredError('Required parameter stepId was null or undefined when calling getAllBuildStepParameters.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/steps/{stepId}/parameters' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'stepId' + '}', encodeURIComponent(String(stepId))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all build steps of the matching build configuration. * @param btLocator * @param fields */ public async getAllBuildSteps(btLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getAllBuildSteps.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/steps' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all build templates of the matching build configuration. * @param btLocator * @param fields */ public async getAllBuildTemplates(btLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getAllBuildTemplates.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/templates' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all build configurations. * @param locator * @param fields */ public async getAllBuildTypes(locator?: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/buildTypes'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "BuildTypeLocator")); } if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all investigations of the matching build configuration. * @param btLocator * @param fields */ public async getAllInvestigationsOfBuildType(btLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getAllInvestigationsOfBuildType.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/investigations' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all snapshot dependencies of the matching build configuration. * @param btLocator * @param fields */ public async getAllSnapshotDependencies(btLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getAllSnapshotDependencies.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/snapshot-dependencies' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all triggers of the matching build configuration. * @param btLocator * @param fields */ public async getAllTriggers(btLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getAllTriggers.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/triggers' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all VCS roots of the matching build configuration. * @param btLocator * @param fields */ public async getAllVcsRootsOfBuildType(btLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getAllVcsRootsOfBuildType.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/vcs-root-entries' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get an artifact dependency of the matching build configuration. * @param btLocator * @param artifactDepLocator * @param fields */ public async getArtifactDependency(btLocator: string, artifactDepLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getArtifactDependency.'); } // verify required parameter 'artifactDepLocator' is not null or undefined if (artifactDepLocator === null || artifactDepLocator === undefined) { throw new RequiredError('Required parameter artifactDepLocator was null or undefined when calling getArtifactDependency.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/artifact-dependencies/{artifactDepLocator}' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'artifactDepLocator' + '}', encodeURIComponent(String(artifactDepLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get a parameter of an artifact dependency of the matching build configuration. * @param btLocator * @param artifactDepLocator * @param fieldName */ public async getArtifactDependencyParameter(btLocator: string, artifactDepLocator: string, fieldName: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getArtifactDependencyParameter.'); } // verify required parameter 'artifactDepLocator' is not null or undefined if (artifactDepLocator === null || artifactDepLocator === undefined) { throw new RequiredError('Required parameter artifactDepLocator was null or undefined when calling getArtifactDependencyParameter.'); } // verify required parameter 'fieldName' is not null or undefined if (fieldName === null || fieldName === undefined) { throw new RequiredError('Required parameter fieldName was null or undefined when calling getArtifactDependencyParameter.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/artifact-dependencies/{artifactDepLocator}/{fieldName}' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'artifactDepLocator' + '}', encodeURIComponent(String(artifactDepLocator))) .replace('{' + 'fieldName' + '}', encodeURIComponent(String(fieldName))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get a build feature of the matching build configuration. * @param btLocator * @param featureId * @param fields */ public async getBuildFeature(btLocator: string, featureId: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getBuildFeature.'); } // verify required parameter 'featureId' is not null or undefined if (featureId === null || featureId === undefined) { throw new RequiredError('Required parameter featureId was null or undefined when calling getBuildFeature.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/features/{featureId}' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'featureId' + '}', encodeURIComponent(String(featureId))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get a parameter of a build feature of the matching build configuration. * @param btLocator * @param featureId * @param parameterName */ public async getBuildFeatureParameter(btLocator: string, featureId: string, parameterName: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getBuildFeatureParameter.'); } // verify required parameter 'featureId' is not null or undefined if (featureId === null || featureId === undefined) { throw new RequiredError('Required parameter featureId was null or undefined when calling getBuildFeatureParameter.'); } // verify required parameter 'parameterName' is not null or undefined if (parameterName === null || parameterName === undefined) { throw new RequiredError('Required parameter parameterName was null or undefined when calling getBuildFeatureParameter.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/features/{featureId}/parameters/{parameterName}' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'featureId' + '}', encodeURIComponent(String(featureId))) .replace('{' + 'parameterName' + '}', encodeURIComponent(String(parameterName))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get the setting of a build feature of the matching build configuration. * @param btLocator * @param featureId * @param name */ public async getBuildFeatureSetting(btLocator: string, featureId: string, name: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getBuildFeatureSetting.'); } // verify required parameter 'featureId' is not null or undefined if (featureId === null || featureId === undefined) { throw new RequiredError('Required parameter featureId was null or undefined when calling getBuildFeatureSetting.'); } // verify required parameter 'name' is not null or undefined if (name === null || name === undefined) { throw new RequiredError('Required parameter name was null or undefined when calling getBuildFeatureSetting.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/features/{featureId}/{name}' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'featureId' + '}', encodeURIComponent(String(featureId))) .replace('{' + 'name' + '}', encodeURIComponent(String(name))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get build parameter. * @param name * @param btLocator * @param fields */ public async getBuildParameterOfBuildType(name: string, btLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'name' is not null or undefined if (name === null || name === undefined) { throw new RequiredError('Required parameter name was null or undefined when calling getBuildParameterOfBuildType.'); } // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getBuildParameterOfBuildType.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/parameters/{name}' .replace('{' + 'name' + '}', encodeURIComponent(String(name))) .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get build parameter specification. * @param name * @param btLocator */ public async getBuildParameterSpecificationOfBuildType(name: string, btLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'name' is not null or undefined if (name === null || name === undefined) { throw new RequiredError('Required parameter name was null or undefined when calling getBuildParameterSpecificationOfBuildType.'); } // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getBuildParameterSpecificationOfBuildType.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/parameters/{name}/type/rawValue' .replace('{' + 'name' + '}', encodeURIComponent(String(name))) .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get type of build parameter. * @param name * @param btLocator */ public async getBuildParameterTypeOfBuildType(name: string, btLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'name' is not null or undefined if (name === null || name === undefined) { throw new RequiredError('Required parameter name was null or undefined when calling getBuildParameterTypeOfBuildType.'); } // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getBuildParameterTypeOfBuildType.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/parameters/{name}/type' .replace('{' + 'name' + '}', encodeURIComponent(String(name))) .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get value of build parameter. * @param name * @param btLocator */ public async getBuildParameterValueOfBuildType(name: string, btLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'name' is not null or undefined if (name === null || name === undefined) { throw new RequiredError('Required parameter name was null or undefined when calling getBuildParameterValueOfBuildType.'); } // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getBuildParameterValueOfBuildType.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/parameters/{name}/value' .replace('{' + 'name' + '}', encodeURIComponent(String(name))) .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get build parameters. * @param btLocator * @param locator * @param fields */ public async getBuildParametersOfBuildType(btLocator: string, locator?: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getBuildParametersOfBuildType.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/parameters' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "")); } if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get a build step of the matching build configuration. * @param btLocator * @param stepId * @param fields */ public async getBuildStep(btLocator: string, stepId: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getBuildStep.'); } // verify required parameter 'stepId' is not null or undefined if (stepId === null || stepId === undefined) { throw new RequiredError('Required parameter stepId was null or undefined when calling getBuildStep.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/steps/{stepId}' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'stepId' + '}', encodeURIComponent(String(stepId))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get a parameter of a build step of the matching build configuration. * @param btLocator * @param stepId * @param parameterName */ public async getBuildStepParameter(btLocator: string, stepId: string, parameterName: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getBuildStepParameter.'); } // verify required parameter 'stepId' is not null or undefined if (stepId === null || stepId === undefined) { throw new RequiredError('Required parameter stepId was null or undefined when calling getBuildStepParameter.'); } // verify required parameter 'parameterName' is not null or undefined if (parameterName === null || parameterName === undefined) { throw new RequiredError('Required parameter parameterName was null or undefined when calling getBuildStepParameter.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/steps/{stepId}/parameters/{parameterName}' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'stepId' + '}', encodeURIComponent(String(stepId))) .replace('{' + 'parameterName' + '}', encodeURIComponent(String(parameterName))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get the setting of a build step of the matching build configuration. * @param btLocator * @param stepId * @param fieldName */ public async getBuildStepSetting(btLocator: string, stepId: string, fieldName: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getBuildStepSetting.'); } // verify required parameter 'stepId' is not null or undefined if (stepId === null || stepId === undefined) { throw new RequiredError('Required parameter stepId was null or undefined when calling getBuildStepSetting.'); } // verify required parameter 'fieldName' is not null or undefined if (fieldName === null || fieldName === undefined) { throw new RequiredError('Required parameter fieldName was null or undefined when calling getBuildStepSetting.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/steps/{stepId}/{fieldName}' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'stepId' + '}', encodeURIComponent(String(stepId))) .replace('{' + 'fieldName' + '}', encodeURIComponent(String(fieldName))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get a template of the matching build configuration. * @param btLocator * @param templateLocator * @param fields */ public async getBuildTemplate(btLocator: string, templateLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getBuildTemplate.'); } // verify required parameter 'templateLocator' is not null or undefined if (templateLocator === null || templateLocator === undefined) { throw new RequiredError('Required parameter templateLocator was null or undefined when calling getBuildTemplate.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/templates/{templateLocator}' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'templateLocator' + '}', encodeURIComponent(String(templateLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get build configuration matching the locator. * @param btLocator * @param fields */ public async getBuildType(btLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getBuildType.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get tags of builds of the matching build configuration. * @param btLocator * @param field */ public async getBuildTypeBuildTags(btLocator: string, field?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getBuildTypeBuildTags.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/buildTags' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (field !== undefined) { requestContext.setQueryParam("field", ObjectSerializer.serialize(field, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get builds of the matching build configuration. * @param btLocator * @param fields */ public async getBuildTypeBuilds(btLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getBuildTypeBuilds.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/builds' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get a field of the matching build configuration. * @param btLocator * @param field */ public async getBuildTypeField(btLocator: string, field: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getBuildTypeField.'); } // verify required parameter 'field' is not null or undefined if (field === null || field === undefined) { throw new RequiredError('Required parameter field was null or undefined when calling getBuildTypeField.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/{field}' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'field' + '}', encodeURIComponent(String(field))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get the settings file of the matching build configuration. * @param btLocator */ public async getBuildTypeSettingsFile(btLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getBuildTypeSettingsFile.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/settingsFile' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get metadata of specific file. * @param path * @param btLocator * @param fields * @param resolveParameters */ public async getFileMetadataOfBuildType(path: string, btLocator: string, fields?: string, resolveParameters?: boolean, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'path' is not null or undefined if (path === null || path === undefined) { throw new RequiredError('Required parameter path was null or undefined when calling getFileMetadataOfBuildType.'); } // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getFileMetadataOfBuildType.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/vcs/files/latest/metadata{path}' .replace('{' + 'path' + '}', encodeURIComponent(String(path))) .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } if (resolveParameters !== undefined) { requestContext.setQueryParam("resolveParameters", ObjectSerializer.serialize(resolveParameters, "boolean", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * List files under this path. * @param path * @param btLocator * @param basePath * @param locator * @param fields * @param resolveParameters */ public async getFilesListForSubpathOfBuildType(path: string, btLocator: string, basePath?: string, locator?: string, fields?: string, resolveParameters?: boolean, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'path' is not null or undefined if (path === null || path === undefined) { throw new RequiredError('Required parameter path was null or undefined when calling getFilesListForSubpathOfBuildType.'); } // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getFilesListForSubpathOfBuildType.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/vcs/files/latest/{path}' .replace('{' + 'path' + '}', encodeURIComponent(String(path))) .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (basePath !== undefined) { requestContext.setQueryParam("basePath", ObjectSerializer.serialize(basePath, "string", "")); } if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "")); } if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } if (resolveParameters !== undefined) { requestContext.setQueryParam("resolveParameters", ObjectSerializer.serialize(resolveParameters, "boolean", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * List all files. * @param btLocator * @param basePath * @param locator * @param fields * @param resolveParameters */ public async getFilesListOfBuildType(btLocator: string, basePath?: string, locator?: string, fields?: string, resolveParameters?: boolean, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getFilesListOfBuildType.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/vcs/files/latest' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (basePath !== undefined) { requestContext.setQueryParam("basePath", ObjectSerializer.serialize(basePath, "string", "")); } if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "")); } if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } if (resolveParameters !== undefined) { requestContext.setQueryParam("resolveParameters", ObjectSerializer.serialize(resolveParameters, "boolean", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get a snapshot dependency of the matching build configuration. * @param btLocator * @param snapshotDepLocator * @param fields */ public async getSnapshotDependency(btLocator: string, snapshotDepLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getSnapshotDependency.'); } // verify required parameter 'snapshotDepLocator' is not null or undefined if (snapshotDepLocator === null || snapshotDepLocator === undefined) { throw new RequiredError('Required parameter snapshotDepLocator was null or undefined when calling getSnapshotDependency.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/snapshot-dependencies/{snapshotDepLocator}' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'snapshotDepLocator' + '}', encodeURIComponent(String(snapshotDepLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get a trigger of the matching build configuration. * @param btLocator * @param triggerLocator * @param fields */ public async getTrigger(btLocator: string, triggerLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getTrigger.'); } // verify required parameter 'triggerLocator' is not null or undefined if (triggerLocator === null || triggerLocator === undefined) { throw new RequiredError('Required parameter triggerLocator was null or undefined when calling getTrigger.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/triggers/{triggerLocator}' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'triggerLocator' + '}', encodeURIComponent(String(triggerLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get a parameter of a trigger of the matching build configuration. * @param btLocator * @param triggerLocator * @param fieldName */ public async getTriggerParameter(btLocator: string, triggerLocator: string, fieldName: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getTriggerParameter.'); } // verify required parameter 'triggerLocator' is not null or undefined if (triggerLocator === null || triggerLocator === undefined) { throw new RequiredError('Required parameter triggerLocator was null or undefined when calling getTriggerParameter.'); } // verify required parameter 'fieldName' is not null or undefined if (fieldName === null || fieldName === undefined) { throw new RequiredError('Required parameter fieldName was null or undefined when calling getTriggerParameter.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/triggers/{triggerLocator}/{fieldName}' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'triggerLocator' + '}', encodeURIComponent(String(triggerLocator))) .replace('{' + 'fieldName' + '}', encodeURIComponent(String(fieldName))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get a VCS root of the matching build configuration. * @param btLocator * @param vcsRootLocator * @param fields */ public async getVcsRoot(btLocator: string, vcsRootLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getVcsRoot.'); } // verify required parameter 'vcsRootLocator' is not null or undefined if (vcsRootLocator === null || vcsRootLocator === undefined) { throw new RequiredError('Required parameter vcsRootLocator was null or undefined when calling getVcsRoot.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/vcs-root-entries/{vcsRootLocator}' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'vcsRootLocator' + '}', encodeURIComponent(String(vcsRootLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get checkout rules of a VCS root of the matching build configuration. * @param btLocator * @param vcsRootLocator */ public async getVcsRootCheckoutRules(btLocator: string, vcsRootLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getVcsRootCheckoutRules.'); } // verify required parameter 'vcsRootLocator' is not null or undefined if (vcsRootLocator === null || vcsRootLocator === undefined) { throw new RequiredError('Required parameter vcsRootLocator was null or undefined when calling getVcsRootCheckoutRules.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/vcs-root-entries/{vcsRootLocator}/checkout-rules' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'vcsRootLocator' + '}', encodeURIComponent(String(vcsRootLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all VCS root instances of the matching build configuration. * @param btLocator * @param fields */ public async getVcsRootInstancesOfBuildType(btLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getVcsRootInstancesOfBuildType.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/vcsRootInstances' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get specific file zipped. * @param path * @param btLocator * @param basePath * @param locator * @param name * @param resolveParameters */ public async getZippedFileOfBuildType(path: string, btLocator: string, basePath?: string, locator?: string, name?: string, resolveParameters?: boolean, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'path' is not null or undefined if (path === null || path === undefined) { throw new RequiredError('Required parameter path was null or undefined when calling getZippedFileOfBuildType.'); } // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling getZippedFileOfBuildType.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/vcs/files/latest/archived{path}' .replace('{' + 'path' + '}', encodeURIComponent(String(path))) .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (basePath !== undefined) { requestContext.setQueryParam("basePath", ObjectSerializer.serialize(basePath, "string", "")); } if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "")); } if (name !== undefined) { requestContext.setQueryParam("name", ObjectSerializer.serialize(name, "string", "")); } if (resolveParameters !== undefined) { requestContext.setQueryParam("resolveParameters", ObjectSerializer.serialize(resolveParameters, "boolean", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Detach all templates from the matching build configuration. * @param btLocator * @param inlineSettings */ public async removeAllTemplates(btLocator: string, inlineSettings?: boolean, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling removeAllTemplates.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/templates' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (inlineSettings !== undefined) { requestContext.setQueryParam("inlineSettings", ObjectSerializer.serialize(inlineSettings, "boolean", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Detach a template from the matching build configuration. * @param btLocator * @param templateLocator * @param inlineSettings */ public async removeTemplate(btLocator: string, templateLocator: string, inlineSettings?: boolean, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling removeTemplate.'); } // verify required parameter 'templateLocator' is not null or undefined if (templateLocator === null || templateLocator === undefined) { throw new RequiredError('Required parameter templateLocator was null or undefined when calling removeTemplate.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/templates/{templateLocator}' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'templateLocator' + '}', encodeURIComponent(String(templateLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (inlineSettings !== undefined) { requestContext.setQueryParam("inlineSettings", ObjectSerializer.serialize(inlineSettings, "boolean", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update an agent requirement of the matching build configuration. * @param btLocator * @param agentRequirementLocator * @param fields * @param body */ public async replaceAgentRequirement(btLocator: string, agentRequirementLocator: string, fields?: string, body?: AgentRequirement, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling replaceAgentRequirement.'); } // verify required parameter 'agentRequirementLocator' is not null or undefined if (agentRequirementLocator === null || agentRequirementLocator === undefined) { throw new RequiredError('Required parameter agentRequirementLocator was null or undefined when calling replaceAgentRequirement.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/agent-requirements/{agentRequirementLocator}' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'agentRequirementLocator' + '}', encodeURIComponent(String(agentRequirementLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "AgentRequirement", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update all agent requirements of the matching build configuration. * @param btLocator * @param fields * @param body */ public async replaceAllAgentRequirements(btLocator: string, fields?: string, body?: AgentRequirements, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling replaceAllAgentRequirements.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/agent-requirements' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "AgentRequirements", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update all artifact dependencies of the matching build configuration. * @param btLocator * @param fields * @param body */ public async replaceAllArtifactDependencies(btLocator: string, fields?: string, body?: ArtifactDependencies, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling replaceAllArtifactDependencies.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/artifact-dependencies' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "ArtifactDependencies", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update all build features of the matching build configuration. * @param btLocator * @param fields * @param body */ public async replaceAllBuildFeatures(btLocator: string, fields?: string, body?: Features, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling replaceAllBuildFeatures.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/features' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Features", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update all build steps of the matching build configuration. * @param btLocator * @param fields * @param body */ public async replaceAllBuildSteps(btLocator: string, fields?: string, body?: Steps, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling replaceAllBuildSteps.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/steps' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Steps", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update all snapshot dependencies of the matching build configuration. * @param btLocator * @param fields * @param body */ public async replaceAllSnapshotDependencies(btLocator: string, fields?: string, body?: SnapshotDependencies, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling replaceAllSnapshotDependencies.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/snapshot-dependencies' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "SnapshotDependencies", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update all triggers of the matching build configuration. * @param btLocator * @param fields * @param body */ public async replaceAllTriggers(btLocator: string, fields?: string, body?: Triggers, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling replaceAllTriggers.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/triggers' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Triggers", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update all VCS roots of the matching build configuration. * @param btLocator * @param fields * @param body */ public async replaceAllVcsRoots(btLocator: string, fields?: string, body?: VcsRootEntries, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling replaceAllVcsRoots.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/vcs-root-entries' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "VcsRootEntries", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update an artifact dependency of the matching build configuration. * @param btLocator * @param artifactDepLocator * @param fields * @param body */ public async replaceArtifactDependency(btLocator: string, artifactDepLocator: string, fields?: string, body?: ArtifactDependency, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling replaceArtifactDependency.'); } // verify required parameter 'artifactDepLocator' is not null or undefined if (artifactDepLocator === null || artifactDepLocator === undefined) { throw new RequiredError('Required parameter artifactDepLocator was null or undefined when calling replaceArtifactDependency.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/artifact-dependencies/{artifactDepLocator}' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'artifactDepLocator' + '}', encodeURIComponent(String(artifactDepLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "ArtifactDependency", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update a build feature of the matching build configuration. * @param btLocator * @param featureId * @param fields * @param body */ public async replaceBuildFeature(btLocator: string, featureId: string, fields?: string, body?: Feature, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling replaceBuildFeature.'); } // verify required parameter 'featureId' is not null or undefined if (featureId === null || featureId === undefined) { throw new RequiredError('Required parameter featureId was null or undefined when calling replaceBuildFeature.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/features/{featureId}' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'featureId' + '}', encodeURIComponent(String(featureId))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Feature", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update a parameter of a build feature of the matching build configuration. * @param btLocator * @param featureId * @param fields * @param body */ public async replaceBuildFeatureParameters(btLocator: string, featureId: string, fields?: string, body?: Properties, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling replaceBuildFeatureParameters.'); } // verify required parameter 'featureId' is not null or undefined if (featureId === null || featureId === undefined) { throw new RequiredError('Required parameter featureId was null or undefined when calling replaceBuildFeatureParameters.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/features/{featureId}/parameters' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'featureId' + '}', encodeURIComponent(String(featureId))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Properties", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Replace a build step of the matching build configuration. * @param btLocator * @param stepId * @param fields * @param body */ public async replaceBuildStep(btLocator: string, stepId: string, fields?: string, body?: Step, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling replaceBuildStep.'); } // verify required parameter 'stepId' is not null or undefined if (stepId === null || stepId === undefined) { throw new RequiredError('Required parameter stepId was null or undefined when calling replaceBuildStep.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/steps/{stepId}' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'stepId' + '}', encodeURIComponent(String(stepId))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Step", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update a snapshot dependency of the matching build configuration. * @param btLocator * @param snapshotDepLocator * @param fields * @param body */ public async replaceSnapshotDependency(btLocator: string, snapshotDepLocator: string, fields?: string, body?: SnapshotDependency, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling replaceSnapshotDependency.'); } // verify required parameter 'snapshotDepLocator' is not null or undefined if (snapshotDepLocator === null || snapshotDepLocator === undefined) { throw new RequiredError('Required parameter snapshotDepLocator was null or undefined when calling replaceSnapshotDependency.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/snapshot-dependencies/{snapshotDepLocator}' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'snapshotDepLocator' + '}', encodeURIComponent(String(snapshotDepLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "SnapshotDependency", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update a trigger of the matching build configuration. * @param btLocator * @param triggerLocator * @param fields * @param body */ public async replaceTrigger(btLocator: string, triggerLocator: string, fields?: string, body?: Trigger, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling replaceTrigger.'); } // verify required parameter 'triggerLocator' is not null or undefined if (triggerLocator === null || triggerLocator === undefined) { throw new RequiredError('Required parameter triggerLocator was null or undefined when calling replaceTrigger.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/triggers/{triggerLocator}' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'triggerLocator' + '}', encodeURIComponent(String(triggerLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Trigger", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update a parameter of an agent requirement of the matching build configuration. * @param btLocator * @param agentRequirementLocator * @param fieldName * @param body */ public async setAgentRequirementParameter(btLocator: string, agentRequirementLocator: string, fieldName: string, body?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling setAgentRequirementParameter.'); } // verify required parameter 'agentRequirementLocator' is not null or undefined if (agentRequirementLocator === null || agentRequirementLocator === undefined) { throw new RequiredError('Required parameter agentRequirementLocator was null or undefined when calling setAgentRequirementParameter.'); } // verify required parameter 'fieldName' is not null or undefined if (fieldName === null || fieldName === undefined) { throw new RequiredError('Required parameter fieldName was null or undefined when calling setAgentRequirementParameter.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/agent-requirements/{agentRequirementLocator}/{fieldName}' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'agentRequirementLocator' + '}', encodeURIComponent(String(agentRequirementLocator))) .replace('{' + 'fieldName' + '}', encodeURIComponent(String(fieldName))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "text/plain" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "string", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update a parameter of an artifact dependency of the matching build configuration. * @param btLocator * @param artifactDepLocator * @param fieldName * @param body */ public async setArtifactDependencyParameter(btLocator: string, artifactDepLocator: string, fieldName: string, body?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling setArtifactDependencyParameter.'); } // verify required parameter 'artifactDepLocator' is not null or undefined if (artifactDepLocator === null || artifactDepLocator === undefined) { throw new RequiredError('Required parameter artifactDepLocator was null or undefined when calling setArtifactDependencyParameter.'); } // verify required parameter 'fieldName' is not null or undefined if (fieldName === null || fieldName === undefined) { throw new RequiredError('Required parameter fieldName was null or undefined when calling setArtifactDependencyParameter.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/artifact-dependencies/{artifactDepLocator}/{fieldName}' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'artifactDepLocator' + '}', encodeURIComponent(String(artifactDepLocator))) .replace('{' + 'fieldName' + '}', encodeURIComponent(String(fieldName))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "text/plain" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "string", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update a parameter of a build feature of the matching build configuration. * @param btLocator * @param featureId * @param name * @param body */ public async setBuildFeatureParameter(btLocator: string, featureId: string, name: string, body?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling setBuildFeatureParameter.'); } // verify required parameter 'featureId' is not null or undefined if (featureId === null || featureId === undefined) { throw new RequiredError('Required parameter featureId was null or undefined when calling setBuildFeatureParameter.'); } // verify required parameter 'name' is not null or undefined if (name === null || name === undefined) { throw new RequiredError('Required parameter name was null or undefined when calling setBuildFeatureParameter.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/features/{featureId}/{name}' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'featureId' + '}', encodeURIComponent(String(featureId))) .replace('{' + 'name' + '}', encodeURIComponent(String(name))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "text/plain" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "string", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update a parameter of a build step of the matching build configuration. * @param btLocator * @param stepId * @param fieldName * @param body */ public async setBuildStepParameter(btLocator: string, stepId: string, fieldName: string, body?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling setBuildStepParameter.'); } // verify required parameter 'stepId' is not null or undefined if (stepId === null || stepId === undefined) { throw new RequiredError('Required parameter stepId was null or undefined when calling setBuildStepParameter.'); } // verify required parameter 'fieldName' is not null or undefined if (fieldName === null || fieldName === undefined) { throw new RequiredError('Required parameter fieldName was null or undefined when calling setBuildStepParameter.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/steps/{stepId}/{fieldName}' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'stepId' + '}', encodeURIComponent(String(stepId))) .replace('{' + 'fieldName' + '}', encodeURIComponent(String(fieldName))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "text/plain" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "string", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update a field of the matching build configuration. * @param btLocator * @param field * @param body */ public async setBuildTypeField(btLocator: string, field: string, body?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling setBuildTypeField.'); } // verify required parameter 'field' is not null or undefined if (field === null || field === undefined) { throw new RequiredError('Required parameter field was null or undefined when calling setBuildTypeField.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/{field}' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'field' + '}', encodeURIComponent(String(field))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "text/plain" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "string", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update all templates of the matching build configuration. * @param btLocator * @param optimizeSettings * @param fields * @param body */ public async setBuildTypeTemplates(btLocator: string, optimizeSettings?: boolean, fields?: string, body?: BuildTypes, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling setBuildTypeTemplates.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/templates' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (optimizeSettings !== undefined) { requestContext.setQueryParam("optimizeSettings", ObjectSerializer.serialize(optimizeSettings, "boolean", "")); } if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "BuildTypes", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update a parameter of a trigger of the matching build configuration. * @param btLocator * @param triggerLocator * @param fieldName * @param body */ public async setTriggerParameter(btLocator: string, triggerLocator: string, fieldName: string, body?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling setTriggerParameter.'); } // verify required parameter 'triggerLocator' is not null or undefined if (triggerLocator === null || triggerLocator === undefined) { throw new RequiredError('Required parameter triggerLocator was null or undefined when calling setTriggerParameter.'); } // verify required parameter 'fieldName' is not null or undefined if (fieldName === null || fieldName === undefined) { throw new RequiredError('Required parameter fieldName was null or undefined when calling setTriggerParameter.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/triggers/{triggerLocator}/{fieldName}' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'triggerLocator' + '}', encodeURIComponent(String(triggerLocator))) .replace('{' + 'fieldName' + '}', encodeURIComponent(String(fieldName))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "text/plain" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "string", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update build parameter. * @param name * @param btLocator * @param fields * @param body */ public async updateBuildParameterOfBuildType(name: string, btLocator: string, fields?: string, body?: Property, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'name' is not null or undefined if (name === null || name === undefined) { throw new RequiredError('Required parameter name was null or undefined when calling updateBuildParameterOfBuildType.'); } // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling updateBuildParameterOfBuildType.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/parameters/{name}' .replace('{' + 'name' + '}', encodeURIComponent(String(name))) .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Property", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update build parameter specification. * @param name * @param btLocator * @param body */ public async updateBuildParameterSpecificationOfBuildType(name: string, btLocator: string, body?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'name' is not null or undefined if (name === null || name === undefined) { throw new RequiredError('Required parameter name was null or undefined when calling updateBuildParameterSpecificationOfBuildType.'); } // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling updateBuildParameterSpecificationOfBuildType.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/parameters/{name}/type/rawValue' .replace('{' + 'name' + '}', encodeURIComponent(String(name))) .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "text/plain" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "string", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update type of build parameter. * @param name * @param btLocator * @param body */ public async updateBuildParameterTypeOfBuildType(name: string, btLocator: string, body?: Type, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'name' is not null or undefined if (name === null || name === undefined) { throw new RequiredError('Required parameter name was null or undefined when calling updateBuildParameterTypeOfBuildType.'); } // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling updateBuildParameterTypeOfBuildType.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/parameters/{name}/type' .replace('{' + 'name' + '}', encodeURIComponent(String(name))) .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Type", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update value of build parameter. * @param name * @param btLocator * @param body */ public async updateBuildParameterValueOfBuildType(name: string, btLocator: string, body?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'name' is not null or undefined if (name === null || name === undefined) { throw new RequiredError('Required parameter name was null or undefined when calling updateBuildParameterValueOfBuildType.'); } // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling updateBuildParameterValueOfBuildType.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/parameters/{name}/value' .replace('{' + 'name' + '}', encodeURIComponent(String(name))) .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "text/plain" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "string", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update build parameters. * @param btLocator * @param fields * @param body */ public async updateBuildParametersOfBuildType(btLocator: string, fields?: string, body?: Properties, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling updateBuildParametersOfBuildType.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/parameters' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Properties", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update a VCS root of the matching build configuration. * @param btLocator * @param vcsRootLocator * @param fields * @param body */ public async updateBuildTypeVcsRoot(btLocator: string, vcsRootLocator: string, fields?: string, body?: VcsRootEntry, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling updateBuildTypeVcsRoot.'); } // verify required parameter 'vcsRootLocator' is not null or undefined if (vcsRootLocator === null || vcsRootLocator === undefined) { throw new RequiredError('Required parameter vcsRootLocator was null or undefined when calling updateBuildTypeVcsRoot.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/vcs-root-entries/{vcsRootLocator}' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'vcsRootLocator' + '}', encodeURIComponent(String(vcsRootLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "VcsRootEntry", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update checkout rules of a VCS root of the matching build configuration. * @param btLocator * @param vcsRootLocator * @param body */ public async updateBuildTypeVcsRootCheckoutRules(btLocator: string, vcsRootLocator: string, body?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'btLocator' is not null or undefined if (btLocator === null || btLocator === undefined) { throw new RequiredError('Required parameter btLocator was null or undefined when calling updateBuildTypeVcsRootCheckoutRules.'); } // verify required parameter 'vcsRootLocator' is not null or undefined if (vcsRootLocator === null || vcsRootLocator === undefined) { throw new RequiredError('Required parameter vcsRootLocator was null or undefined when calling updateBuildTypeVcsRootCheckoutRules.'); } // Path Params const localVarPath = '/app/rest/buildTypes/{btLocator}/vcs-root-entries/{vcsRootLocator}/checkout-rules' .replace('{' + 'btLocator' + '}', encodeURIComponent(String(btLocator))) .replace('{' + 'vcsRootLocator' + '}', encodeURIComponent(String(vcsRootLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "text/plain" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "string", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } } export class BuildTypeApiResponseProcessor { /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to addAgentRequirementToBuildType * @throws ApiException if the response code was not in [200, 299] */ public async addAgentRequirementToBuildType(response: ResponseContext): Promise<AgentRequirement > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: AgentRequirement = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "AgentRequirement", "" ) as AgentRequirement; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: AgentRequirement = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "AgentRequirement", "" ) as AgentRequirement; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to addArtifactDependencyToBuildType * @throws ApiException if the response code was not in [200, 299] */ public async addArtifactDependencyToBuildType(response: ResponseContext): Promise<ArtifactDependency > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: ArtifactDependency = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "ArtifactDependency", "" ) as ArtifactDependency; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: ArtifactDependency = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "ArtifactDependency", "" ) as ArtifactDependency; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to addBuildFeatureToBuildType * @throws ApiException if the response code was not in [200, 299] */ public async addBuildFeatureToBuildType(response: ResponseContext): Promise<Feature > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Feature = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Feature", "" ) as Feature; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Feature = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Feature", "" ) as Feature; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to addBuildStepToBuildType * @throws ApiException if the response code was not in [200, 299] */ public async addBuildStepToBuildType(response: ResponseContext): Promise<Step > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Step = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Step", "" ) as Step; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Step = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Step", "" ) as Step; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to addBuildTemplate * @throws ApiException if the response code was not in [200, 299] */ public async addBuildTemplate(response: ResponseContext): Promise<BuildType > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: BuildType = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "BuildType", "" ) as BuildType; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: BuildType = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "BuildType", "" ) as BuildType; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to addParameterToBuildFeature * @throws ApiException if the response code was not in [200, 299] */ public async addParameterToBuildFeature(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to addParameterToBuildStep * @throws ApiException if the response code was not in [200, 299] */ public async addParameterToBuildStep(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to addSnapshotDependencyToBuildType * @throws ApiException if the response code was not in [200, 299] */ public async addSnapshotDependencyToBuildType(response: ResponseContext): Promise<SnapshotDependency > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: SnapshotDependency = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "SnapshotDependency", "" ) as SnapshotDependency; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: SnapshotDependency = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "SnapshotDependency", "" ) as SnapshotDependency; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to addTriggerToBuildType * @throws ApiException if the response code was not in [200, 299] */ public async addTriggerToBuildType(response: ResponseContext): Promise<Trigger > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Trigger = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Trigger", "" ) as Trigger; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Trigger = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Trigger", "" ) as Trigger; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to addVcsRootToBuildType * @throws ApiException if the response code was not in [200, 299] */ public async addVcsRootToBuildType(response: ResponseContext): Promise<VcsRootEntry > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: VcsRootEntry = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "VcsRootEntry", "" ) as VcsRootEntry; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: VcsRootEntry = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "VcsRootEntry", "" ) as VcsRootEntry; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to createBuildParameterOfBuildType * @throws ApiException if the response code was not in [200, 299] */ public async createBuildParameterOfBuildType(response: ResponseContext): Promise<Property > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Property = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Property", "" ) as Property; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Property = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Property", "" ) as Property; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to createBuildType * @throws ApiException if the response code was not in [200, 299] */ public async createBuildType(response: ResponseContext): Promise<BuildType > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: BuildType = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "BuildType", "" ) as BuildType; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: BuildType = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "BuildType", "" ) as BuildType; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to deleteAgentRequirement * @throws ApiException if the response code was not in [200, 299] */ public async deleteAgentRequirement(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to deleteArtifactDependency * @throws ApiException if the response code was not in [200, 299] */ public async deleteArtifactDependency(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to deleteBuildParameterOfBuildType * @throws ApiException if the response code was not in [200, 299] */ public async deleteBuildParameterOfBuildType(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to deleteBuildParametersOfBuildType * @throws ApiException if the response code was not in [200, 299] */ public async deleteBuildParametersOfBuildType(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to deleteBuildStep * @throws ApiException if the response code was not in [200, 299] */ public async deleteBuildStep(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to deleteBuildStepParameters * @throws ApiException if the response code was not in [200, 299] */ public async deleteBuildStepParameters(response: ResponseContext): Promise<Properties > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Properties = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Properties", "" ) as Properties; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Properties = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Properties", "" ) as Properties; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to deleteBuildType * @throws ApiException if the response code was not in [200, 299] */ public async deleteBuildType(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to deleteFeatureOfBuildType * @throws ApiException if the response code was not in [200, 299] */ public async deleteFeatureOfBuildType(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to deleteSnapshotDependency * @throws ApiException if the response code was not in [200, 299] */ public async deleteSnapshotDependency(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to deleteTrigger * @throws ApiException if the response code was not in [200, 299] */ public async deleteTrigger(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to deleteVcsRootOfBuildType * @throws ApiException if the response code was not in [200, 299] */ public async deleteVcsRootOfBuildType(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to downloadFileOfBuildType * @throws ApiException if the response code was not in [200, 299] */ public async downloadFileOfBuildType(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAgentRequirement * @throws ApiException if the response code was not in [200, 299] */ public async getAgentRequirement(response: ResponseContext): Promise<AgentRequirement > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: AgentRequirement = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "AgentRequirement", "" ) as AgentRequirement; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: AgentRequirement = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "AgentRequirement", "" ) as AgentRequirement; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAgentRequirementParameter * @throws ApiException if the response code was not in [200, 299] */ public async getAgentRequirementParameter(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAliases * @throws ApiException if the response code was not in [200, 299] */ public async getAliases(response: ResponseContext): Promise<Items > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Items = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Items", "" ) as Items; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Items = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Items", "" ) as Items; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAllAgentRequirements * @throws ApiException if the response code was not in [200, 299] */ public async getAllAgentRequirements(response: ResponseContext): Promise<AgentRequirements > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: AgentRequirements = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "AgentRequirements", "" ) as AgentRequirements; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: AgentRequirements = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "AgentRequirements", "" ) as AgentRequirements; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAllArtifactDependencies * @throws ApiException if the response code was not in [200, 299] */ public async getAllArtifactDependencies(response: ResponseContext): Promise<ArtifactDependencies > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: ArtifactDependencies = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "ArtifactDependencies", "" ) as ArtifactDependencies; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: ArtifactDependencies = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "ArtifactDependencies", "" ) as ArtifactDependencies; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAllBranchesOfBuildType * @throws ApiException if the response code was not in [200, 299] */ public async getAllBranchesOfBuildType(response: ResponseContext): Promise<Branches > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Branches = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Branches", "" ) as Branches; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Branches = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Branches", "" ) as Branches; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAllBuildFeatureParameters * @throws ApiException if the response code was not in [200, 299] */ public async getAllBuildFeatureParameters(response: ResponseContext): Promise<Properties > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Properties = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Properties", "" ) as Properties; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Properties = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Properties", "" ) as Properties; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAllBuildFeatures * @throws ApiException if the response code was not in [200, 299] */ public async getAllBuildFeatures(response: ResponseContext): Promise<Features > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Features = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Features", "" ) as Features; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Features = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Features", "" ) as Features; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAllBuildStepParameters * @throws ApiException if the response code was not in [200, 299] */ public async getAllBuildStepParameters(response: ResponseContext): Promise<Properties > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Properties = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Properties", "" ) as Properties; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Properties = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Properties", "" ) as Properties; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAllBuildSteps * @throws ApiException if the response code was not in [200, 299] */ public async getAllBuildSteps(response: ResponseContext): Promise<Steps > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Steps = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Steps", "" ) as Steps; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Steps = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Steps", "" ) as Steps; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAllBuildTemplates * @throws ApiException if the response code was not in [200, 299] */ public async getAllBuildTemplates(response: ResponseContext): Promise<BuildTypes > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: BuildTypes = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "BuildTypes", "" ) as BuildTypes; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: BuildTypes = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "BuildTypes", "" ) as BuildTypes; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAllBuildTypes * @throws ApiException if the response code was not in [200, 299] */ public async getAllBuildTypes(response: ResponseContext): Promise<BuildTypes > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: BuildTypes = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "BuildTypes", "" ) as BuildTypes; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: BuildTypes = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "BuildTypes", "" ) as BuildTypes; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAllInvestigationsOfBuildType * @throws ApiException if the response code was not in [200, 299] */ public async getAllInvestigationsOfBuildType(response: ResponseContext): Promise<Investigations > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Investigations = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Investigations", "" ) as Investigations; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Investigations = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Investigations", "" ) as Investigations; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAllSnapshotDependencies * @throws ApiException if the response code was not in [200, 299] */ public async getAllSnapshotDependencies(response: ResponseContext): Promise<SnapshotDependencies > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: SnapshotDependencies = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "SnapshotDependencies", "" ) as SnapshotDependencies; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: SnapshotDependencies = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "SnapshotDependencies", "" ) as SnapshotDependencies; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAllTriggers * @throws ApiException if the response code was not in [200, 299] */ public async getAllTriggers(response: ResponseContext): Promise<Triggers > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Triggers = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Triggers", "" ) as Triggers; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Triggers = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Triggers", "" ) as Triggers; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAllVcsRootsOfBuildType * @throws ApiException if the response code was not in [200, 299] */ public async getAllVcsRootsOfBuildType(response: ResponseContext): Promise<VcsRootEntries > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: VcsRootEntries = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "VcsRootEntries", "" ) as VcsRootEntries; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: VcsRootEntries = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "VcsRootEntries", "" ) as VcsRootEntries; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getArtifactDependency * @throws ApiException if the response code was not in [200, 299] */ public async getArtifactDependency(response: ResponseContext): Promise<ArtifactDependency > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: ArtifactDependency = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "ArtifactDependency", "" ) as ArtifactDependency; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: ArtifactDependency = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "ArtifactDependency", "" ) as ArtifactDependency; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getArtifactDependencyParameter * @throws ApiException if the response code was not in [200, 299] */ public async getArtifactDependencyParameter(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuildFeature * @throws ApiException if the response code was not in [200, 299] */ public async getBuildFeature(response: ResponseContext): Promise<Feature > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Feature = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Feature", "" ) as Feature; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Feature = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Feature", "" ) as Feature; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuildFeatureParameter * @throws ApiException if the response code was not in [200, 299] */ public async getBuildFeatureParameter(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuildFeatureSetting * @throws ApiException if the response code was not in [200, 299] */ public async getBuildFeatureSetting(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuildParameterOfBuildType * @throws ApiException if the response code was not in [200, 299] */ public async getBuildParameterOfBuildType(response: ResponseContext): Promise<Property > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Property = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Property", "" ) as Property; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Property = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Property", "" ) as Property; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuildParameterSpecificationOfBuildType * @throws ApiException if the response code was not in [200, 299] */ public async getBuildParameterSpecificationOfBuildType(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuildParameterTypeOfBuildType * @throws ApiException if the response code was not in [200, 299] */ public async getBuildParameterTypeOfBuildType(response: ResponseContext): Promise<Type > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Type = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Type", "" ) as Type; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Type = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Type", "" ) as Type; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuildParameterValueOfBuildType * @throws ApiException if the response code was not in [200, 299] */ public async getBuildParameterValueOfBuildType(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuildParametersOfBuildType * @throws ApiException if the response code was not in [200, 299] */ public async getBuildParametersOfBuildType(response: ResponseContext): Promise<Properties > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Properties = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Properties", "" ) as Properties; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Properties = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Properties", "" ) as Properties; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuildStep * @throws ApiException if the response code was not in [200, 299] */ public async getBuildStep(response: ResponseContext): Promise<Step > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Step = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Step", "" ) as Step; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Step = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Step", "" ) as Step; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuildStepParameter * @throws ApiException if the response code was not in [200, 299] */ public async getBuildStepParameter(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuildStepSetting * @throws ApiException if the response code was not in [200, 299] */ public async getBuildStepSetting(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuildTemplate * @throws ApiException if the response code was not in [200, 299] */ public async getBuildTemplate(response: ResponseContext): Promise<BuildType > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: BuildType = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "BuildType", "" ) as BuildType; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: BuildType = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "BuildType", "" ) as BuildType; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuildType * @throws ApiException if the response code was not in [200, 299] */ public async getBuildType(response: ResponseContext): Promise<BuildType > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: BuildType = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "BuildType", "" ) as BuildType; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: BuildType = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "BuildType", "" ) as BuildType; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuildTypeBuildTags * @throws ApiException if the response code was not in [200, 299] */ public async getBuildTypeBuildTags(response: ResponseContext): Promise<Tags > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Tags = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Tags", "" ) as Tags; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Tags = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Tags", "" ) as Tags; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuildTypeBuilds * @throws ApiException if the response code was not in [200, 299] */ public async getBuildTypeBuilds(response: ResponseContext): Promise<Builds > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Builds = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Builds", "" ) as Builds; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Builds = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Builds", "" ) as Builds; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuildTypeField * @throws ApiException if the response code was not in [200, 299] */ public async getBuildTypeField(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuildTypeSettingsFile * @throws ApiException if the response code was not in [200, 299] */ public async getBuildTypeSettingsFile(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getFileMetadataOfBuildType * @throws ApiException if the response code was not in [200, 299] */ public async getFileMetadataOfBuildType(response: ResponseContext): Promise<any > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: any = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "any", "" ) as any; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: any = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "any", "" ) as any; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getFilesListForSubpathOfBuildType * @throws ApiException if the response code was not in [200, 299] */ public async getFilesListForSubpathOfBuildType(response: ResponseContext): Promise<Files > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Files = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Files", "" ) as Files; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Files = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Files", "" ) as Files; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getFilesListOfBuildType * @throws ApiException if the response code was not in [200, 299] */ public async getFilesListOfBuildType(response: ResponseContext): Promise<Files > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Files = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Files", "" ) as Files; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Files = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Files", "" ) as Files; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getSnapshotDependency * @throws ApiException if the response code was not in [200, 299] */ public async getSnapshotDependency(response: ResponseContext): Promise<SnapshotDependency > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: SnapshotDependency = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "SnapshotDependency", "" ) as SnapshotDependency; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: SnapshotDependency = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "SnapshotDependency", "" ) as SnapshotDependency; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getTrigger * @throws ApiException if the response code was not in [200, 299] */ public async getTrigger(response: ResponseContext): Promise<Trigger > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Trigger = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Trigger", "" ) as Trigger; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Trigger = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Trigger", "" ) as Trigger; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getTriggerParameter * @throws ApiException if the response code was not in [200, 299] */ public async getTriggerParameter(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getVcsRoot * @throws ApiException if the response code was not in [200, 299] */ public async getVcsRoot(response: ResponseContext): Promise<VcsRootEntry > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: VcsRootEntry = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "VcsRootEntry", "" ) as VcsRootEntry; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: VcsRootEntry = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "VcsRootEntry", "" ) as VcsRootEntry; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getVcsRootCheckoutRules * @throws ApiException if the response code was not in [200, 299] */ public async getVcsRootCheckoutRules(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getVcsRootInstancesOfBuildType * @throws ApiException if the response code was not in [200, 299] */ public async getVcsRootInstancesOfBuildType(response: ResponseContext): Promise<VcsRootInstances > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: VcsRootInstances = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "VcsRootInstances", "" ) as VcsRootInstances; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: VcsRootInstances = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "VcsRootInstances", "" ) as VcsRootInstances; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getZippedFileOfBuildType * @throws ApiException if the response code was not in [200, 299] */ public async getZippedFileOfBuildType(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to removeAllTemplates * @throws ApiException if the response code was not in [200, 299] */ public async removeAllTemplates(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to removeTemplate * @throws ApiException if the response code was not in [200, 299] */ public async removeTemplate(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to replaceAgentRequirement * @throws ApiException if the response code was not in [200, 299] */ public async replaceAgentRequirement(response: ResponseContext): Promise<AgentRequirement > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: AgentRequirement = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "AgentRequirement", "" ) as AgentRequirement; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: AgentRequirement = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "AgentRequirement", "" ) as AgentRequirement; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to replaceAllAgentRequirements * @throws ApiException if the response code was not in [200, 299] */ public async replaceAllAgentRequirements(response: ResponseContext): Promise<AgentRequirements > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: AgentRequirements = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "AgentRequirements", "" ) as AgentRequirements; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: AgentRequirements = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "AgentRequirements", "" ) as AgentRequirements; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to replaceAllArtifactDependencies * @throws ApiException if the response code was not in [200, 299] */ public async replaceAllArtifactDependencies(response: ResponseContext): Promise<ArtifactDependencies > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: ArtifactDependencies = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "ArtifactDependencies", "" ) as ArtifactDependencies; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: ArtifactDependencies = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "ArtifactDependencies", "" ) as ArtifactDependencies; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to replaceAllBuildFeatures * @throws ApiException if the response code was not in [200, 299] */ public async replaceAllBuildFeatures(response: ResponseContext): Promise<Features > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Features = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Features", "" ) as Features; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Features = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Features", "" ) as Features; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to replaceAllBuildSteps * @throws ApiException if the response code was not in [200, 299] */ public async replaceAllBuildSteps(response: ResponseContext): Promise<Steps > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Steps = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Steps", "" ) as Steps; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Steps = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Steps", "" ) as Steps; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to replaceAllSnapshotDependencies * @throws ApiException if the response code was not in [200, 299] */ public async replaceAllSnapshotDependencies(response: ResponseContext): Promise<SnapshotDependencies > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: SnapshotDependencies = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "SnapshotDependencies", "" ) as SnapshotDependencies; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: SnapshotDependencies = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "SnapshotDependencies", "" ) as SnapshotDependencies; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to replaceAllTriggers * @throws ApiException if the response code was not in [200, 299] */ public async replaceAllTriggers(response: ResponseContext): Promise<Triggers > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Triggers = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Triggers", "" ) as Triggers; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Triggers = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Triggers", "" ) as Triggers; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to replaceAllVcsRoots * @throws ApiException if the response code was not in [200, 299] */ public async replaceAllVcsRoots(response: ResponseContext): Promise<VcsRootEntries > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: VcsRootEntries = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "VcsRootEntries", "" ) as VcsRootEntries; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: VcsRootEntries = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "VcsRootEntries", "" ) as VcsRootEntries; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to replaceArtifactDependency * @throws ApiException if the response code was not in [200, 299] */ public async replaceArtifactDependency(response: ResponseContext): Promise<ArtifactDependency > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: ArtifactDependency = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "ArtifactDependency", "" ) as ArtifactDependency; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: ArtifactDependency = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "ArtifactDependency", "" ) as ArtifactDependency; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to replaceBuildFeature * @throws ApiException if the response code was not in [200, 299] */ public async replaceBuildFeature(response: ResponseContext): Promise<Feature > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Feature = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Feature", "" ) as Feature; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Feature = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Feature", "" ) as Feature; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to replaceBuildFeatureParameters * @throws ApiException if the response code was not in [200, 299] */ public async replaceBuildFeatureParameters(response: ResponseContext): Promise<Properties > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Properties = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Properties", "" ) as Properties; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Properties = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Properties", "" ) as Properties; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to replaceBuildStep * @throws ApiException if the response code was not in [200, 299] */ public async replaceBuildStep(response: ResponseContext): Promise<Step > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Step = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Step", "" ) as Step; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Step = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Step", "" ) as Step; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to replaceSnapshotDependency * @throws ApiException if the response code was not in [200, 299] */ public async replaceSnapshotDependency(response: ResponseContext): Promise<SnapshotDependency > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: SnapshotDependency = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "SnapshotDependency", "" ) as SnapshotDependency; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: SnapshotDependency = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "SnapshotDependency", "" ) as SnapshotDependency; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to replaceTrigger * @throws ApiException if the response code was not in [200, 299] */ public async replaceTrigger(response: ResponseContext): Promise<Trigger > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Trigger = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Trigger", "" ) as Trigger; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Trigger = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Trigger", "" ) as Trigger; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setAgentRequirementParameter * @throws ApiException if the response code was not in [200, 299] */ public async setAgentRequirementParameter(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setArtifactDependencyParameter * @throws ApiException if the response code was not in [200, 299] */ public async setArtifactDependencyParameter(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setBuildFeatureParameter * @throws ApiException if the response code was not in [200, 299] */ public async setBuildFeatureParameter(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setBuildStepParameter * @throws ApiException if the response code was not in [200, 299] */ public async setBuildStepParameter(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setBuildTypeField * @throws ApiException if the response code was not in [200, 299] */ public async setBuildTypeField(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setBuildTypeTemplates * @throws ApiException if the response code was not in [200, 299] */ public async setBuildTypeTemplates(response: ResponseContext): Promise<BuildTypes > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: BuildTypes = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "BuildTypes", "" ) as BuildTypes; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: BuildTypes = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "BuildTypes", "" ) as BuildTypes; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setTriggerParameter * @throws ApiException if the response code was not in [200, 299] */ public async setTriggerParameter(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to updateBuildParameterOfBuildType * @throws ApiException if the response code was not in [200, 299] */ public async updateBuildParameterOfBuildType(response: ResponseContext): Promise<Property > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Property = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Property", "" ) as Property; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Property = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Property", "" ) as Property; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to updateBuildParameterSpecificationOfBuildType * @throws ApiException if the response code was not in [200, 299] */ public async updateBuildParameterSpecificationOfBuildType(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to updateBuildParameterTypeOfBuildType * @throws ApiException if the response code was not in [200, 299] */ public async updateBuildParameterTypeOfBuildType(response: ResponseContext): Promise<Type > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Type = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Type", "" ) as Type; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Type = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Type", "" ) as Type; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to updateBuildParameterValueOfBuildType * @throws ApiException if the response code was not in [200, 299] */ public async updateBuildParameterValueOfBuildType(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to updateBuildParametersOfBuildType * @throws ApiException if the response code was not in [200, 299] */ public async updateBuildParametersOfBuildType(response: ResponseContext): Promise<Properties > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Properties = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Properties", "" ) as Properties; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Properties = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Properties", "" ) as Properties; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to updateBuildTypeVcsRoot * @throws ApiException if the response code was not in [200, 299] */ public async updateBuildTypeVcsRoot(response: ResponseContext): Promise<VcsRootEntry > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: VcsRootEntry = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "VcsRootEntry", "" ) as VcsRootEntry; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: VcsRootEntry = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "VcsRootEntry", "" ) as VcsRootEntry; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to updateBuildTypeVcsRootCheckoutRules * @throws ApiException if the response code was not in [200, 299] */ public async updateBuildTypeVcsRootCheckoutRules(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } } <file_sep>/ts-schema/schema/rest-api/deno/apis/ProjectApi.ts // TODO: better import syntax? import { BaseAPIRequestFactory, RequiredError } from './baseapi.ts'; import {Configuration} from '../configuration.ts'; import { RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http.ts'; import {ObjectSerializer} from '../models/ObjectSerializer.ts'; import {ApiException} from './exception.ts'; import {isCodeInRange} from '../util.ts'; import { AgentPool } from '../models/AgentPool.ts'; import { AgentPools } from '../models/AgentPools.ts'; import { Branches } from '../models/Branches.ts'; import { BuildType } from '../models/BuildType.ts'; import { BuildTypes } from '../models/BuildTypes.ts'; import { NewBuildTypeDescription } from '../models/NewBuildTypeDescription.ts'; import { NewProjectDescription } from '../models/NewProjectDescription.ts'; import { Project } from '../models/Project.ts'; import { ProjectFeature } from '../models/ProjectFeature.ts'; import { ProjectFeatures } from '../models/ProjectFeatures.ts'; import { Projects } from '../models/Projects.ts'; import { Properties } from '../models/Properties.ts'; import { Property } from '../models/Property.ts'; import { Type } from '../models/Type.ts'; /** * no description */ export class ProjectApiRequestFactory extends BaseAPIRequestFactory { /** * Assign the matching project to the agent pool. * @param projectLocator * @param body */ public async addAgentPoolsProject(projectLocator: string, body?: AgentPool, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling addAgentPoolsProject.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}/agentPools' .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "AgentPool", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Add a build configuration to the matching project. * @param projectLocator * @param fields * @param body */ public async addBuildType(projectLocator: string, fields?: string, body?: NewBuildTypeDescription, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling addBuildType.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}/buildTypes' .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "NewBuildTypeDescription", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Add a feature. * @param projectLocator * @param fields * @param body */ public async addFeature(projectLocator: string, fields?: string, body?: ProjectFeature, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling addFeature.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}/projectFeatures' .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "ProjectFeature", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Create a new project. * @param body */ public async addProject(body?: NewProjectDescription, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/projects'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "NewProjectDescription", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Create a new secure token for the matching project. * @param projectLocator * @param body */ public async addSecureToken(projectLocator: string, body?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling addSecureToken.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}/secure/tokens' .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "text/plain" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "string", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Add a build configuration template to the matching project. * @param projectLocator * @param fields * @param body */ public async addTemplate(projectLocator: string, fields?: string, body?: NewBuildTypeDescription, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling addTemplate.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}/templates' .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "NewBuildTypeDescription", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Create a build parameter. * @param projectLocator * @param fields * @param body */ public async createBuildParameter(projectLocator: string, fields?: string, body?: Property, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling createBuildParameter.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}/parameters' .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Property", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Delete build parameter. * @param name * @param projectLocator */ public async deleteBuildParameter(name: string, projectLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'name' is not null or undefined if (name === null || name === undefined) { throw new RequiredError('Required parameter name was null or undefined when calling deleteBuildParameter.'); } // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling deleteBuildParameter.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}/parameters/{name}' .replace('{' + 'name' + '}', encodeURIComponent(String(name))) .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Delete all build parameters. * @param projectLocator */ public async deleteBuildParameters(projectLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling deleteBuildParameters.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}/parameters' .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Delete a matching feature. * @param featureLocator * @param projectLocator */ public async deleteFeature(featureLocator: string, projectLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'featureLocator' is not null or undefined if (featureLocator === null || featureLocator === undefined) { throw new RequiredError('Required parameter featureLocator was null or undefined when calling deleteFeature.'); } // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling deleteFeature.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}/projectFeatures/{featureLocator}' .replace('{' + 'featureLocator' + '}', encodeURIComponent(String(featureLocator))) .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Delete project matching the locator. * @param projectLocator */ public async deleteProject(projectLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling deleteProject.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}' .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get agent pools appointed to the matching project. * @param projectLocator * @param fields */ public async getAgentPoolsProject(projectLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling getAgentPoolsProject.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}/agentPools' .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all branches of the matching project. * @param projectLocator * @param locator * @param fields */ public async getAllBranches(projectLocator: string, locator?: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling getAllBranches.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}/branches' .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "")); } if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all projects. * @param locator * @param fields */ public async getAllProjects(locator?: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/projects'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "")); } if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all subprojects ordered of the matching project. * @param projectLocator * @param field */ public async getAllSubprojectsOrdered(projectLocator: string, field?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling getAllSubprojectsOrdered.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}/order/projects' .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (field !== undefined) { requestContext.setQueryParam("field", ObjectSerializer.serialize(field, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get build parameter. * @param name * @param projectLocator * @param fields */ public async getBuildParameter(name: string, projectLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'name' is not null or undefined if (name === null || name === undefined) { throw new RequiredError('Required parameter name was null or undefined when calling getBuildParameter.'); } // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling getBuildParameter.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}/parameters/{name}' .replace('{' + 'name' + '}', encodeURIComponent(String(name))) .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get build parameter specification. * @param name * @param projectLocator */ public async getBuildParameterSpecification(name: string, projectLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'name' is not null or undefined if (name === null || name === undefined) { throw new RequiredError('Required parameter name was null or undefined when calling getBuildParameterSpecification.'); } // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling getBuildParameterSpecification.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}/parameters/{name}/type/rawValue' .replace('{' + 'name' + '}', encodeURIComponent(String(name))) .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get type of build parameter. * @param name * @param projectLocator */ public async getBuildParameterType(name: string, projectLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'name' is not null or undefined if (name === null || name === undefined) { throw new RequiredError('Required parameter name was null or undefined when calling getBuildParameterType.'); } // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling getBuildParameterType.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}/parameters/{name}/type' .replace('{' + 'name' + '}', encodeURIComponent(String(name))) .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get value of build parameter. * @param name * @param projectLocator */ public async getBuildParameterValue(name: string, projectLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'name' is not null or undefined if (name === null || name === undefined) { throw new RequiredError('Required parameter name was null or undefined when calling getBuildParameterValue.'); } // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling getBuildParameterValue.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}/parameters/{name}/value' .replace('{' + 'name' + '}', encodeURIComponent(String(name))) .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get build parameters. * @param projectLocator * @param locator * @param fields */ public async getBuildParameters(projectLocator: string, locator?: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling getBuildParameters.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}/parameters' .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "")); } if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get the default template of the matching project. * @param projectLocator * @param fields */ public async getDefaultTemplate(projectLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling getDefaultTemplate.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}/defaultTemplate' .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get a matching feature. * @param featureLocator * @param projectLocator * @param fields */ public async getFeature(featureLocator: string, projectLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'featureLocator' is not null or undefined if (featureLocator === null || featureLocator === undefined) { throw new RequiredError('Required parameter featureLocator was null or undefined when calling getFeature.'); } // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling getFeature.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}/projectFeatures/{featureLocator}' .replace('{' + 'featureLocator' + '}', encodeURIComponent(String(featureLocator))) .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all features. * @param projectLocator * @param locator * @param fields */ public async getFeatures(projectLocator: string, locator?: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling getFeatures.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}/projectFeatures' .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "")); } if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get project matching the locator. * @param projectLocator * @param fields */ public async getProject(projectLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling getProject.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}' .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get a field of the matching project. * @param projectLocator * @param field */ public async getProjectField(projectLocator: string, field: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling getProjectField.'); } // verify required parameter 'field' is not null or undefined if (field === null || field === undefined) { throw new RequiredError('Required parameter field was null or undefined when calling getProjectField.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}/{field}' .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))) .replace('{' + 'field' + '}', encodeURIComponent(String(field))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get the parent project of the matching project. * @param projectLocator * @param fields */ public async getProjectParentProject(projectLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling getProjectParentProject.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}/parentProject' .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get the settings file of the matching build configuration. * @param projectLocator */ public async getProjectSettingsFile(projectLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling getProjectSettingsFile.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}/settingsFile' .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all templates of the matching project. * @param projectLocator * @param fields */ public async getProjectTemplates(projectLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling getProjectTemplates.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}/templates' .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get a secure token of the matching project. * @param projectLocator * @param token */ public async getSecureValue(projectLocator: string, token: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling getSecureValue.'); } // verify required parameter 'token' is not null or undefined if (token === null || token === undefined) { throw new RequiredError('Required parameter token was null or undefined when calling getSecureValue.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}/secure/values/{token}' .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))) .replace('{' + 'token' + '}', encodeURIComponent(String(token))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Remove the default template from the matching project. * @param projectLocator * @param fields */ public async removeDefaultTemplate(projectLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling removeDefaultTemplate.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}/defaultTemplate' .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Unassign a project from the matching agent pool. * @param projectLocator * @param agentPoolLocator */ public async removeProjectFromAgentPool(projectLocator: string, agentPoolLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling removeProjectFromAgentPool.'); } // verify required parameter 'agentPoolLocator' is not null or undefined if (agentPoolLocator === null || agentPoolLocator === undefined) { throw new RequiredError('Required parameter agentPoolLocator was null or undefined when calling removeProjectFromAgentPool.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}/agentPools/{agentPoolLocator}' .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))) .replace('{' + 'agentPoolLocator' + '}', encodeURIComponent(String(agentPoolLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update agent pools apppointed to the matching project. * @param projectLocator * @param fields * @param body */ public async setAgentPoolsProject(projectLocator: string, fields?: string, body?: AgentPools, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling setAgentPoolsProject.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}/agentPools' .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "AgentPools", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update all build configurations order of the matching project. * @param projectLocator * @param field * @param body */ public async setBuildTypesOrder(projectLocator: string, field?: string, body?: BuildTypes, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling setBuildTypesOrder.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}/order/buildTypes' .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (field !== undefined) { requestContext.setQueryParam("field", ObjectSerializer.serialize(field, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "BuildTypes", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update the default template of the matching project. * @param projectLocator * @param fields * @param body */ public async setDefaultTemplate(projectLocator: string, fields?: string, body?: BuildType, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling setDefaultTemplate.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}/defaultTemplate' .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "BuildType", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update the parent project of the matching project. * @param projectLocator * @param fields * @param body */ public async setParentProject(projectLocator: string, fields?: string, body?: Project, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling setParentProject.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}/parentProject' .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Project", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update a field of the matching project. * @param projectLocator * @param field * @param body */ public async setProjectField(projectLocator: string, field: string, body?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling setProjectField.'); } // verify required parameter 'field' is not null or undefined if (field === null || field === undefined) { throw new RequiredError('Required parameter field was null or undefined when calling setProjectField.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}/{field}' .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))) .replace('{' + 'field' + '}', encodeURIComponent(String(field))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "text/plain" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "string", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update all subprojects order of the matching project. * @param projectLocator * @param field * @param body */ public async setSubprojectsOrder(projectLocator: string, field?: string, body?: Projects, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling setSubprojectsOrder.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}/order/projects' .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (field !== undefined) { requestContext.setQueryParam("field", ObjectSerializer.serialize(field, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Projects", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update build parameter. * @param name * @param projectLocator * @param fields * @param body */ public async updateBuildParameter(name: string, projectLocator: string, fields?: string, body?: Property, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'name' is not null or undefined if (name === null || name === undefined) { throw new RequiredError('Required parameter name was null or undefined when calling updateBuildParameter.'); } // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling updateBuildParameter.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}/parameters/{name}' .replace('{' + 'name' + '}', encodeURIComponent(String(name))) .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Property", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update build parameter specification. * @param name * @param projectLocator * @param body */ public async updateBuildParameterSpecification(name: string, projectLocator: string, body?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'name' is not null or undefined if (name === null || name === undefined) { throw new RequiredError('Required parameter name was null or undefined when calling updateBuildParameterSpecification.'); } // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling updateBuildParameterSpecification.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}/parameters/{name}/type/rawValue' .replace('{' + 'name' + '}', encodeURIComponent(String(name))) .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "text/plain" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "string", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update type of build parameter. * @param name * @param projectLocator * @param body */ public async updateBuildParameterType(name: string, projectLocator: string, body?: Type, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'name' is not null or undefined if (name === null || name === undefined) { throw new RequiredError('Required parameter name was null or undefined when calling updateBuildParameterType.'); } // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling updateBuildParameterType.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}/parameters/{name}/type' .replace('{' + 'name' + '}', encodeURIComponent(String(name))) .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Type", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update value of build parameter. * @param name * @param projectLocator * @param body */ public async updateBuildParameterValue(name: string, projectLocator: string, body?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'name' is not null or undefined if (name === null || name === undefined) { throw new RequiredError('Required parameter name was null or undefined when calling updateBuildParameterValue.'); } // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling updateBuildParameterValue.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}/parameters/{name}/value' .replace('{' + 'name' + '}', encodeURIComponent(String(name))) .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "text/plain" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "string", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update build parameters. * @param projectLocator * @param fields * @param body */ public async updateBuildParameters(projectLocator: string, fields?: string, body?: Properties, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling updateBuildParameters.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}/parameters' .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Properties", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update a matching feature. * @param featureLocator * @param projectLocator * @param fields * @param body */ public async updateFeature(featureLocator: string, projectLocator: string, fields?: string, body?: ProjectFeature, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'featureLocator' is not null or undefined if (featureLocator === null || featureLocator === undefined) { throw new RequiredError('Required parameter featureLocator was null or undefined when calling updateFeature.'); } // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling updateFeature.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}/projectFeatures/{featureLocator}' .replace('{' + 'featureLocator' + '}', encodeURIComponent(String(featureLocator))) .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "ProjectFeature", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update all features. * @param projectLocator * @param fields * @param body */ public async updateFeatures(projectLocator: string, fields?: string, body?: ProjectFeatures, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'projectLocator' is not null or undefined if (projectLocator === null || projectLocator === undefined) { throw new RequiredError('Required parameter projectLocator was null or undefined when calling updateFeatures.'); } // Path Params const localVarPath = '/app/rest/projects/{projectLocator}/projectFeatures' .replace('{' + 'projectLocator' + '}', encodeURIComponent(String(projectLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "ProjectFeatures", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } } export class ProjectApiResponseProcessor { /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to addAgentPoolsProject * @throws ApiException if the response code was not in [200, 299] */ public async addAgentPoolsProject(response: ResponseContext): Promise<AgentPool > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: AgentPool = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "AgentPool", "" ) as AgentPool; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: AgentPool = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "AgentPool", "" ) as AgentPool; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to addBuildType * @throws ApiException if the response code was not in [200, 299] */ public async addBuildType(response: ResponseContext): Promise<BuildType > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: BuildType = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "BuildType", "" ) as BuildType; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: BuildType = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "BuildType", "" ) as BuildType; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to addFeature * @throws ApiException if the response code was not in [200, 299] */ public async addFeature(response: ResponseContext): Promise<any > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: any = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "any", "" ) as any; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: any = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "any", "" ) as any; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to addProject * @throws ApiException if the response code was not in [200, 299] */ public async addProject(response: ResponseContext): Promise<Project > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Project = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Project", "" ) as Project; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Project = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Project", "" ) as Project; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to addSecureToken * @throws ApiException if the response code was not in [200, 299] */ public async addSecureToken(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to addTemplate * @throws ApiException if the response code was not in [200, 299] */ public async addTemplate(response: ResponseContext): Promise<BuildType > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: BuildType = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "BuildType", "" ) as BuildType; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: BuildType = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "BuildType", "" ) as BuildType; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to createBuildParameter * @throws ApiException if the response code was not in [200, 299] */ public async createBuildParameter(response: ResponseContext): Promise<Property > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Property = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Property", "" ) as Property; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Property = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Property", "" ) as Property; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to deleteBuildParameter * @throws ApiException if the response code was not in [200, 299] */ public async deleteBuildParameter(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to deleteBuildParameters * @throws ApiException if the response code was not in [200, 299] */ public async deleteBuildParameters(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to deleteFeature * @throws ApiException if the response code was not in [200, 299] */ public async deleteFeature(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to deleteProject * @throws ApiException if the response code was not in [200, 299] */ public async deleteProject(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAgentPoolsProject * @throws ApiException if the response code was not in [200, 299] */ public async getAgentPoolsProject(response: ResponseContext): Promise<AgentPools > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: AgentPools = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "AgentPools", "" ) as AgentPools; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: AgentPools = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "AgentPools", "" ) as AgentPools; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAllBranches * @throws ApiException if the response code was not in [200, 299] */ public async getAllBranches(response: ResponseContext): Promise<Branches > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Branches = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Branches", "" ) as Branches; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Branches = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Branches", "" ) as Branches; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAllProjects * @throws ApiException if the response code was not in [200, 299] */ public async getAllProjects(response: ResponseContext): Promise<Projects > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Projects = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Projects", "" ) as Projects; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Projects = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Projects", "" ) as Projects; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAllSubprojectsOrdered * @throws ApiException if the response code was not in [200, 299] */ public async getAllSubprojectsOrdered(response: ResponseContext): Promise<Projects > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Projects = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Projects", "" ) as Projects; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Projects = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Projects", "" ) as Projects; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuildParameter * @throws ApiException if the response code was not in [200, 299] */ public async getBuildParameter(response: ResponseContext): Promise<Property > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Property = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Property", "" ) as Property; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Property = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Property", "" ) as Property; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuildParameterSpecification * @throws ApiException if the response code was not in [200, 299] */ public async getBuildParameterSpecification(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuildParameterType * @throws ApiException if the response code was not in [200, 299] */ public async getBuildParameterType(response: ResponseContext): Promise<Type > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Type = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Type", "" ) as Type; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Type = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Type", "" ) as Type; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuildParameterValue * @throws ApiException if the response code was not in [200, 299] */ public async getBuildParameterValue(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getBuildParameters * @throws ApiException if the response code was not in [200, 299] */ public async getBuildParameters(response: ResponseContext): Promise<Properties > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Properties = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Properties", "" ) as Properties; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Properties = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Properties", "" ) as Properties; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getDefaultTemplate * @throws ApiException if the response code was not in [200, 299] */ public async getDefaultTemplate(response: ResponseContext): Promise<BuildType > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: BuildType = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "BuildType", "" ) as BuildType; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: BuildType = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "BuildType", "" ) as BuildType; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getFeature * @throws ApiException if the response code was not in [200, 299] */ public async getFeature(response: ResponseContext): Promise<any > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: any = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "any", "" ) as any; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: any = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "any", "" ) as any; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getFeatures * @throws ApiException if the response code was not in [200, 299] */ public async getFeatures(response: ResponseContext): Promise<any > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: any = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "any", "" ) as any; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: any = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "any", "" ) as any; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getProject * @throws ApiException if the response code was not in [200, 299] */ public async getProject(response: ResponseContext): Promise<Project > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Project = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Project", "" ) as Project; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Project = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Project", "" ) as Project; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getProjectField * @throws ApiException if the response code was not in [200, 299] */ public async getProjectField(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getProjectParentProject * @throws ApiException if the response code was not in [200, 299] */ public async getProjectParentProject(response: ResponseContext): Promise<Project > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Project = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Project", "" ) as Project; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Project = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Project", "" ) as Project; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getProjectSettingsFile * @throws ApiException if the response code was not in [200, 299] */ public async getProjectSettingsFile(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getProjectTemplates * @throws ApiException if the response code was not in [200, 299] */ public async getProjectTemplates(response: ResponseContext): Promise<BuildTypes > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: BuildTypes = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "BuildTypes", "" ) as BuildTypes; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: BuildTypes = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "BuildTypes", "" ) as BuildTypes; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getSecureValue * @throws ApiException if the response code was not in [200, 299] */ public async getSecureValue(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to removeDefaultTemplate * @throws ApiException if the response code was not in [200, 299] */ public async removeDefaultTemplate(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to removeProjectFromAgentPool * @throws ApiException if the response code was not in [200, 299] */ public async removeProjectFromAgentPool(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setAgentPoolsProject * @throws ApiException if the response code was not in [200, 299] */ public async setAgentPoolsProject(response: ResponseContext): Promise<AgentPools > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: AgentPools = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "AgentPools", "" ) as AgentPools; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: AgentPools = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "AgentPools", "" ) as AgentPools; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setBuildTypesOrder * @throws ApiException if the response code was not in [200, 299] */ public async setBuildTypesOrder(response: ResponseContext): Promise<BuildTypes > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: BuildTypes = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "BuildTypes", "" ) as BuildTypes; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: BuildTypes = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "BuildTypes", "" ) as BuildTypes; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setDefaultTemplate * @throws ApiException if the response code was not in [200, 299] */ public async setDefaultTemplate(response: ResponseContext): Promise<BuildType > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: BuildType = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "BuildType", "" ) as BuildType; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: BuildType = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "BuildType", "" ) as BuildType; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setParentProject * @throws ApiException if the response code was not in [200, 299] */ public async setParentProject(response: ResponseContext): Promise<Project > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Project = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Project", "" ) as Project; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Project = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Project", "" ) as Project; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setProjectField * @throws ApiException if the response code was not in [200, 299] */ public async setProjectField(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to setSubprojectsOrder * @throws ApiException if the response code was not in [200, 299] */ public async setSubprojectsOrder(response: ResponseContext): Promise<Projects > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Projects = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Projects", "" ) as Projects; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Projects = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Projects", "" ) as Projects; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to updateBuildParameter * @throws ApiException if the response code was not in [200, 299] */ public async updateBuildParameter(response: ResponseContext): Promise<Property > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Property = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Property", "" ) as Property; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Property = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Property", "" ) as Property; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to updateBuildParameterSpecification * @throws ApiException if the response code was not in [200, 299] */ public async updateBuildParameterSpecification(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to updateBuildParameterType * @throws ApiException if the response code was not in [200, 299] */ public async updateBuildParameterType(response: ResponseContext): Promise<Type > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Type = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Type", "" ) as Type; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Type = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Type", "" ) as Type; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to updateBuildParameterValue * @throws ApiException if the response code was not in [200, 299] */ public async updateBuildParameterValue(response: ResponseContext): Promise<string > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: string = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "string", "" ) as string; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to updateBuildParameters * @throws ApiException if the response code was not in [200, 299] */ public async updateBuildParameters(response: ResponseContext): Promise<Properties > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Properties = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Properties", "" ) as Properties; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Properties = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Properties", "" ) as Properties; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to updateFeature * @throws ApiException if the response code was not in [200, 299] */ public async updateFeature(response: ResponseContext): Promise<any > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: any = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "any", "" ) as any; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: any = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "any", "" ) as any; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to updateFeatures * @throws ApiException if the response code was not in [200, 299] */ public async updateFeatures(response: ResponseContext): Promise<any > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: any = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "any", "" ) as any; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: any = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "any", "" ) as any; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } } <file_sep>/ts-schema/schema/rest-api/deno/models/all.ts export * from './Agent.ts' export * from './AgentLocator.ts' export * from './AgentPool.ts' export * from './AgentPoolLocator.ts' export * from './AgentPools.ts' export * from './AgentRequirement.ts' export * from './AgentRequirements.ts' export * from './Agents.ts' export * from './ArtifactDependencies.ts' export * from './ArtifactDependency.ts' export * from './AuditAction.ts' export * from './AuditEvent.ts' export * from './AuditEvents.ts' export * from './AuditLocator.ts' export * from './AuthorizedInfo.ts' export * from './Branch.ts' export * from './BranchLocator.ts' export * from './BranchVersion.ts' export * from './Branches.ts' export * from './Build.ts' export * from './BuildCancelRequest.ts' export * from './BuildChange.ts' export * from './BuildChanges.ts' export * from './BuildLocator.ts' export * from './BuildQueueLocator.ts' export * from './BuildTriggeringOptions.ts' export * from './BuildType.ts' export * from './BuildTypeLocator.ts' export * from './BuildTypes.ts' export * from './Builds.ts' export * from './Change.ts' export * from './ChangeLocator.ts' export * from './Changes.ts' export * from './CloudImage.ts' export * from './CloudImages.ts' export * from './CloudInstance.ts' export * from './CloudInstances.ts' export * from './CloudProfile.ts' export * from './CloudProfiles.ts' export * from './Comment.ts' export * from './Compatibilities.ts' export * from './Compatibility.ts' export * from './CompatibilityPolicy.ts' export * from './Customizations.ts' export * from './Datas.ts' export * from './EnabledInfo.ts' export * from './Entries.ts' export * from './Entry.ts' export * from './Environment.ts' export * from './Feature.ts' export * from './Features.ts' export * from './File.ts' export * from './FileChange.ts' export * from './FileChanges.ts' export * from './Files.ts' export * from './Group.ts' export * from './Groups.ts' export * from './Href.ts' export * from './Investigation.ts' export * from './InvestigationLocator.ts' export * from './Investigations.ts' export * from './Issue.ts' export * from './IssueUsage.ts' export * from './Issues.ts' export * from './IssuesUsages.ts' export * from './Items.ts' export * from './LicenseKey.ts' export * from './LicenseKeys.ts' export * from './LicensingData.ts' export * from './Link.ts' export * from './Links.ts' export * from './MetaData.ts' export * from './Metric.ts' export * from './MetricTag.ts' export * from './MetricTags.ts' export * from './MetricValue.ts' export * from './MetricValues.ts' export * from './Metrics.ts' export * from './MultipleOperationResult.ts' export * from './Mute.ts' export * from './MuteLocator.ts' export * from './Mutes.ts' export * from './NewBuildTypeDescription.ts' export * from './NewProjectDescription.ts' export * from './OperationResult.ts' export * from './ParsedTestName.ts' export * from './Permission.ts' export * from './PermissionAssignment.ts' export * from './PermissionAssignments.ts' export * from './PermissionRestriction.ts' export * from './PermissionRestrictions.ts' export * from './PinInfo.ts' export * from './Plugin.ts' export * from './Plugins.ts' export * from './Problem.ts' export * from './ProblemLocator.ts' export * from './ProblemOccurrence.ts' export * from './ProblemOccurrenceLocator.ts' export * from './ProblemOccurrences.ts' export * from './ProblemScope.ts' export * from './ProblemTarget.ts' export * from './Problems.ts' export * from './ProgressInfo.ts' export * from './Project.ts' export * from './ProjectFeature.ts' export * from './ProjectFeatures.ts' export * from './ProjectLocator.ts' export * from './Projects.ts' export * from './Properties.ts' export * from './Property.ts' export * from './Related.ts' export * from './RelatedEntities.ts' export * from './RelatedEntity.ts' export * from './RepositoryState.ts' export * from './Requirements.ts' export * from './Resolution.ts' export * from './Revision.ts' export * from './Revisions.ts' export * from './Role.ts' export * from './Roles.ts' export * from './Server.ts' export * from './SnapshotDependencies.ts' export * from './SnapshotDependency.ts' export * from './StateField.ts' export * from './Step.ts' export * from './Steps.ts' export * from './Tag.ts' export * from './TagLocator.ts' export * from './Tags.ts' export * from './Test.ts' export * from './TestCounters.ts' export * from './TestLocator.ts' export * from './TestOccurrence.ts' export * from './TestOccurrenceLocator.ts' export * from './TestOccurrences.ts' export * from './TestRunMetadata.ts' export * from './Tests.ts' export * from './Token.ts' export * from './Tokens.ts' export * from './Trigger.ts' export * from './TriggeredBy.ts' export * from './Triggers.ts' export * from './Type.ts' export * from './TypedValue.ts' export * from './User.ts' export * from './UserGroupLocator.ts' export * from './UserLocator.ts' export * from './Users.ts' export * from './VcsCheckStatus.ts' export * from './VcsLabel.ts' export * from './VcsLabels.ts' export * from './VcsRoot.ts' export * from './VcsRootEntries.ts' export * from './VcsRootEntry.ts' export * from './VcsRootInstance.ts' export * from './VcsRootInstanceLocator.ts' export * from './VcsRootInstances.ts' export * from './VcsRootLocator.ts' export * from './VcsRoots.ts' export * from './VcsStatus.ts' <file_sep>/ts-schema/schema/json/project_extension.ts import { AllXOR } from "../xor.ts"; export type ProjectExtension = | ProjectExtensionReportTab | ProjectExtensionOAuthProvider | ProjectExtensionIssueTracker | ProjectExtensionSharedResource | ProjectExtensionPackageRepository | ProjectExtensionKeepRules | ProjectExtensionVersionedSettings; export interface ProjectExtensionBase { /** * This id is used as an attribute on the extension xml node. * * eg: `<extension id="foo">` * * It is not something you have access to in UI and * normally TeamCity will generate this value. * * eg: `PROJECT_EXT_1`, `PROJECT_EXT_2`, `PROJECT_EXT_3`, etc... */ id: string; } export type ProjectExtensionReportTab = | ProjectExtensionBuildReportTab | ProjectExtensionProjectReportTab; export interface ProjectExtensionReportTabBase extends ProjectExtensionBase { /** * see: https://www.jetbrains.com/help/teamcity/2020.2/including-third-party-reports-in-the-build-results.html */ type: "ReportTab"; /** * Specify a unique title of the report tab that will be displayed in the web UI. */ title: string; /** * Specify the path to the artifacts to be displayed as the contents * of the report page. The path must be relative to the root of the * build artifact directory. * * To use a file from an archive, use the `path-to-archive!relative-path` * syntax, for example: `javadoc.zip!/index.html`. * * See the list of supported archives. * https://www.jetbrains.com/help/teamcity/2020.2/patterns-for-accessing-build-artifacts.html#Obtaining+Artifacts+from+a+Build+Script * * You can use the file browser next to the field to select artifacts. * Parameter references are supported here, for example, * `%parameter%.zip!index.htm`. */ startPage: string; } export interface ProjectExtensionBuildReportTab extends ProjectExtensionReportTabBase { /** * Here you can define artifact-based tabs for build results. * * Appears on the Build Results page for each build that produced an artifact * with the specified name. These report tabs are defined in a project and are * inherited in its subprojects. * * To override an inherited Report tab in a subproject, create a new report * tab with the same name as the inherited one in the subproject. */ subType: "BuildReportTab"; } export interface ProjectExtensionProjectReportTab extends ProjectExtensionReportTabBase { /** * Here you can define custom artifact-based tabs for the Project Home page. * * Appears on the Project Home page for a particular project only if a build * within the project produces the specified reports' artifact. */ subType: "ProjectReportTab"; /** * Select the build configuration and specify the build whose artifacts will * be shown on the tab. */ buildTypeId: string; /** * Select whether the report should be taken from the last successful, * pinned, finished build or the build with the specified build number * or the last build with the specified tag. */ revisionRuleName: | "lastSuccessful" | "lastPinned" | "lastFinished" | "buildNumber" | "buildTag"; /** * If `revisionRuleName=buildNumber` or `revisionRuleName=buildTag` * this is the value of the build number or tag. */ revisionRuleValue?: string; } export type ProjectExtensionOAuthProvider = | ProjectExtensionOAuthProviderAmazonDocker | ProjectExtensionOAuthProviderBitBucketCloud | ProjectExtensionOAuthProviderDocker | ProjectExtensionOAuthProviderGithub | ProjectExtensionOAuthProviderGitlab | ProjectExtensionOAuthProviderJetBrainsSpace | ProjectExtensionOAuthProviderSlackConnection | ProjectExtensionOAuthProviderTfs; export interface ProjectExtensionOAuthProviderBase extends ProjectExtensionBase { /** * This is another base type, it refers to the Connections page of a Project. */ type: "OAuthProvider"; /** * Provide some name to distinguish this connection from others. */ displayName: string; } export interface ProjectExtensionOAuthProviderAmazonDocker extends ProjectExtensionOAuthProviderBase { /** * Connect TeamCity to an AWS ECR docker registry to simplify docker operations. */ providerType: "AmazonDocker"; /** * Registry Id / AWS Account Id */ registryID: string; /** * The AWS Region identifier for where the ECR registry resides. */ region: string; /** * The `AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY` to use otherwise the * default AWS Credential Provider Chain is used. */ auth?: { accessKeyId: string; secretAccessKey: `credentialsJSON:${string}`; }; /** * An IAM role to assume, using AWS STS temporary keys. * * If not supplied then the provided `AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY` * key pair or the default AWS Credential Provider Chain will be used directly. */ role?: { arn: string; /** * External ID is strongly recommended to be used in role trust relationship condition. * * see: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user_externalid.html */ externalID?: string; }; } export interface ProjectExtensionOAuthProviderBitBucketCloud extends ProjectExtensionOAuthProviderBase { /** * Connect TeamCity to https://bitbucket.org * * see: https://www.jetbrains.com/help/teamcity/integrating-teamcity-with-vcs-hosting-services.html#Connecting+to+Bitbucket+Cloud */ providerType: "BitBucketCloud"; /** * The Bitbucket API Key. */ key: string; /** * The Bitbucket API Secret. * * > HINT: If you really truly do not want to use a `credentialsJSON` pointer * > here, instead preferring a password parameter you can still do that but * > you will have to cast the string. This is hard on purpose, you should * > always prefer `credentialsJSON` over a parameter with a password spec. */ secret: `credentialsJSON:${string}`; } export interface ProjectExtensionOAuthProviderDocker extends ProjectExtensionOAuthProviderBase { /** * Connect TeamCity to a Docker Registry. * * see: https://www.jetbrains.com/help/teamcity/2020.2/configuring-connections-to-docker.html */ providerType: "Docker"; /** * The URL to the Docker Registry. * * Format: `[http(s)://]hostname[:port]`, by default `https://` is used. */ repositoryUrl: string; /** * The username & password to authenticate against the Docker Registry. * * Leave blank for anonymous access. */ auth?: { /** * The Docker Registry username. */ username: string; /** * The Docker Registry password. * * > HINT: If you really truly do not want to use a `credentialsJSON` pointer * > here, instead preferring a password parameter you can still do that but * > you will have to cast the string. This is hard on purpose, you should * > always prefer `credentialsJSON` over a parameter with a password spec. */ password: `<PASSWORD>:${string}`; }; } export interface ProjectExtensionOAuthProviderGithub extends ProjectExtensionOAuthProviderBase { /** * Connect TeamCity to https://github.com or a Github Enterprise server. * * see: https://www.jetbrains.com/help/teamcity/integrating-teamcity-with-vcs-hosting-services.html#Connecting+to+GitHub */ providerType: "Github"; /** * If using Github Enterprise, provide your servers URL. * * Defaults to: `https://github.com`. */ serverUrl?: string; /** * The oAuth Client ID. */ clientId: string; /** * The oAuth Client Secret. * * > HINT: If you really truly do not want to use a `credentialsJSON` pointer * > here, instead preferring a password parameter you can still do that but * > you will have to cast the string. This is hard on purpose, you should * > always prefer `credentialsJSON` over a parameter with a password spec. */ secret: `credentialsJSON:${string}`; } export interface ProjectExtensionOAuthProviderGitlab extends ProjectExtensionOAuthProviderBase { /** * Connect TeamCity to https://gitlab.com or a Gitlab CE/EE server. * * see: https://www.jetbrains.com/help/teamcity/integrating-teamcity-with-vcs-hosting-services.html#Connecting+to+GitLab */ providerType: "Gitlab"; /** * If using Gitlab CE/EE, provide your servers URL. * * Defaults to: `https://gitlab.com`. */ serverUrl?: string; /** * The oAuth Client ID. */ clientId: string; /** * The oAuth Client Secret. * * > HINT: If you really truly do not want to use a `credentialsJSON` pointer * > here, instead preferring a password parameter you can still do that but * > you will have to cast the string. This is hard on purpose, you should * > always prefer `credentialsJSON` over a parameter with a password spec. */ secret: `credentialsJSON:${string}`; } export interface ProjectExtensionOAuthProviderJetBrainsSpace extends ProjectExtensionOAuthProviderBase { /** * Connect TeamCity to https://www.jetbrains.com/space/ * * see: https://www.jetbrains.com/help/space/ci-server-integration.html#configure-your-teamcity-project */ providerType: "JetBrains Space"; /** * Your space server URL. */ serverUrl: string; /** * The oAuth Client ID. */ clientId: string; /** * The oAuth Client Secret. * * > HINT: If you really truly do not want to use a `credentialsJSON` pointer * > here, instead preferring a password parameter you can still do that but * > you will have to cast the string. This is hard on purpose, you should * > always prefer `credentialsJSON` over a parameter with a password spec. */ secret: `credentialsJSON:${string}`; } export interface ProjectExtensionOAuthProviderSlackConnection extends ProjectExtensionOAuthProviderBase { /** * This is used by the "Slack Notifier". * * see: https://www.jetbrains.com/help/teamcity/notifications.html#Configuring+Slack+Connection */ providerType: "slackConnection"; /** * The oAuth Client ID. */ clientId: string; /** * The oAuth Client Secret. * * > HINT: If you really truly do not want to use a `credentialsJSON` pointer * > here, instead preferring a password parameter you can still do that but * > you will have to cast the string. This is hard on purpose, you should * > always prefer `credentialsJSON` over a parameter with a password spec. */ clientSecret: `<PASSWORD>:${string}`; /** * The bot user token. * * see: https://api.slack.com/docs/token-types#bot * * > HINT: If you really truly do not want to use a `credentialsJSON` pointer * > here, instead preferring a password parameter you can still do that but * > you will have to cast the string. This is hard on purpose, you should * > always prefer `credentialsJSON` over a parameter with a password spec. */ botToken: `credentials<PASSWORD>:${string}`; } export interface ProjectExtensionOAuthProviderTfs extends ProjectExtensionOAuthProviderBase { /** * Connect TeamCity to Azure Devops or VSTS. aka: TFS. * * see: https://www.jetbrains.com/help/teamcity/integrating-teamcity-with-vcs-hosting-services.html#Connecting+to+Azure+DevOps+Services */ providerType: "tfs"; /** * URL format: * - Azure DevOps: `https://dev.azure.com/<organization>` * - VSTS: `https://<account>.visualstudio.com` */ serverUrl: string; /** * The oAuth bearer token. * * > HINT: If you really truly do not want to use a `credentialsJSON` pointer * > here, instead preferring a password parameter you can still do that but * > you will have to cast the string. This is hard on purpose, you should * > always prefer `credentialsJSON` over a parameter with a password spec. */ accessToken: `<PASSWORD>:${string}`; } export type ProjectExtensionIssueTracker = | ProjectExtensionIssueTrackerBitBucket | ProjectExtensionIssueTrackerBugzilla | ProjectExtensionIssueTrackerGithub | ProjectExtensionIssueTrackerJira | ProjectExtensionIssueTrackerTfs | ProjectExtensionIssueTrackerYoutrack; export interface ProjectExtensionIssueTrackerBase extends ProjectExtensionBase { /** * This is another base type, it refers to the Issue Trackers page of a Project. */ type: "IssueTracker"; /** * Provide some name to distinguish this tracker from others. */ displayName: string; } export interface ProjectExtensionIssueTrackerBitBucket extends ProjectExtensionIssueTrackerBase { /** * Connect TeamCity to the Bitbucket Issue Tracker. * * see: https://www.jetbrains.com/help/teamcity/2020.2/bitbucket-cloud.html */ providerType: "BitBucketIssues"; /** * The url to your bit bucket repository. */ repositoryUrl: string; /** * Issue ID Pattern: a Java Regular Expression pattern to find the issue ID * in the text. The matched text (or the first group if there are groups * defined) is used as the issue number. * * Defaults to: `#(\d+)`. * * see: https://www.jetbrains.com/help/teamcity/2020.2/integrating-teamcity-with-issue-tracker.html#Converting+Strings+into+Links+to+Issues * also: http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Pattern.html */ pattern?: string; /** * Credentials to log in to the issue tracker, if it requires authorization. */ auth?: { /** * The username used to connect to BitBucket. * * > HINT: For Bitbucket Cloud team accounts, it is possible to use the * > team name as the username and the API key as the password. */ username: string; /** * The password used to connect to Bitbucket * * > HINT: If you really truly do not want to use a `credentialsJSON` pointer * > here, instead preferring a password parameter you can still do that but * > you will have to cast the string. This is hard on purpose, you should * > always prefer `credentialsJSON` over a parameter with a password spec. */ password: `<PASSWORD>:${string}`; }; } export interface ProjectExtensionIssueTrackerBugzilla extends ProjectExtensionIssueTrackerBase { /** * Connext TeamCity to a Bugzilla Issue Tracker. * * see: https://www.jetbrains.com/help/teamcity/2020.2/bugzilla.html */ providerType: "bugzilla"; /** * The url to your bugzilla server. */ serverUrl: string; /** * Issue ID Pattern: a Java Regular Expression pattern to find the issue ID * in the text. The matched text (or the first group if there are groups * defined) is used as the issue number. * * Defaults to: `#(\d+)`. * * see: https://www.jetbrains.com/help/teamcity/2020.2/integrating-teamcity-with-issue-tracker.html#Converting+Strings+into+Links+to+Issues * also: http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Pattern.html */ pattern?: string; /** * Credentials to log in to the issue tracker, if it requires authorization. * * > HINT: If the username and password are specified, you need to have * > Bugzilla XML-RPC interface switched on. This is not required if you * > use anonymous access to Bugzilla without the username and password. */ auth?: { /** * The username used to connect to Bugzilla. */ username: string; /** * The password used to connect to Bugzilla * * > HINT: If you really truly do not want to use a `credentialsJSON` pointer * > here, instead preferring a password parameter you can still do that but * > you will have to cast the string. This is hard on purpose, you should * > always prefer `credentialsJSON` over a parameter with a password spec. */ password: `<PASSWORD>:${string}`; }; } export interface ProjectExtensionIssueTrackerGithub extends ProjectExtensionIssueTrackerBase { /** * Connect TeamCity to a Github Issue Tracker. * * see: https://www.jetbrains.com/help/teamcity/2020.2/github.html */ providerType: "GithubIssues"; /** * The url to your Github repository. */ repositoryUrl: string; /** * Issue ID Pattern: a Java Regular Expression pattern to find the issue ID * in the text. The matched text (or the first group if there are groups * defined) is used as the issue number. * * Defaults to: `#(\d+)`. * * see: https://www.jetbrains.com/help/teamcity/2020.2/integrating-teamcity-with-issue-tracker.html#Converting+Strings+into+Links+to+Issues * also: http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Pattern.html */ pattern?: string; /** * Credentials to log in to the issue tracker, if it requires authorization. * * > HINT: Authentication via login/password is deprecated by GitHub. * > We highly recommend that you authenticate with access tokens instead. */ auth?: AllXOR<[{ /** * A Github Token. * * > HINT: If you really truly do not want to use a `credentialsJSON` pointer * > here, instead preferring a password parameter you can still do that but * > you will have to cast the string. This is hard on purpose, you should * > always prefer `credentialsJSON` over a parameter with a password spec. */ token: `<PASSWORD>:${string}`; }, { /** * The github username. * * > HINT: Authentication via login/password is deprecated by GitHub. * > We highly recommend that you authenticate with access tokens instead. */ username: string; /** * The github password for the given username. * * > HINT: If you really truly do not want to use a `credentialsJSON` pointer * > here, instead preferring a password parameter you can still do that but * > you will have to cast the string. This is hard on purpose, you should * > always prefer `credentialsJSON` over a parameter with a password spec. */ password: `<PASSWORD>:${string}`; }]>; } export interface ProjectExtensionIssueTrackerJira extends ProjectExtensionIssueTrackerBase { /** * Connect TeamCity to a Jira Issue Tracker. * * see: https://www.jetbrains.com/help/teamcity/2020.2/jira.html */ providerType: "jira"; /** * The url to your Jira server. * * > HINT: Using Jira Cloud, your URL will be something like: * > `https://<my-org>.atlassian.net` */ serverUrl: string; /** * A list of Jira Project Keys to watch. * * If none provided then all keys will be automatically synchronized. * * see: https://www.jetbrains.com/help/teamcity/2020.2/integrating-teamcity-with-issue-tracker.html#Converting+Strings+into+Links+to+Issues */ projectKeys?: string[]; /** * Enter username for self-hosted Jira or email for Jira Cloud. */ username: string; /** * Enter password for self-hosted Jira or access token for Jira Cloud */ password: string; /** * OAuth credentials to send build/deploy information to Jira Cloud. * * Since version 2020.1, TeamCity can report build statuses directly to * Jira Cloud in real time. To configure this extra option, you need to * provide the Jira Client ID and Server secret when configuring a * connection and add a respective build feature. * * > HINT: This is applicable only to Jira Cloud. */ oAuth?: { /** * The oAuth Client ID. */ clientId: string; /** * The oAuth Client secret. * * > HINT: If you really truly do not want to use a `credentialsJSON` pointer * > here, instead preferring a password parameter you can still do that but * > you will have to cast the string. This is hard on purpose, you should * > always prefer `credentialsJSON` over a parameter with a password spec. */ clientSecret: `credentialsJSON:${string}`; }; } export interface ProjectExtensionIssueTrackerYoutrack extends ProjectExtensionIssueTrackerBase { /** * Connect TeamCity to a Jet Brains YouTrack Issue Tracker. * * see: https://www.jetbrains.com/help/teamcity/2020.2/youtrack.html */ providerType: "youtrack"; /** * The url to your YouTrack server. */ serverUrl: string; /** * A list of Project IDs to watch. * * If none provided then all IDs will be automatically synchronized. * * see: https://www.jetbrains.com/help/teamcity/2020.2/integrating-teamcity-with-issue-tracker.html#Converting+Strings+into+Links+to+Issues */ projectIDs?: string[]; /** * Credentials to log in to the issue tracker. */ auth: AllXOR<[{ /** * A YouTrack Token. * * > HINT: If you really truly do not want to use a `credentialsJSON` pointer * > here, instead preferring a password parameter you can still do that but * > you will have to cast the string. This is hard on purpose, you should * > always prefer `credentialsJSON` over a parameter with a password spec. */ token: `<PASSWORD>:${string}`; }, { /** * The YouTrack username. * * > HINT: Authentication via login/password is deprecated by GitHub. * > We highly recommend that you authenticate with access tokens instead. */ username: string; /** * The YouTrack password for the given username. * * > HINT: If you really truly do not want to use a `credentialsJSON` pointer * > here, instead preferring a password parameter you can still do that but * > you will have to cast the string. This is hard on purpose, you should * > always prefer `credentialsJSON` over a parameter with a password spec. */ password: `<PASSWORD>:${string}`; }]>; } export interface ProjectExtensionIssueTrackerTfs extends ProjectExtensionIssueTrackerBase { /** * Connect TeamCity to a TFS based Issue Tracker. aka: Azure DevOps * * see: https://www.jetbrains.com/help/teamcity/2020.2/team-foundation-work-items.html */ providerType: "tfs"; /** * The url to your TFS server. * * URL format: * - TFS: `http[s]://<host>[:<port>]/tfs/<collection>/<project>` * - Azure DevOps: `https://dev.azure.com/<organization>/<project>` * - VSTS: `https://<account>.visualstudio.com/<project>` */ serverUrl: string; /** * Issue ID Pattern: a Java Regular Expression pattern to find the issue ID * in the text. The matched text (or the first group if there are groups * defined) is used as the issue number. * * Defaults to: `#(\d+)`. * * see: https://www.jetbrains.com/help/teamcity/2020.2/integrating-teamcity-with-issue-tracker.html#Converting+Strings+into+Links+to+Issues * also: http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Pattern.html */ pattern?: string; /** * You should probably prefer token based auth. * * see: https://www.jetbrains.com/help/teamcity/2020.2/team-foundation-server.html#Authentication+Notes */ auth: AllXOR<[{ /** * A Personal Access Token. * * > HINT: If you really truly do not want to use a `credentialsJSON` pointer * > here, instead preferring a password parameter you can still do that but * > you will have to cast the string. This is hard on purpose, you should * > always prefer `credentialsJSON` over a parameter with a password spec. */ token: `<PASSWORD>:${string}`; }, { /** * To use the user/pass pair authentication, you have to enable alternate * credentials in your Azure DevOps account, where you can set a secondary * username and password to use when configuring a VCS root. * * > HINT: Azure DevOps stops supporting alternate credentials since March 2, 2020. * > To be able to authenticate in Azure DevOps, please use alternative methods * > instead (such as personal access tokens). */ username: string; /** * The password for the given username. * * > HINT: If you really truly do not want to use a `credentialsJSON` pointer * > here, instead preferring a password parameter you can still do that but * > you will have to cast the string. This is hard on purpose, you should * > always prefer `credentialsJSON` over a parameter with a password spec. */ password: `<PASSWORD>:${string}`; }]>; } export type ProjectExtensionSharedResource = & ProjectExtensionBase & { /** * The Shared Resources build feature allows limiting concurrently running * builds using a shared resource, such as an external (to the CI server) * resource, for example, a test database, or a server with a limited number * of connections. * * see: https://www.jetbrains.com/help/teamcity/2020.2/shared-resources.html */ type: "JetBrains.SharedResources"; /** * The name of the shared resource to distinguish it from others. */ name: string; /** * If the resource is enabled or not. * * Defaults to `true`. */ enabled?: boolean; } & AllXOR<[ { /** * Quota is a number of concurrent read locks that can be acquired on the resource. * * Write locks are always exclusive, only a single running build with a * write lock is allowed. * * > HINT: Set this to -1 to get an infinite number of read locks. * * see: https://www.jetbrains.com/help/teamcity/2020.2/shared-resources.html#Locks+for+Resources+with+Quotas */ quota: number; }, { /** * Or a resource can represent a set of custom values, such as URLs. * * Resources with custom values support three types of locks: * * - Locks on any available value: a build that uses the resource will * start if at least one of the values is available. If all values are * being used at the moment, the build will wait in the queue. * * - Locks on all values: a build will lock all the values of the resource. * No other builds that use this resource will start until the current * one is finished. * * - Locks on a specific value: only a specific value of the resource will * be passed to the build. If the value is already taken by a running build, * the new build will wait in the queue until the value becomes available. * * see: https://www.jetbrains.com/help/teamcity/2020.2/shared-resources.html#Locks+for+Resources+with+Custom+Values */ values: string[]; }, ]>; export type ProjectExtensionPackageRepository = ProjectExtensionPackageRepositoryNuget; export interface ProjectExtensionPackageRepositoryBase extends ProjectExtensionBase { /** * This is another base type, it refers to different types of built-in * Package Repositories/Feeds that TeamCity can be configured to provide. */ type: "PackageRepository"; /** * Provide some name to distinguish this repository from others. */ displayName: string; /** * An optional human friendly description of the repository. */ description?: string; } export interface ProjectExtensionPackageRepositoryNuget extends ProjectExtensionPackageRepositoryBase { /** * If you want to publish your NuGet packages to a limited audience, * for example, to use them internally, you can use TeamCity as a NuGet feed. * You can configure multiple NuGet feeds for a TeamCity project. * * The built-in TeamCity NuGet feed supports API v1/v2/v3. * * see: https://www.jetbrains.com/help/teamcity/2020.2/using-teamcity-as-nuget-feed.html */ providerType: "nuget"; /** * NuGet packages indexer is an internal TeamCity tool that can index NuGet * packages and add them to TeamCity remote private feeds, with no need for * additional authorization. * * When the NuGet packages indexer build feature is added to a build configuration, * all `.nupkg` files published as build artifacts will be indexed and added to * the selected NuGet feed. Indexing is performed on the agent side. * * Defaults to: `false`. * * see: https://www.jetbrains.com/help/teamcity/2020.2/nuget-packages-indexer.html */ indexPackages?: boolean; } export interface ProjectExtensionKeepRules extends ProjectExtensionBase { /** * The clean-up rules define how to clean data in the current project, * its subprojects and build configurations. * * Keep rules define what data to preserve during the clean-up. They are very * flexible but take more effort to configure than base rules. Multiple keep * rules can be assigned to a project or build configuration. Read how to * configure a keep rule. * * see: https://www.jetbrains.com/help/teamcity/2020.2/clean-up.html#Clean-up+Rules */ type: "keepRules"; /** * Is the rule enabled or not? * * Default to: `true`. */ enabled?: boolean; /** * Defines what build data to preserve. Provide one or more of these options. * Supplying the `everything` option is the same as supplying all the options. */ keep: ("everything" | "artifacts" | "logs" | "statistics")[]; /** * If keeping artifacts, which artifacts should we keep. * * > HINT: If none is provided all artifacts are kept. */ artifactPatterns?: string[]; /** * To keep artifacts in dependencies or not. This option controls if the * builds of the dependency build configurations are also cleaned up. * * With this option enabled, if some build is preserved by this rule, all * artifacts of its dependency builds will also be preserved. * * The option works similarly to the Dependencies option of a base rule. * * Defaults to `true`. */ keepDependantArtifacts?: boolean; /** * Defines which builds this cleanup rule applies to. */ filter: { /** * Whether to include failed builds or not. * * Defaults to `successful`. */ status?: "any" | "successful" | "failed"; /** * Whether to include personal builds or not. * * A personal build is a build-out of the common build sequence which * typically uses the changes not yet committed into the version control. * * Personal builds are usually initiated from one of the supported IDEs * via the Remote Run procedure. You can also upload a patch with changes * directly to the server... * * > HINT: If left undefined then both personal builds & * > non personal builds will be matched by this filter. * * see: https://www.jetbrains.com/help/teamcity/personal-build.html */ personal?: boolean; /** * Matches builds with any specified tag. */ tags?: string[]; /** * A list of branch patterns to match against. * * Defaults to `+:*`. */ branches?: string[]; /** * Matches only Active Branches. * * If left undefined then both active & inactive builds will be matched. * * > HINT: Yes this can be applied with custom branch patterns too. * * see: https://www.jetbrains.com/help/teamcity/working-with-feature-branches.html#Active+branches */ onlyActiveBranches?: boolean; /** * The filter can be applied per every matching branch, or to all builds in * matching branches as one set. This affects how many builds are preserved: * e.g. 30 last builds in each branch or 30 last builds among all branches. * * Defaults to `true`; */ perBranch?: boolean; }; /** * Defines a quantity or time range for matching builds to be preserved. * * > HINT: If left undefined then all matching builds will be preserved. */ range?: { type: | "lastNDays" | "lastNBuilds" | "NDaysSinceLastBuild" | "NDaysSinceLastSuccessfulBuild"; n: number; }; } export interface ProjectExtensionVersionedSettings extends ProjectExtensionBase { /** * TeamCity allows the two-way synchronization of the project settings with * the version control repository. Supported VCSs are Git, Mercurial, Perforce, * Subversion, and Azure DevOps Server (formerly TFS). * * You can store settings in the XML format or in the Kotlin language and * define settings programmatically using the Kotlin-based DSL. * * > HINT: Or in this case we will be keeping our settings in YAML/JSON * > or maybe even TypeScript files & then generating that into XML. * > The entire premise behind this very project. * * see: https://www.jetbrains.com/help/teamcity/2020.2/storing-project-settings-in-version-control.html */ type: "versionedSettings"; /** * Enable or disable synchronization. * * Defaults to `true`. */ enabled?: boolean; /** * The ID of a VcsRoot that will be used to synchronize settings with. * * > HINT: Yes you could have a totally different repo or branch that * > contained the `.teamcity` folder if so inclined... */ vscRootID: string; /** * There are two possible sources of build settings: * * (1) the current settings on the TeamCity server, that is the latest settings' * changes applied to the server (either made via the UI, or via a commit * to the .teamcity directory in the VCS root), and * * (2) the settings in the VCS on the revision selected for a build. * * Therefore, it is possible to start builds with settings different from those * currently defined in the build configuration. For projects with enabled * versioned settings, you can instruct TeamCity which settings to take when * build starts. * * The 3 modes: * * `ALWAYS_USE_CURRENT`: all builds use current project settings from the * TeamCity server. Settings' changes in branches, history, and personal * builds are ignored. Users cannot run a build with custom project settings. * * `PREFER_CURRENT`: a build uses the latest project settings from the TeamCity * server. Users can run a build with older project settings via the custom * build dialog. * * `PREFER_VCS`: builds in branches and history builds, which use settings * from VCS, load settings from the versioned settings' revision calculated * for the build. Users can change configuration settings in personal builds * from IDE or can run a build with project settings current on the TeamCity * server via the custom build dialog. * * Defaults to `PREFER_VCS`. * * see: https://www.jetbrains.com/help/teamcity/2020.2/storing-project-settings-in-version-control.html#StoringProjectSettingsinVersionControl-DefiningSettingstoApplytoBuilds */ mode?: "ALWAYS_USE_CURRENT" | "PREFER_CURRENT" | "PREFER_VCS"; /** * Show settings changes in builds. * * Defaults to `true`. */ showChanges?: boolean; /** * Store secure values (like passwords or API tokens) outside of VCS. * * Defaults to `true`. */ useCredentialsJSON?: boolean; /** * The format in which the Settings are stored. * * Obviously this tool doesn't support kotlin in anyway shape or form. * None the less for the sake of completeness here is the property. * * Defaults to `xml`. */ format?: "xml" | "kotlin" | { kotlin: true; /** * One of the advantages of the portable DSL script is that the script can * be used by more than one project on the same server or more than one * server (hence the name: portable). * * Defaults to `true`. * * see: https://www.jetbrains.com/help/teamcity/2020.2/kotlin-dsl.html#Sharing+Kotlin+DSL+Scripts * also: https://www.jetbrains.com/help/teamcity/2020.2/kotlin-dsl.html#Non-Portable+DSL */ generatePortableDSL?: boolean; /** * Since TeamCity 2019.2, you can customize the DSL generation behavior using * context parameters configured in the TeamCity UI. Context parameters are * specified as a part of the project versioned settings in the UI. * * > HINT: Context parameters are a Kotlin only thing, XML configuration * > can not & does not need to use context parameters. And since this * > project generates XML this is also essentially useless but here for * > the sake of completeness. * * see: https://www.jetbrains.com/help/teamcity/2020.2/kotlin-dsl.html#Using+Context+Parameters+in+DSL */ context?: Record<string, string>; }; } <file_sep>/ts-schema/schema/builders/project_extension.ts import * as x from "../xml/mod.ts"; import * as j from "../json/mod.ts"; export function projectExtensionBuilder( input: j.ProjectExtension, ): x.ProjectExtension { let param: x.Parameter[]; switch (input.type) { case "ReportTab": param = reportTab(input); break; case "OAuthProvider": param = oAuthProvider(input); break; case "IssueTracker": param = issueTracker(input); break; case "JetBrains.SharedResources": param = sharedResource(input); break; case "PackageRepository": param = packageRepository(input); break; case "keepRules": param = keepRule(input); break; case "versionedSettings": param = versionedSettings(input); break; default: throw new Error("unsupported project extension type"); } return { "@id": input.id, "@type": input.type, parameters: { param, }, }; } function reportTab(input: j.ProjectExtensionReportTab): x.Parameter[] { const output: x.Parameter[] = []; output.push({ "@name": "type", "@value": input.subType, }); output.push({ "@name": "title", "@value": input.title, }); output.push({ "@name": "startPage", "@value": input.startPage, }); switch (input.subType) { case "BuildReportTab": // Nothing to do here break; case "ProjectReportTab": projectReportTab(input).forEach((_) => output.push(_)); break; default: throw new Error("unsupported report tab sub type"); } return output; } function projectReportTab( input: j.ProjectExtensionProjectReportTab, ): x.Parameter[] { const output: x.Parameter[] = []; output.push({ "@name": "buildTypeId", "@value": input.buildTypeId, }); output.push({ "@name": "revisionRuleName", "@value": input.revisionRuleName, }); if (input.revisionRuleName === "buildNumber") { if (typeof input.revisionRuleValue === "undefined") { throw new Error( "revisionRuleName=buildNumber but no value for revisionRuleValue", ); } output.push({ "@name": "revisionRuleBuildNumber", "@value": input.revisionRuleValue, }); } if (input.revisionRuleName === "buildTag") { if (typeof input.revisionRuleValue === "undefined") { throw new Error( "revisionRuleName=buildTag but no value for revisionRuleValue", ); } output.push({ "@name": "revisionRuleBuildTag", "@value": input.revisionRuleValue, }); } return output; } function oAuthProvider(input: j.ProjectExtensionOAuthProvider): x.Parameter[] { const output: x.Parameter[] = []; output.push({ "@name": "displayName", "@value": input.displayName, }); switch (input.providerType) { case "AmazonDocker": amazonDockerOAuthProvider(input).forEach((_) => output.push(_)); break; case "BitBucketCloud": bitBucketCloudOAuthProvider(input).forEach((_) => output.push(_)); break; case "Docker": dockerOAuthProvider(input).forEach((_) => output.push(_)); break; case "Github": gitHubOAuthProvider(input).forEach((_) => output.push(_)); break; case "Gitlab": gitLabOAuthProvider(input).forEach((_) => output.push(_)); break; case "JetBrains Space": jetBrainsSpaceOAuthProvider(input).forEach((_) => output.push(_)); break; case "slackConnection": slackConnectionOAuthProvider(input).forEach((_) => output.push(_)); break; case "tfs": tfsOAuthProvider(input).forEach((_) => output.push(_)); break; default: throw new Error("unsupported oAuth providerType"); } return output; } function amazonDockerOAuthProvider( input: j.ProjectExtensionOAuthProviderAmazonDocker, ): x.Parameter[] { const output: x.Parameter[] = [{ "@name": "providerType", "@value": "AmazonDocker", }]; output.push({ "@name": "aws.region.name", "@value": input.region, }); output.push({ "@name": "registryId", "@value": input.registryID, }); output.push({ "@name": "aws.use.default.credential.provider.chain", "@value": input.auth ? "false" : "true", }); if (typeof input.auth !== "undefined") { output.push({ "@name": "aws.access.key.id", "@value": input.auth.accessKeyId, }); output.push({ "@name": "secure:aws.secret.access.key", "@value": input.auth.secretAccessKey, }); } output.push({ "@name": "aws.credentials.type", "@value": input.role ? "aws.temp.credentials" : "aws.access.keys", }); if (typeof input.role !== "undefined") { output.push({ "@name": "aws.iam.role.arn", "@value": input.role.arn, }); if (typeof input.role.externalID !== "undefined") { output.push({ "@name": "aws.external.id", "@value": input.role.externalID, }); } } return output; } function bitBucketCloudOAuthProvider( input: j.ProjectExtensionOAuthProviderBitBucketCloud, ): x.Parameter[] { const output: x.Parameter[] = [ { "@name": "providerType", "@value": "BitBucketCloud" }, ]; output.push({ "@name": "clientId", "@value": input.key }); output.push({ "@name": "secure:clientSecret", "@value": input.secret }); return output; } function dockerOAuthProvider( input: j.ProjectExtensionOAuthProviderDocker, ): x.Parameter[] { const output: x.Parameter[] = [ { "@name": "providerType", "@value": "Docker" }, ]; output.push({ "@name": "repositoryUrl", "@value": input.repositoryUrl }); if (typeof input.auth !== "undefined") { output.push({ "@name": "userName", "@value": input.auth.username }); output.push({ "@name": "secure:userPass", "@value": input.auth.password }); } return output; } function gitHubOAuthProvider( input: j.ProjectExtensionOAuthProviderGithub, ): x.Parameter[] { const output: x.Parameter[] = [ { "@name": "providerType", "@value": input.serverUrl ? "GHE" : "GitHub", }, ]; output.push({ "@name": "gitHubUrl", "@value": input.serverUrl ?? "https://github.com/", }); output.push({ "@name": "clientId", "@value": input.clientId, }); output.push({ "@name": "secure:clientSecret", "@value": input.secret, }); // NOTE: This parameter does not surface in the UI anywhere // & only appears for the github.com provider. if (typeof input.serverUrl === "undefined") { output.push({ "@name": "defaultTokenScope", "@value": "public_repo,repo,repo:status,write:repo_hook", }); } return output; } function gitLabOAuthProvider( input: j.ProjectExtensionOAuthProviderGitlab, ): x.Parameter[] { const output: x.Parameter[] = [ { "@name": "providerType", "@value": input.serverUrl ? "GitLabCEorEE" : "GitLabCom", }, ]; if (typeof input.serverUrl !== "undefined") { output.push({ "@name": "gitLabUrl", "@value": input.serverUrl }); } output.push({ "@name": "clientId", "@value": input.clientId, }); output.push({ "@name": "secure:clientSecret", "@value": input.secret, }); return output; } function jetBrainsSpaceOAuthProvider( input: j.ProjectExtensionOAuthProviderJetBrainsSpace, ): x.Parameter[] { const output: x.Parameter[] = [ { "@name": "providerType", "@value": "JetBrains Space" }, ]; output.push({ "@name": "spaceServerUrl", "@value": input.serverUrl }); output.push({ "@name": "spaceClientId", "@value": input.clientId }); output.push({ "@name": "secure:spaceClientSecret", "@value": input.secret }); return output; } function slackConnectionOAuthProvider( input: j.ProjectExtensionOAuthProviderSlackConnection, ): x.Parameter[] { const output: x.Parameter[] = [ { "@name": "providerType", "@value": "slackConnection" }, ]; output.push({ "@name": "clientId", "@value": input.clientId }); output.push({ "@name": "secure:token", "@value": input.botToken }); output.push({ "@name": "secure:clientSecret", "@value": input.clientSecret }); return output; } function tfsOAuthProvider( input: j.ProjectExtensionOAuthProviderTfs, ): x.Parameter[] { const output: x.Parameter[] = [ { "@name": "providerType", "@value": "tfs" }, { "@name": "type", "@value": "token" }, // NOTE: This seemed to be hard coded thing in the XML ]; output.push({ "@name": "serverUrl", "@value": input.serverUrl }); output.push({ "@name": "secure:accessToken", "@value": input.accessToken }); return output; } function issueTracker(input: j.ProjectExtensionIssueTracker): x.Parameter[] { const output: x.Parameter[] = []; output.push({ "@name": "name", "@value": input.displayName, }); output.push({ "@name": "type", "@value": input.providerType, }); switch (input.providerType) { case "BitBucketIssues": bitBucketIssueTracker(input).forEach((_) => output.push(_)); break; case "bugzilla": bugzillaIssueTracker(input).forEach((_) => output.push(_)); break; case "GithubIssues": githubIssueTracker(input).forEach((_) => output.push(_)); break; case "jira": jiraIssueTracker(input).forEach((_) => output.push(_)); break; case "tfs": tfsIssueTracker(input).forEach((_) => output.push(_)); break; case "youtrack": youtrackIssueTracker(input).forEach((_) => output.push(_)); break; default: throw new Error("unsupported issue tracker providerType"); } return output; } function bitBucketIssueTracker( input: j.ProjectExtensionIssueTrackerBitBucket, ): x.Parameter[] { const output: x.Parameter[] = []; output.push({ "@name": "repository", "@value": input.repositoryUrl, }); output.push({ "@name": "pattern", "@value": input.pattern ?? "#(\d+)", }); output.push({ "@name": "authType", "@value": input.auth ? "loginpassword" : "anonymous", }); if (typeof input.auth !== "undefined") { output.push({ "@name": "username", "@value": input.auth.username }); output.push({ "@name": "secure:password", "@value": input.auth.password }); } return output; } function bugzillaIssueTracker( input: j.ProjectExtensionIssueTrackerBugzilla, ): x.Parameter[] { const output: x.Parameter[] = []; output.push({ "@name": "host", "@value": input.serverUrl, }); output.push({ "@name": "pattern", "@value": input.pattern ?? "#(\d+)", }); output.push({ "@name": "authType", "@value": input.auth ? "loginpassword" : "anonymous", }); if (typeof input.auth !== "undefined") { output.push({ "@name": "username", "@value": input.auth.username }); output.push({ "@name": "secure:password", "@value": input.auth.password }); } return output; } function githubIssueTracker( input: j.ProjectExtensionIssueTrackerGithub, ): x.Parameter[] { const output: x.Parameter[] = []; output.push({ "@name": "repository", "@value": input.repositoryUrl, }); output.push({ "@name": "pattern", "@value": input.pattern ?? "#(\d+)", }); output.push({ "@name": "authType", "@value": input.auth ? (input.auth.token ? "accesstoken" : "loginpassword") : "anonymous", }); if (typeof input.auth !== "undefined") { if (typeof input.auth.token !== "undefined") { output.push({ "@name": "secure:accessToken", "@value": input.auth.token, }); } if ( typeof input.auth.username !== "undefined" && typeof input.auth.password !== "<PASSWORD>" ) { output.push({ "@name": "username", "@value": input.auth.username, }); output.push({ "@name": "secure:password", "@value": input.auth.password, }); } } return output; } function jiraIssueTracker( input: j.ProjectExtensionIssueTrackerJira, ): x.Parameter[] { const output: x.Parameter[] = []; output.push({ "@name": "host", "@value": input.serverUrl, }); const keys = input?.projectKeys ?? []; if (keys.length > 0) { output.push({ "@name": "autoSync", "@value": "false" }); output.push({ "@name": "idPrefix", "@value": keys.join(" ") }); } else { output.push({ "@name": "autoSync", "@value": "true" }); } output.push({ "@name": "username", "@value": input.username }); output.push({ "@name": "secure:password", "@value": input.password }); if (typeof input.oAuth !== "undefined") { output.push({ "@name": "jiraCloudClientId", "@value": input.oAuth.clientId, }); output.push({ "@name": "secure:jiraCloudServerSecret", "@value": input.oAuth.clientSecret, }); } return output; } function youtrackIssueTracker( input: j.ProjectExtensionIssueTrackerYoutrack, ): x.Parameter[] { const output: x.Parameter[] = []; output.push({ "@name": "host", "@value": input.serverUrl, }); const ids = input?.projectIDs ?? []; if (ids.length > 0) { output.push({ "@name": "autoSync", "@value": "false" }); output.push({ "@name": "idPrefix", "@value": ids.join(" ") }); } else { output.push({ "@name": "autoSync", "@value": "true" }); } output.push({ "@name": "authType", "@value": input.auth.token ? "accesstoken" : "loginpassword", }); if (typeof input.auth.token !== "undefined") { output.push({ "@name": "secure:accessToken", "@value": input.auth.token }); } if ( typeof input.auth.username !== "undefined" && typeof input.auth.password !== "undefined" ) { output.push({ "@name": "username", "@value": input.auth.username }); output.push({ "@name": "secure:password", "@value": input.auth.password }); } return output; } function tfsIssueTracker( input: j.ProjectExtensionIssueTrackerTfs, ): x.Parameter[] { const output: x.Parameter[] = []; output.push({ "@name": "host", "@value": input.serverUrl, }); output.push({ "@name": "pattern", "@value": input.pattern ?? "#(\d+)", }); if (typeof input.auth.token !== "undefined") { output.push({ "@name": "secure:password", "@value": input.auth.token }); } else { if ( typeof input.auth.username !== "undefined" && typeof input.auth.password !== "<PASSWORD>" ) { output.push({ "@name": "username", "@value": input.auth.username, }); output.push({ "@name": "secure:password", "@value": input.auth.password, }); } else { throw new Error( "tfs issue tracker expects a single token for auth or a user/pass pair", ); } } return output; } function sharedResource( input: j.ProjectExtensionSharedResource, ): x.Parameter[] { const output: x.Parameter[] = []; output.push({ "@name": "name", "@value": input.name, }); output.push({ "@name": "enabled", "@value": (input.enabled ?? true) ? "true" : "false", }); output.push({ "@name": "type", "@value": input.quota ? "quoted" : "custom", }); if (typeof input.quota !== "undefined") { output.push({ "@name": "quota", "@value": `${input.quota}`, }); } if (typeof input.values !== "undefined") { output.push({ "@name": "values", "#text": input.values.join("\n"), }); } return output; } function packageRepository( input: j.ProjectExtensionPackageRepository, ): x.Parameter[] { const output: x.Parameter[] = []; output.push({ "@name": "type", "@value": input.providerType, }); output.push({ "@name": "name", "@value": input.displayName, }); if (typeof input.description !== "undefined") { output.push({ "@name": "description", "@value": input.description, }); } switch (input.providerType) { case "nuget": nugetPackageRepository(input).forEach((_) => output.push(_)); break; default: throw new Error("unsupported package repository providerType"); } return output; } function nugetPackageRepository( input: j.ProjectExtensionPackageRepositoryNuget, ): x.Parameter[] { return [{ "@name": "description", "@value": (input.indexPackages ?? false) ? "true" : "false", }]; } function keepRule(input: j.ProjectExtensionKeepRules): x.Parameter[] { const output: x.Parameter[] = []; output.push({ "@name": "ruleDisabled", "@value": (input.enabled ?? true) ? "true" : "false", }); if (input.keep.length === 0 && input.keep[0] === "everything") { input.keep = ["artifacts", "logs", "statistics"]; } input.keep.forEach((v, i) => { i++; output.push({ "@name": `keepData.${i}.type`, "@value": v, }); if (v === "artifacts") { output.push({ "@name": `keepData.${i}.artifactPatterns`, "#text": (input?.artifactPatterns ?? ["+:**/*"]).join("\n"), }); } }); output.push({ "@name": "preserveArtifacts", "@value": (input?.keepDependantArtifacts ?? true) ? "true" : "false", }); let filterCount = 0; const status = input.filter?.status ?? "successful"; if (status !== "any") { filterCount++; output.push({ "@name": `filters.${filterCount}.type`, "@value": "buildStatus", }); output.push({ "@name": `filters.${filterCount}.status`, "@value": status, }); } if (typeof input.filter?.personal !== "undefined") { filterCount++; output.push({ "@name": `filters.${filterCount}.type`, "@value": "personalBuild", }); output.push({ "@name": `filters.${filterCount}.personal`, "@value": input.filter.personal ? "personal" : "not_personal", }); } if (typeof input.filter?.tags !== "undefined") { filterCount++; output.push({ "@name": `filters.${filterCount}.type`, "@value": "tags", }); output.push({ "@name": `filters.${filterCount}.tagsList`, "#text": input.filter.tags.join("\n"), }); } if (typeof input.filter?.branches !== "undefined") { filterCount++; output.push({ "@name": `filters.${filterCount}.type`, "@value": "branchPattern", }); output.push({ "@name": `filters.${filterCount}.pattern`, "#text": input.filter.branches.join("\n"), }); } if (typeof input.filter?.onlyActiveBranches !== "undefined") { filterCount++; output.push({ "@name": `filters.${filterCount}.type`, "@value": "branchActivity", }); output.push({ "@name": `filters.${filterCount}.activity`, "@value": input.filter.onlyActiveBranches ? "active" : "inactive", }); } output.push({ "@name": "limit.type", "@value": input.range?.type ?? "all", }); if (typeof input?.range !== "undefined") { output.push({ "@name": `limit.${ input.range.type === "lastNBuilds" ? "buildsCount" : "daysCount" }`, "@value": input.range.n.toString(), }); } if (input.filter?.perBranch === true) { output.push({ "@name": "partitions.1.type", "@value": "perBranch", }); } return output; } function versionedSettings( input: j.ProjectExtensionVersionedSettings, ): x.Parameter[] { const output: x.Parameter[] = []; output.push({ "@name": "enabled", "@value": (input.enabled ?? true) ? "true" : "false", }); output.push({ "@name": "rootId", "@value": input.vscRootID, }); output.push({ "@name": "buildSettings", "@value": input.mode ?? "PREFER_VCS", }); output.push({ "@name": "showChanges", "@value": (input.showChanges ?? true) ? "true" : "false", }); if (input.useCredentialsJSON ?? true) { output.push({ "@name": "credentialsStorageType", "@value": "credentialsJSON", }); } const format = input.format ?? "xml"; if (format === "kotlin") { output.push({ "@name": "format", "@value": "kotlin" }); output.push({ "@name": "useRelativeIds", "@value": "true" }); } else { if (typeof format === "object") { output.push({ "@name": "format", "@value": "kotlin", }); output.push({ "@name": "useRelativeIds", "@value": (format.generatePortableDSL ?? true) ? "true" : "false", }); for (const [k, v] of Object.entries(format.context ?? {})) { output.push({ "@name": `context.${k}`, "@value": v }); } } } return output; } <file_sep>/ts-schema/schema/rest-api/deno/models/Metric.ts /** * TeamCity REST API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * OpenAPI spec version: 2018.1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { MetricTags } from './MetricTags.ts'; import { MetricValues } from './MetricValues.ts'; import { HttpFile } from '../http/http.ts'; export class Metric { 'name'?: string; 'description'?: string; 'prometheusName'?: string; 'metricValues'?: MetricValues; 'metricTags'?: MetricTags; static readonly discriminator: string | undefined = undefined; static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [ { "name": "name", "baseName": "name", "type": "string", "format": "" }, { "name": "description", "baseName": "description", "type": "string", "format": "" }, { "name": "prometheusName", "baseName": "prometheusName", "type": "string", "format": "" }, { "name": "metricValues", "baseName": "metricValues", "type": "MetricValues", "format": "" }, { "name": "metricTags", "baseName": "metricTags", "type": "MetricTags", "format": "" } ]; static getAttributeTypeMap() { return Metric.attributeTypeMap; } public constructor() { } } <file_sep>/ts-schema/schema/builders/project_cleanup.ts import * as x from "../xml/mod.ts"; import * as j from "../json/mod.ts"; export function projectCleanupBuilder( input: j.ProjectCleanup, ): x.ProjectCleanup { const cleanup: x.ProjectCleanup = { options: { option: [{ "@name": "disableCleanupPolicies", "@value": (input.disableCleanupPolicies ?? false) ? "true" : "false", }], }, }; if ( typeof input.preventDependenciesArtifactsFromCleanup !== "undefined" ) { cleanup.options?.option.push({ "@name": "preventDependenciesArtifactsFromCleanup", "@value": input.preventDependenciesArtifactsFromCleanup ? "true" : "false", }); } if (Array.isArray(input.policies) && input.policies.length > 0) { cleanup.policy = []; for (const jPolicy of input.policies) { const xPolicy: x.ProjectCleanupPolicy = { "@type": "daysAndBuilds", "@cleanup-level": jPolicy.cleanupLevel, parameters: { param: [], }, }; if ( typeof jPolicy.keepDays === "undefined" && typeof jPolicy.keepBuilds === "undefined" ) { throw new Error( "project cleanup policy needs to define at least one of `keepDays` or `keepBuilds`", ); } if (typeof jPolicy.keepDays !== "undefined") { xPolicy.parameters.param.push({ "@name": "keepDays.count", "@value": jPolicy.keepDays.toString(), }); } if (typeof jPolicy.keepBuilds !== "undefined") { xPolicy.parameters.param.push({ "@name": "keepBuilds.count", "@value": jPolicy.keepBuilds.toString(), }); } if (jPolicy.cleanupLevel === "ARTIFACTS") { if (typeof jPolicy.patterns !== "undefined") { xPolicy.parameters.param.push({ "@name": "artifactPatterns", "#text": jPolicy.patterns.join("\n"), }); } } cleanup.policy.push(xPolicy); } } return cleanup; } <file_sep>/ts-schema/schema/rest-api/deno/apis/InvestigationApi.ts // TODO: better import syntax? import { BaseAPIRequestFactory, RequiredError } from './baseapi.ts'; import {Configuration} from '../configuration.ts'; import { RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http.ts'; import {ObjectSerializer} from '../models/ObjectSerializer.ts'; import {ApiException} from './exception.ts'; import {isCodeInRange} from '../util.ts'; import { Investigation } from '../models/Investigation.ts'; import { Investigations } from '../models/Investigations.ts'; /** * no description */ export class InvestigationApiRequestFactory extends BaseAPIRequestFactory { /** * Create a new investigation. * @param fields * @param body */ public async addInvestigation(fields?: string, body?: Investigation, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/investigations'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Investigation", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Create multiple new investigations. * @param fields * @param body */ public async addMultipleInvestigations(fields?: string, body?: Investigations, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/investigations/multiple'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Investigations", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Delete investigation matching the locator. * @param investigationLocator */ public async deleteInvestigation(investigationLocator: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'investigationLocator' is not null or undefined if (investigationLocator === null || investigationLocator === undefined) { throw new RequiredError('Required parameter investigationLocator was null or undefined when calling deleteInvestigation.'); } // Path Params const localVarPath = '/app/rest/investigations/{investigationLocator}' .replace('{' + 'investigationLocator' + '}', encodeURIComponent(String(investigationLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get all investigations. * @param locator * @param fields */ public async getAllInvestigations(locator?: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // Path Params const localVarPath = '/app/rest/investigations'; // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (locator !== undefined) { requestContext.setQueryParam("locator", ObjectSerializer.serialize(locator, "string", "")); } if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Get investigation matching the locator. * @param investigationLocator * @param fields */ public async getInvestigation(investigationLocator: string, fields?: string, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'investigationLocator' is not null or undefined if (investigationLocator === null || investigationLocator === undefined) { throw new RequiredError('Required parameter investigationLocator was null or undefined when calling getInvestigation.'); } // Path Params const localVarPath = '/app/rest/investigations/{investigationLocator}' .replace('{' + 'investigationLocator' + '}', encodeURIComponent(String(investigationLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } /** * Update investigation matching the locator. * @param investigationLocator * @param fields * @param body */ public async replaceInvestigation(investigationLocator: string, fields?: string, body?: Investigation, options?: Configuration): Promise<RequestContext> { let config = options || this.configuration; // verify required parameter 'investigationLocator' is not null or undefined if (investigationLocator === null || investigationLocator === undefined) { throw new RequiredError('Required parameter investigationLocator was null or undefined when calling replaceInvestigation.'); } // Path Params const localVarPath = '/app/rest/investigations/{investigationLocator}' .replace('{' + 'investigationLocator' + '}', encodeURIComponent(String(investigationLocator))); // Make Request Context const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params if (fields !== undefined) { requestContext.setQueryParam("fields", ObjectSerializer.serialize(fields, "string", "")); } // Header Params // Form Params // Body Params const contentType = ObjectSerializer.getPreferredMediaType([ "application/xml", "application/json" ]); requestContext.setHeaderParam("Content-Type", contentType); const serializedBody = ObjectSerializer.stringify( ObjectSerializer.serialize(body, "Investigation", ""), contentType ); requestContext.setBody(serializedBody); let authMethod = null; // Apply auth methods authMethod = config.authMethods["Authorization"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } return requestContext; } } export class InvestigationApiResponseProcessor { /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to addInvestigation * @throws ApiException if the response code was not in [200, 299] */ public async addInvestigation(response: ResponseContext): Promise<Investigation > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Investigation = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Investigation", "" ) as Investigation; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Investigation = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Investigation", "" ) as Investigation; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to addMultipleInvestigations * @throws ApiException if the response code was not in [200, 299] */ public async addMultipleInvestigations(response: ResponseContext): Promise<Investigations > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Investigations = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Investigations", "" ) as Investigations; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Investigations = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Investigations", "" ) as Investigations; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to deleteInvestigation * @throws ApiException if the response code was not in [200, 299] */ public async deleteInvestigation(response: ResponseContext): Promise< void> { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("0", response.httpStatusCode)) { throw new ApiException<string>(response.httpStatusCode, "successful operation"); } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { return; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getAllInvestigations * @throws ApiException if the response code was not in [200, 299] */ public async getAllInvestigations(response: ResponseContext): Promise<Investigations > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Investigations = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Investigations", "" ) as Investigations; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Investigations = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Investigations", "" ) as Investigations; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to getInvestigation * @throws ApiException if the response code was not in [200, 299] */ public async getInvestigation(response: ResponseContext): Promise<Investigation > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Investigation = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Investigation", "" ) as Investigation; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Investigation = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Investigation", "" ) as Investigation; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } /** * Unwraps the actual response sent by the server from the response context and deserializes the response content * to the expected objects * * @params response Response returned by the server for a request to replaceInvestigation * @throws ApiException if the response code was not in [200, 299] */ public async replaceInvestigation(response: ResponseContext): Promise<Investigation > { const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); if (isCodeInRange("200", response.httpStatusCode)) { const body: Investigation = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Investigation", "" ) as Investigation; return body; } // Work around for missing responses in specification, e.g. for petstore.yaml if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { const body: Investigation = ObjectSerializer.deserialize( ObjectSerializer.parse(await response.body.text(), contentType), "Investigation", "" ) as Investigation; return body; } let body = response.body || ""; throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\""); } }
74778d23a46e56f53c475b0dc1e2c440cc2509d4
[ "Markdown", "TypeScript" ]
76
TypeScript
brad-jones/teamcity-playground
7f714a76629970785c19bd7fc83dfb4b7ad0eca2
8b5812856952888aa653c1d35934df0bdbc4b859
refs/heads/master
<file_sep>#!/usr/bin/python import ephem from datetime import datetime from datetime import timedelta import time import os day_shots = 30 dawn_shots = 7 twilight_shots = 7 snapshot_script = "/root/Timelapse/snapshot.py" # cabin location and elevation cabin = ephem.Observer() cabin.lat = '42.380238' cabin.lon = '-71.116130' cabin.elevation = 56 # set time to midnight today cabin.date = datetime.now().replace(hour=0, minute=1, second=0, microsecond=0) # determine interval for snapshot_interval photos per day sun = ephem.Sun() sunrise = ephem.localtime(cabin.next_rising(sun)) sunset = ephem.localtime(cabin.next_setting(sun)) sunnoon = ephem.localtime(cabin.next_transit(sun)) cabin.horizon = '-10' dawn = ephem.localtime(cabin.next_rising(sun, use_center=True)) twilight = ephem.localtime(cabin.next_setting(sun, use_center=True)) # clear out all previous at jobs os.system('atrm $(atq | cut -f1) > /dev/null 2>&1') # schedule at jobs for each snapshot # schedule dawn shots dawn_interval = (sunrise - dawn) / dawn_shots time = dawn for shot in range(dawn_shots): if (time > datetime.now()): os.system("echo " + snapshot_script + " | at -t " + time.strftime("%y%m%d%H%M")) time += dawn_interval # schedule normal shots day_interval = (sunset-sunrise) / day_shots time = sunrise for shot in range(day_shots): if (time > datetime.now()): os.system("echo " + snapshot_script + " | at -t " + time.strftime("%y%m%d%H%M")) time += day_interval # schedule twilight shots twilight_interval = (twilight - sunset) / twilight_shots time = sunset for shot in range(twilight_shots): if (time > datetime.now()): os.system("echo " + snapshot_script + " | at -t " + time.strftime("%y%m%d%H%M")) time += twilight_interval <file_sep>#!/usr/local/bin/python3 import ephem from datetime import datetime from datetime import timedelta from PIL import Image import time import os #timelapse_directory = '/Users/dlaporte/Dropbox/Apps/Cabin Timelapse' timelapse_directory = '/Users/dlaporte/Desktop/test' timelapse_prefix = 'cabin-timelapse-' #timelapse_suffix = 'tiff' timelapse_suffix = 'jpg' timelapse_start = '01/17/19' timelapse_end = '01/17/19' start = datetime.strptime(timelapse_start, '%m/%d/%y') end = datetime.strptime(timelapse_end, '%m/%d/%y') days = {} day = start count = 0 daily_total = None target_width = None target_height = None while (day <= end): files = [] for file in os.listdir(timelapse_directory): if file.endswith(timelapse_suffix): if file.startswith(timelapse_prefix + day.strftime('%Y-%m-%d') + '-'): files.append(file) im = Image.open(timelapse_directory + '/' + file) if target_height is None: target_height = im.size[1] target_width = im.size[0] else: if target_height != im.size[1]: exit(day.strftime('%Y-%m-%d') + ': mis-matched resolution (' + str(len(im.size[0])) + ')') if daily_total is None: daily_total = len(files) else: if daily_total != len(files): exit(day.strftime('%Y-%m-%d') + ': mis-matched days (' + str(len(files)) + ')') files.sort() days[count] = files day += timedelta(days=1) count += 1 row_height = int(target_height / daily_total) column_width = int(target_width / count) print("there are " + str(count) + " days") print("there are " + str(daily_total) + " images per day") print("row height " + str(row_height)) print("column width " + str(column_width)) x = 0 y = 0 for row in days: x += row_height for column in days[row]: y += column_width print(x) print(y) print(column) exit() <file_sep>#!/usr/bin/python from datetime import datetime import time import os file_prefix = "cabin-timelapse-" pktriggercord_cli = "/usr/bin/pktriggercord-cli --model K-5 --file_format dng -m AV -i 100 -a 11 --ae_metering=" save_location = "/root/cabin-timelapse" dropbox_uploader = "/root/bin/dropbox_uploader.sh" # dropbox location is relative to "/Apps/Cabin Timelapse" dropbox_subdir = datetime.now().strftime("%Y-%m-%d") dropbox_location = dropbox_subdir # create directory for snapshots os.system(dropbox_uploader + " mkdir " + dropbox_location) filename = save_location + "/" + file_prefix + datetime.now().strftime('%Y-%m-%d-%H-%M-%S') + ".dng" os.system(pktriggercord_cli + " > " + filename) os.system(dropbox_uploader + " upload " + filename + " " + dropbox_location + " && rm -f " + filename) <file_sep>#!/usr/local/bin/python3 # join the output of this script into rows using: # # montage 101*.jpg -mode concatenate -tile 44 cabin1.png # montage 102*.jpg -mode concatenate -tile 44 cabin2.png # etc... # # and then join those using: # # montage cabin*.png -mode concatenate -tile 1 cabin.png # import ephem from datetime import datetime from datetime import timedelta #from PIL import Image from wand.image import Image import time import os #timelapse_directory = '/Users/dlaporte/Dropbox/Apps/Cabin Timelapse' timelapse_directory = '/Users/dlaporte/Dropbox/test' timelapse_prefix = 'cabin-timelapse-' #timelapse_suffix = 'tiff' timelapse_suffix = 'jpg' final_directory = '/Users/dlaporte/Dropbox/Code/Timelapse/test-byrow' timelapse_start = '01/17/19' timelapse_end = '01/20/19' start = datetime.strptime(timelapse_start, '%m/%d/%y') end = datetime.strptime(timelapse_end, '%m/%d/%y') days = {} day = start count = 0 daily_total = None target_width = None target_height = None while (day <= end): images = [] for file in sorted(os.listdir(timelapse_directory)): if file.endswith(timelapse_suffix): print(file) if file.startswith(timelapse_prefix + day.strftime('%Y-%m-%d') + '-'): with Image(filename=timelapse_directory + '/' + file) as img: if target_height is None: target_height = img.height target_width = img.width else: if target_height != img.height: exit(day.strftime('%Y-%m-%d') + ': mis-matched resolution (' + str(img.height) + ')') images.append(img.clone()) if daily_total is None: daily_total = len(images) else: if daily_total != len(images): exit(day.strftime('%Y-%m-%d') + ': mis-matched days (' + str(len(images)) + ')') days[count] = images day += timedelta(days=1) count += 1 row_height = int(target_height / count) column_width = int(target_width / daily_total) print("there are " + str(count) + " days") print("there are " + str(daily_total) + " images per day") print("row height " + str(row_height)) print("column width " + str(column_width)) x = 0 y = 0 day_num = 100 img_num = 100 for day in days: day_num += 1 for img in days[day]: img.rotate(1.7) img.crop(x, y, width=column_width, height=row_height) file = str(day_num) + '_' + str(img_num) + '.jpg' img.save(filename=final_directory + '/' + file) img_num += 1 x += column_width y += row_height x = 0 exit()
bf773a6a24aced3b261bb90f06338ab3b0d25f4b
[ "Python" ]
4
Python
dlaporte/Timelapse
eff8c08ce4c623823a3417b5ed380cada54260da
d426e7f357f4b18216bac595c0d03de322e441b3
refs/heads/master
<repo_name>poakapx/Reacting_to_day_time_1<file_sep>/GetTime2.js function GetTime() { var date = new Date(); var hour = date.getHours(); if (hour >= 5 && hour < 12) { greeting = "Доброе утро!"; } else if (hour >= 12 && hour < 18) { greeting = "Добрый день!"; } else if (hour >= 18 && hour < 24) { greeting = "Добрый вечер!"; } else if (hour >= 24 && hour < 5) { greeting = "Доброй ночи!"; } return greeting; } GetTime()
92a7a638f2a9db2f92f42f0041fd98ba313e33d2
[ "JavaScript" ]
1
JavaScript
poakapx/Reacting_to_day_time_1
7aafb132b1cccc0ddee6a30bfb3b4b34255685af
d2feac86e7cdb6bbbecebe7626cb8f835777ffbc
refs/heads/master
<repo_name>jlstack/WebScraping<file_sep>/RegisterSnipe.py __author__ = 'lukestack' from selenium import webdriver import time from datetime import datetime, timedelta USERNAME = '' PASSWORD = '' REGISTERPIN = '' SEMESTER = 'Fall 2015' CRNS = ["11156", "10387", "16238", "10383", "10384", "10658", "13435"] # max 10 CRNS REGISTERDATE = datetime(2015, 3, 30, 1, 40) # datetime('Year', 'Month', 'Date', 'Hour(0-23)', 'Minute') present = datetime.now() while present.date() < REGISTERDATE.date(): time.sleep(60 * 15) # sleeps for 15 minutes present = datetime.now() while present.time() < REGISTERDATE.time(): time.sleep(1) # sleeps for 1 second before checking again present = datetime.now() try: path_to_chromedriver = '/Users/lukestack/Downloads/chromedriver' # change path as needed browser = webdriver.Chrome(executable_path = path_to_chromedriver) url = 'https://portal4.appstate.edu/cp/home/displaylogin' browser.get(url) browser.find_element_by_xpath("//*[@id='leftcol']/fieldset/form[1]/span/input").send_keys(USERNAME) browser.find_element_by_xpath("//*[@id='leftcol']/fieldset/form[2]/span/input[1]").send_keys(PASSWORD) browser.find_element_by_xpath("//*[@id='leftcol']/fieldset/p[1]/input[1]").click() browser.find_element_by_xpath("//*[@id='tabs_tda']/tbody/tr/td[2]/div/a").click() iframe = browser.find_elements_by_tag_name('iframe')[0] browser.switch_to.frame(iframe) browser.find_elements_by_xpath("//td[contains(@class, 'taboff')]")[0].click() browser.find_element_by_xpath("//a[contains(text(),'Registration')]").click() browser.find_element_by_xpath("//a[contains(text(),'Add/Drop')]").click() browser.find_element_by_id("term_id").click() browser.find_element_by_xpath("//*[@id='term_id']/option[contains(text(),'" + SEMESTER + "')]").click() browser.find_element_by_xpath("//input").click() browser.find_element_by_xpath("//input").send_keys(REGISTERPIN) browser.find_element_by_xpath("//input[contains(@type, 'submit')]").click() crn_inputs = browser.find_elements_by_xpath("//input[contains(@id, 'crn_id')]") print crn_inputs for i in range(len(CRNS)): crn_inputs[i].send_keys(CRNS[i]) browser.find_element_by_xpath("/html/body/div[3]/form/input[contains(@value, 'Submit Changes')]").click() time.sleep(5) browser.close() except: pass<file_sep>/README.md # WebScraping For database project and for fun. You will need [chromedriver] for this. [chromedriver]: http://chromedriver.storage.googleapis.com/index.html?path=2.15/ <file_sep>/CourseScrape.py __author__ = 'lukestack' from selenium import webdriver import time USERNAME = '' PASSWORD = '' REGISTERPIN = '' try: path_to_chromedriver = '/Users/lukestack/Downloads/chromedriver' # change path as needed browser = webdriver.Chrome(executable_path = path_to_chromedriver) url = 'https://portal4.appstate.edu/cp/home/displaylogin' browser.get(url) browser.find_element_by_xpath("//*[@id='leftcol']/fieldset/form[1]/span/input").send_keys(USERNAME) browser.find_element_by_xpath("//*[@id='leftcol']/fieldset/form[2]/span/input[1]").send_keys(PASSWORD) browser.find_element_by_xpath("//*[@id='leftcol']/fieldset/p[1]/input[1]").click() browser.find_element_by_xpath("//*[@id='tabs_tda']/tbody/tr/td[2]/div/a").click() iframe = browser.find_elements_by_tag_name('iframe')[0] browser.switch_to.frame(iframe) browser.find_elements_by_xpath("//td[contains(@class, 'taboff')]")[0].click() browser.find_element_by_xpath("//a[contains(text(),'Registration')]").click() browser.find_element_by_xpath("//a[contains(text(),'Add/Drop')]").click() browser.find_element_by_id("term_id").click() browser.find_element_by_xpath("//*[@id='term_id']/option[1]").click() browser.find_element_by_xpath("//input").click() browser.find_element_by_xpath("//input").send_keys(REGISTERPIN) browser.find_element_by_xpath("//input[contains(@type, 'submit')]").click() """ for result in results: print result.text """ except: pass time.sleep(5) browser.close()
045de593bea386d61492286cdd228ee9d6e3c3d2
[ "Markdown", "Python" ]
3
Python
jlstack/WebScraping
bed7ddbea49cc08c1fc4d6c382f9406f870d9fdb
63f3254f0be78740c5b0e171d1426a05d670b868
refs/heads/master
<repo_name>evibobevy/revolve<file_sep>/lib/mobileMenu.js $(document).ready(function(){ $("#show").click(function(){ $("ul").show(); }); $("#hide").click(function(){ $("ul").hide(); $(".mobileMenu").hide(); $("#nav").show(); }); }); var vid = document.getElementById("myVideo"); function enableControls() { vid.controls = true; vid.load(); }
8fcf71a542e76490b32ec8e07a801cabc11cb4a3
[ "JavaScript" ]
1
JavaScript
evibobevy/revolve
116e0564109593ac52e1938967d330be98ca1251
78715d575fc64ca9e127daeb6d95a0a226a58a3d
refs/heads/main
<repo_name>chinmaygit/tasty_api<file_sep>/pages/api/request.ts import axios, {Method} from 'axios'; export type Headers = {contentType: string}; export type Request = { url: string; method: Method; requestName: string; headers: Headers; body: object; }; export type Response = {status: number; headers: Headers; body: object}; export default async (req, res) => { let request: Request = req.body; // console.log('REQUEST', request); try { let response = await axios({ method: request.method, url: request.url, headers: request.headers, data: request.body, }); let jsonResponse: Response = { status: response.status, body: response.data, headers: response.headers, }; res.json(jsonResponse); } catch (error) { let jsonResponse: Response = { status: error.response.status, body: {}, headers: error.response.headers, }; res.json(jsonResponse); } };
331a262e13626820b3c75781c1385f169672d8df
[ "TypeScript" ]
1
TypeScript
chinmaygit/tasty_api
43505cbdc1ed4e119a260b3652f448c2055dc378
898a2bf4b586193c0d5b0df7da79fdc394e55283
refs/heads/master
<repo_name>guilhermemntt/fastify-mongo-boilerplate<file_sep>/src/services/fastify.service.ts import fastifyJwt from "fastify-jwt"; import fastify from "fastify"; import fastifyCors from "fastify-cors"; import multer from "fastify-multer"; import { Server, IncomingMessage, ServerResponse } from "http"; import routes from "../routes/index.route"; import { AddressInfo } from "net"; import { Service } from "./index.service"; import moment from "moment"; interface BlacklistedToken { jti: string; exp: number; iat: number; } interface FastifyService extends Service { jwtSign: (payload: any) => any; jwtBlacklistToken: (token: string) => void; jwtGetToken: (request: fastify.FastifyRequest) => string; } let server: fastify.FastifyInstance<Server, IncomingMessage, ServerResponse>; let blacklist: BlacklistedToken[] = []; let jwtidCounter: number = 0; const fastifyService: FastifyService = { init: async () => { try { server = fastify({}); if (process.env.SERVER_JWT === "true") server.register(fastifyJwt, { secret: process.env.SERVER_JWT_SECRET, trusted: (request, decodedToken) => blacklist.some( blacklistedToken => blacklistedToken.jti == decodedToken.jti ) ? false : (decodedToken as any).payload }); server.register(multer.contentParser); server.register(fastifyCors); routes.forEach(route => { server.route(route); }); await server.listen(Number(process.env.SERVER_PORT), "0.0.0.0"); console.log( `[FASTIFY] Fastify service initialized on port ${ (server.server.address() as AddressInfo).port }.` ); } catch (error) { console.log("[FASTIFY] Error during fastify service initialization"); throw error; } }, jwtSign: _payload => { try { if (!server) throw new Error("[FASTIFY] Fastify service not initialized yet"); if (process.env.SERVER_JWT !== "true") throw new Error("[FASTIFY] Fastify JWT flag is not setted"); console.log("[FASTIFY] Generating fastify JWT sign"); const payload = JSON.parse(JSON.stringify(_payload)); jwtidCounter = jwtidCounter + 1; return server.jwt.sign( { payload }, { expiresIn: Number(process.env.SERVER_JWT_TIMEOUT), jwtid: jwtidCounter + "" } ); } catch (error) { console.log("[FASTIFY] Error during fastify JWT sign"); throw error; } }, jwtGetToken: request => { try { if (!server) throw new Error("[FASTIFY] Fastify service not initialized yet"); if (process.env.SERVER_JWT !== "true") throw new Error("[FASTIFY] Fastify JWT flag is not setted"); if ( !request.headers.authorization || request.headers.authorization.split(" ")[0] !== "Bearer" ) throw new Error("[FASTIFY] Fastify JWT token not provided"); return request.headers.authorization.split(" ")[1]; } catch (error) { console.log("[FASTIFY] Error getting JWT token"); throw error; } }, jwtBlacklistToken: token => { try { if (!server) throw new Error("[FASTIFY] Fastify service not initialized yet"); if (process.env.SERVER_JWT !== "true") throw new Error("[FASTIFY] Fastify JWT flag is not setted"); while ( blacklist.length && moment().diff("1970-01-01 00:00:00Z", "seconds") > blacklist[0].exp ) { console.log( `[FASTIFY] Removing from blacklist timed out JWT with id ${blacklist[0].jti}` ); blacklist.shift(); } const { jti, exp, iat } = server.jwt.decode(token); console.log(`[FASTIFY] Adding JWT ${token} with id ${jti} to blacklist`); blacklist.push({ jti, exp, iat }); } catch (error) { console.log("[FASTIFY] Error blacklisting fastify JWT token"); throw error; } } }; export { fastifyService }; <file_sep>/src/services/redis.service.ts import redis, { RedisClient } from "redis"; import { Service } from "./index.service"; interface RedisService extends Service { get: (key: string) => Promise<string>; set: (key: string, value: string) => Promise<string>; } let client: RedisClient; const redisService: RedisService = { init: async () => { try { client = redis.createClient({ host: process.env.REDIS_HOST, port: Number(process.env.REDIS_PORT) }); console.log("[REDIS] Redis service initialized"); } catch (error) { console.log("[REDIS] Error during Redis service initialization"); throw error; } }, get: async (key: string): Promise<string> => { try { if (!client) throw new Error("[REDIS] Redis service not initialized yet"); return new Promise((resolve, reject) => { client.get(key, (error, reply) => { if (error) reject(error); resolve(reply); console.log("[REDIS] Getting data"); }); }); } catch (error) { console.log("[REDIS] Error getting data"); throw error; } }, set: async (key: string, value: string): Promise<string> => { try { if (!client) throw new Error("[REDIS] Redis service not initialized yet"); return new Promise((resolve, reject) => { client.set(key, value, "EX", 3600, (error, reply) => { if (error) reject(error); console.log("[REDIS] Setting data"); resolve(reply); }); }); } catch (error) { console.log("[REDIS] Error setting data"); throw error; } } }; export { redisService }; <file_sep>/src/hooks/authenticate.hook.ts import fastify from "fastify"; const authenticationHook: fastify.FastifyMiddleware = async ( request, reply ) => { try { if (process.env.SERVER_JWT === "true") await request.jwtVerify(); } catch (error) { console.log("[FASTIFY] Unauthorized error with JWT validation \n", error); reply.code(401).send(); } }; export { authenticationHook }; <file_sep>/src/types/index.type.ts import { ObjectID, Collection, Db } from "mongodb"; export interface Address { complement?: string; number: number; street: string; neighborhood: string; city: string; state: string; country: string; zipCode: string; users: ObjectID[]; } export interface User { cpf: string; name: string; sex: "M" | "F"; birth: Date; } export interface Collections { addresses: Collection<Address>; users: Collection<User>; } export function getTypesCollections(mongoClient: Db): Collections { return { users: mongoClient.collection<User>("users"), addresses: mongoClient.collection<Address>("addresses") }; } <file_sep>/src/routes/user.route.ts import { userController } from "../controllers/user.controller"; import fastify from "fastify"; type Routes = fastify.RouteOptions[]; const userRoutes: Routes = [ { method: "GET", url: "/user", handler: userController.get }, { method: "GET", url: "/user/:_id", handler: userController.find }, { method: "POST", url: "/user", handler: userController.add }, { method: "PUT", url: "/user", handler: userController.update }, { method: "DELETE", url: "/user/:_id", handler: userController.delete } ]; export { userRoutes }; <file_sep>/src/index.ts import dotenv from "dotenv"; import { fastifyService } from "./services/fastify.service"; import { Service } from "./services/index.service"; import { mongoService } from "./services/mongo.service"; import { oneSignalService } from "./services/onesignal.service"; import { firebaseService } from "./services/firebase.service"; import { emailerService } from "./services/emailer.service"; import { redisService } from "./services/redis.service"; import { awsService } from "./services/aws.service"; dotenv.config({ path: "../.env" }); const services: Service[] = [mongoService, fastifyService]; (async () => { try { for (const service of services) { await service.init(); } console.log("Server initialized."); //PUT ADITIONAL CODE HERE. } catch (error) { console.log(error); process.exit(1); } })(); <file_sep>/src/services/firebase.service.ts import firebase from "firebase-admin"; import { Service } from "./index.service"; interface FirebaseService extends Service { sendToTopic: (title, body, topic) => Promise<void>; } let locked = true; const firebaseService: FirebaseService = { init: async () => { try { const serviceAccount = require(process.env .GOOGLE_APPLICATION_CREDENTIALS); firebase.initializeApp({ credential: firebase.credential.cert(serviceAccount), databaseURL: `https://${serviceAccount.project_id}.firebaseio.com` }); locked = false; console.log("[FIREBASE] Firebase service initialized"); } catch (error) { console.log("[FIREBASE] Error during Firebase service initialization"); throw error; } }, sendToTopic: async (title, body, topic) => { try { if (locked) throw new Error("[FIREBASE] Firebase service not initialized yet"); const response = await firebase .messaging() .sendToTopic(`/topics/${topic}`, { notification: { title, body, content_available: "true" }, data: { title, body, content_available: "true" } }); console.log(`[FIREBASE] Notification successfully sended`); console.log( `[FIREBASE] Sended message data: ${JSON.stringify(response)}` ); } catch (error) { console.log("[FIREBASE] Error sending notification"); throw error; } } }; export { firebaseService }; <file_sep>/README.md # fastify-mongo-boilerplate Deploy a Node.js server very quickly with Fastify and MongoDB. ## File structure - :file_folder: dist/ - :file_folder: node_modules/ - :open_file_folder: src/ - :file_folder: controllers/ - :open_file_folder: types/ - :page_facing_up: index.type.ts - :open_file_folder: routes/ - :page_facing_up: index.route.ts - :open_file_folder: services/ - :page_facing_up: index.service.ts - :page_facing_up: aws.service.ts - :page_facing_up: emailer.service.ts - :page_facing_up: fastify.service.ts - :page_facing_up: firebase.service.ts - :page_facing_up: redis.service.ts - :page_facing_up: mongo.service.ts - :page_facing_up: index.ts - :page_facing_up: example.env - :page_facing_up: package.json - :page_facing_up: postman.json - :page_facing_up: README.md - :page_facing_up: tsconfig.json - :page_facing_up: yarn.lock ## Run First of all, install [**typescript**](https://www.npmjs.com/package/typescript) and [**nodemon**](https://www.npmjs.com/package/nodemon) gobally with [**yarn**](https://yarnpkg.com/lang/en/). 1. At the repository root, download the dependencies with **yarn**: ``` yarn ``` 2. Rename the file *example.env* to *.env*, and edit the environment variables. Some of them are required when using Fastify and TypeORM as ```JWT_SECRET```,```SERVER_PORT``` and ```MONGO_``` ones. 3. Make sure you're running your database service. Create your collection types in *types/index.type.ts*. 4. Add aditional services at *index.ts* services array, if necessary. 5. Add aditional **.route.ts* files into *index.route.ts* routes array, if necessary. 6. Run **tsc -w** at project root directory. 7. Additionally, run **nodemon** at dist/ directory. 8. Edit src/ TypeScript code with automatic reload! <file_sep>/src/services/aws.service.ts import fs from "fs"; import AWS from "aws-sdk"; import path from "path"; import uuid from "uuid"; import { Service } from "./index.service"; import { File } from "fastify-multer/lib/interfaces"; interface AWSService extends Service { uploadFile: ( file: File & { uuid?: string }, extension: string, bucketPath?: string ) => Promise<string>; deleteFile: ( fileUUID: string, extension: string, bucketPath?: string ) => Promise<void>; deleteFiles: ( fileUUIDArray: string[], extension: string, bucketPath?: string ) => Promise<void>; } let s3: AWS.S3; const root = path.dirname((require.main as NodeModule).filename); const awsService: AWSService = { init: async () => { try { s3 = new AWS.S3({ accessKeyId: process.env.AWS_KEYID, secretAccessKey: process.env.AWS_SECRETKEY } as any); console.log("[AWS] AWS service initialized"); } catch (error) { console.log("[AWS] Error during AWS service initialization"); throw error; } }, uploadFile: async (file, extension, bucketPath = "") => { if (!s3) throw new Error("[AWS] AWS service not initialized yet"); if (!file.uuid) console.log(`[AWS] File ${file.filename} has no uuid, creating uuid`); const _uuid = file.uuid || uuid.v4(); console.log(`[AWS] Assigned uuid ${_uuid} to file ${file.filename}`); try { const _file = fs.readFileSync(`${root}/${file.path}`); const params = { Bucket: process.env.AWS_BUCKET, Key: `${bucketPath}${_uuid}.${extension}`, Body: _file, ACL: "public-read", ContentType: file.mimetype || "application/octet-stream" }; return await new Promise((resolve, reject) => { s3.upload( params, (s3Err: Error, data: AWS.S3.ManagedUpload.SendData) => { try { if (s3Err) throw s3Err; console.log( `[AWS] File uploaded successfully at ${data.Location}` ); `${root}/${file.path}`; fs.unlinkSync(`${root}/${file.path}`); console.log( `[AWS] Deleting file ${root}/${file.path} from temp directory` ); resolve(_uuid); } catch (error) { reject(error); } } ); }); } catch (error) { console.log("[AWS] Error during file upload"); console.log( `[AWS] Deleting file ${root}/${file.path} from temp directory` ); fs.unlinkSync(`${root}/${file.path}`); throw error; } }, deleteFile: (fileUUID, extension, bucketPath = "") => { try { if (!s3) throw new Error("[AWS] AWS service not initialized yet"); return new Promise((resolve, reject) => { s3.deleteObject( { Key: `${bucketPath}${fileUUID}.${extension}`, Bucket: process.env.AWS_BUCKET as string }, (s3Err: Error, data: AWS.S3.DeleteObjectOutput) => { if (s3Err) { reject(s3Err); } console.log(`[AWS] File ${fileUUID} deleted succefully.`); resolve; } ); }); } catch (error) { console.log("[AWS] Error during file deletion"); throw error; } }, deleteFiles: async (fileUUIDArray, extension, bucketPath = "") => { try { if (!s3) throw new Error("[AWS] AWS service not initialized yet"); await Promise.all( fileUUIDArray.map(fileUUID => this.deleteFile(fileUUID, extension, bucketPath) ) ); console.log("[AWS] All files deleted succefully."); } catch (error) { console.log("[AWS] Error during files deletion"); throw error; } } }; export { awsService }; <file_sep>/src/services/onesignal.service.ts import fetch from "node-fetch"; import { Service } from "./index.service"; interface OneSignalService extends Service { sendNotification: ( userId: number | string, notif: { title: string; body: string } ) => Promise<any>; } let locked = true; const oneSignalService: OneSignalService = { init: async () => { locked = false; console.log("[ONESIGNAL] OneSignal service initialized"); }, sendNotification: async ( userId: number | string, notif: { title: string; body: string } ) => { try { if (locked) throw new Error("[ONESIGNAL] OneSginal service not initialized yet"); const response = await fetch( `https://onesignal.com/api/v1/notifications`, { method: "POST", headers: { "Content-Type": "application/json; charset=utf-8", Authorization: `Basic ${process.env.ONESIGNAL_REST_API_KEY}` }, body: JSON.stringify({ app_id: process.env.ONESIGNAL_APP_ID, contents: { en: notif.body }, headings: { en: notif.title }, include_external_user_ids: [userId.toString()] }) } ); const responseJSON = await response.json(); if (response.status != 200) throw new Error(responseJSON); console.log(`[ONESIGNAL] Notification successfully sended`); console.log( `[ONESIGNAL] Sended message data: ${JSON.stringify(responseJSON)}` ); return responseJSON; } catch (error) { console.log(`[ONESIGNAL] Error sending notification`); throw error; } } }; export { oneSignalService }; <file_sep>/src/routes/index.route.ts import fastify from "fastify"; import { userRoutes } from "./user.route"; type Routes = fastify.RouteOptions[]; const routes: Routes = [...userRoutes]; export default routes; <file_sep>/src/controllers/user.controller.ts import { mongoService } from "../services/mongo.service"; import fastify from "fastify"; import { User } from "../types/index.type"; import { ObjectID } from "mongodb"; interface userController { get: fastify.RequestHandler; find: fastify.RequestHandler; add: fastify.RequestHandler; update: fastify.RequestHandler; delete: fastify.RequestHandler; } let userController: userController = { get: async (request, reply) => { try { const users: User[] = await mongoService .getCollections() .users.find() .toArray(); reply.status(200).send(users); } catch (error) { console.log(error); reply.status(500).send(); } }, find: async (request, reply) => { try { const { _id } = request.params; const user: User = await mongoService .getCollections() .users.findOne({ _id: new ObjectID(_id) }); reply.status(200).send(user); } catch (error) { console.log(error); reply.status(500).send(); } }, add: async (request, reply) => { try { const user = await mongoService .getCollections() .users.insertOne(request.body); reply.status(200).send(user); } catch (error) { console.log(error); reply.status(500).send(); } }, update: async (request, reply) => { try { const { _id } = request.body; const user = await mongoService.getCollections().users.updateOne( { _id: new ObjectID(_id) }, { $set: request.body } ); reply.status(200).send(user); } catch (error) { console.log(error); reply.status(500).send(); } }, delete: async (request, reply) => { try { const { _id } = request.params; const user = await mongoService .getCollections() .users.deleteOne({ _id: new ObjectID(_id) }); reply.status(200).send(user); } catch (error) { console.log(error); reply.status(500).send(); } } }; export { userController }; <file_sep>/src/services/emailer.service.ts import nodemailer, { Transporter } from "nodemailer"; import { Service } from "./index.service"; import fs from "fs"; interface EmailerService extends Service { sendMail: ( subject: string, to: string, text?: string, htmlFilePath?: string, from?: string ) => Promise<void>; } let transporter: Transporter; const emailerService: EmailerService = { init: async () => { try { transporter = nodemailer.createTransport({ service: process.env.EMAIL_SERVICE, auth: { user: process.env.EMAIL_USER, pass: process.env.EMAIL_PASSWORD } } as any); console.log("[EMAILER] Emailer service initialized."); } catch (error) { console.log("[EMAILER] Error during emailer service initialization"); throw error; } }, sendMail: async (subject, to, text, htmlFilePath, from) => { try { if (!transporter) throw new Error("[EMAILER] Emailer service not initialized yet."); const mailOptions = { from: from || process.env.EMAIL_ADDRESS, to, subject, text, html: htmlFilePath && fs.readFileSync(htmlFilePath) }; return await new Promise((resolve, reject) => { transporter.sendMail(mailOptions, (error, info) => { if (!error) { console.log(`[EMAILER] Email sent to ${to}: ${info.response}`); resolve(); } else { reject(error); } }); }); } catch (error) { console.log(`[EMAILER] Error sending email to ${to}`); throw error; } } }; export { emailerService }; <file_sep>/src/services/index.service.ts export interface Service { init: () => Promise<void>; } <file_sep>/src/services/mongo.service.ts import { MongoClient, Db } from "mongodb"; import { Service } from "./index.service"; import { Collections, getTypesCollections } from "../types/index.type"; interface MongoService extends Service { getCollections: () => Collections; } let collections: Collections; const mongoService: MongoService = { init: async () => { try { const url = `mongodb://${process.env.MONGO_HOST}:${process.env.MONGO_PORT}`; MongoClient.connect(url, (error, client) => { if (error) throw error; const mongoClient = client.db(process.env.MONGO_NAME); collections = getTypesCollections(mongoClient); }); console.log("[MONGODB] MongoDB service initialized"); } catch (error) { console.log("[MONGODB] Error during MongoDB service initialization"); throw error; } }, getCollections: () => { try { if (!collections) throw new Error("[MONGODB] MongoDB service not initialized yet"); return collections; } catch (error) { console.log(`[MONGODB] Error returning MongoDB collections`); throw error; } } }; export { mongoService };
2c9a6f7efffa7a00d80ab4cccbe8d66fa1cc5c00
[ "Markdown", "TypeScript" ]
15
TypeScript
guilhermemntt/fastify-mongo-boilerplate
d4524b023430c7c25ff429ce38e560d6f81a6dd8
ebe01018f5ebed2236563c3cbb5120bdc8666548
refs/heads/master
<file_sep>#include <bits/stdc++.h> using namespace std; #define NUM_SCORE 13 #define MAX_ROUND 12 #define NUM_DICE 5 int player[2][NUM_SCORE]; const string scoreType[NUM_SCORE] = { "Aces ", "Deuces ", "Threes ", "Fours ", "Fives ", "Sixes ", "Bonus(>=65) ", "Choice ", "4 of a Kind ", "Full House ", "Small Straight", "Large Straight", "Yacht " }; void startingYacht(); void printScore(int round); void playingYacht(); void turn(int player); void victory(); int main(){ ios_base::sync_with_stdio(false); while(-1){ startingYacht(); playingYacht(); victory(); } } void startingYacht(){ for(int i = 0; i < NUM_SCORE; i++){ player[0][i] = 0; player[1][i] = 0; } int menu; cout << "==================" << endl << " YACHT DICE " << endl << "==================" << endl; while(-1){ cout << "1. 시작하기" << endl << "2. 종료하기" << endl << "나의 대답 : "; cin >> menu; if(menu == 1) break; else if(menu == 2) exit(0); else cout << endl << "!!! 올바르지 않은 숫자입니다. 다시 골라주세요. !!!" << endl << endl; } } void playingYacht(){ for(int round = 1; round <= MAX_ROUND; round++){ printScore(round); turn(1); printScore(-1); turn(2); } } void printScore(int round){ if(round != -1){ cout << endl << "==================" << endl << " " << round << " ROUND " << endl << "==================" << endl; } cout << "****************** ******************" << endl << "**** PLAYER 1 **** **** PLAYER 2 ****" << endl << "****************** ******************" << endl; int p1 = 0, p2 = 0; for(int i = 0; i < NUM_SCORE; i++){ if(i == 6){ if(p1 >= 63) player[0][i] = 35; if(p2 >= 63) player[1][i] = 35; if(p1 >= 10) cout << "SumOfCategorie" << " :" << p1 << " "; else cout << "SumOfCategorie" << " : " << p1 << " "; if(p2 >= 10) cout << "SumOfCategorie" << " :" << p2 << endl; else cout << "SumOfCategorie" << " : " << p2 << endl; } p1 += player[0][i]; p2 += player[1][i]; if(player[0][i] >= 10) cout << scoreType[i] << " :" << player[0][i] << " "; else cout << scoreType[i] << " : " << player[0][i] << " "; if(player[1][i] >= 10) cout << scoreType[i] << " :" << player[1][i] << endl; else cout << scoreType[i] << " : " << player[1][i] << endl; } cout << "플레이어 1 총합 : " << p1 << " 플레이어 2 총합 : " << p2 << endl; } void turn(int P){ cout << endl << "------------------" << endl << " PLAYER " << P << " TURN " << endl << "------------------" << endl; int reroll = 3; vector<int> dice(NUM_DICE, 0); vector<bool> pinned(NUM_DICE, false); while(-1){ cout << endl << "1. 리롤하기 (" << reroll << "회 남았습니다.)" << endl << "2. 점수 결정하기" << endl << "플레이어 " << P << "의 선택 : "; int menu; cin >> menu; if((reroll == 0 && menu == 1) || (reroll == 3 && menu == 2) || (menu != 1 && menu != 2 )){ cout << endl << "!!! 올바르지 않은 숫자입니다. 다시 골라주세요. !!!" << endl << endl; continue; } if(menu == 1){ reroll--; srand((unsigned int)time(NULL)); cout << endl << "++++++++++++++++++" << endl << "pinned : "; for(int i = 0; i < NUM_DICE; i++){ if(!pinned[i]){ dice[i] = rand() % 6 + 1; cout << " "; } else cout << "V "; } cout << endl << "주사위 : "; for(int i = 0; i < NUM_DICE; i++) cout << dice[i] << " "; cout << endl << "++++++++++++++++++" << endl << "주사위 고정하기 (범위 : 1 ~ 5) (주사위 고정이 끝나면 -1를 입력하세요)" << endl; int t; while(-1){ cout << "플레이어 " << P << "의 선택 : "; cin >> t; if(t >= 1 && t <= 5){ pinned[t - 1] = !pinned[t - 1]; cout << endl << "++++++++++++++++++" << endl; cout << "pinned : "; for(int i = 0; i < NUM_DICE; i++){ if(!pinned[i]) cout << " "; else cout << "V "; } cout << endl << "주사위 : "; for(int i = 0; i < NUM_DICE; i++) cout << dice[i] << " "; cout << endl; cout << "++++++++++++++++++" << endl; } else if(t == -1) break; else cout << endl << "!!! 올바르지 않은 숫자입니다. 다시 골라주세요. !!!" << endl << endl; } } else if(menu == 2){ vector<bool> canAddress(NUM_SCORE, true); vector<int> cntArr(7, 0); int sum = 0; for(int i = 0; i < NUM_SCORE; i++){ if(i == 6) canAddress[i] = false; if(player[P - 1][i] != 0) canAddress[i] = false; } for(int i = 0; i < NUM_DICE; i++){ cntArr[dice[i]]++; sum += dice[i]; } while(-1){ cout << endl << "점수를 어디에 적용할까요?" << endl; for(int i = 0; i < NUM_SCORE; i++){ if(canAddress[i]) cout << i + 1 << " : " << scoreType[i] << endl; } cout << "플레이어 " << P << "의 선택 : "; int t; cin >> t; if(t <= 0 || t >= 14 || !canAddress[t - 1]) cout << endl << "!!! 올바르지 않은 숫자입니다. 다시 골라주세요. !!!" << endl << endl; else{ // score calc if(t >= 1 && t <= 6){ player[P - 1][t - 1] = cntArr[t] * t; } else if(t == 8){ player[P - 1][t - 1] = sum; } else if(t == 9){ bool flag = false; for(auto c : cntArr){ if(c >= 4) flag = true; } if(flag) player[P - 1][t - 1] = sum; else player[P - 1][t - 1] = 0; } else if(t == 10){ bool flag_2 = false, flag_3 = false; for(auto c : cntArr){ if(c == 3) flag_3 = true; if(c == 2) flag_2 = true; } if(flag_2 && flag_3) player[P - 1][t - 1] = sum; else player[P - 1][t - 1] = 0; } else if(t == 11){ int cnt = 0; for(int i = 1; i <= 6; i++){ if(cnt == 4) break; if(cntArr[i] >= 1) cnt++; else cnt = 0; } if(cnt >= 4) player[P - 1][t - 1] = 15; else player[P - 1][t - 1] = 0; } else if(t == 12){ int cnt = 0; for(int i = 1; i <= 6; i++){ if(cnt == 5) break; if(cntArr[i] >= 1) cnt++; else cnt = 0; } if(cnt >= 5) player[P - 1][t - 1] = 30; else player[P - 1][t - 1] = 0; } else if(t == 13){ bool flag = false; for(auto c : cntArr){ if(c == 5) flag = true; } if(flag) player[P - 1][t - 1] = 50; else player[P - 1][t - 1] = 0; } break; } } break; } } } void victory(){ int p1 = 0, p2 = 0; for(int i = 0; i < NUM_SCORE; i++){ if(i == 6){ if(p1 >= 63) player[0][i] = 35; if(p2 >= 63) player[1][i] = 35; } p1 += player[0][i]; p2 += player[1][i]; } cout << "플레이어 1 총합 : " << p1 << " 플레이어 2 총합 : " << p2 << endl; if(p1 > p2) cout << "플레이어 1 우승!" << endl << "플레이어 1 우승!" << endl << "플레이어 1 우승!" << endl; else if(p1 == p2) cout << "무승부!" << endl << "무승부!" << endl << "무승부!" << endl; else cout << "플레이어 2 우승!" << endl << "플레이어 2 우승!" << endl << "플레이어 2 우승!" << endl; } <file_sep># yacht-dice - [yacht-dice 게임에 대한 정보](https://store.nintendo.co.kr/70010000029718) - [yacht-dice rule](https://namu.wiki/w/%EC%95%BC%EC%B0%8C) - 승우아빠 님과 철면수심 님의 방송을 보고 C++로 구현해보고 싶은 마음이 들어 구현했습니다.
b9e9b1aa906171e0c58081c3683771f8f398d2c5
[ "Markdown", "C++" ]
2
C++
96glory/yacht-dice
5e23eadedfc31502a5040dff92851927391181a4
09b3098bc9d7604cfb23d7fd7afe0683a231be1e
refs/heads/master
<file_sep>#!/bin/bash # Compiles src.md into README.md and push to master gitex src.md README.md -i _gitex git add img/ _gitex/ *.md if [ "$#" -eq 1 ]; then git commit git push origin master fi <file_sep># Asynchronous family ## Asynchronous Advantage Actor-Critic (A3C) Asynchronous Methods for Deep Reinforcement Learning. [[arxiv '16]](http://arxiv.org/abs/1602.01783) - RMSProp with shared stats (i.e. moving average of squared gradient), updated asynchronously and without locking. - One can explicitly use different exploration policies in each actor-learner to maximize this diversity. Thus, we do not use a replay memory and rely on parallel actors employing different exploration policies to perform the stabilizing role undertaken by experience replay in the DQN training algorithm. ### Vanilla A3C ![A3C](img/A3C.png =75%x75%) ### Async baselines One-step Q ![Async_Q](img/Async_1Q.png =50%x50%) N-step Q ![Async_Q](img/Async_nQ.png =75%x75%) ## Actor-Critic with Experience Replay (ACER) Sample Efficient Actor-Critic with Experience Replay. [[arxiv '16]](http://arxiv.org/abs/1611.01224) ![ACER_1](img/ACER_1.png =50%x50%) ![ACER_2](img/ACER_2.png =75%x75%) # DQN family ## Original Human-level Control through Deep Reinforcement Learning. [[Nature '14]](http://www.nature.com/nature/journal/v518/n7540/abs/nature14236.html) ## Double DQN Deep Reinforcement Learning with Double Q-learning. [[arxiv '15]](http://arxiv.org/abs/1509.06461) The max operator in standard Q-learning and DQN uses the same values both to select and to evaluate an action. This makes it more likely to select overestimated values, resulting in overoptimistic value estimates. To prevent this, we can decouple the selection from the evaluation. - Vanilla target: $R_{t+1} + \gamma \max_a Q(S_{t+1}, a; \theta)$ - Double DQN target: $R_{t+1} + \gamma Q(S_{t+1}, argmax_a\,Q(S_{t+1}, a; \theta); \theta')$ ![Double_DQN](img/Double_DQN.png =75%x75%) ## Dueling DQN Dueling Network Architectures for Deep Reinforcement Learning. [[arxiv '15]](http://arxiv.org/abs/1511.06581) - Dueling network represents two separate estimators: one for the state value function and one for the state-dependent action advantage function. - To address the issue of identifiability, we can force the advantage function estimator to have zero advantage at the chosen action. This can be achieved by subtracting either $max(\mathcal{A})$ or average $\bar{\mathcal{A}}$ from the action value. The latter is better in practice. Formula for the decomposition of Q-value: $$Q(s,a;\theta,\alpha,\beta) \\ = V(s;\theta,\beta) + \\ (A(s,a;\theta,\alpha) - \frac{1}{|\mathcal{A}|} \sum_{a'} A(s,a';\theta,\alpha))$$ - $\theta$ is shared parameter for the network. - $\alpha$ parameterizes output stream for advantage function $\mathcal{A}$. - $\beta$ parameterizes output stream for value function _V_. ## Prioritized Experience Replay Prioritized Experience Replay. [[arxiv '15]](http://arxiv.org/abs/1511.05952) We define the probability of sampling transition _i_ as $$ P(i) = \frac{p_i^\alpha}{\sum_k p_k^\alpha} $$ where $p_i$ is the priority of each transition and exponent $\alpha$ determines how much prioritization is used. $\alpha = 0$ corresponds to uniform random sampling. Two variants of priority assignment: 1. Proportional to TD error: $p_i = |\delta_i| + \epsilon$ where the positive $\epsilon$ ensures transitions with zero TD error will also be revisited. 2. Rank-based: $p_i = \frac{1}{rank(i)}$ sorted with respect to TD error $|\delta_i|$. More robust. Tricks must be used to efficiently compute the above two priorities (i.e. does not increase by _O(N)_). Importance-sampling weights $w_i$ must be used to correct the bias introduced by prioritized replay: $$ w_i = (\frac{1}{N} \frac{1}{P(i)})^{-\beta} $$ and linearly anneal $\beta$ from $\beta_0$ at the beginning of training to 1. ![PER](img/prioritized_experience_replay.png =75%x75%) ## Normalized Advantage Function (NAF) Continuous Deep Q-Learning with Model-based Acceleration. [[arxiv '16]](http://arxiv.org/abs/1603.00748) Formulate advantage function such that the maximum is trivial to find. $$ Q(x, u) = V(x) + A(x, u) $$ $$ A(x, u) = -\frac{1}{2} (u - \mu(x))^T P(x) (u - \mu(x)) $$ All the above functions _Q_, _V_, _A_, _P_ are parameterized. $P(x)$ is a state-dependent, positive-definite square matrix where $P(x; \theta^P) = L(x; \theta^P) L(x; \theta^P)^T$ and $L(x)$ is a lower-triangular matrix whose entries come from a linear output layer of a neural network, with the diagonal terms exponentiated. The action that maximizes _Q_ is always $\mu(x; \theta^\mu)$. ![NAF](img/NAF.png =50%x50%) ## Bootstrapped DQN Deep Exploration via Bootstrapped DQN. [[arxiv '16]](http://arxiv.org/abs/1602.04621) ![bootstrapped](img/Bootstrapped_DQN.png =75%x75%) <file_sep># Asynchronous family ## Asynchronous Advantage Actor-Critic (A3C) Asynchronous Methods for Deep Reinforcement Learning. [[arxiv '16]](http://arxiv.org/abs/1602.01783) - RMSProp with shared stats (i.e. moving average of squared gradient), updated asynchronously and without locking. - One can explicitly use different exploration policies in each actor-learner to maximize this diversity. Thus, we do not use a replay memory and rely on parallel actors employing different exploration policies to perform the stabilizing role undertaken by experience replay in the DQN training algorithm. ### Vanilla A3C <img src="img/A3C.png" alt="A3C" width="75%" height="75%" /> ### Async baselines One-step Q <img src="img/Async_1Q.png" alt="Async_Q" width="50%" height="50%" /> N-step Q <img src="img/Async_nQ.png" alt="Async_Q" width="75%" height="75%" /> ## Actor-Critic with Experience Replay (ACER) Sample Efficient Actor-Critic with Experience Replay. [[arxiv '16]](http://arxiv.org/abs/1611.01224) <img src="img/ACER_1.png" alt="ACER_1" width="50%" height="50%" /> <img src="img/ACER_2.png" alt="ACER_2" width="75%" height="75%" /> # DQN family ## Original Human-level Control through Deep Reinforcement Learning. [[Nature '14]](http://www.nature.com/nature/journal/v518/n7540/abs/nature14236.html) ## Double DQN Deep Reinforcement Learning with Double Q-learning. [[arxiv '15]](http://arxiv.org/abs/1509.06461) The max operator in standard Q-learning and DQN uses the same values both to select and to evaluate an action. This makes it more likely to select overestimated values, resulting in overoptimistic value estimates. To prevent this, we can decouple the selection from the evaluation. - Vanilla target: <img src="_gitex/tex_0803ba81f2fab1c4a4aeb8a3544d95f9.png" alt="R_{t+1} + \gamma \max_a Q(S_{t+1}, a; \theta)" height="18" /> - Double DQN target: <img src="_gitex/tex_0da09c3ac1d534875b4247dcae32f765.png" alt="R_{t+1} + \gamma Q(S_{t+1}, argmax_a\,Q(S_{t+1}, a; \theta); \theta')" height="18" /> <img src="img/Double_DQN.png" alt="Double_DQN" width="75%" height="75%" /> ## Dueling DQN Dueling Network Architectures for Deep Reinforcement Learning. [[arxiv '15]](http://arxiv.org/abs/1511.06581) - Dueling network represents two separate estimators: one for the state value function and one for the state-dependent action advantage function. - To address the issue of identifiability, we can force the advantage function estimator to have zero advantage at the chosen action. This can be achieved by subtracting either <img src="_gitex/tex_92c1ebec698f9d396676d7f62b6f7860.png" alt="max(\mathcal{A})" height="18" /> or average <img src="_gitex/tex_8d9f4d43dd58fa69dc5dc5381763f2ac.png" alt="\bar{\mathcal{A}}" height="17" /> from the action value. The latter is better in practice. Formula for the decomposition of Q-value: <img src="_gitex/tex_1ba08fcb2d7574a32d4d6920c8cc0dfc.png" alt="Q(s,a;\theta,\alpha,\beta) \\ = V(s;\theta,\beta) + \\ (A(s,a;\theta,\alpha) - \frac{1}{|\mathcal{A}|} \sum_{a'} A(s,a';\theta,\alpha))" height="51" /> - <img src="_gitex/tex_25328cdc28b5efd70b1ff684010b3840.png" alt="\theta" height="13" /> is shared parameter for the network. - <img src="_gitex/tex_29ad4d780791e8f06fe23e545dfac699.png" alt="\alpha" height="8" /> parameterizes output stream for advantage function <img src="_gitex/tex_c8d5b1b8f8e1e08a507931cb4f91f3fe.png" alt="\mathcal{A}" height="14" />. - <img src="_gitex/tex_d2df1bc88fc935017f9ba3c2c41ab83f.png" alt="\beta" height="17" /> parameterizes output stream for value function _V_. ## Prioritized Experience Replay Prioritized Experience Replay. [[arxiv '15]](http://arxiv.org/abs/1511.05952) We define the probability of sampling transition _i_ as <img src="_gitex/tex_cb83dfd89b099f0d25ddaca52c9b327e.png" alt=" P(i) = \frac{p_i^\alpha}{\sum_k p_k^\alpha} " height="46" /> where <img src="_gitex/tex_4720f569b0fa044352808cf82e3c2f86.png" alt="p_i" height="12" /> is the priority of each transition and exponent <img src="_gitex/tex_29ad4d780791e8f06fe23e545dfac699.png" alt="\alpha" height="8" /> determines how much prioritization is used. <img src="_gitex/tex_f79b1ab1598eb601f44b86439921bb4d.png" alt="\alpha = 0" height="13" /> corresponds to uniform random sampling. Two variants of priority assignment: 1. Proportional to TD error: <img src="_gitex/tex_e5c41506f6c8286523d67b8647d29d31.png" alt="p_i = |\delta_i| + \epsilon" height="18" /> where the positive <img src="_gitex/tex_f076b7374665d1831da46eafb6602870.png" alt="\epsilon" height="8" /> ensures transitions with zero TD error will also be revisited. 2. Rank-based: <img src="_gitex/tex_f0472e41053485b0c7f427f61b55baeb.png" alt="p_i = \frac{1}{rank(i)}" height="24" /> sorted with respect to TD error <img src="_gitex/tex_098ab9a04b9aa3f66987b3b7a9354c1d.png" alt="|\delta_i|" height="18" />. More robust. Tricks must be used to efficiently compute the above two priorities (i.e. does not increase by _O(N)_). Importance-sampling weights <img src="_gitex/tex_6056c278287cd1c46b7db79f99659cbe.png" alt="w_i" height="11" /> must be used to correct the bias introduced by prioritized replay: <img src="_gitex/tex_c4ed4de1c117074c3eb02e3860af75bb.png" alt=" w_i = (\frac{1}{N} \frac{1}{P(i)})^{-\beta} " height="45" /> and linearly anneal <img src="_gitex/tex_d2df1bc88fc935017f9ba3c2c41ab83f.png" alt="\beta" height="17" /> from <img src="_gitex/tex_ef1502bd58b2f08354ddcecced8cb5e1.png" alt="\beta_0" height="17" /> at the beginning of training to 1. <img src="img/prioritized_experience_replay.png" alt="PER" width="75%" height="75%" /> ## Normalized Advantage Function (NAF) Continuous Deep Q-Learning with Model-based Acceleration. [[arxiv '16]](http://arxiv.org/abs/1603.00748) Formulate advantage function such that the maximum is trivial to find. <img src="_gitex/tex_557c74798ca1f2f20733395d43371372.png" alt=" Q(x, u) = V(x) + A(x, u) " height="20" /> <img src="_gitex/tex_f41274d2916204258d89a3a7e301f4b5.png" alt=" A(x, u) = -\frac{1}{2} (u - \mu(x))^T P(x) (u - \mu(x)) " height="40" /> All the above functions _Q_, _V_, _A_, _P_ are parameterized. <img src="_gitex/tex_8a19c1b51bd0f75541d7d3a804117416.png" alt="P(x)" height="18" /> is a state-dependent, positive-definite square matrix where <img src="_gitex/tex_8bcf3b7eaf6701a4b07f7d953f811695.png" alt="P(x; \theta^P) = L(x; \theta^P) L(x; \theta^P)^T" height="19" /> and <img src="_gitex/tex_ced227530642eba53120e69161d078a8.png" alt="L(x)" height="18" /> is a lower-triangular matrix whose entries come from a linear output layer of a neural network, with the diagonal terms exponentiated. The action that maximizes _Q_ is always <img src="_gitex/tex_9f881e772f191cb912a960ca78aa0aa8.png" alt="\mu(x; \theta^\mu)" height="18" />. <img src="img/NAF.png" alt="NAF" width="50%" height="50%" /> ## Bootstrapped DQN Deep Exploration via Bootstrapped DQN. [[arxiv '16]](http://arxiv.org/abs/1602.04621) <img src="img/Bootstrapped_DQN.png" alt="bootstrapped" width="75%" height="75%" />
c0b2399b679de51a58a0afc8787ffdf52eeb07ca
[ "Markdown", "Shell" ]
3
Shell
RongRG/RL-Pseudocode
aa3273c62343a4de12436c9294de1e221917d309
14029b14509ea2bfbf6116dc85ce29022a4005ee
refs/heads/master
<file_sep><?php class Cuisine { private $style; private $id; function __construct($style, $id = null) { $this->style = $style; $this->id = $id; } function getId() { return $this->id; } function setCuisine($new_style) { $this->style = (string) $new_style; } function getCuisine() { return $this->style; } function save() { //insert into the table cuisine and add to the column name $executed = $GLOBALS['DB']->exec("INSERT INTO cuisine (name) VALUES ('{$this->getCuisine()}');"); if ($executed) { $this->id = $GLOBALS['DB']->lastInsertId(); return true; } else { return false; } } static function find($search_id) { $found_cuisine = null; $returned_cuisines = $GLOBALS['DB']->prepare("SELECT * FROM cuisine WHERE id = :id"); $returned_cuisines->bindParam(':id', $search_id, PDO::PARAM_STR); $returned_cuisines->execute(); foreach($returned_cuisines as $cuisine) { // style is our property up above //name is from our table $style = $cuisine['name']; $id = $cuisine['id']; if ($id == $search_id) { $found_cuisine = new Cuisine($style, $id); } } return $found_cuisine; } function getRestaurant() { $restaurants = Array(); $returned_restaurants = $GLOBALS['DB']->query("SELECT * FROM restaurants WHERE cuisine_id = {$this->getId()};"); foreach($returned_restaurants as $restaurant) { $name = $restaurant['restaurant_name']; $address = $restaurant['address']; $hours = $restaurant['hours']; $cost = $restaurant['cost']; $cuisine_id = $restaurant['cuisine_id']; $id = $restaurant['id']; $new_restaurant = new Restaurant($name, $address, $hours, $cost, $cuisine_id, $id); array_push($restaurants, $new_restaurant); } return $restaurants; } //There maybe a bad smell in this function too static function getAll() { $returned_cuisines = $GLOBALS['DB']->query("SELECT * FROM cuisine;"); $cuisines = array(); foreach($returned_cuisines as $cuisine) { $style = $cuisine['name']; $id = $cuisine['id']; $new_cuisine = new Cuisine($style, $id); array_push($cuisines, $new_cuisine); } return $cuisines; } // $style-name above is from the name in the table static function deleteAll() { //There maube an err on what is called in the delete from $executed = $GLOBALS['DB']->exec("DELETE FROM cuisine;"); if ($executed) { return true; } else { return false; } } } ?> <file_sep><?php /** * @backupGlobals disabled * @backupStaticAttributes disabled */ require_once "src/Restaurant.php"; require_once "src/Cuisine.php"; $server = 'mysql:host=localhost:8889;dbname=food_test'; $username = 'root'; $password = '<PASSWORD>'; $DB = new PDO($server, $username, $password); class RestaurantTest extends PHPUnit_Framework_TestCase { protected function tearDown() { Restaurant::deleteAll(); Cuisine::deleteAll(); } // function testSave() // { // $cuisine = "turds"; // $test_cuisine = new Cuisine($cuisine); // $executed = $test_cuisine->save(); // // $name = "<NAME>: eat my shorts"; // $address = "333 NE 33rd Ave"; // $hours = "12pm-10pm"; // $cost = "super expensive"; // $test_restaurant_name = new Restaurant($name, $address, $hours, $cost, $cuisine_id); // // $executed = $test_restaurant_name->save(); // // // // $this->assertTrue($executed, "Task not successfully saved to database"); // } function testSave() { $cuisine = "turds"; $test_cuisine = new Cuisine($cuisine); $test_cuisine->save(); $name = "<NAME>: eat my shorts"; $address = "333 NE 33rd Ave"; $hours = "12pm-10pm"; $cost = "super expensive"; $cuisine_id = $test_cuisine->getId(); $test_restaurant_name = new Restaurant($name, $address, $hours, $cost, $cuisine_id); $executed = $test_restaurant_name->save(); $this->assertTrue($executed, "Task not successfully saved to database"); } function testGetName() { $cuisine = "Pok Pok"; $test_cuisine = new Cuisine($cuisine); $test_cuisine->save(); $cuisine_id = $test_cuisine->getId(); $name = "<NAME>: eat my shorts"; $address = "333 NE 33rd Ave"; $hours = "12pm-10pm"; $cost = "super expensive"; $test_restaurant_name = new Restaurant($name, $address, $hours, $cost, $cuisine_id); $test_restaurant_name->save(); $result = $test_restaurant_name->getName(); $this->assertEquals($name, $result); } function testSetName() { //Arrange $cuisine = "pho jasmine"; $test_cuisine = new Cuisine($cuisine); $test_cuisine->save(); $cuisine_id = $test_cuisine->getId(); $name = "<NAME>: eat my shorts"; $address = "333 NE 33rd Ave"; $hours = "12pm-10pm"; $cost = "super expensive"; $test_restaurant_name = new Restaurant($name, $address, $hours, $cost, $cuisine_id); $test_restaurant_name->save(); $test_restaurant_name->setName("Boogah"); $result = $test_restaurant_name->getName(); //Assert $this->assertEquals("Boogah", $result); } function testDeleteAll() { $cuisine = "pho jasmine"; $test_cuisine = new Cuisine($cuisine); $test_cuisine->save(); $cuisine_id = $test_cuisine->getId(); $name = "<NAME>: eat my shorts"; $address = "333 NE 33rd Ave"; $hours = "12pm-10pm"; $cost = "super expensive"; $test_restaurant_name = new Restaurant($name, $address, $hours, $cost, $cuisine_id); $test_restaurant_name->save(); $name_2 = "<NAME>: eat my shorts"; $address = "333 NE 33rd Ave"; $hours = "12pm-10pm"; $cost = "super expensive"; $test_restaurant_name_2 = new Restaurant($name_2, $address, $hours, $cost, $cuisine_id); $test_restaurant_name_2->save(); Restaurant::deleteAll(); $result = Restaurant::getAll(); $this->assertEquals([], $result); } } ?> <file_sep>table name: Cuisine fields: name (varchar(255) ALTER TABLE cuisine ADD id serial PRIMARY KEY; <file_sep><?php require_once __DIR__."/../vendor/autoload.php"; require_once __DIR__."/../src/Cuisine.php"; require_once __DIR__."/../src/Restaurant.php"; $server = 'mysql:host=localhost:8889;dbname=food'; $username = 'root'; $password = '<PASSWORD>'; $DB = new PDO($server, $username, $password); use Symfony\Component\Debug\Debug; Debug::enable(); $app = new Silex\Application(); $app['debug'] = true; use Symfony\Component\HttpFoundation\Request; Request::enableHttpMethodParameterOverride(); $app->register(new Silex\Provider\TwigServiceProvider(), array( 'twig.path' => __DIR__.'/../views' )); $app->get("/", function() use($app) { return $app['twig']->render('index.html.twig', array(Cuisine::getAll())); }); // $app->get("/", function() use($app) { // return $app['twig']->render('index.html.twig', array(Restaurant::getAll())); // }); $app->post("/", function() use ($app) { $cuisine = $_POST['cuisine']; $new_cuisine = new Cuisine($cuisine); // var_dump($cuisine); $new_cuisine->save(); return $app['twig']->render('add_restaurant.html.twig', array('cuisines' => Cuisine::getAll())); }); $app->post("/add_restaurant", function() use ($app) { $restaurant = $_POST['name']; var_dump($name); $address = $_POST['address']; var_dump($address); $hours = $_POST['hours']; $cost = $_POST['cost']; $cuisine_id = $_POST['cuisine_id']; $restaurant = new Restaurant($name, $address, $hours, $cost, $cuisine_id); $restaurant->save(); var_dump($restaurant); return $app['twig']->render('add_restaurant.html.twig', array('restaurants' =>Restaurant::getAll())); }); $app->get("/add_restaurants/{id}", function($id) use ($app) { $new_cuisine = Cuisine::find($id); return $app['twig']->render('add_restaurants.html.twig', array('cuisines' => $new_cuisine, 'restaurants' => $restaurant->getTasks())); }); $app->post("/delete_cuisine", function() use ($app) { Cuisine::deleteAll(); return $app['twig']->render('delete_cuisine.html.twig'); }); $app->post("/delete_restaurants", function() use ($app) { Restaurant::deleteAll(); return $app['twig']->render('delete_restaurants.html.twig'); }); return $app; ?> <file_sep><?php /** * @backupGlobals disabled * @backupStaticAttributes disabled */ require_once "src/Cuisine.php"; require_once "src/Restaurant.php"; $server = 'mysql:host=localhost:8889;dbname=food_test'; $username = 'root'; $password = '<PASSWORD>'; $DB = new PDO($server, $username, $password); class CuisineTest extends PHPUnit_Framework_TestCase { protected function tearDown() { Cuisine::deleteAll(); Restaurant::deleteAll(); } function testSave() { $cuisine = "turds"; $test_cuisine = new Cuisine($cuisine); $executed = $test_cuisine->save(); $this->assertTrue($executed, "Task not successfully saved to database"); } function testGetId() { //Arrange $cuisine = "Lebanese"; $test_cuisine = new Cuisine($cuisine); $test_cuisine->save(); //Act $result = $test_cuisine->getId(); //assert $this->assertTrue(is_numeric($result)); } function testGetFoodType() { //Arrange $cuisine = 'pho'; $test_cuisine = new Cuisine($cuisine); //Act $result = $test_cuisine->getCuisine(); //Assert $this->assertEquals($cuisine, $result); } function testSetFoodType() { $cuisine = "Mexican"; $test_cuisine = new Cuisine($cuisine); $new_cuisine = "Ethiopian"; $test_cuisine->setCuisine($new_cuisine); $result = $test_cuisine->getCuisine(); $this->assertEquals($new_cuisine, $result); } function testFind() { $cuisine = "Dim Sum"; $cuisine_2 = "Chinese"; $test_cuisine = new Cuisine($cuisine); $test_cuisine->save(); $test_cuisine_2 = new Cuisine($cuisine_2); $test_cuisine_2->save(); $result = Cuisine::find($test_cuisine->getId()); $this->assertEquals($test_cuisine, $result); } function testDeleteAll() { $cuisine = "Cereal"; $cuisine_2 = "Pancakes"; $test_cuisine = new Cuisine($cuisine); $test_cuisine->save(); $test_cuisine_2 = new Cuisine($cuisine_2); $test_cuisine_2->save(); Cuisine::deleteAll(); $result = Cuisine::getAll(); $this->assertEquals([], $result); } function testGetRestaurant() { //Arrange $cuisine = "Mexican"; $cuisine2 = "whole paycheck"; $test_cuisine = new Cuisine($cuisine); $test_cuisine->save(); $test_cuisine_id = $test_cuisine->getId(); $test_cuisine2 = new Cuisine($cuisine2); $test_cuisine2->save(); $test_cuisine_id2 = $test_cuisine2->getId(); $name = "ihop"; $address = "444 NE 38th"; $hours = "12-8"; $cost = "2"; $test_restaurant_name = new Restaurant($name, $address, $hours, $cost, $test_cuisine_id); $test_restaurant_name->save(); var_dump($test_restaurant_name); $name2 = "cheese"; $address2 = "444 NE 38th"; $hours2 = "12-8"; $cost2 = "1"; $test_restaurant_name2 = new Restaurant($name2, $address2, $hours2, $cost2, $test_cuisine_id2); $test_restaurant_name2->save(); var_dump($test_restaurant_name2); //Act $result = $test_cuisine->getRestaurant(); //Assert $this->assertEquals([$test_restaurant_name], $result); } // function testGetRestaurant() // { // //Arrange // $cuisine = "KFC"; // $test_cuisine = new Cuisine($cuisine); // $test_cuisine->save(); // // $cuisine_id = $test_cuisine->getId(); // // // $name = "ihop"; // $address = "444 NE 38th"; // $hours = "12-8"; // $cost = "$$$$"; // // $cuisine_id = // $test_restaurant_name = new Restaurant($name, $address, $hours, $cost, $cuisine_id); // $test_restaurant_name->save(); // // $name2 = "turds"; // $address2 = "420 NE 38th"; // $hours2 = "12-12"; // $cost2 = "$$$$"; // $test_restaurant_name2 = new Restaurant($name2, $address2, $hours2, $cost2, $cuisine_id2); // $test_restaurant_name2->save(); // $cuisine_id2 = $test_cuisine2->getId(); // // //Act // $result = $test_cuisine->getRestaurant(); // // $test_cuisine->Restaurant($test_restaurant_name2); // // //Assert // $this->assertEquals([$test_restaurant_name, $test_restaurant_name2], $result); // } } ?>
ec37961c6f76730cf4f3d442c3b3bf80d26da05b
[ "Markdown", "PHP" ]
5
PHP
jakeruleaux-zz/restaurant-php
f83413b40726ddb68b2c5981273bbb82271a793c
f233529953e5ccfc5846055f8e2c2f271b472eb6
refs/heads/master
<file_sep>#addin Cake.GitVersioning var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); // Repository-specific variables for build tasks var buildNumber = GitVersioningGetVersion().SemVer2; var artifactsDir = "./artifacts"; var projectToPublish = "./src/KubernetesClient/KubernetesClient.csproj"; var solution = "./kubernetes-client.sln"; var feedzKey = EnvironmentVariable("NUGET_FEEDZ_API_KEY"); // Shared build tasks that hopefully should be copy-pastable Information($"Running on TeamCity: {TeamCity.IsRunningOnTeamCity}"); Information($"Building: {buildNumber}"); Task("Clean") .Does(() => { CleanDirectory(artifactsDir); }); Task("Restore") .IsDependentOn("Clean") .Does(() => { DotNetCoreRestore(solution); }); Task("Build") .IsDependentOn("Restore") .Does(() => { DotNetCoreBuild(solution, new DotNetCoreBuildSettings { Configuration = configuration }); }); Task("Test") .IsDependentOn("Build") .Does(() => { var settings = new DotNetCoreTestSettings { Configuration = configuration, ArgumentCustomization = args => args.Append("/p:Include=\"[KubernetesClient]*\"") .Append("/p:Exclude=\"[KubernetesClient]k8s.Models.*\"") .Append("/p:Exclude=\"[KubernetesClient]k8s.Internal.*\"") }; var projectFiles = GetFiles("./tests/**/*.csproj"); foreach (var file in projectFiles) { DotNetCoreTest(file.FullPath, settings); } }); Task("Pack-NuGet") .IsDependentOn("Test") .Does(() => { DotNetCorePack(projectToPublish, new DotNetCorePackSettings { Configuration = configuration, OutputDirectory = artifactsDir }); }); Task("Push-NuGet") .IsDependentOn("Pack-NuGet") .Does(() => { if (!String.IsNullOrEmpty (feedzKey)) { Information("Have a feedz key so pushing package"); DotNetCoreNuGetPush($"./{artifactsDir}/Gearset.KubernetesClient.{buildNumber}.nupkg", new DotNetCoreNuGetPushSettings { Source = "https://f.feedz.io/gearsethq/gearset-kubernetes-client/nuget", ApiKey = feedzKey }); } else { Information("No Feedz key so skipping package push"); } }); Task("Default") .IsDependentOn("Push-NuGet"); RunTarget(target);
b552ab18b9a557c4acb3dd5199baf4bf042909f6
[ "C#" ]
1
C#
Gearset/kubernetes-client
357859b708592710322e124de8a6ab71ec2c8079
49841bacab60afb232c1452f98cbabf532cec150
refs/heads/master
<file_sep>/* eslint-disable no-unused-vars */ function split(wholeArray) { let firstHalf = wholeArray.slice(0, Math.floor(wholeArray.length / 2)) let secondHalf = wholeArray.slice(Math.floor(wholeArray.length / 2)) return [firstHalf, secondHalf]; } function merge(array1, array2){ let outputArray = [] let alength=array1.length+array2.length; while (outputArray.length < alength){ let num; if (array1[0] < array2[0] || !array2[0]){ num = array1.shift() outputArray.push(num) } else { num = array2.shift(); outputArray.push(num) } } return outputArray } function mergeSort(array) { let result =[] let count= array.length if (count === 1){ return array } else if(count>1){ let oldarr1=mergeSort(split(array)[0]) let oldarr2=mergeSort(split(array)[1]) result = merge(oldarr1, oldarr2) } return result } <file_sep>//THIS SORTS AN EMPTY ARRAY describe('Bubble Sort', function(){ beforeEach(function () { swapCounter = 0; // replace existing `tootsiepop['lick']` method }); it('handles an empty array', function(){ expect( bubbleSort([]) ).toEqual( [] ); //swap = 0 }); it('handles an single array', function(){ expect( bubbleSort([5]) ).toEqual( [5] ); //swap = 0 }); it('handles an double array', function(){ expect( bubbleSort([9, 5]) ).toEqual( [5, 9] ); //swap = 1 }); it('handles an multiple numbers in array', function(){ expect( bubbleSort([2,6,8,5,4,9]) ).toEqual( [2,4,5,6,8,9] ); //swap = 5 expect( bubbleSort([6,5,4,3,2,1]) ).toEqual( [1,2,3,4,5,6] ); //swap = 15 }); it('handles already sorted array', function(){ expect( bubbleSort([4,6,8,13]) ).toEqual( [4,6,8,13] ); //swap = 0 }); });<file_sep>function bubbleSort(array) { if(array.length <= 1){ return array; }else{ return swap(array); } } function swap (array){ let swapped = false; let newArr = array for(let i = 0; i <= array.length - 2; i++){ if(newArr[i] > newArr[i + 1]){ swapped = true; let placeholder = newArr[i]; newArr[i] = newArr[i+1]; newArr[i+1] = placeholder; } } if (swapped === true){ newArr = swap(newArr); } return newArr; } <file_sep>describe('Split Array function', function() { it('is able to split an array into two halves', function() { expect( split([5, 3, 9, 7, 4]) ).toEqual( [[5, 3], [9, 7, 4]] ); // your code here }); }); describe('Merge function', function(){ it('is able to merge two sorted arrays into one sorted array', function(){ expect( merge([3, 5] ,[4, 71]) ).toEqual( [3, 4, 5, 71] ); // test the merging algorithm }); }); describe('MergeSort function', function(){ it('is able to merge two sorted arrays into one sorted array', function(){ expect( mergeSort([3, 5, 4, 7]) ).toEqual( [3, 4, 5, 7] ); expect( mergeSort([5, 18, 2, 6, 13, 20, 4]) ).toEqual( [2, 4, 5, 6, 13, 18, 20] ) // test the merging algorithm }); });
cf9a7caf11c61191ef442decdabcd853c74398cc
[ "JavaScript" ]
4
JavaScript
macp92/bubblesort
e827c3221789872acda26f1e91182b7472c956fb
d33ef838961c67f495db917491e830b9ab1c59e4
refs/heads/master
<repo_name>migorez/musikero<file_sep>/MusiKero/app/src/main/java/com/bubble/musikero/controlador/Reproduccion/MusicPlayerService.java package com.bubble.musikero.controlador.Reproduccion; import android.app.Service; import android.content.Context; import android.content.Intent; import android.media.AudioManager; import android.media.MediaPlayer; import android.net.Uri; import android.os.Binder; import android.os.IBinder; import android.os.PowerManager; import android.support.annotation.Nullable; import android.widget.Toast; import com.bubble.musikero.model.structure.PlayItem; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class MusicPlayerService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, MediaPlayer.OnCompletionListener, AudioManager.OnAudioFocusChangeListener { public static final String ACTION_PLAY = "com.bubble.musikero.action.PLAY"; public static final String ACTION_STOP = "com.bubble.musikero.action.STOP"; public static final String ACTION_PAUSE = "com.bubble.musikero.action.PAUSE"; public static final String ACTION_NEXT = "com.bubble.musikero.action.NEXT"; public static final String ACTION_PREV = "com.bubble.musikero.action.PREV"; public static final String ACTION_ADDTAIL = "com.bubble.musikero.action.ADDTAIL"; public static final String ACTION_PLAYALL = "com.bubble.musikero.action.PLAYALL"; public static final String ARG_PLAYLIST_ID = "playlist_id"; public static final String ARG_FOLDER_PLAYLIST_PATH = "folder_playlist_path"; private static final float FOCO_AUDIO_DUCK_VOLUME = 0.1f; private IBinder m_service_conector; public enum AudioFocus { Focused, NoFocusCanDuck, NoFocusNoDuck } private AudioFocus m_audio_focus = AudioFocus.NoFocusNoDuck; private enum PlayingState { Stopped, Paused, Playing } private PlayingState m_playing_state = PlayingState.Stopped; private long m_playlist_id; private String m_folder_path; private List<Uri> m_playlist; private AudioManager m_audio_manager; private MediaPlayer m_player; private void initMediaPlayer() { if (m_player == null) { m_player = new MediaPlayer(); m_player.setOnPreparedListener(this); m_player.setOnCompletionListener(this); m_player.setOnErrorListener(this); } else { m_player.reset(); } m_player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK); } // CICLO DE VIDA @Override public void onCreate() { super.onCreate(); m_audio_manager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE); m_service_conector = new Conector(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { String action = intent.getAction(); if (action.equals(ACTION_PLAY)) { play(intent.getData(), intent.getLongExtra(this.ARG_PLAYLIST_ID, 0), intent.getStringExtra(this.ARG_FOLDER_PLAYLIST_PATH)); } else if (action.equals(ACTION_STOP)) { stopPlayer(); } else if (action.equals(ACTION_PAUSE)) { pausePlayer(); } else if (action.equals(ACTION_NEXT)) { nextPlay(null); } else if (action.equals(ACTION_PREV)) { prevPlay(); } else if (action.equals(ACTION_PLAYALL)) { } return Service.START_NOT_STICKY; } @Override public void onDestroy() { leaveAudioFocus(); liberarRecursos(true); m_playing_state = PlayingState.Stopped; } // IMPLEMENT METHODS AND INTERFACES /** * Metodo general confirmatorio de la obtencion del foco de la salida de audio del dispositivo*/ private boolean getAudioFocus() { if (m_audio_focus != AudioFocus.Focused) { if (m_audio_manager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { m_audio_focus = AudioFocus.Focused; return true; } return false; } return true; } /** * Metodo necesario para liberar recursos, en este caso el foco del audio del dispositivo*/ private boolean leaveAudioFocus() { return m_audio_manager.abandonAudioFocus(this) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED; } @Override public void onAudioFocusChange(int focusChange) { // este metodo no se lanza al pedir el foco al audio manager, // https://developer.android.com/guide/topics/media-apps/volume-and-earphones.html switch (focusChange) { case AudioManager.AUDIOFOCUS_GAIN: // no pasa por aqui cuando se lanza por primera vez m_audio_focus = AudioFocus.Focused; break; case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK: m_audio_focus = AudioFocus.NoFocusCanDuck; break; case AudioManager.AUDIOFOCUS_LOSS: case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT: m_audio_focus = AudioFocus.NoFocusNoDuck; break; default: break; } throwPlaying(); } /** * Tocar o iniciar/pausar reproduccion*/ private void throwPlaying() { if (m_audio_focus == AudioFocus.NoFocusNoDuck) { if (m_player.isPlaying()) { m_player.pause(); m_playing_state = PlayingState.Paused; } } else { if (m_audio_focus == AudioFocus.NoFocusCanDuck) { // setVolume recibe dos valores float para un audio estereo, izq y der m_player.setVolume(FOCO_AUDIO_DUCK_VOLUME, FOCO_AUDIO_DUCK_VOLUME); // we'll be relatively quiet } else { m_player.setVolume(1.0f, 1.0f); // we can be loud / podemos ser ruidosos } if (!m_player.isPlaying()) { m_player.start(); m_playing_state = PlayingState.Playing; } } } private void liberarRecursos(boolean total_clean) { // http://www.truiton.com/2014/10/android-foreground-service-example/ stopForeground(true); // foreground es una configuracion para interactuar con el servicio desde la barra de notificaciones if (m_player != null && total_clean){ m_player.reset(); m_player.release(); m_player = null; } } /** * Decision de reproduccion*/ private void play(Uri uri, long playlist_id, String folder_path) { if (getAudioFocus()) { // el ganar el foco al pedirlo al AudioManager no ejecuta la interfaz. if (m_playing_state == PlayingState.Stopped || uri != null || folder_path != null) { m_playlist_id = playlist_id; // por defecto sera 0 indicando la lista "Seleccion actual" m_folder_path = folder_path; nextPlay(uri); } else { // si viene de la ventana reproduccion verificara la seleccion de la lista de reproduccion. if (playlist_id != m_playlist_id) { m_playlist_id = playlist_id; nextPlay(null); return; } if (m_playing_state == PlayingState.Paused){ throwPlaying(); } else { m_player.pause(); m_playing_state = PlayingState.Paused; } } } else { Toast.makeText(getApplicationContext(), "Otra aplicación acapara el audio del dispositivo.", Toast.LENGTH_LONG).show(); } } /** * Siguiente archivo a reproducir*/ private void nextPlay(Uri uri) { m_playing_state = PlayingState.Stopped; liberarRecursos(false); initMediaPlayer(); if (uri != null) { addToPlayList(uri); } else { uri = nextUriPlayBack(); if (uri == null) { Toast.makeText(getApplicationContext(), "No hay mas que reproducir.", Toast.LENGTH_LONG).show(); stopSelf(); return; } } try { m_player.setDataSource(getApplicationContext(), uri); m_player.setAudioStreamType(AudioManager.STREAM_MUSIC); m_player.prepareAsync(); } catch (IOException eh) { Toast.makeText(getApplicationContext(), "Error al conseguir el archivo", Toast.LENGTH_LONG).show(); eh.printStackTrace(); } } /** * */ @Nullable private Uri nextUriPlayBack() { /*if (m_playlist_id == PlayerFragment.DEFAULT_PLAYLISTS[0].getPlaylist().getId()) { if (m_folder_path != null) { fetchPlayList(m_proveedor_contenido.getSongList(m_folder_path)); } } else if (m_playlist_id == PlayerFragment.DEFAULT_PLAYLISTS[1].getPlaylist().getId()) { fetchPlayList(m_proveedor_contenido.getSongList(null)); } // si le especifico que reproduzca lo que hay en cola else if (m_playlist_id == PlayerFragment.DEFAULT_PLAYLISTS[2].getPlaylist().getId()) { } else { fetchPlayList(m_proveedor_contenido.getPlayListContent(m_playlist_id)); } if (m_playlist != null && m_playlist.size() > 0) { Random random = new Random(); return m_playlist.get(random.nextInt(m_playlist.size())); }*/ return null; } @Override public void onPrepared(MediaPlayer mp) { throwPlaying(); } @Override public void onCompletion(MediaPlayer mp) { nextPlay(null); } @Override public boolean onError(MediaPlayer mp, int what, int extra) { initMediaPlayer(); return true; } /** * Detener la reproduccion*/ private void stopPlayer() { if (m_player != null && m_playing_state != PlayingState.Stopped && leaveAudioFocus()) { liberarRecursos(true); m_playing_state = PlayingState.Stopped; MusicPlayerService.this.stopSelf(); } } private void pausePlayer() { if (m_playing_state == PlayingState.Playing) { m_player.pause(); m_playing_state = PlayingState.Paused; } } /** * */ private void prevPlay() { if (m_player != null) { nextPlay(null); } } public void addToPlayList(Uri uri) { if (m_playlist == null) m_playlist = new ArrayList<>(); m_playlist.add(uri); } /** * */ public long getActualPlaylistId() { return m_playlist_id; } // BIND SERVICE @Override public IBinder onBind(Intent intent) { return m_service_conector; } public class Conector extends Binder { public Conector() { super(); } public MusicPlayerService getMusicService() { return MusicPlayerService.this; } } // retorno el objeto MediaPlayer de la instancia del servicio para obtener su informacion en los // componentes que se enlacen al servicio public MediaPlayer getPlayer() { return m_player; } } <file_sep>/MusiKero/app/src/main/java/com/bubble/musikero/view/pages/SongFragment.java package com.bubble.musikero.view.pages; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.AsyncTaskLoader; import android.support.v4.content.Loader; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import com.bubble.musikero.R; import com.bubble.musikero.controlador.Reproduccion.MusicPlayerService; import com.bubble.musikero.model.PlayItemProvider; import com.bubble.musikero.model.structure.PlayItem; import com.bubble.musikero.model.structure.Song; import java.util.ArrayList; import java.util.List; /** * Created by Miguel on 05/09/2017. */ public class SongFragment extends Fragment implements LoaderManager.LoaderCallbacks<List<PlayItem>> { // ATTRIBUTES private static final int INSTANCE_LOADER_MANAGER = 0; // instancia del widget de la UI para mostrar el listado de objetos tipo Song // https://developer.android.com/guide/topics/ui/layout/recyclerview.html private RecyclerView m_recycler_view; // implement RecyclerView.Adapter private SongRecyclerAdapter m_recycler_adapter; // CONSTRUCTION public SongFragment() { // Required empty public constructor for method newInstance } /** * Static void make that every component which request this fragment as it´s component */ public static SongFragment newInstance() { return new SongFragment(); } // CONFIG AND INIT // config view components private View m_initView(View m_view) { // config form recyclerview m_recycler_view = (RecyclerView) m_view.findViewById(R.id.rv_song_fragment); m_recycler_view.setLayoutManager(new LinearLayoutManager(getContext())); // adapter and data of recyclerview m_recycler_adapter = new SongRecyclerAdapter(); m_recycler_view.setAdapter(m_recycler_adapter); return m_view; } // FRAGMENT LIFECYCLE @Override public void onAttach(Context context) { super.onAttach(context); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View m_view = inflater.inflate(R.layout.song_fragment, container, false); return m_initView(m_view); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public void onStart() { super.onStart(); loadRecyclerView(); } @Override public void onResume() { super.onResume(); } @Override public void onPause() { super.onPause(); } @Override public void onStop() { super.onStop(); } @Override public void onDestroyView() { super.onDestroyView(); } @Override public void onDestroy() { super.onDestroy(); } @Override public void onDetach() { super.onDetach(); } // END LIFECYCLE // IMPLEMENTS METHODS AND INTERFACES // metodo versatil para la recarga de la lista segun los parametros requeridos private void loadRecyclerView() { getLoaderManager().restartLoader // loader instance flag, bundle data, load reacts listener (SongFragment.this.INSTANCE_LOADER_MANAGER, null, SongFragment.this); } // load recyclerview data asyncronously @Override public Loader<List<PlayItem>> onCreateLoader(int id, Bundle args) { // create a new asyncloader that recover the data return new PlayItemRecyclerLoader(SongFragment.this.getContext()); } @Override public void onLoadFinished(Loader<List<PlayItem>> loader, List<PlayItem> data) { m_recycler_adapter.setItemList(data); } @Override public void onLoaderReset(Loader<List<PlayItem>> loader) { m_recycler_adapter.setItemList(null); } // INNER CLASS // static inner class for load the music-data from device´s content, in this case all songs stored private static class PlayItemRecyclerLoader extends AsyncTaskLoader<List<PlayItem>> { public PlayItemRecyclerLoader(Context context) { super(context); } @Override protected void onStartLoading() { super.onStartLoading(); forceLoad(); } @Override public List<PlayItem> loadInBackground() { // object that resolve the access to the device´s content return PlayItemProvider.getDeviceSongs(PlayItemRecyclerLoader.this.getContext()); } } // implement RecyclerView.Adapter for manage the list of this fragment private static class SongRecyclerAdapter extends RecyclerView.Adapter<SongItemViewHolder> { // list of items to show private List<PlayItem> m_list; // Implements RecyclerView.Adapter // 1 @Override public int getItemCount() { return m_list != null ? m_list.size() : 0; } // 2 @Override public SongItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new SongItemViewHolder( // view LayoutInflater.from(parent.getContext()). // context inflate(R.layout.itemsong_layout, parent, false) // xml layout ); } // 3 @Override public void onBindViewHolder(SongItemViewHolder holder, int position) { holder.onBindView(m_list.get(position)); } // Implement Own Methods public void setItemList(List<PlayItem> list) { m_list = null; if (list != null) { m_list = new ArrayList<>(); m_list.addAll(list); } SongRecyclerAdapter.this.notifyDataSetChanged(); // ctrl + Q for info } } /***/ private static class SongItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { private TextView txv_song_name, txv_song_duration; private Song m_song_item; public SongItemViewHolder(View itemView) { super(itemView); txv_song_name = (TextView) itemView.findViewById(R.id.txv_song_name); txv_song_duration = (TextView) itemView.findViewById(R.id.txv_song_duration); itemView.setOnClickListener(SongItemViewHolder.this); } public void onBindView(PlayItem item) { m_song_item = (Song) item; // Song extends from PlayItem txv_song_name.setText(item.getDisplayName()); txv_song_duration.setText(item.getLengLife()); } @Override public void onClick(View view) { view.getContext().startService( new Intent( MusicPlayerService.ACTION_PLAY, m_song_item.getUri(), view.getContext(), MusicPlayerService.class ) ); Toast.makeText(view.getContext(), "Reproduciendo: " + m_song_item.getDisplayName(), Toast.LENGTH_LONG).show(); } } }<file_sep>/MusiKero/app/src/main/java/com/bubble/musikero/model/structure/PlayItem.java package com.bubble.musikero.model.structure; /** * Created by Miguel on 31/07/2017. */ public abstract class PlayItem { // can refs file, directory, uri // atributo que definira la clase heredera //protected static String ITEMTYPE; // abstract class cannot instanciate. Protected constructor so that the class that extends // from this is able to generate a public constructor. protected PlayItem() { } public abstract String getDisplayName(); public abstract String getLengLife(); public abstract String getNature(); } //public abstract List actionListItemClick(int position); /*private Song song; private Folder folder; private boolean im_folder = false; private PlayList playlist; *//** * Constructor utilizado para archivos reproducibles como tal*//* public PlayItem(long id, String display, String ruta, long duracion) { song = new Song(id, display, ruta, duracion); im_folder = false; } *//** * Constructor empleado para representar carpetas en el mismo widget*//* public PlayItem(String name_folder, String path) { folder = new Folder(name_folder, path); im_folder = true; } public PlayItem(long id_playlist, String name_playlist) { playlist = new PlayList(id_playlist, name_playlist); } public Song getSong() { return song != null ? song : null; } public Folder getFolder() { return folder != null ? folder : null; } public boolean imFolder() { return im_folder; } public PlayList getPlaylist() { return playlist != null ? playlist : null; } *//** * Sub-clase de Itemlist que lo establecera como item de archivo o cancion reproducible*//* public class Song { // Modificadores de acceso a constructores y campos. // refs = http://www.aprenderaprogramar.com/index.php?option=com_content&view=article&id=665:public-private-y-protected-javatipos-de-modificadores-de-acceso-visibilidad-en-clases-subclases-cu00693b&catid=68&Itemid=188 // en este caso se usara private porque estos atributos son inamovibles en cada objeto. private long m_id; private String m_display_name; private String m_path; private long m_duration; private String m_folder_name; private String m_folder_path; *//** * Constructor*//* public Song(long id, String display, String ruta, long duracion){ m_id = id; m_display_name = display; m_path = ruta; m_duration = duracion; int index_last_slash = m_path.lastIndexOf("/"); m_folder_path = m_path.substring(0, index_last_slash); // desde el primer (incluido) hasta antes del segundo valor (sin sin incluirlo) index_last_slash = m_folder_path.lastIndexOf("/"); m_folder_name = m_folder_path.substring(index_last_slash + 1); } public long getId() { return m_id; } public String getDisplayName() { return m_display_name; } public String getRuta() { return m_path; } public String getDuracion() { java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("mm:ss"); return sdf.format(new Date(m_duration)); } public String getNameFolder() { return m_folder_name; } public String getFolderPath() { return m_folder_path; } public Uri obtenerUriArchivo() { return ContentUris.withAppendedId( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, m_id); } } *//** * Sub-clase de Itemlist que lo establecera como item de carpeta*//* public class Folder { private String m_name; private String m_path; public Folder(String nameFolder, String path) { m_name = nameFolder; m_path = path; } public String getName() { return m_name; } public String getPath() { return m_path; } } public class PlayList { private long m_id; private String m_name; public PlayList(long id, String name) { m_id = id; m_name = name; } public long getId() { return m_id; } public String getName() { return m_name; } }*/ <file_sep>/MusiKero/app/src/main/java/com/bubble/musikero/view/widgets/ItemRecyclerAdapter.java package com.bubble.musikero.view.widgets; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.bubble.musikero.R; import com.bubble.musikero.model.structure.PlayItem; import java.util.ArrayList; import java.util.List; /** * Created by Miguel on 09/09/2017. * This class will provide the configuration of the lists in the app. This will be react to the methods * of the class PlayItem those must be implement by the class that extends of PlayItem, that is: * Song, Folder n Playlist */ public class ItemRecyclerAdapter extends RecyclerView.Adapter<ItemRecyclerAdapter.ItemViewHolder> { // refs => https://www.raywenderlich.com/126528/android-recyclerview-tutorial // fields /** * listener usado para que sea implementado por el fragmento que utiliza este adaptador en su * RecyclerView para que al clicar un elemento de la lista, el fragmento responda en su instancia * con sus recursos.*/ private static ItemRecyclerClickListener m_item_recycler_click_listener; // collection of items private List<PlayItem> m_list; /** construct /* the implement RecyclerView.Adapter request a list of PlayItem for build its views. */ public ItemRecyclerAdapter(List<PlayItem> list, ItemRecyclerClickListener item_recycler_click_listener) { m_list = list; m_item_recycler_click_listener = item_recycler_click_listener; } /** * Void setItems sets m_list in a new ArrayList whit the List<PlayItem> passed replacing all * the previous items * */ public void setItems(List<PlayItem> item_list) { m_list = new ArrayList<>(); if (item_list != null) { m_list.addAll(item_list); } notifyDataSetChanged(); } // the compiler execute this code before deploy views onCreateViewHolder and onBindViewHolder // for know how many must do. Al instanciar el adaptador con esta lista nula, logicamente no se // desplegara nada. @Override public int getItemCount() { return m_list != null ? m_list.size() : 0; } @Override public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // return a new ItemViewHolder to which set a view inflated references a xml file in app resources return new ItemViewHolder( LayoutInflater.from(parent.getContext()).inflate (R.layout.itemsong_layout, parent, false) // xml file ); } @Override public void onBindViewHolder(ItemViewHolder holder, int position) { holder.onBindView(m_list.get(position)); } // --- // INNER CLASS // ITEM HOLDER Represent and hold the interpreter of the PlayItem class in the UI static class ItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { //public static final String ARG_ID = "m_id"; private PlayItem m_item; // wdgts //private FrameLayout m_image_layout; private TextView txv_display_item, txv_lenglife_item; // construct public ItemViewHolder(View itemView) { super(itemView); // txv_display_item = (TextView) itemView.findViewById(R.id.txv_display_item); // txv_lenglife_item = (TextView) itemView.findViewById(R.id.txv_lenglife_item); itemView.setOnClickListener(ItemViewHolder.this); } // config on bind to view (just on starting) // PlayItem could be: Song, Folder or Playlist public void onBindView(PlayItem item/*, int position*/) { m_item = item; txv_display_item.setText(item.getDisplayName()); if (item.getLengLife() != null) { txv_lenglife_item.setText(item.getLengLife()); } } // listener onclik ui @Override public void onClick(View itemView) { m_item_recycler_click_listener.onItemRecyclerClick(m_item); } } // INTERFACES TO COMUNICATE /** * Created by <NAME> on 10/09/2017. * Interface that allow us to bring access to the event of touch or click on each item for * implements the process consequent */ public interface ItemRecyclerClickListener { void onItemRecyclerClick(PlayItem item); } } <file_sep>/README.md # musikero mp3 personal player <file_sep>/MusiKero/app/src/main/java/com/bubble/musikero/model/structure/Folder.java package com.bubble.musikero.model.structure; /** * Created by Miguel on 02/08/2017. */ public class Folder extends PlayItem { public static final String ITEMTYPE = "Folder"; private String m_name; private String m_path; public Folder(String name, String path) { //ITEMTYPE = TAG; m_name = name; m_path = path; } @Override public String getDisplayName() { return m_name; } @Override public String getLengLife() { return null; } @Override public String getNature() { return ITEMTYPE; } public String getPath() { return m_path; } @Override public String toString() { return ITEMTYPE; } }
8bfb0ac94d96432da3fd39f65eb8f3c23395e746
[ "Markdown", "Java" ]
6
Java
migorez/musikero
be1b146d6754815ee1f56c84161818d7f889b254
c9c87acd16288ce1401a3175b1247074069f3628
refs/heads/master
<file_sep>package edu.edaily.sysuedaily.utils; public class Constant { public static final String DEBUG_TAB = "SYSU_EDAILY"; public static final String PATH_PIC = "/sdcard/sysuedaily/pic/"; public static final String PATH_SPIC = "/sdcard/sysuedaily/spic/"; public static final String NEWS_KIND = "news_kind"; public static final String NEWS_TITLE = "news_title"; public static final String NEWS_DATE_FROM = "news_date_from"; public static final String NEWS_TEXT = "news_text"; public static final String NEWS_GID = "news_gid"; public static final String NEWS_TABLE = "news_table"; public static final String NEWS_ID = "news_id"; public static final String SRV_URL = ""; public static final String SYNC_NEWS = "news/"; public static final int SRV_RESP_SUC = 200; // Weibo public static final String CONSUMER_KEY = "2765470881"; public static final String CONSUMER_SECRET = "<KEY>"; } <file_sep>package edu.edaily.sysuedaily.utils; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.provider.BaseColumns; public class NewsDBHelper extends SQLiteOpenHelper { public static final String DBNAME = "news.db"; public static final int VERSION = 1; public static final String T_HEADLINE = "headline_table"; public static final String T_CAMPUS = "campus_table"; public static final String T_LECTURE = "lecture_table"; public static final String T_JOB = "job_table"; public static final String T_VISION = "vision_table"; public static final String C_ID = BaseColumns._ID; public static final String C_TITLE = "title"; public static final String C_GLOBAL_ID = "global_id"; public static final String C_SHORT_DESCRIPTION = "short_description"; public static final String C_TEXT = "text"; public static final String C_PIC = "pic"; public static final String C_SPIC = "s_pic"; public static final String C_DATE = "date"; public static final String[] C_COLUMNS = { BaseColumns._ID, C_TITLE, C_GLOBAL_ID, C_SHORT_DESCRIPTION, C_TEXT, C_PIC, C_SPIC, C_DATE }; public static final String T_COMMENT = "comment_table"; public static final String C_CONTENT = "content"; public static final String C_RATE = "rate"; private static final String CREATE_NEWS_COLUMNS = " (" + C_ID + " INT PRIMARY KEY, " + C_TITLE + " TEXT NOT NULL, " + C_GLOBAL_ID + " INT NOT NULL, " + C_SHORT_DESCRIPTION + " TEXT NOT NULL, " + C_TEXT + " TEXT NOT NULL, " + C_PIC + " TEXT NOT NULL, " + C_SPIC + " TEXT NOT NULL, " + C_DATE + " TEXT NOT NULL" + ")"; private static final String CREATE_HEADLINE = "CREATE TABLE " + T_HEADLINE + CREATE_NEWS_COLUMNS; private static final String CREATE_CAMPUS = "CREATE TABLE " + T_CAMPUS + CREATE_NEWS_COLUMNS; private static final String CREATE_LECTURE = "CREATE TABLE " + T_LECTURE + CREATE_NEWS_COLUMNS; private static final String CREATE_JOB = "CREATE TABLE " + T_JOB + CREATE_NEWS_COLUMNS; private static final String CREATE_VISION = "CREATE TABLE " + T_VISION + CREATE_NEWS_COLUMNS; public NewsDBHelper(Context context) { super(context, DBNAME, null, VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_HEADLINE); db.execSQL(CREATE_CAMPUS); db.execSQL(CREATE_LECTURE); db.execSQL(CREATE_JOB); db.execSQL(CREATE_VISION); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE * IF EXISTS"); } } <file_sep>package edu.edaily.sysuedaily.tabactivities; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import android.app.Activity; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Parcelable; import android.provider.BaseColumns; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.util.DisplayMetrics; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; import edu.edaily.sysuedaily.DetailActivity; import edu.edaily.sysuedaily.R; import edu.edaily.sysuedaily.utils.Constant; import edu.edaily.sysuedaily.utils.NewsDBHelper; public class HeadlineActivity extends Activity { ListView list; Cursor cursor; SQLiteDatabase newsdb; FrameLayout header; ImageView iv1, iv2, iv3; ViewPager pager; TextView pageTitle; int currentItem = 0; private Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { pager.setCurrentItem(currentItem);// 切换当前显示的图片 }; }; boolean[] picstat; boolean[] spicstat; Bitmap[] headpic; Bitmap[] spic; ArrayList<ImageView> headImgViews; ArrayList<View> dots; private ScheduledExecutorService scheduledExecutorService; private static final String[] FROM = {NewsDBHelper.C_TITLE, NewsDBHelper.C_SHORT_DESCRIPTION}; private static final int[] TO = {R.id.textview_activity_headline_list_content_title, R.id.textview_activity_headline_list_content_short}; ArrayList<HashMap<String, Object>> headcontent; String[] testArray = {"今日岭南学院教育改革会召开", "2月29日系“女性表白日” ", "AV女优进课堂 合适否?", "谷歌社交网站G+难以提高用户活跃度", "珠海宝镜湾岩画中的巫舞"}; String[] textArray = {" 6月19日下午,岭南学院本科教育改革动员大会在岭南MBA中心大楼召开。" + "我校校长许宁生、校长助理李文军,岭南学院院长徐信忠、书记张文彪,以及岭南学院全体教职员工、各项目主任、近40名学生代表参加了此次大会。" + "\n 主管本科教学的陆军副院长介绍了岭南学院本科教育改革方案,详细阐述了改革的原因、理念及岭南学院本科项目教育目标," + "介绍了通过博雅教育与专业教育的整合、多维的教学评估和外部考官制度内外相结合的质量保障体系、学生指导方案、海外实习与社会实践等翔实的举措," + "培养适应社会需要的卓越人才。陆军副院长说,在本次本科教育改革的酝酿、思考、讨论和形成的改革方案过程中,学院始终牢记本科教育的核心——学生," + "学生的未来必将影响社会乃至人类的未来。正因为如此,教育改革必须极其慎重,必须是渐进、分阶段的,要实现改革目标还需要全体教师长期、" + "艰辛的努力和无私奉献,我们会以谦卑的心态不断学习、思考、改进。", "", "", "", ""}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_headline); // Init header = (FrameLayout) LayoutInflater.from(HeadlineActivity.this).inflate(R.layout.linearlayout_headline_slide, null); pageTitle = (TextView) header.findViewById(R.id.textview_headline_slide); pager = (ViewPager) header.findViewById(R.id.viewpager_headline_slide); list = (ListView) findViewById(R.id.listview_activity_headline); picstat = new boolean[3]; spicstat = new boolean[1000]; for (int i = 0; i < picstat.length; ++ i) picstat[i] = false; for (int i = 0; i < spicstat.length; ++ i) spicstat[i] = false; headpic = new Bitmap[3]; for (int i = 0; i < headpic.length; ++ i) headpic[i] = null; spic = new Bitmap[1000]; for (int i = 0; i < spic.length; ++ i) spic[i] = null; headImgViews = new ArrayList<ImageView>(); headcontent = new ArrayList<HashMap<String, Object>>(); dots = new ArrayList<View>(); dots.add(header.findViewById(R.id.view_headline_slide_dot0)); dots.add(header.findViewById(R.id.view_headline_slide_dot1)); dots.add(header.findViewById(R.id.view_headline_slide_dot2)); newsdb = new NewsDBHelper(this).getWritableDatabase(); ContentValues values = new ContentValues(); values.put(NewsDBHelper.C_PIC, ""); values.put(NewsDBHelper.C_SPIC, ""); values.put(NewsDBHelper.C_DATE, new Date().toString()); values.put(NewsDBHelper.C_SHORT_DESCRIPTION, "DESCRIPTION"); for (int i = 0; i < 3; ++ i) { values.put(NewsDBHelper.C_GLOBAL_ID, i); values.put(NewsDBHelper.C_TITLE, testArray[i]); values.put(NewsDBHelper.C_TEXT, textArray[i]); newsdb.insertOrThrow(NewsDBHelper.T_HEADLINE, null, values); } newsdb.close(); // 构造三个头条 headcontent newsdb = new NewsDBHelper(this).getReadableDatabase(); cursor = queryNews(newsdb); cursor.moveToFirst(); for (int i = 0; i < 3; ++ i) { HashMap<String, Object> head = new HashMap<String, Object>(); head.put(NewsDBHelper.C_TITLE, cursor.getString(cursor.getColumnIndexOrThrow(NewsDBHelper.C_TITLE))); head.put(NewsDBHelper.C_GLOBAL_ID, cursor.getLong(cursor.getColumnIndexOrThrow(NewsDBHelper.C_GLOBAL_ID))); headcontent.add(head); cursor.moveToNext(); } OnClickListener clickImage = new OnClickListener() { public void onClick(View v) { ImageView view = (ImageView) v; int tag = (Integer) v.getTag(); cursor.moveToPosition(tag); Intent intent = new Intent(HeadlineActivity.this, DetailActivity.class); intent.putExtra(Constant.NEWS_KIND, "HEADLINE"); intent.putExtra(Constant.NEWS_TABLE, NewsDBHelper.T_HEADLINE); intent.putExtra(Constant.NEWS_ID, cursor.getLong(cursor.getColumnIndexOrThrow(BaseColumns._ID))); intent.putExtra(Constant.NEWS_GID, cursor.getLong(cursor.getColumnIndexOrThrow(NewsDBHelper.C_GLOBAL_ID))); intent.putExtra(Constant.NEWS_TITLE, cursor.getString(cursor.getColumnIndexOrThrow(NewsDBHelper.C_TITLE))); startActivity(intent); } }; // 初始化图片ImageView for (int i = 0; i < headpic.length; i++) { ImageView imageView = new ImageView(this); imageView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); imageView.setImageResource(R.drawable.headline_pic_loading); imageView.setTag(i); imageView.setOnClickListener(clickImage); if (headpic[i] == null) new FetchPic(imageView).execute((Long) headcontent.get(i).get(NewsDBHelper.C_GLOBAL_ID), (long) i); imageView.setScaleType(ScaleType.CENTER_CROP); headImgViews.add(imageView); } pageTitle.setText((String) headcontent.get(0).get(NewsDBHelper.C_TITLE)); pager.setAdapter(new PageAdapter());// 设置填充ViewPager页面的适配器 // 设置一个监听器,当ViewPager中的页面改变时调用 pager.setOnPageChangeListener(new MyPageChangeListener()); list.addHeaderView(header); list.setAdapter(new CursorAdapter(this, cursor)); list.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { if (arg2 == 0) return; cursor.moveToPosition(arg2 - 1); Intent intent = new Intent(HeadlineActivity.this, DetailActivity.class); intent.putExtra(Constant.NEWS_KIND, "HEADLINE"); intent.putExtra(Constant.NEWS_TABLE, NewsDBHelper.T_HEADLINE); intent.putExtra(Constant.NEWS_ID, cursor.getLong(cursor.getColumnIndexOrThrow(BaseColumns._ID))); intent.putExtra(Constant.NEWS_GID, cursor.getLong(cursor.getColumnIndexOrThrow(NewsDBHelper.C_GLOBAL_ID))); intent.putExtra(Constant.NEWS_TITLE, cursor.getString(cursor.getColumnIndexOrThrow(NewsDBHelper.C_TITLE))); startActivity(intent); } }); } @Override protected void onStart() { scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); // 当Activity显示出来后,每两秒钟切换一次图片显示 scheduledExecutorService.scheduleAtFixedRate(new ScrollTask(), 1, 5, TimeUnit.SECONDS); super.onStart(); } @Override protected void onStop() { // 当Activity不可见的时候停止切换 scheduledExecutorService.shutdown(); super.onStop(); } @Override protected void onDestroy() { newsdb.close(); super.onDestroy(); } private class ScrollTask implements Runnable { public void run() { synchronized (pager) { System.out.println("currentItem: " + currentItem); currentItem = (currentItem + 1) % headImgViews.size(); handler.obtainMessage().sendToTarget(); // 通过Handler切换图片 } } } private class MyPageChangeListener implements OnPageChangeListener { private int oldPosition = 0; /** * This method will be invoked when a new page becomes selected. * position: Position index of the new selected page. */ public void onPageSelected(int position) { currentItem = position; pageTitle.setText((String) headcontent.get(position).get(NewsDBHelper.C_TITLE)); dots.get(oldPosition).setBackgroundResource(R.drawable.dot_normal); dots.get(position).setBackgroundResource(R.drawable.dot_focused); oldPosition = position; } public void onPageScrollStateChanged(int arg0) { } public void onPageScrolled(int arg0, float arg1, int arg2) { } } private class PageAdapter extends PagerAdapter { @Override public int getCount() { return headcontent.size(); } @Override public Object instantiateItem(View arg0, int arg1) { ((ViewPager) arg0).addView(headImgViews.get(arg1)); return headImgViews.get(arg1); } @Override public void destroyItem(View arg0, int arg1, Object arg2) { ((ViewPager) arg0).removeView((View) arg2); } @Override public boolean isViewFromObject(View arg0, Object arg1) { return arg0 == arg1; } @Override public void restoreState(Parcelable arg0, ClassLoader arg1) { } @Override public Parcelable saveState() { return null; } @Override public void startUpdate(View arg0) { } @Override public void finishUpdate(View arg0) { } } private Cursor queryNews(SQLiteDatabase db) { return db.query(NewsDBHelper.T_HEADLINE, NewsDBHelper.C_COLUMNS, null, null, null, null, null); } class CursorAdapter extends SimpleCursorAdapter { public CursorAdapter(Context context, Cursor c) { super(context, R.layout.linearlayout_headline_activity_list_content, c, FROM, TO); } @Override public void bindView(View view, Context context, Cursor cursor) { super.bindView(view, context, cursor); LinearLayout ll = (LinearLayout) view; long gid = cursor.getLong(cursor.getColumnIndex(NewsDBHelper.C_GLOBAL_ID)); new FetchSPic((ImageView) ll.findViewById(R.id.imageview_headline_list_content_spic)).execute(gid); } } class FetchPic extends AsyncTask<Long, Void, Bitmap> { Long gid; int listid; ImageView view; public FetchPic(ImageView view) { this.view = view; } @Override protected Bitmap doInBackground(Long... arg0) { gid = arg0[0]; listid = arg0[1].intValue(); Bitmap img = null; if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { final String filepath = Constant.PATH_PIC + arg0[0] + ".png"; if (picstat[listid]) this.cancel(true); else { picstat[listid] = true; File p = new File(filepath); if (p.isFile()) { img = BitmapFactory.decodeFile(filepath); } else { if (!isCancelled()) { } } } } return img; } @Override protected void onPostExecute(Bitmap result) { headpic[listid] = result; view.setImageBitmap(result); super.onPostExecute(result); } } class FetchSPic extends AsyncTask<Long, Void, Bitmap> { ImageView simage; public FetchSPic(ImageView v) { simage = v; } @Override protected Bitmap doInBackground(Long... arg0) { Bitmap img = null; if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { String filepath = Constant.PATH_SPIC + arg0[0]; if (new File(filepath + ".lock").isFile()) this.cancel(true); else { File lockfile = new File(filepath + ".lock"); try { lockfile.createNewFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } File p = new File(filepath + ".png"); if (p.isFile()) { img = BitmapFactory.decodeFile(filepath + ".png"); } else { if (!isCancelled()) { } } lockfile.delete(); } } return img; } @Override protected void onPostExecute(Bitmap result) { if (result != null) simage.setImageBitmap(result); super.onPostExecute(result); } } } <file_sep>package edu.edaily.sysuedaily.utils; import java.io.BufferedReader; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import android.util.Base64; public class Remote { public static class News { public JSONObject getNews(JSONObject object) throws IOException, JSONException { JSONObject ret = postConnect(object, Constant.SRV_URL + Constant.SYNC_NEWS); return ret; } public boolean getPic(String urlstr, String path) throws IOException { try { URL url = new URL(urlstr); URLConnection connection = url.openConnection(); InputStream is = connection.getInputStream(); byte[] bs = new byte[30720]; int len; OutputStream os = new FileOutputStream(path); while ((len = is.read(bs)) != -1) { os.write(bs, 0, len); } os.close(); is.close(); return true; } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } } private static JSONObject postConnect(JSONObject object, String serverurl) throws IOException, JSONException { JSONObject retobj = null; try { URL url = new URL(serverurl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoInput(true); connection.setDoOutput(true); connection.connect(); String postStr = Base64.encodeToString(object.toString().getBytes(), Base64.URL_SAFE | Base64.NO_WRAP); PrintWriter pw = new PrintWriter(connection.getOutputStream()); pw.print(postStr); pw.flush(); pw.close(); int respCode = connection.getResponseCode(); if (respCode == Constant.SRV_RESP_SUC) { InputStreamReader isr = new InputStreamReader(connection.getInputStream()); BufferedReader br = new BufferedReader(isr); String respMsg = br.readLine(); retobj = new JSONObject((String) (new JSONTokener(respMsg).nextValue())); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return retobj; } } <file_sep>package edu.edaily.sysuedaily; import android.app.TabActivity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TabHost; import android.widget.TabHost.TabSpec; import edu.edaily.sysuedaily.tabactivities.HelpActivity; import edu.edaily.sysuedaily.tabactivities.IrrigationActivity; import edu.edaily.sysuedaily.tabactivities.NewsActivity; import edu.edaily.sysuedaily.tabactivities.TopicActivity; import edu.edaily.sysuedaily.tabactivities.WeiboActivity; public class MainActivity extends TabActivity { TabHost tabhost; TabSpec weibo, news, topic, help, irrigation; Button discover; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tabhost = getTabHost(); news = tabhost.newTabSpec("NEWS").setIndicator("NEWS").setContent(new Intent(this, NewsActivity.class)); tabhost.addTab(news); topic = tabhost.newTabSpec("TOPIC").setIndicator("TOPIC").setContent(new Intent(this, TopicActivity.class)); tabhost.addTab(topic); weibo = tabhost.newTabSpec("WEIBO").setIndicator("WEIBO").setContent(new Intent(this, WeiboActivity.class)); tabhost.addTab(weibo); help = tabhost.newTabSpec("HELP").setIndicator("HELP").setContent(new Intent(this, HelpActivity.class)); tabhost.addTab(help); irrigation = tabhost.newTabSpec("IRRIGATION").setIndicator("IRRIGATION").setContent(new Intent(this, IrrigationActivity.class)); tabhost.addTab(irrigation); discover = (Button) findViewById(R.id.button_activity_main_discover); discover.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { startActivity(new Intent(MainActivity.this, DiscoverActivity.class)); overridePendingTransition(R.anim.push_up, R.anim.dont_move); } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menuitem_activity_main_setting: startActivity(new Intent(this, PrefsActivity.class)); break; } return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.activity_main_menu, menu); return true; } } <file_sep>package edu.edaily.sysuedaily; import android.app.Activity; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; public class LoadActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_load); new LoadContents().execute(null); } class LoadContents extends AsyncTask<String, String, String> { @Override protected String doInBackground(String... arg0) { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @Override protected void onPostExecute(String result) { startActivity(new Intent(LoadActivity.this, MainActivity.class)); finish(); super.onPostExecute(result); } } }
23addb2e9bab1adf7949d99e6e7bd9546656df25
[ "Java" ]
6
Java
zonyitoo/SYSU_EDAILY
72f8e44daffcbc684082f86b87fb92e8d617e884
cbbc8269bbfd405e328b303dbc6845092f8c58d6
refs/heads/main
<file_sep># java-frame-study java框架demo <file_sep>package client; import lombok.extern.slf4j.Slf4j; import org.apache.thrift.TException; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.transport.TSocket; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import thrift.UserService; import javax.annotation.PostConstruct; /** * @author zhangtao * @Title: Client * @Package: client * @Description: Client * @date 2020-12-18 23:49 */ @Component @Slf4j public class ClientProxy { @Value("${thrift.ip}") private String ip; @Value("${thrift.port}") private int port; @Value("${thrift.timeout}") private int timeout; private UserService.Client client; //@PostConstruct public void startClient(String userName) { TTransport transport = null; try { transport = new TSocket(ip, port, timeout); // 协议要和服务端一致 TProtocol protocol = new TBinaryProtocol(transport); client = new UserService.Client(protocol); transport.open(); for (int i = 0; i < 25; i++) { log.info(client.sayHello("carl")); log.info(client.getName(1)); log.info(client.isExist("carl")+""); } } catch (TTransportException e) { log.error("thrift客户端启动失败", e); } catch (TException e) { log.error("thrift客户端启动失败", e); } finally { if (null != transport) { transport.close(); } } } public UserService.Client getClient() { return client; } } <file_sep>package service; import com.google.common.eventbus.EventBus; import entity.Cat; import entity.User; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * @author zhangtao * @Title: EventProducers * @Package: service * @Description: EventProducers - 事件生产者[Producers] * @date 2020-12-18 00:00 */ @Slf4j @Service public class EventProducers { @Autowired EventBus eventBus; @Autowired CatEventBusChangeRecorder catEventBusChangeRecorder; @Autowired UserEventBusChangeRecorder userEventBusChangeRecorder; public void init() { eventBus.register(catEventBusChangeRecorder); log.info("事件监听者[CatEventBusChangeRecorder]注册成功!!!"); eventBus.register(userEventBusChangeRecorder); log.info("事件监听者[UserEventBusChangeRecorder]注册成功!!!"); } public void post() { log.info("事件生产者[EventProducers]开始生产数据!!!!"); for (int i = 0; i < 10; i++) { eventBus.post(Cat.builder().type("cat-" + i).color("cat-color" + i).name("cat-" + i).build()); log.debug("cat-" + i + " event post----------"); eventBus.post(User.builder().age(12 + i).name("name-" + i).sex((i%2==0?"女":"男")).build()); log.debug("user-" + i + " event post----------"); try { Thread.sleep(1); } catch (InterruptedException e) { log.error(e.getMessage()); } } log.info("事件生产者[EventProducers]结束生产数据!!!!"); } } <file_sep>import com.google.common.cache.*; import java.util.concurrent.TimeUnit; /** * @author zhangtao * @Title: GuavaCacheDemo1 * @Package: PACKAGE_NAME * @Description: GuavaCacheDemo1[加载方式一] * @date 2020-12-21 20:36 */ public class GuavaCacheDemo1 { public static void main(String[] args) { //1- 提供缓存加载器 CacheLoader<String,String> cacheLoader = new CacheLoader<String, String>() { @Override public String load(String key) throws Exception { Thread.sleep(100); if("key".equals(key)){ return null; } System.out.println(key+" is loaded from a cacheloder!"); return key + "`s value"; } }; //2- 移除监听器 RemovalListener<String,String> removalListener=new RemovalListener<String, String>() { @Override public void onRemoval(RemovalNotification<String, String> removalNotification) { System.out.println("["+removalNotification.getKey()+":"+removalNotification.getValue()+"] is evicted!"); } }; //3- 构建loadingcache LoadingCache<String,String> loadingCache= CacheBuilder.newBuilder() //缓存容量 .maximumSize(10) //缓存失效时间 .expireAfterWrite(10, TimeUnit.MINUTES) //提供移除监听器 .removalListener(removalListener) //提供缓存加载器 .build(cacheLoader); for(int i=0;i<20;i++){ String key="key-"+i; String value="value-"+i; loadingCache.put(key,value); System.out.println("[key:"+key+" value:"+value+"] put into cache!"); } // 如果存在就获取 否则返回null System.out.println(loadingCache.getIfPresent("key")); System.out.println(loadingCache.getIfPresent("key-11")); } } <file_sep>package entity; import lombok.Builder; import lombok.Data; /** * @author zhangtao * @Title: User * @Package: entity * @Description: user entity * @date 2020-12-17 23:40 */ @Data @Builder public class User { private String name; private String sex; private int age; } <file_sep>package com.carl.quant.jyth; /** * @author zhangtao * @Title: JythConfig * @Package: com.carl.quant.jyth * @Description: JythConfig * @date 1/11/21 10:30 PM * todo */ public class JythConfig { } <file_sep>import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import service.EventProducers; /** * @author zhangtao * @Title: AppStarter * @Package: PACKAGE_NAME * @Description: AppStarter * @date 2020-12-18 00:32 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"classpath:eventbus.xml"}) public class AppStarter { @Autowired EventProducers eventProducers; @Test public void start(){ eventProducers.init(); eventProducers.post(); } } <file_sep>/** * @author zhangtao * @Title: ThreadAcid * @Package: PACKAGE_NAME * @Description: * @date 2/2/21 9:40 PM */ public class ThreadAcid { public static void main(String[] args) throws InterruptedException { final Counter counter = new Counter(); for (int i = 0; i < 6; i++) { new Thread(new Runnable() { @Override public void run() { for (int j = 0; j < 10000; j++) { counter.increament2(); } System.out.println("done....."); } }).start(); } Thread.sleep(6000L); System.out.println(counter.getI()); } } <file_sep>package com.carl.quant.jyth; import java.util.concurrent.BlockingQueue; import java.util.concurrent.SynchronousQueue; /** * @author zhangtao * @Title: MainInterpreter * @Package: com.carl.quant.jyth * @Description: 主解释器 * @date 1/11/21 10:39 PM * todo */ public final class MainInterpreter implements AutoCloseable{ private static MainInterpreter instance=null; private static PyConfig pyConfig=null; private static String[] sharedMoudlesArgv=null; private Thread thread; private BlockingQueue<String> importQueue=new SynchronousQueue<>(); private BlockingQueue<Object> importResults=new SynchronousQueue<>(); private Throwable error; /** * 单例 */ private MainInterpreter(){} /** * python解释器初始化 * @return * @throws Exception */ protected static synchronized MainInterpreter getMainInterpreter() throws Exception { if(null==instance){ try { instance=new MainInterpreter(); instance.initialize(); }catch (Exception e){ instance.close(); } }else if(null!=instance.error){ throw new Exception("python解释器前一次初始化失败!",instance.error); } return instance; } /** * python解释器初始化实现 todo */ private void initialize() { } @Override public void close() throws Exception { } } <file_sep>package server; import lombok.extern.slf4j.Slf4j; import org.apache.thrift.TException; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import thrift.UserService; /** * @author zhangtao * @Title: UserServiceImpl * @Package: server * @Description: 实现接口UserService.IFACE : thrift-server * @date 2020-12-18 22:28 */ @Slf4j @Component public class UserServiceImpl implements UserService.Iface { private final static String CARL = "carl"; @Override public String getName(int id) throws TException { log.info("received getName, id = {}:", id); return CARL; } @Override public boolean isExist(String name) throws TException { return CARL.equals(name); } @Override public String sayHello(String name) throws TException { return "Hi," + name + " welcome to thrift demo world"; } } <file_sep>import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import server.ServerStater; /** * @author zhangtao * @Title: AppStarter * @Package: PACKAGE_NAME * @Description: * @date 2020-12-18 23:15 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"classpath:thrift.xml"}) public class ServerStarter { @Autowired ServerStater serverStater; @Test public void startServer(){ serverStater.startServer(); } } <file_sep>package com.carl.quant.jyth; /** * @author zhangtao * @Title: * @Package: com.carl.quant.jyth * @Description: * @date 1/11/21 10:28 PM * todo */ public final class MemoryManager { public MemoryManager(){} } <file_sep>thrift.ip=localhost thrift.port=2345 thrift.timeout=3000 <file_sep>package com.carl.quant.jyth; /** * @author zhangtao * @Title: * @Package: com.carl.quant.jyth * @Description: * @date 1/11/21 10:41 PM * todo */ public class PyConfig { }
eaf49dc2d005f2ef8470812d075bf2ad24e3186a
[ "Markdown", "Java", "INI" ]
14
Markdown
CarlBeBetter/java-frame-study
df540fde354e47048e8088860486a658faea7d96
43b2c73f2f023a0300f96c062e0197f9a7db34bf
refs/heads/master
<file_sep>import ASUS.GPIO as GPIO import time GPIO.setwarnings(False) GPIO.setmode(GPIO.ASUS) GPIO.setup(252,GPIO.OUT) GPIO.setup(253,GPIO.OUT) GPIO.setup(164,GPIO.OUT) GPIO.setup(166,GPIO.OUT) GPIO.setup(167,GPIO.OUT) GPIO.setup(257,GPIO.OUT) GPIO.setup(256,GPIO.OUT) GPIO.setup(254,GPIO.OUT) GPIO.setup(165,GPIO.OUT) GPIO.setup(168,GPIO.OUT) GPIO.setup(238,GPIO.OUT) GPIO.setup(185,GPIO.OUT) GPIO.setup(224,GPIO.OUT) GPIO.setup(161,GPIO.OUT) GPIO.setup(160,GPIO.OUT) GPIO.setup(184,GPIO.OUT) GPIO.setup(162,GPIO.OUT) GPIO.setup(163,GPIO.OUT) GPIO.setup(171,GPIO.OUT) GPIO.setup(255,GPIO.OUT) GPIO.setup(251,GPIO.OUT) GPIO.setup(239,GPIO.OUT) GPIO.setup(223,GPIO.OUT) GPIO.setup(187,GPIO.OUT) GPIO.setup(188,GPIO.OUT) try: while True: #open led print("open led") GPIO.output(252,GPIO.HIGH) GPIO.output(253,GPIO.HIGH) GPIO.output(164,GPIO.HIGH) GPIO.output(166,GPIO.HIGH) GPIO.output(167,GPIO.HIGH) GPIO.output(257,GPIO.HIGH) GPIO.output(256,GPIO.HIGH) GPIO.output(254,GPIO.HIGH) GPIO.output(165,GPIO.HIGH) GPIO.output(168,GPIO.HIGH) GPIO.output(238,GPIO.HIGH) GPIO.output(185,GPIO.HIGH) GPIO.output(224,GPIO.HIGH) GPIO.output(161,GPIO.HIGH) GPIO.output(160,GPIO.HIGH) GPIO.output(184,GPIO.HIGH) GPIO.output(162,GPIO.HIGH) GPIO.output(163,GPIO.HIGH) GPIO.output(171,GPIO.HIGH) GPIO.output(255,GPIO.HIGH) GPIO.output(251,GPIO.HIGH) GPIO.output(239,GPIO.HIGH) GPIO.output(223,GPIO.HIGH) GPIO.output(187,GPIO.HIGH) GPIO.output(188,GPIO.HIGH) time.sleep(0.3) # 500ms # close led print("close led") GPIO.output(252,GPIO.LOW) GPIO.output(253,GPIO.LOW) GPIO.output(164,GPIO.LOW) GPIO.output(166,GPIO.LOW) GPIO.output(167,GPIO.LOW) GPIO.output(257,GPIO.LOW) GPIO.output(256,GPIO.LOW) GPIO.output(254,GPIO.LOW) GPIO.output(165,GPIO.LOW) GPIO.output(168,GPIO.LOW) GPIO.output(238,GPIO.LOW) GPIO.output(185,GPIO.LOW) GPIO.output(224,GPIO.LOW) GPIO.output(161,GPIO.LOW) GPIO.output(160,GPIO.LOW) GPIO.output(184,GPIO.LOW) GPIO.output(162,GPIO.LOW) GPIO.output(163,GPIO.LOW) GPIO.output(171,GPIO.LOW) GPIO.output(255,GPIO.LOW) GPIO.output(251,GPIO.LOW) GPIO.output(239,GPIO.LOW) GPIO.output(223,GPIO.LOW) GPIO.output(187,GPIO.LOW) GPIO.output(188,GPIO.LOW) time.sleep(0.3) # 500ms except KeyboardInterrupt: GPIO.cleanup()
7125980d50c3ed160c923659eee94a9c02b12a6e
[ "Python" ]
1
Python
sperinck/hello-world
57b104165372717f98871c4886e31bb2ac170133
7b3e4983183e147ebead33cc142122ee6126f282
refs/heads/master
<file_sep>'use strict'; if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) { $('html').addClass('ismobile') } $(document).ready(function() { function scrollBar(selector, theme, mousewheelaxis) { $(selector).mCustomScrollbar({ theme: theme, scrollInertia: 100, axis: 'yx', mouseWheel: { enable: false, axis: mousewheelaxis, preventDefault: false } }) } if (!$('html').hasClass('ismobile')) { if ($('.c-overflow')[0]) { scrollBar('.c-overflow', 'minimal-dark', 'y') } } if ($('.navigation__sub')[0]) { $('body').on('click', '.navigation__sub > a', function(e) { e.preventDefault(); $(this).closest('.navigation__sub').toggleClass('navigation__sub--toggled'); $(this).parent().find('ul').stop().slideToggle(250) }) } if ($('.top-search')[0]) { $('body').on('focus', '.top-search__input', function() { $('.top-search').addClass('top-search--focused') }); $('body').on('click', '.top-menu__trigger > a', function(e) { e.preventDefault(); $('.top-search').addClass('top-search--focused'); $('.top-search__input').focus() }); $('body').on('click', '.top-search__reset', function() { $('.top-search').removeClass('top-search--focused '); $('.top-search__input').val('') }); $('body').on('blur', '.top-search__input', function() { var x = $(this).val(); if (!x.length > 0) { $('.top-search').removeClass('top-search--focused') } }) } if ($('.collapse')[0]) { $('.collapse').on('show.bs.collapse', function(e) { $(this).closest('.panel').find('.panel-heading').addClass('active') }); $('.collapse').on('hide.bs.collapse', function(e) { $(this).closest('.panel').find('.panel-heading').removeClass('active') }); $('https://download.pixelexperience.org/js/inc/.collapse.in').each(function() { $(this).closest('.panel').find('.panel-heading').addClass('active') }) } if ($('html').hasClass('ie9')) { $('input, textarea').placeholder({ customClass: 'ie9-placeholder' }) } var $body = $('body'); var $this = $(this); var target; $body.on('click', '[data-mae-action]', function(e) { var action = $(this).data('mae-action'); e.preventDefault(); switch (action) { case 'block-open': target = $(this).data('mae-target'); $(target).addClass('toggled'); $body.addClass('block-opened'); $body.append('<div data-mae-action="block-close" data-mae-target="' + target + '" class="mae-backdrop mae-backdrop--sidebar" />') break; case 'block-close': $(target).removeClass('toggled'); $body.removeClass('block-opened'); $('.mae-backdrop--sidebar').remove(); break; case 'open-download-modal': var modal_id = $(this).data('modal-id'); $("#" + modal_id).modal('show'); break; case 'download': var modal_id = $(this).data('modal-id'); $("#" + modal_id).modal('hide'); var file_uid = $(this).data('file-uid'); var file_name = $(this).data('file-name'); var device_codename = $(this).data('device-codename'); startDownload(file_uid, file_name, device_codename); break } }) }); function startDownload(file_uid, file_name, device_codename) { $.ajax({url: "/download/" + file_uid, success: function(result){ if (result == "1"){ result = "https://downloads.sourceforge.net/project/pixelexperience/" + device_codename + "/" + file_name + "?r=&ts=" + Math.floor(Date.now() / 1000); }else{ result = "https://get.pixelexperience.org/get_file/" + result + "/"; } var link = document.createElement('a'); link.href = result; link.rel = "noopener noreferrer"; document.body.appendChild(link); link.click(); showSuccessDownload(file_uid, file_name, device_codename); }, error: function(result){ location.reload(); }}); swal({ icon: "info", text: "Contacting server...", closeOnClickOutside: true, closeOnEsc: true }); $(".swal-icon").replaceWith("<div style='padding:50px;'><div class='preloader preloader--xl preloader--light'><svg viewBox='25 25 50 50'><circle cx='50' cy='50' r='20'></circle></svg></div></div>"); $(".swal-text").html("<center>Contacting server...<br><br><a href=\"https://www.packet.com/\" target=\"_blank\"><img src=\"https://aosiprom.com/img/packet.png\" alt=\"\"><br><i style=\"color:#384c63\"></a>Hosted on <a href=\"https://www.packet.com/\" target=\"_blank\">Packet.com</a> - Cloud &amp; Edge Computing Infrastructure Provider</i></center>"); $(".swal-button-container").remove(); } function showSuccessDownload(file_uid, file_name, device_codename) { swal({ icon: "success", title: "Download started", text: "Your download should already have started", closeOnClickOutside: true, closeOnEsc: true, buttons: { retry: { text: "Not started? Try again", value: "retry", }, confirm: true } }).then((value) => { if (value == "retry") { window.location.href = "https://download.pixelexperience.org/changelog/" + device_codename + "/" + file_name + "/" } }); } function getSearchHints(hints) { var result = []; for (var i = 0; i < hints.length; i++) { result.push(hints[i].text) } return result } function getCodenameByHint(hints, hint) { for (var i = 0; i < hints.length; i++) { if (hints[i].text == hint) { return hints[i].codename } } return "" }
c34d82180238e67b8641a4a8435e6be6ee8ef37c
[ "JavaScript" ]
1
JavaScript
OwO-Studio/Pr0j3c1X.github.io
73abe1abd2718cfea1d0a6e1d5c88ab724104cab
0e6ab508a87ee6640b3a4f23a7fa35273947d360
refs/heads/master
<repo_name>bastelbjoern/JLD505<file_sep>/JLD505.ino #include <SPI.h> #include <Wire.h> #include <EEPROM.h> #include <mcp_can.h> #include <INA226.h> #include <EEPROMAnything.h> #include <SoftwareSerial.h> #include <AltSoftSerial.h> #include <DS2480B.h> #include <DallasTemperature.h> #include <FrequencyTimer2.h> /* Notes on what needs to be done: - Timing analysis showed that the USB, CANBUS, and BT routines take up entirely too much time. They can delay processing by almost 100ms! */ //#define DEBUG_TIMING //if this is defined you'll get time related debugging messages SoftwareSerial BTSerial(A2, A3); // RX | TX AltSoftSerial altSerial; //pins 8 and 9 DS2480B ds(altSerial); DallasTemperature sensors(&ds); //These have been moved to eeprom. After initial compile the values will be read from EEPROM. //These thus set the default value to write to eeprom upon first start up #define MAX_CHARGE_V 180 #define MAX_CHARGE_A 120 #define TARGET_CHARGE_V 170 #define MIN_CHARGE_A 10 //set the proper digital pins for these #define IN0 4 #define IN1 7 #define OUT0 5 #define OUT1 6 INA226 ina; const unsigned long Interval = 10; unsigned long Time = 0; unsigned long PreviousMillis = 0; unsigned long CurrentMillis = 0; float Voltage = 0; float Current = 0; float Power = 0; int Count = 0; byte Command = 0; // "z" will reset the AmpHours and KiloWattHours counters volatile uint8_t bStartConversion = 0; volatile uint8_t bGetTemperature = 0; volatile uint8_t timerIntCounter = 0; volatile uint8_t timerFastCounter = 0; volatile uint8_t sensorReadPosition = 255; uint8_t tempSensorCount = 0; int32_t canMsgID = 0; unsigned char canMsg[8]; unsigned char Flag_Recv = 0; volatile uint8_t debugTick = 0; typedef struct { uint8_t valid; //a token to store EEPROM version and validity. If it matches expected value then EEPROM is not reset to defaults float ampHours; float kiloWattHours; float packSizeKWH; float voltageCalibration; float currentCalibration; uint16_t maxChargeVoltage; uint16_t targetChargeVoltage; uint8_t maxChargeAmperage; uint8_t minChargeAmperage; } EESettings; EESettings settings; #define EEPROM_VALID 0xDE //Bunch o' chademo related stuff. uint8_t bStartedCharge = 0; //we have started a charge since the plug was inserted. Prevents attempts to restart charging if it stopped previously uint8_t bChademoMode = 0; //accessed but not modified in ISR so it should be OK non-volatile uint8_t bChademoSendRequests = 0; //should we be sending periodic status updates? volatile uint8_t bChademoRequest = 0; //is it time to send one of those updates? //target values are what we send with periodic frames and can be changed. uint8_t askingAmps = 0; //how many amps to ask for. Trends toward targetAmperage uint8_t bListenEVSEStatus = 0; //should we pay attention to stop requests and such yet? uint8_t bDoMismatchChecks = 0; //should we be checking for voltage and current mismatches? uint32_t mismatchStart; uint32_t stateMilli; uint32_t insertionTime = 0; enum CHADEMOSTATE { STARTUP, SEND_INITIAL_PARAMS, WAIT_FOR_EVSE_PARAMS, SET_CHARGE_BEGIN, WAIT_FOR_BEGIN_CONFIRMATION, CLOSE_CONTACTORS, RUNNING, CEASE_CURRENT, WAIT_FOR_ZERO_CURRENT, OPEN_CONTACTOR, FAULTED, STOPPED, LIMBO }; CHADEMOSTATE chademoState = STOPPED; CHADEMOSTATE stateHolder = STOPPED; typedef struct { uint8_t supportWeldCheck; uint16_t availVoltage; uint8_t availCurrent; uint16_t thresholdVoltage; //evse calculates this. It is the voltage at which it'll abort charging to save the battery pack in case we asked for something stupid } EVSE_PARAMS; EVSE_PARAMS evse_params; typedef struct { uint16_t presentVoltage; uint8_t presentCurrent; uint8_t status; uint16_t remainingChargeSeconds; } EVSE_STATUS; EVSE_STATUS evse_status; typedef struct { uint16_t targetVoltage; //what voltage we want the EVSE to put out uint8_t targetCurrent; //what current we'd like the EVSE to provide uint8_t remainingKWH; //report # of KWh in the battery pack (charge level) uint8_t battOverVolt : 1; //we signal that battery or a cell is too high of a voltage uint8_t battUnderVolt : 1; //we signal that battery is too low uint8_t currDeviation : 1; //we signal that measured current is not the same as EVSE is reporting uint8_t battOverTemp : 1; //we signal that battery is too hot uint8_t voltDeviation : 1; //we signal that we measure a different voltage than EVSE reports uint8_t chargingEnabled : 1; //ask EVSE to enable charging uint8_t notParked : 1; //advise EVSE that we're not in park. uint8_t chargingFault : 1; //signal EVSE that we found a fault uint8_t contactorOpen : 1; //tell EVSE whether we've closed the charging contactor uint8_t stopRequest : 1; //request that the charger cease operation before we really get going } CARSIDE_STATUS; CARSIDE_STATUS carStatus; //The IDs for chademo comm - both carside and EVSE side so we know what to listen for //as well. #define CARSIDE_BATT 0x100 #define CARSIDE_CHARGETIME 0x101 #define CARSIDE_CONTROL 0x102 #define EVSE_PARAMS 0x108 #define EVSE_STATUS 0x109 #define CARSIDE_FAULT_OVERV 1 //over voltage #define CARSIDE_FAULT_UNDERV 2 //Under voltage #define CARSIDE_FAULT_CURR 4 //current mismatch #define CARSIDE_FAULT_OVERT 8 //over temperature #define CARSIDE_FAULT_VOLTM 16 //voltage mismatch #define CARSIDE_STATUS_CHARGE 1 //charging enabled #define CARSIDE_STATUS_NOTPARK 2 //shifter not in safe state #define CARSIDE_STATUS_MALFUN 4 //vehicle did something dumb #define CARSIDE_STATUS_CONTOP 8 //main contactor open #define CARSIDE_STATUS_CHSTOP 16 //charger stop before even charging #define EVSE_STATUS_CHARGE 1 //charger is active #define EVSE_STATUS_ERR 2 //something went wrong #define EVSE_STATUS_CONNLOCK 4 //connector is currently locked #define EVSE_STATUS_INCOMPAT 8 //parameters between vehicle and charger not compatible #define EVSE_STATUS_BATTERR 16 //something wrong with battery?! #define EVSE_STATUS_STOPPED 32 //charger is stopped void MCP2515_ISR() { Flag_Recv = 1; } void timer2Int() { timerFastCounter++; if (timerFastCounter == 8) { debugTick = 1; if (bChademoMode && bChademoSendRequests) bChademoRequest = 1; timerFastCounter = 0; timerIntCounter++; if (timerIntCounter < 10) { bGetTemperature = 1; sensorReadPosition++; } if (timerIntCounter == 10) { bStartConversion = 1; sensorReadPosition = 255; } if (timerIntCounter == 18) { timerIntCounter = 0; } } } //will wait delayTime milliseconds and then transition to new state. Sets state to LIMBO in the meantime void chademoDelayedState(int newstate, uint16_t delayTime) { chademoState = LIMBO; stateHolder = (CHADEMOSTATE)newstate; stateMilli = millis() + delayTime; } void setup() { //first thing configure the I/O pins and set them to a sane state pinMode(IN0, INPUT); pinMode(IN1, INPUT); pinMode(OUT0, OUTPUT); pinMode(OUT1, OUTPUT); digitalWrite(OUT0, LOW); digitalWrite(OUT1, LOW); pinMode(A1, OUTPUT); //KEY - Must be HIGH pinMode(A0, INPUT); //STATE digitalWrite(A1, HIGH); pinMode(3, INPUT_PULLUP); //enable weak pull up on MCP2515 int pin connected to INT1 on MCU Serial.begin(115200); BTSerial.begin(115200); altSerial.begin(9600); sensors.begin(); sensors.setWaitForConversion(false); //we're handling the time delay ourselves so no need to wait when asking for temperatures CAN.begin(CAN_500KBPS); attachInterrupt(1, MCP2515_ISR, FALLING); // start interrupt ina.begin(69); ina.configure(INA226_AVERAGES_16, INA226_BUS_CONV_TIME_1100US, INA226_SHUNT_CONV_TIME_1100US, INA226_MODE_SHUNT_BUS_CONT); EEPROM_readAnything(0, settings); if (settings.valid != EEPROM_VALID) //not proper version so reset to defaults { settings.valid = EEPROM_VALID; settings.ampHours = 0.0; settings.kiloWattHours = 0.0; settings.currentCalibration = 300.0/0.075; //800A 75mv shunt settings.voltageCalibration = (100000.0*830000.0/930000.0+1000000.0)/(100275.0*830000.0/930000.0); // (Voltage Divider with (100k in parallel with 830k) and 1M ) settings.packSizeKWH = 15.0; //just a random guess. Maybe it should default to zero though? settings.maxChargeAmperage = MAX_CHARGE_A; settings.maxChargeVoltage = MAX_CHARGE_V; settings.targetChargeVoltage = TARGET_CHARGE_V; settings.minChargeAmperage = MIN_CHARGE_A; EEPROM_writeAnything(0, settings); } attachInterrupt(0, Save, FALLING); FrequencyTimer2::setPeriod(25000); //interrupt every 25ms FrequencyTimer2::setOnOverflow(timer2Int); Serial.print(F("Found ")); tempSensorCount = sensors.getDeviceCount(); Serial.print(tempSensorCount); Serial.println(F(" temperature sensors.")); carStatus.targetCurrent = settings.maxChargeAmperage; carStatus.targetVoltage = settings.targetChargeVoltage; carStatus.contactorOpen = 1; } void loop() { uint8_t pos; CurrentMillis = millis(); uint8_t len; #ifdef DEBUG_TIMING if (debugTick == 1) { debugTick = 0; Serial.println(millis()); } #endif if(CurrentMillis - PreviousMillis >= Interval) { Time = CurrentMillis - PreviousMillis; PreviousMillis = CurrentMillis; if (!bDoMismatchChecks && chademoState == RUNNING) { if (CurrentMillis > mismatchStart) bDoMismatchChecks = 1; } if (chademoState == LIMBO && CurrentMillis > stateMilli) { chademoState = stateHolder; } Count++; Voltage = ina.readBusVoltage() * settings.voltageCalibration; Current = ina.readShuntVoltage() * settings.currentCalibration; settings.ampHours += Current * (float)Time / 1000.0 / 3600.0; Power = Voltage * Current / 1000.0; settings.kiloWattHours += Power * (float)Time / 1000.0 / 3600.0; if (chademoState == RUNNING && bDoMismatchChecks) { if (abs(Voltage - evse_status.presentVoltage) > 7 && !carStatus.voltDeviation) { Serial.println(F("Voltage mismatch! Aborting!")); carStatus.voltDeviation = 1; chademoState = CEASE_CURRENT; } if (abs(Current - evse_status.presentCurrent) > 7 && !carStatus.currDeviation) { Serial.println(F("Current mismatch! Aborting!")); carStatus.currDeviation = 1; chademoState = CEASE_CURRENT; } if (Voltage > settings.maxChargeVoltage) { Serial.println(F("Over voltage fault!")); carStatus.battOverVolt = 1; chademoState = CEASE_CURRENT; } //Constant Current/Constant Voltage Taper checks. If minimum current is set to zero, we terminate once target voltage is reached. //If not zero, we will adjust current up or down as needed to maintain voltage until current decreases to the minimum entered if(Count==20) //To allow batteries time to react, we only do this once in 50 counts { if (Voltage > settings.targetChargeVoltage-1) //All initializations complete and we're running.We've reached charging target { if (settings.minChargeAmperage = 0 || carStatus.targetCurrent < settings.minChargeAmperage) chademoState = CEASE_CURRENT; //Terminate charging else carStatus.targetCurrent--; //Taper. Actual decrease occurs in sendChademoStatus } else //Only adjust upward if we have previous adjusted downward and do not exceed max amps { if (carStatus.targetCurrent < settings.maxChargeAmperage)carStatus.targetCurrent++; } } } //if (!bChademoMode) //{ if (Count >= 50) { Count = 0; USB(); if (!bChademoMode) //save some processor time by not doing these in chademo mode { CANBUS(); BT(); } else { Serial.print(F("Chademo Mode: ")); Serial.println(chademoState); } Save(); } //} } if (Flag_Recv || CAN.checkReceive() == CAN_MSGAVAIL) { Flag_Recv = 0; CAN.readMsgBuf(&len, canMsg); // read data, len: data length, buf: data buf canMsgID = CAN.getCanId(); if (canMsgID == EVSE_PARAMS) { if (chademoState == WAIT_FOR_EVSE_PARAMS) chademoDelayedState(SET_CHARGE_BEGIN, 100); evse_params.supportWeldCheck = canMsg[0]; evse_params.availVoltage = canMsg[1] + canMsg[2] * 256; evse_params.availCurrent = canMsg[3]; evse_params.thresholdVoltage = canMsg[4] + canMsg[5] * 256; //if charger cannot provide our requested voltage then GTFO if (evse_params.availVoltage < carStatus.targetVoltage) { Serial.println(F("EVSE can't provide needed voltage. Aborting.")); Serial.println(evse_params.availVoltage); chademoState = CEASE_CURRENT; } //if we want more current then it can provide then revise our request to match max output if (evse_params.availCurrent < carStatus.targetCurrent) carStatus.targetCurrent = evse_params.availCurrent; } if (canMsgID == EVSE_STATUS) { evse_status.presentVoltage = canMsg[1] + 256 * canMsg[2]; evse_status.presentCurrent = canMsg[3]; evse_status.status = canMsg[5]; if (canMsg[6] < 0xFF) { evse_status.remainingChargeSeconds = canMsg[6] * 10; } else { evse_status.remainingChargeSeconds = canMsg[7] * 60; } //on fault try to turn off current immediately and cease operation if ((evse_status.status & 0x1A) != 0) //if bits 1, 3, or 4 are set then we have a problem. { Serial.println(F("EVSE reports fault. Aborting.")); if (chademoState == RUNNING) chademoState = CEASE_CURRENT; } if (chademoState == RUNNING) { if (bListenEVSEStatus) { if ((evse_status.status & EVSE_STATUS_STOPPED) != 0) { Serial.println(F("EVSE requests we stop charging.")); chademoState = CEASE_CURRENT; } //if there is no remaining time then gracefully shut down if (evse_status.remainingChargeSeconds == 0) { Serial.println(F("EVSE reports time elapsed. Finishing.")); chademoState = CEASE_CURRENT; } } else { //if charger is not reporting being stopped and is reporting remaining time then enable the checks. if ((evse_status.status & EVSE_STATUS_STOPPED) == 0 && evse_status.remainingChargeSeconds > 0) bListenEVSEStatus = 1; } } } } if (bStartConversion == 1) { bStartConversion = 0; sensors.requestTemperatures(); } if (bGetTemperature) { bGetTemperature = 0; pos = sensorReadPosition; if (pos < tempSensorCount) { Serial.print(pos); Serial.print(": "); //sensors.isConnected(pos); // Serial.println(sensors.getCelsius(pos)); Serial.println(sensors.getTempCByIndex(pos)); } } if (!digitalRead(IN1)) //IN1 goes low if we have been plugged into the chademo port { if (insertionTime == 0) { insertionTime = millis(); } else if (millis() > insertionTime + 500) { if (bChademoMode == 0) { bChademoMode = 1; if (chademoState == STOPPED && !bStartedCharge) { chademoState = STARTUP; Serial.println(F("Starting Chademo process.")); carStatus.battOverTemp = 0; carStatus.battOverVolt = 0; carStatus.battUnderVolt = 0; carStatus.chargingFault = 0; carStatus.chargingEnabled = 0; carStatus.contactorOpen = 1; carStatus.currDeviation = 0; carStatus.notParked = 0; carStatus.stopRequest = 0; carStatus.voltDeviation = 0; } } } } else { insertionTime = 0; if (bChademoMode == 1) { Serial.println(F("Stopping chademo process.")); bChademoMode = 0; bStartedCharge = 0; chademoState = STOPPED; //maybe it would be a good idea to try to see if EVSE is still transmitting to us and providing current //as it is not a good idea to open the contactors under load. But, IN1 shouldn't trigger //until the EVSE is ready. Also, the EVSE should have us locked so the only way the plug should come out under //load is if the idiot driver took off in the car. Bad move moron. digitalWrite(OUT0, LOW); digitalWrite(OUT1, LOW); } } if (bChademoMode) { if (bChademoSendRequests && bChademoRequest) { bChademoRequest = 0; sendChademoStatus(); sendChademoBattSpecs(); sendChademoChargingTime(); //Serial.println("Tx"); } switch (chademoState) { case STARTUP: //really useful state huh? chademoDelayedState(SEND_INITIAL_PARAMS, 100); break; case SEND_INITIAL_PARAMS: //we could do calculations to see how long the charge should take based on SOC and //also set a more realistic starting amperage. Options for the future. //One problem with that is that we don't yet know the EVSE parameters so we can't know //the max allowable amperage just yet. bChademoSendRequests = 1; //causes chademo frames to be sent out every 100ms chademoDelayedState(WAIT_FOR_EVSE_PARAMS, 100); Serial.println(F("Sent parameters to EVSE. Waiting.")); break; case WAIT_FOR_EVSE_PARAMS: //for now do nothing while we wait. Might want to try to resend start up messages periodically if no reply break; case SET_CHARGE_BEGIN: Serial.println(F("Setting begin charge request.")); digitalWrite(OUT1, HIGH); //signal that we're ready to charge //carStatus.chargingEnabled = 1; //should this be enabled here??? chademoDelayedState(WAIT_FOR_BEGIN_CONFIRMATION, 150); break; case WAIT_FOR_BEGIN_CONFIRMATION: if (digitalRead(IN0)) //inverse logic from how IN1 works. Be careful! { chademoDelayedState(CLOSE_CONTACTORS, 100); } break; case CLOSE_CONTACTORS: Serial.println(F("Closing contactor")); digitalWrite(OUT0, HIGH); chademoDelayedState(RUNNING, 150); carStatus.contactorOpen = 0; //its closed now carStatus.chargingEnabled = 1; //please sir, I'd like some charge bStartedCharge = 1; mismatchStart = millis() + 10000; //start mismatch checks 10 seconds after we start the charge break; case RUNNING: //do processing here by taking our measured voltage, amperage, and SOC to see if we should be commanding something //different to the EVSE. Also monitor temperatures to make sure we're not incinerating the pack. break; case CEASE_CURRENT: Serial.println(F("Setting current request to zero.")); carStatus.targetCurrent = 0; chademoState = WAIT_FOR_ZERO_CURRENT; break; case WAIT_FOR_ZERO_CURRENT: if (evse_status.presentCurrent == 0) { chademoDelayedState(OPEN_CONTACTOR, 150); } break; case OPEN_CONTACTOR: Serial.println(F("Opening contactor")); digitalWrite(OUT0, LOW); carStatus.contactorOpen = 1; carStatus.chargingEnabled = 0; sendChademoStatus(); //we probably need to force this right now chademoDelayedState(STOPPED, 100); break; case FAULTED: Serial.println(F("Detected fault!")); chademoState = CEASE_CURRENT; //digitalWrite(OUT0, LOW); //digitalWrite(OUT1, LOW); break; case STOPPED: digitalWrite(OUT0, LOW); digitalWrite(OUT1, LOW); bChademoSendRequests = 0; //don't need to keep sending anymore. break; } } } void Save() { EEPROM_writeAnything(0, settings); } void USB() { Serial.print (Voltage, 3); Serial.print ("V "); Serial.print (Current, 2); Serial.print ("A "); Serial.print (settings.ampHours, 1); Serial.print ("Ah "); Serial.print (Power, 1); Serial.print ("kW "); Serial.print (settings.kiloWattHours, 1); Serial.println ("kWh"); if (Serial.available() > 0) {Command = Serial.read(); if (Command == 'z') { Serial.println("Reset Ah & Wh"); settings.ampHours = 0.0; settings.kiloWattHours = 0.0; Serial.println("Done!!!"); } if (Command == '+') { settings.voltageCalibration +=0.004; Serial.println (settings.voltageCalibration, 5); } if (Command == '-') { settings.voltageCalibration -=0.004; Serial.println (settings.voltageCalibration, 5); } while(Serial.available()>0) Serial.read();} } void BT() { BTSerial.print (Voltage, 2); BTSerial.print ("V "); BTSerial.print (Current, 2); BTSerial.print ("A "); BTSerial.print (settings.ampHours, 1); BTSerial.print ("Ah "); BTSerial.print (Power, 1); BTSerial.print ("kW "); BTSerial.print (settings.kiloWattHours, 1); BTSerial.println ("kWh"); /* BTSerial.write(02); BTSerial.write(highByte((int)(Voltage*10))); BTSerial.write(lowByte((int)(Voltage*10))); BTSerial.write(highByte((int)(Current*10))); BTSerial.write(lowByte((int)(Current*10))); BTSerial.write(highByte((int)(AmpHours*10))); BTSerial.write(lowByte((int)(AmpHours*10))); BTSerial.write(highByte((int)(Power*10))); BTSerial.write(lowByte((int)(Power*10))); BTSerial.write(highByte((int)(KiloWattHours*10))); BTSerial.write(lowByte((int)(KiloWattHours*10))); BTSerial.write(03);*/ if (BTSerial.available() > 0) { Command = BTSerial.read(); if (Command == 'z') { settings.ampHours = 0.0; settings.kiloWattHours = 0.0; } while(BTSerial.available()>0) BTSerial.read(); } } void CANBUS() { canMsgID = 0x404; canMsg[0] = highByte((int)(Voltage * 10)); // Voltage High Byte canMsg[1] = lowByte((int)(Voltage * 10)); // Voltage Low Byte canMsg[2] = highByte((int)(Current * 10)); // Current High Byte canMsg[3] = lowByte((int)(Current * 10)); // Current Low Byte canMsg[4] = highByte((int)(settings.ampHours * 10)); // AmpHours High Byte canMsg[5] = lowByte((int)(settings.ampHours * 10)); // AmpHours Low Byte canMsg[6] = 0x00; // Not Used canMsg[7] = 0x00; // Not Used CAN.sendMsgBuf(canMsgID, 0, 6, canMsg); canMsgID = 0x505; canMsg[0] = highByte((int)(Power * 10)); // Power High Byte canMsg[1] = lowByte((int)(Power * 10)); // Power Low Byte canMsg[2] = highByte((int)(settings.kiloWattHours * 10)); // KiloWattHours High Byte canMsg[3] = lowByte((int)(settings.kiloWattHours * 10)); // KiloWattHours Low Byte canMsg[4] = 0x00; // Not Used canMsg[5] = 0x00; // Not Used canMsg[6] = 0x00; // Not Used canMsg[7] = 0x00; // Not Used CAN.sendMsgBuf(canMsgID, 0, 4, canMsg); } void sendChademoBattSpecs() { canMsgID = CARSIDE_BATT; canMsg[0] = 0x00; // Not Used canMsg[1] = 0x00; // Not Used canMsg[2] = 0x00; // Not Used canMsg[3] = 0x00; // Not Used canMsg[4] = lowByte(settings.maxChargeVoltage); canMsg[5] = highByte(settings.maxChargeVoltage); canMsg[6] = (uint8_t)settings.packSizeKWH; canMsg[7] = 0; //not used CAN.sendMsgBuf(canMsgID, 0, 8, canMsg); } void sendChademoChargingTime() { canMsgID = CARSIDE_CHARGETIME; canMsg[0] = 0x00; // Not Used canMsg[1] = 0xFF; //not using 10 second increment mode canMsg[2] = 90; //ask for how long of a charge? It will be forceably stopped if we hit this time canMsg[3] = 60; //how long we think the charge will actually take canMsg[4] = 0; //not used canMsg[5] = 0; //not used canMsg[6] = 0; //not used canMsg[7] = 0; //not used CAN.sendMsgBuf(canMsgID, 0, 8, canMsg); } void sendChademoStatus() { uint8_t faults = 0; uint8_t status = 0; if (carStatus.battOverTemp) faults |= CARSIDE_FAULT_OVERT; if (carStatus.battOverVolt) faults |= CARSIDE_FAULT_OVERV; if (carStatus.battUnderVolt) faults |= CARSIDE_FAULT_UNDERV; if (carStatus.currDeviation) faults |= CARSIDE_FAULT_CURR; if (carStatus.voltDeviation) faults |= CARSIDE_FAULT_VOLTM; if (carStatus.chargingEnabled) status |= CARSIDE_STATUS_CHARGE; if (carStatus.notParked) status |= CARSIDE_STATUS_NOTPARK; if (carStatus.chargingFault) status |= CARSIDE_STATUS_MALFUN; if (carStatus.contactorOpen) status |= CARSIDE_STATUS_CONTOP; if (carStatus.stopRequest) status |= CARSIDE_STATUS_CHSTOP; canMsgID = CARSIDE_CONTROL; canMsg[0] = 2; //tell EVSE we are talking 1.0 protocol canMsg[1] = lowByte(carStatus.targetVoltage); canMsg[2] = highByte(carStatus.targetVoltage); canMsg[3] = askingAmps; canMsg[4] = faults; canMsg[5] = status; canMsg[6] = (uint8_t)settings.kiloWattHours; canMsg[7] = 0; //not used CAN.sendMsgBuf(canMsgID, 0, 8, canMsg); if (chademoState == RUNNING && askingAmps < carStatus.targetCurrent) askingAmps++; //not a typo. We're allowed to change requested amps by +/- 20A per second. We send the above frame every 100ms so a single //increment means we can ramp up 10A per second. But, we want to ramp down quickly if there is a problem so do two which //gives us -20A per second. if (chademoState != RUNNING && askingAmps > 0) askingAmps--; if (askingAmps > carStatus.targetCurrent) askingAmps--; if (askingAmps > carStatus.targetCurrent) askingAmps--; }
3eaa022e908aca76722df71e19b660f3fcbdcc15
[ "C++" ]
1
C++
bastelbjoern/JLD505
68ff1ba703a934071bd1a89fe5be0b01ddd0cfbf
7f329a8da8374c7b47741b35b29ce5a93ffc8bf7
refs/heads/master
<file_sep>var Listener = require('./Workers/listener') prompts = { alreadyInGame: 'You already in game', whoIsInterested: 'Who is interested?', noFreeRecorders: 'Sorry, no free recorders', askRate: 'You just finished playing. How would you rate your experience: 1 (bad) - 5 (great)?', askFeedback: 'Do you have any feedback (optional):', finishPlaying: 'Thank you for playing', textConnect: 'Greetings! Type /next to start', noMoreQuestions: 'Game is over! Type /finish or exit from voice channel' } process.on('unhandledRejection', ex => { console.log('Unhandled promise rejection', ex) }) process.on('uncaughtException', ex => { console.log('Uncaught exception', ex) }) config = require('./config.json') var listener = new Listener(config.general_token, config.recorders_tokens)<file_sep>const Discord = require('discord.js') const Recorder = require('./recorder') const fs = require('fs') module.exports = class Listener { isReadyToStartGame (msg) { if (this.alreadyPlay.includes(msg.author.id)) { msg.channel.send(prompts.alreadyInGame) return false } if (this.unusedToken.length == 0) { msg.channel.send(prompts.noFreeRecorders) return false } try { this.guildId = msg.guild.id } catch (error) { console.log('/startgame was sent to DM') return false } return true } startGame (msg) { if (!this.isReadyToStartGame(msg)) { return false } if (this.interestedState == 0) { msg.channel.send(prompts.whoIsInterested) this.interestedState = 1 this.firstPlayer = msg.author this.firstMember = msg.member this.alreadyPlay.push(msg.author.id) return true } else { this.interestedState = 0 this.secondPlayer = msg.author this.secondMember = msg.member this.alreadyPlay.push(msg.author.id) let recorder = new Recorder() recorder.startRecord( this.unusedToken.pop(), this.firstPlayer.id, this.secondPlayer.id, this.guildId, inputData => this.askQuestions(inputData) ) } } constructor (botToken, additionalTokens) { this.token = botToken this.client = new Discord.Client() this.alreadyPlay = [] this.unusedToken = additionalTokens this.interestedState = 0 this.client.login(this.token) this.client.on('ready', () => { console.log('Listener ready') }) this.client.on('message', msg => { if (msg.content.startsWith(config.prefix + 'startgame')) { this.startGame(msg) } }) } askUser (player, inputData) { var dirname = inputData.dir var waitTime = 60000 var member = this.client.guilds .resolve(this.guildId) .members.resolve(player) this.alreadyPlay.splice(this.alreadyPlay.indexOf(player.id), 1) var playerRate, playerFeedback member.createDM().then(dmChannel => { dmChannel.send(prompts.askRate).then(msg => { const filter = msg => { if (Number(msg.content)) { if (1 <= Number(msg.content) <= 5) { playerRate = msg.content return true } else { return false } } else { return false } } dmChannel .awaitMessages(filter, { max: 1, time: waitTime, errors: ['time'] }) .then(collected => dmChannel.send(prompts.askFeedback).then(msg => { const filter = msg => { playerFeedback = msg.content return true } dmChannel .awaitMessages(filter, { max: 1, time: waitTime, errors: ['time'] }) .finally(() => { dmChannel.send(prompts.finishPlaying) fs.appendFileSync( dirname + '/rate.csv', player.tag + ',' + playerRate + '\n' ) fs.appendFileSync( dirname + '/feedback.csv', player.tag + ',' + playerFeedback + '\n' ) }) }) ) .catch(collected => { dmChannel.send(prompts.finishPlaying) }) }) }) } askQuestions (inputData) { //console.log(inputData) this.unusedToken.push(inputData.token) this.askUser(inputData.firstP, inputData) this.askUser(inputData.secondP, inputData) } }
89ea22d93794626f300e19fb5bc92ae12b529b6c
[ "JavaScript" ]
2
JavaScript
zombie9988/discordownbot
b0646a59208d06b26bf6f64a21826bb7e08ccfd8
c5d7632f34659e0662e1e49f95b8a164026fac71
refs/heads/master
<file_sep>const {Builder, By, Key, until} = require('selenium-webdriver'); const dotenv = require('dotenv'); dotenv.config(); (async function example() { let driver = await new Builder().forBrowser('chrome').build(); try { await driver.get('https://www.researchgate.net/login'); await driver.findElement(By.name('login')).sendKeys(process.env.EMAIL); await driver.findElement(By.name('password')).sendKeys(process.env.PASSWORD, Key.RETURN); await driver.wait(until.titleIs('Home Feed | ResearchGate'), 1000); await driver.findElement(By.className('content-creation-button')).click(); // await driver.wait(1000); // await driver.findElement(By.className('global-sidebar__level-1-item')).click(); } finally { await driver.quit(); } })();
23de238bbacae368b4592ee6781bc810fb066374
[ "JavaScript" ]
1
JavaScript
jnkindi/scrap-researchgate
f33edb6bb192463eb162e2d4fef5260a844c5444
e8393a27326a3d3cf42ad49adc4572bf5f78e085
refs/heads/master
<repo_name>jarvi652/Etch-a-sketch<file_sep>/script.js const start = document.querySelector('#start') const reset = document.querySelector('#reset') const container=document.querySelector('.container') function createGrid(size){ totalSquares = size * size for(let i =0; i < totalSquares; i++){ const newbox = document.createElement('div') newbox.classList.add('box') container.appendChild(newbox) newbox.addEventListener('mouseover', (e) =>{ newbox.style.backgroundColor = 'black' }) } document.documentElement.style.setProperty("--rowNum", size) document.documentElement.style.setProperty("--colNum", size) } function resetGrid(){ while (container.firstChild) { container.removeChild(container.lastChild); } } createGrid(16) start.addEventListener('click', (e)=>{ newsize = prompt('Please enter the size of the grid(max 64):') if(newsize <= 64){ createGrid(newsize) } else if (newsize > 64) { alert('limit exceded. Please Try Again:') } }) reset.addEventListener('click',(e)=>{ resetGrid() })
2479323abf2a625d74856f77a81b01ca2b92a126
[ "JavaScript" ]
1
JavaScript
jarvi652/Etch-a-sketch
78610d50b81dbf45d1223a362eb7dc349c37475c
2768bda56bb0c1babcd16440c4e3be2b08485b84
refs/heads/main
<repo_name>MOMOJMOGG/Leetcode-Practice-Library<file_sep>/Easy/0009# Palindrome Number/PalindromeNumber.c /**** Leetcode-Easy 0009# Palindrome Number *****/ /*** Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. Follow up: Could you solve it without converting the integer to a string? ***/ /*** ■ Example 1: Input: x = 121 Output: true ■ Example 2: Input: x = -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. ■ Example 3: Input: x = 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome. ■ Example 4: Input: x = -101 Output: false <<Constraints>> ■ -231 <= x <= 231 - 1 ***/ //***********************************************************************************// // Develop in C : bool isPalindrome(int x){ if (x < 0 || (x%10 == 0 && x != 0)) // exclusive edge condition return false; int revert = 0; while(x>revert) { revert = revert * 10 + x % 10; x /= 10; } return x == revert || x == revert / 10; } /*** ■ Runtime : 28 ms ■ Memory : 5.9 MB ■ Time complexity : O(log_{10}(n))We divided the input by 10 for every iteration, so the time complexity is O(log_{10}(n)). ■ Space Complexity: O(1). ***/<file_sep>/README.md "# Leetcode-Practice-Library" <file_sep>/Easy/0007# Reverse Integer/ReverseInteger.cpp /**** Leetcode-Easy 0007# Reverse Integer *****/ /*** Given a 32-bit signed integer, reverse digits of an integer. Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. ***/ /*** ■ Example 1: Input: x = 123 Output: 321 ■ Example 2: Input: x = -123 Output: -321 ■ Example 3: Input: x = 120 Output: 21 ■ Example 4: Input: x = 0 Output: 0 <<Constraints>> ■ -231 <= x <= 231 - 1 ***/ //***********************************************************************************// // Develop in C++ : class Solution { public: int reverse(int x) { // int limitation upper bound is 2147483647 int result = 0; // int limitation lower bound is -2147483647 - 1 while(x!=0) { int pop = x % 10; x /= 10; if(result > INT_MAX/10 || (result == INT_MAX/10 && pop > 7)) return 0; if(result < INT_MIN/10 || (result == INT_MIN/10 && pop < -8)) return 0; result = result * 10 + pop; } return result; } }; /*** ■ Runtime : 4 ms ■ Memory : 6.1 MB ■ Time Complexity: O(log(x)). There are roughly log_{10}(x) digits in x. ■ Space Complexity: O(1). ***/<file_sep>/Medium/0633# Sum of Square Numbers/Sum_of_SquareNumbers.c /**** Leetcode-Medium 0633# Sum of Square Numbers *****/ /*** Given a non-negative integer c, decide whether there're two integers a and b such that a2 + b2 = c. ***/ /*** ■ Example 1: Input: c = 5 Output: true Explanation: 1 * 1 + 2 * 2 = 5 ■ Example 2: Input: c = 3 Output: false ■ Example 3: Input: c = 4 Output: true ■ Example 4: Input: c = 2 Output: true ■ Example 5: Input: c = 1 Output: true <<Constraints>> ■ 0 <= c <= 231 - 1 ***/ //***********************************************************************************// // Develop in C : //!!! This is a two pointer solution. Go through the string by once.Sqrt to find the answer more efficiency. bool judgeSquareSum(int c){ long front = 0, end = sqrt(c); // use long invoiding overflow of int. while(front <= end){ long pow_sum = front*front + end*end; if(pow_sum == c) return true; else if (pow_sum > c) end--; else front++; } return false; } /*** ■ Runtime : 0 ms ■ Memory : 5.7 MB ■ Time complexity : O(sqrt(n)) ■ Space Complexity: O(1). ***/<file_sep>/Easy/0007# Reverse Integer/ReverseInteger.c /**** Leetcode-Easy 0007# Reverse Integer *****/ /*** Given a 32-bit signed integer, reverse digits of an integer. Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. ***/ /*** ■ Example 1: Input: x = 123 Output: 321 ■ Example 2: Input: x = -123 Output: -321 ■ Example 3: Input: x = 120 Output: 21 ■ Example 4: Input: x = 0 Output: 0 <<Constraints>> ■ -231 <= x <= 231 - 1 ***/ //***********************************************************************************// // Develop in C : int reverse(int x){ // int limitation upper bound is 2147483647 int result = 0; // int limitation lower bound is -2147483647 - 1 while(x!=0) { int pop = x % 10; x /= 10; if(result > INT_MAX/10 || (result == INT_MAX/10 && pop > 7)) return 0; if(result < INT_MIN/10 || (result == INT_MIN/10 && pop < -8)) return 0; result = result * 10 + pop; } return result; } /*** ■ Runtime : 0 ms ■ Memory : 5.8 MB ■ Time Complexity: O(log(x)). There are roughly log_{10}(x) digits in x. ■ Space Complexity: O(1). ***/<file_sep>/Easy/0009# Palindrome Number/PalindromeNumber.cpp /**** Leetcode-Easy 0009# Palindrome Number *****/ /*** Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. Follow up: Could you solve it without converting the integer to a string? ***/ /*** ■ Example 1: Input: x = 121 Output: true ■ Example 2: Input: x = -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. ■ Example 3: Input: x = 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome. ■ Example 4: Input: x = -101 Output: false <<Constraints>> ■ -231 <= x <= 231 - 1 ***/ //***********************************************************************************// // Develop in C++ : class Solution { public: bool isPalindrome(int x) { if (x < 0 || (x%10 == 0 && x != 0)) // exclusive edge condition return false; int revert = 0; while(x>revert) { revert = revert * 10 + x % 10; x /= 10; } return x == revert || x == revert / 10; } }; /*** ■ Runtime : 24 ms ■ Memory : 6.3 MB ■ Time complexity : O(log_{10}(n))We divided the input by 10 for every iteration, so the time complexity is O(log_{10}(n)). ■ Space Complexity: O(1). ***/<file_sep>/Easy/0001# Two Sum/TwoSum.cpp /**** Leetcode-Easy 0001# Two Sum *****/ /*** Problems: Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order. ***/ /*** ■ Example 1: Input: nums = [2,7,11,15], target = 9 Output: [0,1] Output: Because nums[0] + nums[1] == 9, we return [0, 1]. ■ Example 2: Input: nums = [3,2,4], target = 6 Output: [1,2] ■ Example 3: Input: nums = [3,3], target = 6 Output: [0,1] <<Constraints>> ■ 2 <= nums.length <= 105 ■ -109 <= nums[i] <= 109 ■ -109 <= target <= 109 ■ Only one valid answer exists. ***/ /** ■ Note: The returned array must be malloced, assume caller calls free(). ■ map requirs <map> (its is a red-black tree structure) <<map>> : https://mropengate.blogspot.com/2015/12/cc-map-stl.html <<hash table>> : https://blog.techbridge.cc/2017/01/21/simple-hash-table-intro/ **/ //***********************************************************************************// // Develop in C++ : class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> result; map<int, int> hashmap; map<int, int>::iterator iter; for(int i = 0; i<nums.size(); i++) { iter = hashmap.find(target - nums[i]); if(iter != hashmap.end()) // when hashmap find fail => iter == hashmap.end() { result.push_back(iter->second); // iter->first : value, iter->second : key result.push_back(i); return result; // return answer } else hashmap.insert(pair<int, int>(nums[i], i)); // insert format : <value, key> } return result; } }; /*** ■ Runtime : 16 ms ■ Memory : 10.3 MB ■ Time Complexity: O(n). ■ Space Complexity: O(1). ***/<file_sep>/Easy/0345# Reverse Vowels of a String/ReverseVowels_of_a_String.c /**** Leetcode-Easy 0345# Reverse Vowels of a String *****/ /*** Write a function that takes a string as input and reverse only the vowels of a string. ***/ /*** ■ Example 1: Input: "hello" Output: "holle" ■ Example 2: Input: "leetcode" Output: "leotcede" ■ Note: The vowels does not include the letter "y". ***/ //***********************************************************************************// // Develop in C : //!!! This is a two pointer solution. Go through the string by once. bool isVowel(char charac); char * reverseVowels(char * s){ //printf("Hellow"); char *p1 = s; char *p2 = p1 + strlen(p1); while(p1 < p2){ while(p1 < p2 && !(isVowel(*p1))) p1++; while(p1 < p2 && !(isVowel(*p2))) p2--; if(p1 != p2){ char temp = *p1; *p1++ = *p2; *p2-- = temp; } } return s; } bool isVowel(char charac) { int c = (int)charac; c = tolower(c); return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'); } /*** ■ Runtime : 0 ms ■ Memory : 6.9 MB ■ Time complexity : O(log(n)) ■ Space Complexity: O(1). ***/<file_sep>/Easy/0167# Two Sum II - Input array is sorted/TwoSumII-Input_array_is_sorted.cpp /**** Leetcode-Easy 0167# Two Sum II - Input array is sorted *****/ /*** Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Note: ■ Your returned answers (both index1 and index2) are not zero-based. ■ You may assume that each input would have exactly one solution and you may not use the same element twice. ***/ /*** ■ Example 1: Input: numbers = [2,7,11,15], target = 9 Output: [1,2] Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2. ■ Example 2: Input: numbers = [2,3,4], target = 6 Output: [1,3] ■ Example 3: Input: numbers = [-1,0], target = -1 Output: [1,2] <<Constraints>> ■ 2 <= nums.length <= 3 * 104 ■ -1000 <= nums[i] <= 1000 ■ nums is sorted in increasing order. ■ -1000 <= target <= 1000 ***/ //***********************************************************************************// // Develop in C++ : /** * Note: The returned array must be malloced, assume caller calls free(). */ // !!! This is a two pointer solution. Go through the array by once. class Solution { public: vector<int> twoSum(vector<int>& numbers, int target) { vector<int> result; if(numbers.empty()) return result; // Input NULL condition int front = 0, end = numbers.size()-1; while(front < end){ int sum = numbers[front] + numbers[end]; if(sum == target) { result.push_back(front+1); result.push_back(end+1); return result; } else if(sum < target) front++; else end--; } return result; } }; /*** ■ Runtime : 8 ms ■ Memory : 9.8 MB ■ Time complexity : O(n) ■ Space Complexity: O(1). ***/<file_sep>/Easy/0001# Two Sum/TwoSum.c /**** Leetcode-Easy 0001# Two Sum *****/ /*** Problems: Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order. ***/ /*** ■ Example 1: Input: nums = [2,7,11,15], target = 9 Output: [0,1] Output: Because nums[0] + nums[1] == 9, we return [0, 1]. ■ Example 2: Input: nums = [3,2,4], target = 6 Output: [1,2] ■ Example 3: Input: nums = [3,3], target = 6 Output: [0,1] <<Constraints>> ■ 2 <= nums.length <= 105 ■ -109 <= nums[i] <= 109 ■ -109 <= target <= 109 ■ Only one valid answer exists. ***/ /** ■ Note: The returned array must be malloced, assume caller calls free(). ■ abs requirs <stdlib.h> **/ //***********************************************************************************// // Develop in C : // 1. build hash table function (insert, search, free) struct hashnode{ int value; // hashtable : value int index; // hashtable : key struct hashnode* next; // link list }; void insert(struct hashnode** hashtable, int value, int index, int numSize) { int tempindex = abs(value) % numSize; struct hashnode *tempnode = hashtable[tempindex]; struct hashnode *addnode = (struct hashnode*)malloc(sizeof(struct hashnode)); addnode->value = value; addnode->index = index; addnode->next = tempnode->next; tempnode->next = addnode; } int search(struct hashnode** hashtable, int target, int numSize) { int tempindex = abs(target) % numSize; struct hashnode* tempnode = hashtable[tempindex]->next; while(tempnode) { if(tempnode->value == target) return tempnode->index; // search succeed : return key tempnode = tempnode->next; } return -1; // search fail : return -1 } void freeHashTable(struct hashnode** hashtable, int numSize) { int i = 0; struct hashnode *tempnode = NULL, *deltarget = NULL; for(i = 0; i < numSize; i++) { tempnode = hashtable[i]; deltarget = tempnode; while(tempnode) { deltarget = tempnode; tempnode = tempnode->next; free(deltarget); // free pointer memory } } free(hashtable); // free pointer memory } // 2. twoSum algorithm int* twoSum(int* nums, int numsSize, int target, int* returnSize){ int i = 0; int index = 0; int* result = NULL; *returnSize = 2; // Leetcode requirs "output sizes" setting avoiding output error. /* malloc : ask for memory without value initialization. calloc : ask for memory with value initialization setting as 0. */ struct hashnode** hashtable = (struct hashnode**)malloc(numsSize * sizeof(struct hashnode*)); for(i = 0 ; i< numsSize ; i++) { hashtable[i] = (struct hashnode*)calloc(1, sizeof(struct hashnode)); } for(i = 0 ; i< numsSize ; i++) { index = search(hashtable, target - nums[i], numsSize); if(index == -1) // can't find the answer in hashtable insert(hashtable, nums[i], i, numsSize); // insert hashtable <value, key> else // find the answer in hashtable { // return result and free pointer result = (int *)malloc(sizeof(int)*2); result[0] = index; result[1] = i; freeHashTable(hashtable, numsSize); return result; } } freeHashTable(hashtable, numsSize); return result; } /*** ■ Runtime : 8 ms ■ Memory : 8 MB ■ Time Complexity: O(n). ■ Space Complexity: O(1). ***/<file_sep>/Easy/0167# Two Sum II - Input array is sorted/TwoSumII-Input_array_is_sorted.c /**** Leetcode-Easy 0167# Two Sum II - Input array is sorted *****/ /*** Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Note: ■ Your returned answers (both index1 and index2) are not zero-based. ■ You may assume that each input would have exactly one solution and you may not use the same element twice. ***/ /*** ■ Example 1: Input: numbers = [2,7,11,15], target = 9 Output: [1,2] Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2. ■ Example 2: Input: numbers = [2,3,4], target = 6 Output: [1,3] ■ Example 3: Input: numbers = [-1,0], target = -1 Output: [1,2] <<Constraints>> ■ 2 <= nums.length <= 3 * 104 ■ -1000 <= nums[i] <= 1000 ■ nums is sorted in increasing order. ■ -1000 <= target <= 1000 ***/ //***********************************************************************************// // Develop in C : /** * Note: The returned array must be malloced, assume caller calls free(). */ // !!! This is a two pointer solution. Go through the array by once. int* twoSum(int* numbers, int numbersSize, int target, int* returnSize){ (*returnSize) = 2; // Has to set return Size if (numbers == NULL) return NULL; // Input NULL condition int front = 0, end = numbersSize - 1; int *result = (int *)malloc(sizeof(int)*2); // Use malloc initial setting to invoid error in leetcode while(front < end){ int sum = numbers[front] + numbers[end]; if(sum == target) { result[0] = front+1; result[1] = end+1; return result; } else if(sum < target) front++; else end--; } return result; } /*** ■ Runtime : 4 ms ■ Memory : 6.8 MB ■ Time complexity : O(n) ■ Space Complexity: O(1). ***/<file_sep>/Easy/0345# Reverse Vowels of a String/ReverseVowels_of_a_String.cpp /**** Leetcode-Easy 0345# Reverse Vowels of a String *****/ /*** Write a function that takes a string as input and reverse only the vowels of a string. ***/ /*** ■ Example 1: Input: "hello" Output: "holle" ■ Example 2: Input: "leetcode" Output: "leotcede" ■ Note: The vowels does not include the letter "y". ***/ //***********************************************************************************// // Develop in C++ : //!!! This is a two pointer solution. Go through the string by once. class Solution { public: string reverseVowels(string s) { int p1 = 0, p2 = s.size()-1; while(p1 < p2){ while(p1 < p2 && !isVowel(s[p1])) p1++; while(p1 < p2 && !isVowel(s[p2])) p2--; if(p1 != p2) swap(s[p1++], s[p2--]); } return s; } private: bool isVowel(char c){ c = tolower(c); return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'); } }; /*** ■ Runtime : 8 ms ■ Memory : 8.2 MB ■ Time complexity : O(log(n)) ■ Space Complexity: O(1). ***/<file_sep>/Medium/0633# Sum of Square Numbers/Sum_of_SquareNumbers.cpp /**** Leetcode-Medium 0633# Sum of Square Numbers *****/ /*** Given a non-negative integer c, decide whether there're two integers a and b such that a2 + b2 = c. ***/ /*** ■ Example 1: Input: c = 5 Output: true Explanation: 1 * 1 + 2 * 2 = 5 ■ Example 2: Input: c = 3 Output: false ■ Example 3: Input: c = 4 Output: true ■ Example 4: Input: c = 2 Output: true ■ Example 5: Input: c = 1 Output: true <<Constraints>> ■ 0 <= c <= 231 - 1 ***/ //***********************************************************************************// // Develop in C++ : //!!! This is a two pointer solution. Go through the string by once.Sqrt to find the answer more efficiency. class Solution { public: bool judgeSquareSum(int c) { long front = 0, end = sqrt(c); // use long invoiding overflow of int. while(front <= end){ long pow_sum = front*front + end*end; if(pow_sum == c) return true; else if(pow_sum > c) end--; else front++; } return false; } }; /*** ■ Runtime : 0 ms ■ Memory : 6.4 MB ■ Time complexity : O(sqrt(n)) ■ Space Complexity: O(1). ***/
73af4edb2e9554d60c82290e2bb8a18d6cf09fdd
[ "Markdown", "C", "C++" ]
13
C
MOMOJMOGG/Leetcode-Practice-Library
4df3c429709a51ffb7c872247e901f3e8d8f2cb1
94560ba5e3ce785b0b4e382c8550c0f9ccdc416b
refs/heads/master
<repo_name>LucasHilgevoord/IDP_Hearthstone_PersonalScripts<file_sep>/UI/YourTurn/YourTurn2.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class YourTurn2 : MonoBehaviour { public Animation YourTurnAnim; void Start() { YourTurnAnim = GetComponent<Animation>(); } void Awake() { YourTurnAnim.Play("YourTurnAnim"); } // Update is called once per frame void Update () { } } <file_sep>/UI/Cursor/CustomCursor.cs using UnityEngine; using System.Collections; public class CustomCursor : MonoBehaviour { public Texture2D CursorDrag; public Texture2D CursorNormal; private bool isMouseDragging; private bool CursorLoadActive; void Start() { Invoke("SetCustomCursor", 0.0f); } private void SetCustomCursor() { Cursor.SetCursor(this.CursorNormal, Vector2.zero, CursorMode.Auto); } void Update() { CursorLoadActive = EndTurnBehavior.CursorLoadActive; isMouseDragging = DragCard.isMouseDragging; if (isMouseDragging) { Cursor.SetCursor(this.CursorDrag, Vector2.zero, CursorMode.Auto); } else if (!isMouseDragging && !CursorLoadActive) { Cursor.SetCursor(this.CursorNormal, Vector2.zero, CursorMode.Auto); } /* else { Cursor.SetCursor(this.CursorNormal, Vector2.zero, CursorMode.Auto); } */ } }<file_sep>/Effects/DropEffect.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class DropEffect : MonoBehaviour { // Use this for initialization void Awake() { StartCoroutine(KillEffect()); } IEnumerator KillEffect() { yield return new WaitForSeconds(0.5f); Destroy(this.gameObject); } } <file_sep>/UI/YourTurn/YourTurn.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class YourTurn : MonoBehaviour { public Transform CardPoint; private bool StartCount = false; public static bool ActivateCard = false; public GameObject YourTurnObject; void Start() { StartCount = true; } void Update() { transform.localScale = new Vector4(Mathf.PingPong(Time.time, 6) - 1, transform.localScale.x, transform.localScale.y, transform.localScale.z); Destroy(YourTurnObject, 1); if (StartCount) { StartCoroutine("Wait"); } } IEnumerator Wait() { yield return new WaitForSeconds(1); Debug.Log(StartCount); Debug.Log("Activate"); ActivateCard = true; StartCount = false; } } <file_sep>/UI/Mana/ManaScore.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class ManaScore : MonoBehaviour { public string text; // Use this for initialization void Start () { } void Awake() { TextMesh textObject = this.GetComponent<TextMesh>(); textObject.text = "1/1"; } // Update is called once per frame void Update () { if (DragCard.PlacedCard) { TextMesh textObject = this.GetComponent<TextMesh>(); textObject.text = "0/1"; } } } <file_sep>/EndTurn/HitmarkBehavior.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class HitmarkBehavior : MonoBehaviour { public Animation HitmarkAnim; void Start() { HitmarkAnim = GetComponent<Animation>(); } void Awake() { HitmarkAnim.Play("Hitmark"); StartCoroutine(KillCard()); } IEnumerator KillCard() { yield return new WaitForSeconds(1f); Destroy(this.gameObject); } } <file_sep>/EndTurn/EndTurnBehavior.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class EndTurnBehavior : MonoBehaviour { public static bool NextTurnActive = false; public Animation ButtonClick; private bool FischAttacked = true; public Texture2D CursorLoad; public static bool CursorLoadActive = false; public Image img; public AudioSource audio; // Use this for initialization void Start () { ButtonClick = GetComponent<Animation>(); audio = GetComponent<AudioSource>(); } // Update is called once per frame void Update () { } void OnMouseDown() { audio.Play(); ButtonClick.Play("ButtonClick"); Cursor.SetCursor(this.CursorLoad, Vector2.zero, CursorMode.Auto); CursorLoadActive = true; if (FischAttacked) { NextTurnActive = true; if (NextTurnActive) { Debug.Log("Next Turn"); } } StartCoroutine(Restart()); } IEnumerator Restart() { yield return new WaitForSeconds(2f); NextTurnActive = false; Application.LoadLevel(Application.loadedLevel); } } <file_sep>/Fiesje/fischBehavior.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class fischBehavior : MonoBehaviour { public Animation FischFallAnim; public GameObject Arrow; public Transform ArrowRotation; public GameObject Fisch; public GameObject HitMark; public GameObject Icon; private bool NextTurnActive; public static bool AttackedBoss = false; public AudioSource audio; public GameObject FallDust; //Arrow private int SpawnArrow = 1; void Start() { FischFallAnim = GetComponent<Animation>(); } void Awake() { StartCoroutine(KillCard()); Instantiate(Icon, GameObject.Find("CardIconPos").transform.position, GameObject.Find("CardIconPos").transform.rotation); } IEnumerator KillCard() { yield return new WaitForSeconds(0.5f); FischFallAnim.Play("FischFall"); Destroy(GameObject.Find("Card3")); DragCard.PlacedCard = false; yield return new WaitForSeconds(0.3f); Instantiate(FallDust, this.transform.position, this.transform.rotation); yield return new WaitForSeconds(2.9f); Destroy(GameObject.Find("boar_placement_fiche_FX(Clone)")); } void Update() { audio = GetComponent<AudioSource>(); NextTurnActive = EndTurnBehavior.NextTurnActive; if (!NextTurnActive) { //Debug.Log(SpawnArrow); RaycastHit hit; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray.origin, ray.direction * 1000, out hit)) { if (Input.GetMouseButtonDown(0)) { if (hit.collider.tag == "Fisch") { Debug.Log("FischSelect"); if (SpawnArrow == 1) { SpawnArrow--; Instantiate(Arrow, new Vector3(hit.point.x, hit.point.y + 5, hit.point.z), ArrowRotation.rotation); //Play Audio audio.Play(); } } } if (Input.GetMouseButtonUp(0) && SpawnArrow == 0) { SpawnArrow++; Debug.Log("FischDown"); Destroy(GameObject.Find("Arrow4(Clone)")); } } } if (NextTurnActive) { FischFallAnim.Play("FischAttack"); EndTurnBehavior.NextTurnActive = false; StartCoroutine(SpawnHitmark()); } } IEnumerator SpawnHitmark() { yield return new WaitForSeconds(0.1f); Instantiate(HitMark, GameObject.Find("HitmarkPos").transform.position, GameObject.Find("HitmarkPos").transform.rotation); AttackedBoss = true; } } <file_sep>/EndTurn/BossHealth.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class BossHealth : MonoBehaviour { public Animation HealthAnim; int Health = 30; void Start() { HealthAnim = GetComponent<Animation>(); } void Awake() { TextMesh textObject = this.GetComponent<TextMesh>(); textObject.text = ((int)Health).ToString(); } void Update() { bool AttackedBoss = fischBehavior.AttackedBoss; if (fischBehavior.AttackedBoss) { Health--; TextMesh textObject = this.GetComponent<TextMesh>(); textObject.text = ((int)Health).ToString(); textObject.color = Color.red; StartCoroutine(ColorChange()); fischBehavior.AttackedBoss = false; HealthAnim.Play("BossHealth"); } } IEnumerator ColorChange() { yield return new WaitForSeconds(0.5f); TextMesh textObject = this.GetComponent<TextMesh>(); textObject.color = Color.white; } }<file_sep>/UI/Mana/ManaIcon.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class ManaIcon : MonoBehaviour { private SpriteRenderer spriteR; public Sprite Disable; // Use this for initialization void Start () { spriteR = gameObject.GetComponent<SpriteRenderer>(); } // Update is called once per frame void Update () { if (DragCard.PlacedCard) { spriteR.sprite = Disable; } } } <file_sep>/Arrow/ArrowBehavior.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class ArrowBehavior : MonoBehaviour { int speed = 4; public Transform Fisch; // Use this for initialization void Start () { } // Update is called once per frame void Update() { Vector3 pos = transform.position; RaycastHit hit; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray.origin, ray.direction * 1000, out hit)) { //transform.LookAt(new Vector3(hit.point.x, hit.point.y, hit.point.z)); transform.position = new Vector3(hit.point.x, hit.point.y, hit.point.z); //pos = Input.mousePosition * Time.deltaTime; } } }
15b78b5f7fac3c290dd3740b577572c82ae5fef7
[ "C#" ]
11
C#
LucasHilgevoord/IDP_Hearthstone_PersonalScripts
ffbbbb73cdbc728632039afe70002e01928e3cc8
f86d80bf305b7e40f14f06e8a6627bdb3ae198f3