repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
flaxsearch/hackday
ukmp/java/indexer/src/main/java/uk/co/flax/ukmp/twitter/PartyListHandler.java
// Path: ukmp/java/indexer/src/main/java/uk/co/flax/ukmp/config/PartyConfiguration.java // public class PartyConfiguration { // // private String displayName; // private String twitterScreenName; // private String twitterListSlug; // // /** // * @return the displayName // */ // public String getDisplayName() { // return displayName; // } // // /** // * @param displayName the displayName to set // */ // public void setDisplayName(String displayName) { // this.displayName = displayName; // } // // /** // * @return the twitterOwnerId // */ // public String getTwitterScreenName() { // return twitterScreenName; // } // // /** // * @param twitterOwnerId the twitterOwnerId to set // */ // public void setTwitterScreenName(String twitterOwnerId) { // this.twitterScreenName = twitterOwnerId; // } // // /** // * @return the twitterSlug // */ // public String getTwitterListSlug() { // return twitterListSlug; // } // // /** // * @param twitterSlug the twitterSlug to set // */ // public void setTwitterListSlug(String twitterSlug) { // this.twitterListSlug = twitterSlug; // } // // }
import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import twitter4j.PagableResponseList; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.TwitterFactory; import twitter4j.User; import twitter4j.auth.Authorization; import twitter4j.auth.AuthorizationFactory; import twitter4j.conf.Configuration; import uk.co.flax.ukmp.config.PartyConfiguration; import com.google.common.collect.Sets;
/** * Copyright (c) 2014 Lemur Consulting Ltd. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.flax.ukmp.twitter; /** * @author Matt Pearce */ public class PartyListHandler { private static final Logger LOGGER = LoggerFactory.getLogger(PartyListHandler.class); private static final long REFRESH_TIME = 6 * 60 * 60 * 1000; private final Configuration twitterConfig;
// Path: ukmp/java/indexer/src/main/java/uk/co/flax/ukmp/config/PartyConfiguration.java // public class PartyConfiguration { // // private String displayName; // private String twitterScreenName; // private String twitterListSlug; // // /** // * @return the displayName // */ // public String getDisplayName() { // return displayName; // } // // /** // * @param displayName the displayName to set // */ // public void setDisplayName(String displayName) { // this.displayName = displayName; // } // // /** // * @return the twitterOwnerId // */ // public String getTwitterScreenName() { // return twitterScreenName; // } // // /** // * @param twitterOwnerId the twitterOwnerId to set // */ // public void setTwitterScreenName(String twitterOwnerId) { // this.twitterScreenName = twitterOwnerId; // } // // /** // * @return the twitterSlug // */ // public String getTwitterListSlug() { // return twitterListSlug; // } // // /** // * @param twitterSlug the twitterSlug to set // */ // public void setTwitterListSlug(String twitterSlug) { // this.twitterListSlug = twitterSlug; // } // // } // Path: ukmp/java/indexer/src/main/java/uk/co/flax/ukmp/twitter/PartyListHandler.java import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import twitter4j.PagableResponseList; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.TwitterFactory; import twitter4j.User; import twitter4j.auth.Authorization; import twitter4j.auth.AuthorizationFactory; import twitter4j.conf.Configuration; import uk.co.flax.ukmp.config.PartyConfiguration; import com.google.common.collect.Sets; /** * Copyright (c) 2014 Lemur Consulting Ltd. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.flax.ukmp.twitter; /** * @author Matt Pearce */ public class PartyListHandler { private static final Logger LOGGER = LoggerFactory.getLogger(PartyListHandler.class); private static final long REFRESH_TIME = 6 * 60 * 60 * 1000; private final Configuration twitterConfig;
private final Map<String, PartyConfiguration> parties;
flaxsearch/hackday
ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/resources/TermsHandler.java
// Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/api/Term.java // public class Term implements Comparable<Term> { // // private final String term; // private final long count; // // public Term(String term, long count) { // this.term = term; // this.count = count; // } // // /** // * @return the term // */ // public String getTerm() { // return term; // } // // /** // * @return the count // */ // public long getCount() { // return count; // } // // @Override // public int compareTo(Term t) { // int ret = Long.compare(count, t.count); // if (ret == 0) { // ret = term.compareTo(t.term); // } // // return ret; // } // // @Override // public String toString() { // return term + " [" + count + "]"; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/api/TermsResponse.java // public class TermsResponse { // // @JsonProperty("terms") // private final List<Term> terms; // // private final String error; // // public TermsResponse(List<Term> terms, String error) { // this.terms = terms; // this.error = error; // } // // public TermsResponse(List<Term> terms) { // this(terms, null); // } // // public TermsResponse(String error) { // this(null, error); // } // // /** // * @return the terms // */ // public List<Term> getTerms() { // return terms; // } // // /** // * @return the error // */ // public String getError() { // return error; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/services/TermsManager.java // public class TermsManager implements Managed { // // private static final Logger LOGGER = LoggerFactory.getLogger(TermsManager.class); // // private final TermsManagerThread termsThread; // // public TermsManager(SearchEngine engine, TermsConfiguration config) throws Exception { // termsThread = new TermsManagerThread(engine, config); // } // // @Override // public void start() { // LOGGER.info("Starting terms thread..."); // termsThread.start(); // } // // @Override // public void stop() throws Exception { // LOGGER.info("Shutting down terms thread..."); // termsThread.shutdown(); // } // // /** // * Get an unmodifiable list of the current terms. // * @return the current terms. // */ // public List<Term> getTerms() { // return Collections.unmodifiableList(termsThread.getTerms()); // } // // }
import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import uk.co.flax.ukmp.api.Term; import uk.co.flax.ukmp.api.TermsResponse; import uk.co.flax.ukmp.services.TermsManager;
/** * Copyright (c) 2014 Lemur Consulting Ltd. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.flax.ukmp.resources; /** * Resource handler dealing with the search compopnent. */ @Path("/terms") public class TermsHandler {
// Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/api/Term.java // public class Term implements Comparable<Term> { // // private final String term; // private final long count; // // public Term(String term, long count) { // this.term = term; // this.count = count; // } // // /** // * @return the term // */ // public String getTerm() { // return term; // } // // /** // * @return the count // */ // public long getCount() { // return count; // } // // @Override // public int compareTo(Term t) { // int ret = Long.compare(count, t.count); // if (ret == 0) { // ret = term.compareTo(t.term); // } // // return ret; // } // // @Override // public String toString() { // return term + " [" + count + "]"; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/api/TermsResponse.java // public class TermsResponse { // // @JsonProperty("terms") // private final List<Term> terms; // // private final String error; // // public TermsResponse(List<Term> terms, String error) { // this.terms = terms; // this.error = error; // } // // public TermsResponse(List<Term> terms) { // this(terms, null); // } // // public TermsResponse(String error) { // this(null, error); // } // // /** // * @return the terms // */ // public List<Term> getTerms() { // return terms; // } // // /** // * @return the error // */ // public String getError() { // return error; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/services/TermsManager.java // public class TermsManager implements Managed { // // private static final Logger LOGGER = LoggerFactory.getLogger(TermsManager.class); // // private final TermsManagerThread termsThread; // // public TermsManager(SearchEngine engine, TermsConfiguration config) throws Exception { // termsThread = new TermsManagerThread(engine, config); // } // // @Override // public void start() { // LOGGER.info("Starting terms thread..."); // termsThread.start(); // } // // @Override // public void stop() throws Exception { // LOGGER.info("Shutting down terms thread..."); // termsThread.shutdown(); // } // // /** // * Get an unmodifiable list of the current terms. // * @return the current terms. // */ // public List<Term> getTerms() { // return Collections.unmodifiableList(termsThread.getTerms()); // } // // } // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/resources/TermsHandler.java import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import uk.co.flax.ukmp.api.Term; import uk.co.flax.ukmp.api.TermsResponse; import uk.co.flax.ukmp.services.TermsManager; /** * Copyright (c) 2014 Lemur Consulting Ltd. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.flax.ukmp.resources; /** * Resource handler dealing with the search compopnent. */ @Path("/terms") public class TermsHandler {
private final TermsManager termsManager;
flaxsearch/hackday
ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/resources/TermsHandler.java
// Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/api/Term.java // public class Term implements Comparable<Term> { // // private final String term; // private final long count; // // public Term(String term, long count) { // this.term = term; // this.count = count; // } // // /** // * @return the term // */ // public String getTerm() { // return term; // } // // /** // * @return the count // */ // public long getCount() { // return count; // } // // @Override // public int compareTo(Term t) { // int ret = Long.compare(count, t.count); // if (ret == 0) { // ret = term.compareTo(t.term); // } // // return ret; // } // // @Override // public String toString() { // return term + " [" + count + "]"; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/api/TermsResponse.java // public class TermsResponse { // // @JsonProperty("terms") // private final List<Term> terms; // // private final String error; // // public TermsResponse(List<Term> terms, String error) { // this.terms = terms; // this.error = error; // } // // public TermsResponse(List<Term> terms) { // this(terms, null); // } // // public TermsResponse(String error) { // this(null, error); // } // // /** // * @return the terms // */ // public List<Term> getTerms() { // return terms; // } // // /** // * @return the error // */ // public String getError() { // return error; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/services/TermsManager.java // public class TermsManager implements Managed { // // private static final Logger LOGGER = LoggerFactory.getLogger(TermsManager.class); // // private final TermsManagerThread termsThread; // // public TermsManager(SearchEngine engine, TermsConfiguration config) throws Exception { // termsThread = new TermsManagerThread(engine, config); // } // // @Override // public void start() { // LOGGER.info("Starting terms thread..."); // termsThread.start(); // } // // @Override // public void stop() throws Exception { // LOGGER.info("Shutting down terms thread..."); // termsThread.shutdown(); // } // // /** // * Get an unmodifiable list of the current terms. // * @return the current terms. // */ // public List<Term> getTerms() { // return Collections.unmodifiableList(termsThread.getTerms()); // } // // }
import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import uk.co.flax.ukmp.api.Term; import uk.co.flax.ukmp.api.TermsResponse; import uk.co.flax.ukmp.services.TermsManager;
/** * Copyright (c) 2014 Lemur Consulting Ltd. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.flax.ukmp.resources; /** * Resource handler dealing with the search compopnent. */ @Path("/terms") public class TermsHandler { private final TermsManager termsManager; public TermsHandler(TermsManager termsManager) { this.termsManager = termsManager; } @GET @Produces(MediaType.APPLICATION_JSON)
// Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/api/Term.java // public class Term implements Comparable<Term> { // // private final String term; // private final long count; // // public Term(String term, long count) { // this.term = term; // this.count = count; // } // // /** // * @return the term // */ // public String getTerm() { // return term; // } // // /** // * @return the count // */ // public long getCount() { // return count; // } // // @Override // public int compareTo(Term t) { // int ret = Long.compare(count, t.count); // if (ret == 0) { // ret = term.compareTo(t.term); // } // // return ret; // } // // @Override // public String toString() { // return term + " [" + count + "]"; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/api/TermsResponse.java // public class TermsResponse { // // @JsonProperty("terms") // private final List<Term> terms; // // private final String error; // // public TermsResponse(List<Term> terms, String error) { // this.terms = terms; // this.error = error; // } // // public TermsResponse(List<Term> terms) { // this(terms, null); // } // // public TermsResponse(String error) { // this(null, error); // } // // /** // * @return the terms // */ // public List<Term> getTerms() { // return terms; // } // // /** // * @return the error // */ // public String getError() { // return error; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/services/TermsManager.java // public class TermsManager implements Managed { // // private static final Logger LOGGER = LoggerFactory.getLogger(TermsManager.class); // // private final TermsManagerThread termsThread; // // public TermsManager(SearchEngine engine, TermsConfiguration config) throws Exception { // termsThread = new TermsManagerThread(engine, config); // } // // @Override // public void start() { // LOGGER.info("Starting terms thread..."); // termsThread.start(); // } // // @Override // public void stop() throws Exception { // LOGGER.info("Shutting down terms thread..."); // termsThread.shutdown(); // } // // /** // * Get an unmodifiable list of the current terms. // * @return the current terms. // */ // public List<Term> getTerms() { // return Collections.unmodifiableList(termsThread.getTerms()); // } // // } // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/resources/TermsHandler.java import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import uk.co.flax.ukmp.api.Term; import uk.co.flax.ukmp.api.TermsResponse; import uk.co.flax.ukmp.services.TermsManager; /** * Copyright (c) 2014 Lemur Consulting Ltd. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.flax.ukmp.resources; /** * Resource handler dealing with the search compopnent. */ @Path("/terms") public class TermsHandler { private final TermsManager termsManager; public TermsHandler(TermsManager termsManager) { this.termsManager = termsManager; } @GET @Produces(MediaType.APPLICATION_JSON)
public TermsResponse handleGet() {
flaxsearch/hackday
ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/resources/TermsHandler.java
// Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/api/Term.java // public class Term implements Comparable<Term> { // // private final String term; // private final long count; // // public Term(String term, long count) { // this.term = term; // this.count = count; // } // // /** // * @return the term // */ // public String getTerm() { // return term; // } // // /** // * @return the count // */ // public long getCount() { // return count; // } // // @Override // public int compareTo(Term t) { // int ret = Long.compare(count, t.count); // if (ret == 0) { // ret = term.compareTo(t.term); // } // // return ret; // } // // @Override // public String toString() { // return term + " [" + count + "]"; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/api/TermsResponse.java // public class TermsResponse { // // @JsonProperty("terms") // private final List<Term> terms; // // private final String error; // // public TermsResponse(List<Term> terms, String error) { // this.terms = terms; // this.error = error; // } // // public TermsResponse(List<Term> terms) { // this(terms, null); // } // // public TermsResponse(String error) { // this(null, error); // } // // /** // * @return the terms // */ // public List<Term> getTerms() { // return terms; // } // // /** // * @return the error // */ // public String getError() { // return error; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/services/TermsManager.java // public class TermsManager implements Managed { // // private static final Logger LOGGER = LoggerFactory.getLogger(TermsManager.class); // // private final TermsManagerThread termsThread; // // public TermsManager(SearchEngine engine, TermsConfiguration config) throws Exception { // termsThread = new TermsManagerThread(engine, config); // } // // @Override // public void start() { // LOGGER.info("Starting terms thread..."); // termsThread.start(); // } // // @Override // public void stop() throws Exception { // LOGGER.info("Shutting down terms thread..."); // termsThread.shutdown(); // } // // /** // * Get an unmodifiable list of the current terms. // * @return the current terms. // */ // public List<Term> getTerms() { // return Collections.unmodifiableList(termsThread.getTerms()); // } // // }
import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import uk.co.flax.ukmp.api.Term; import uk.co.flax.ukmp.api.TermsResponse; import uk.co.flax.ukmp.services.TermsManager;
/** * Copyright (c) 2014 Lemur Consulting Ltd. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.flax.ukmp.resources; /** * Resource handler dealing with the search compopnent. */ @Path("/terms") public class TermsHandler { private final TermsManager termsManager; public TermsHandler(TermsManager termsManager) { this.termsManager = termsManager; } @GET @Produces(MediaType.APPLICATION_JSON) public TermsResponse handleGet() { TermsResponse ret;
// Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/api/Term.java // public class Term implements Comparable<Term> { // // private final String term; // private final long count; // // public Term(String term, long count) { // this.term = term; // this.count = count; // } // // /** // * @return the term // */ // public String getTerm() { // return term; // } // // /** // * @return the count // */ // public long getCount() { // return count; // } // // @Override // public int compareTo(Term t) { // int ret = Long.compare(count, t.count); // if (ret == 0) { // ret = term.compareTo(t.term); // } // // return ret; // } // // @Override // public String toString() { // return term + " [" + count + "]"; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/api/TermsResponse.java // public class TermsResponse { // // @JsonProperty("terms") // private final List<Term> terms; // // private final String error; // // public TermsResponse(List<Term> terms, String error) { // this.terms = terms; // this.error = error; // } // // public TermsResponse(List<Term> terms) { // this(terms, null); // } // // public TermsResponse(String error) { // this(null, error); // } // // /** // * @return the terms // */ // public List<Term> getTerms() { // return terms; // } // // /** // * @return the error // */ // public String getError() { // return error; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/services/TermsManager.java // public class TermsManager implements Managed { // // private static final Logger LOGGER = LoggerFactory.getLogger(TermsManager.class); // // private final TermsManagerThread termsThread; // // public TermsManager(SearchEngine engine, TermsConfiguration config) throws Exception { // termsThread = new TermsManagerThread(engine, config); // } // // @Override // public void start() { // LOGGER.info("Starting terms thread..."); // termsThread.start(); // } // // @Override // public void stop() throws Exception { // LOGGER.info("Shutting down terms thread..."); // termsThread.shutdown(); // } // // /** // * Get an unmodifiable list of the current terms. // * @return the current terms. // */ // public List<Term> getTerms() { // return Collections.unmodifiableList(termsThread.getTerms()); // } // // } // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/resources/TermsHandler.java import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import uk.co.flax.ukmp.api.Term; import uk.co.flax.ukmp.api.TermsResponse; import uk.co.flax.ukmp.services.TermsManager; /** * Copyright (c) 2014 Lemur Consulting Ltd. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.flax.ukmp.resources; /** * Resource handler dealing with the search compopnent. */ @Path("/terms") public class TermsHandler { private final TermsManager termsManager; public TermsHandler(TermsManager termsManager) { this.termsManager = termsManager; } @GET @Produces(MediaType.APPLICATION_JSON) public TermsResponse handleGet() { TermsResponse ret;
List<Term> terms = termsManager.getTerms();
flaxsearch/hackday
ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/health/SolrHealthCheck.java
// Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/search/SearchEngine.java // public interface SearchEngine { // // /** Enumeration to indicate return states from store/update ops */ // public enum OperationStatus { // SUCCESS, // FAILURE, // NO_OPERATION // } // // public static final String ID_FIELD = "id"; // // /** // * Test the readiness of the search engine. // * @return <code>true</code> if the search engine is available, // * <code>false</code> if not. // * @throws SearchEngineException if a problem occurs while testing the // * search engine. This does not include the search engine being off-line. // */ // public boolean isServerReady() throws SearchEngineException; // // /** // * Carry out a search and return the results. // * @param query the query details. // * @return the results of the search. // * @throws SearchEngineException if there are problems executing the // * search. // */ // public SearchResults search(Query query) throws SearchEngineException; // // /** // * Get a batch of tweets from the search engine, using a minimal handler // * that only returns the tweet text. This is expected to be used to generate // * the list of terms for the word cloud. // * // * <p>Most search parameters will be filled in from the {@link TermsConfiguration}, // * with only the batch number required to set the search start point.</p> // * @param batchNum the number of the batch to look up, starting from 0. // * @return a list of search results, comprising tweets with text only. // * @throws SearchEngineException if there are problems executing the search. // */ // public SearchResults getTextBatch(int batchNum) throws SearchEngineException; // // public void indexTweets(List<Tweet> tweets) throws SearchEngineException; // // public void deleteTweets(List<String> deleteIds) throws SearchEngineException; // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/search/SearchEngineException.java // public class SearchEngineException extends Exception { // // private static final long serialVersionUID = 1L; // // public SearchEngineException() { // super(); // } // // public SearchEngineException(String msg) { // super(msg); // } // // public SearchEngineException(Throwable t) { // super(t); // } // // public SearchEngineException(String msg, Throwable t) { // super(msg, t); // } // // }
import com.codahale.metrics.health.HealthCheck; import uk.co.flax.ukmp.search.SearchEngine; import uk.co.flax.ukmp.search.SearchEngineException;
/** * Copyright (c) 2013 Lemur Consulting Ltd. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.flax.ukmp.health; /** * Health check to see if Solr server is up and running. */ public class SolrHealthCheck extends HealthCheck { private final SearchEngine searchEngine; /** * Default constructor. */ public SolrHealthCheck(SearchEngine engine) { this.searchEngine = engine; } @Override protected Result check() { try { if (searchEngine.isServerReady()) { return Result.healthy(); } else { return Result.unhealthy("Server is not available - check log for details"); }
// Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/search/SearchEngine.java // public interface SearchEngine { // // /** Enumeration to indicate return states from store/update ops */ // public enum OperationStatus { // SUCCESS, // FAILURE, // NO_OPERATION // } // // public static final String ID_FIELD = "id"; // // /** // * Test the readiness of the search engine. // * @return <code>true</code> if the search engine is available, // * <code>false</code> if not. // * @throws SearchEngineException if a problem occurs while testing the // * search engine. This does not include the search engine being off-line. // */ // public boolean isServerReady() throws SearchEngineException; // // /** // * Carry out a search and return the results. // * @param query the query details. // * @return the results of the search. // * @throws SearchEngineException if there are problems executing the // * search. // */ // public SearchResults search(Query query) throws SearchEngineException; // // /** // * Get a batch of tweets from the search engine, using a minimal handler // * that only returns the tweet text. This is expected to be used to generate // * the list of terms for the word cloud. // * // * <p>Most search parameters will be filled in from the {@link TermsConfiguration}, // * with only the batch number required to set the search start point.</p> // * @param batchNum the number of the batch to look up, starting from 0. // * @return a list of search results, comprising tweets with text only. // * @throws SearchEngineException if there are problems executing the search. // */ // public SearchResults getTextBatch(int batchNum) throws SearchEngineException; // // public void indexTweets(List<Tweet> tweets) throws SearchEngineException; // // public void deleteTweets(List<String> deleteIds) throws SearchEngineException; // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/search/SearchEngineException.java // public class SearchEngineException extends Exception { // // private static final long serialVersionUID = 1L; // // public SearchEngineException() { // super(); // } // // public SearchEngineException(String msg) { // super(msg); // } // // public SearchEngineException(Throwable t) { // super(t); // } // // public SearchEngineException(String msg, Throwable t) { // super(msg, t); // } // // } // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/health/SolrHealthCheck.java import com.codahale.metrics.health.HealthCheck; import uk.co.flax.ukmp.search.SearchEngine; import uk.co.flax.ukmp.search.SearchEngineException; /** * Copyright (c) 2013 Lemur Consulting Ltd. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.flax.ukmp.health; /** * Health check to see if Solr server is up and running. */ public class SolrHealthCheck extends HealthCheck { private final SearchEngine searchEngine; /** * Default constructor. */ public SolrHealthCheck(SearchEngine engine) { this.searchEngine = engine; } @Override protected Result check() { try { if (searchEngine.isServerReady()) { return Result.healthy(); } else { return Result.unhealthy("Server is not available - check log for details"); }
} catch (SearchEngineException e) {
flaxsearch/hackday
ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/services/TermsManager.java
// Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/api/Term.java // public class Term implements Comparable<Term> { // // private final String term; // private final long count; // // public Term(String term, long count) { // this.term = term; // this.count = count; // } // // /** // * @return the term // */ // public String getTerm() { // return term; // } // // /** // * @return the count // */ // public long getCount() { // return count; // } // // @Override // public int compareTo(Term t) { // int ret = Long.compare(count, t.count); // if (ret == 0) { // ret = term.compareTo(t.term); // } // // return ret; // } // // @Override // public String toString() { // return term + " [" + count + "]"; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/config/TermsConfiguration.java // public class TermsConfiguration { // // @Valid @NotNull // private String handler; // @Valid @NotNull // private String field; // @Valid @NotNull // private int limit; // // private String sortOrder; // // @Valid @NotNull // private int batchSize; // @Valid @NotNull // private List<String> filters; // @Valid @NotNull // private String stopWordsFile; // @Valid @NotNull // private int refreshMinutes; // // // /** // * @return the handler // */ // public String getHandler() { // return handler; // } // // /** // * @return the field // */ // public String getField() { // return field; // } // // /** // * @return the limit // */ // public int getLimit() { // return limit; // } // // public String getSortOrder() { // return sortOrder; // } // // /** // * @return the batchSize // */ // public int getBatchSize() { // return batchSize; // } // // /** // * @return the filters // */ // public List<String> getFilters() { // return filters; // } // // /** // * @return the stopWordsFile // */ // public String getStopWordsFile() { // return stopWordsFile; // } // // /** // * @return the refreshMinutes // */ // public int getRefreshMinutes() { // return refreshMinutes; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/search/SearchEngine.java // public interface SearchEngine { // // /** Enumeration to indicate return states from store/update ops */ // public enum OperationStatus { // SUCCESS, // FAILURE, // NO_OPERATION // } // // public static final String ID_FIELD = "id"; // // /** // * Test the readiness of the search engine. // * @return <code>true</code> if the search engine is available, // * <code>false</code> if not. // * @throws SearchEngineException if a problem occurs while testing the // * search engine. This does not include the search engine being off-line. // */ // public boolean isServerReady() throws SearchEngineException; // // /** // * Carry out a search and return the results. // * @param query the query details. // * @return the results of the search. // * @throws SearchEngineException if there are problems executing the // * search. // */ // public SearchResults search(Query query) throws SearchEngineException; // // /** // * Get a batch of tweets from the search engine, using a minimal handler // * that only returns the tweet text. This is expected to be used to generate // * the list of terms for the word cloud. // * // * <p>Most search parameters will be filled in from the {@link TermsConfiguration}, // * with only the batch number required to set the search start point.</p> // * @param batchNum the number of the batch to look up, starting from 0. // * @return a list of search results, comprising tweets with text only. // * @throws SearchEngineException if there are problems executing the search. // */ // public SearchResults getTextBatch(int batchNum) throws SearchEngineException; // // public void indexTweets(List<Tweet> tweets) throws SearchEngineException; // // public void deleteTweets(List<String> deleteIds) throws SearchEngineException; // // }
import io.dropwizard.lifecycle.Managed; import java.util.Collections; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.co.flax.ukmp.api.Term; import uk.co.flax.ukmp.config.TermsConfiguration; import uk.co.flax.ukmp.search.SearchEngine;
/** * Copyright (c) 2014 Lemur Consulting Ltd. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.flax.ukmp.services; /** * Manager class for handling the terms list. */ public class TermsManager implements Managed { private static final Logger LOGGER = LoggerFactory.getLogger(TermsManager.class); private final TermsManagerThread termsThread;
// Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/api/Term.java // public class Term implements Comparable<Term> { // // private final String term; // private final long count; // // public Term(String term, long count) { // this.term = term; // this.count = count; // } // // /** // * @return the term // */ // public String getTerm() { // return term; // } // // /** // * @return the count // */ // public long getCount() { // return count; // } // // @Override // public int compareTo(Term t) { // int ret = Long.compare(count, t.count); // if (ret == 0) { // ret = term.compareTo(t.term); // } // // return ret; // } // // @Override // public String toString() { // return term + " [" + count + "]"; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/config/TermsConfiguration.java // public class TermsConfiguration { // // @Valid @NotNull // private String handler; // @Valid @NotNull // private String field; // @Valid @NotNull // private int limit; // // private String sortOrder; // // @Valid @NotNull // private int batchSize; // @Valid @NotNull // private List<String> filters; // @Valid @NotNull // private String stopWordsFile; // @Valid @NotNull // private int refreshMinutes; // // // /** // * @return the handler // */ // public String getHandler() { // return handler; // } // // /** // * @return the field // */ // public String getField() { // return field; // } // // /** // * @return the limit // */ // public int getLimit() { // return limit; // } // // public String getSortOrder() { // return sortOrder; // } // // /** // * @return the batchSize // */ // public int getBatchSize() { // return batchSize; // } // // /** // * @return the filters // */ // public List<String> getFilters() { // return filters; // } // // /** // * @return the stopWordsFile // */ // public String getStopWordsFile() { // return stopWordsFile; // } // // /** // * @return the refreshMinutes // */ // public int getRefreshMinutes() { // return refreshMinutes; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/search/SearchEngine.java // public interface SearchEngine { // // /** Enumeration to indicate return states from store/update ops */ // public enum OperationStatus { // SUCCESS, // FAILURE, // NO_OPERATION // } // // public static final String ID_FIELD = "id"; // // /** // * Test the readiness of the search engine. // * @return <code>true</code> if the search engine is available, // * <code>false</code> if not. // * @throws SearchEngineException if a problem occurs while testing the // * search engine. This does not include the search engine being off-line. // */ // public boolean isServerReady() throws SearchEngineException; // // /** // * Carry out a search and return the results. // * @param query the query details. // * @return the results of the search. // * @throws SearchEngineException if there are problems executing the // * search. // */ // public SearchResults search(Query query) throws SearchEngineException; // // /** // * Get a batch of tweets from the search engine, using a minimal handler // * that only returns the tweet text. This is expected to be used to generate // * the list of terms for the word cloud. // * // * <p>Most search parameters will be filled in from the {@link TermsConfiguration}, // * with only the batch number required to set the search start point.</p> // * @param batchNum the number of the batch to look up, starting from 0. // * @return a list of search results, comprising tweets with text only. // * @throws SearchEngineException if there are problems executing the search. // */ // public SearchResults getTextBatch(int batchNum) throws SearchEngineException; // // public void indexTweets(List<Tweet> tweets) throws SearchEngineException; // // public void deleteTweets(List<String> deleteIds) throws SearchEngineException; // // } // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/services/TermsManager.java import io.dropwizard.lifecycle.Managed; import java.util.Collections; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.co.flax.ukmp.api.Term; import uk.co.flax.ukmp.config.TermsConfiguration; import uk.co.flax.ukmp.search.SearchEngine; /** * Copyright (c) 2014 Lemur Consulting Ltd. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.flax.ukmp.services; /** * Manager class for handling the terms list. */ public class TermsManager implements Managed { private static final Logger LOGGER = LoggerFactory.getLogger(TermsManager.class); private final TermsManagerThread termsThread;
public TermsManager(SearchEngine engine, TermsConfiguration config) throws Exception {
flaxsearch/hackday
ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/services/TermsManager.java
// Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/api/Term.java // public class Term implements Comparable<Term> { // // private final String term; // private final long count; // // public Term(String term, long count) { // this.term = term; // this.count = count; // } // // /** // * @return the term // */ // public String getTerm() { // return term; // } // // /** // * @return the count // */ // public long getCount() { // return count; // } // // @Override // public int compareTo(Term t) { // int ret = Long.compare(count, t.count); // if (ret == 0) { // ret = term.compareTo(t.term); // } // // return ret; // } // // @Override // public String toString() { // return term + " [" + count + "]"; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/config/TermsConfiguration.java // public class TermsConfiguration { // // @Valid @NotNull // private String handler; // @Valid @NotNull // private String field; // @Valid @NotNull // private int limit; // // private String sortOrder; // // @Valid @NotNull // private int batchSize; // @Valid @NotNull // private List<String> filters; // @Valid @NotNull // private String stopWordsFile; // @Valid @NotNull // private int refreshMinutes; // // // /** // * @return the handler // */ // public String getHandler() { // return handler; // } // // /** // * @return the field // */ // public String getField() { // return field; // } // // /** // * @return the limit // */ // public int getLimit() { // return limit; // } // // public String getSortOrder() { // return sortOrder; // } // // /** // * @return the batchSize // */ // public int getBatchSize() { // return batchSize; // } // // /** // * @return the filters // */ // public List<String> getFilters() { // return filters; // } // // /** // * @return the stopWordsFile // */ // public String getStopWordsFile() { // return stopWordsFile; // } // // /** // * @return the refreshMinutes // */ // public int getRefreshMinutes() { // return refreshMinutes; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/search/SearchEngine.java // public interface SearchEngine { // // /** Enumeration to indicate return states from store/update ops */ // public enum OperationStatus { // SUCCESS, // FAILURE, // NO_OPERATION // } // // public static final String ID_FIELD = "id"; // // /** // * Test the readiness of the search engine. // * @return <code>true</code> if the search engine is available, // * <code>false</code> if not. // * @throws SearchEngineException if a problem occurs while testing the // * search engine. This does not include the search engine being off-line. // */ // public boolean isServerReady() throws SearchEngineException; // // /** // * Carry out a search and return the results. // * @param query the query details. // * @return the results of the search. // * @throws SearchEngineException if there are problems executing the // * search. // */ // public SearchResults search(Query query) throws SearchEngineException; // // /** // * Get a batch of tweets from the search engine, using a minimal handler // * that only returns the tweet text. This is expected to be used to generate // * the list of terms for the word cloud. // * // * <p>Most search parameters will be filled in from the {@link TermsConfiguration}, // * with only the batch number required to set the search start point.</p> // * @param batchNum the number of the batch to look up, starting from 0. // * @return a list of search results, comprising tweets with text only. // * @throws SearchEngineException if there are problems executing the search. // */ // public SearchResults getTextBatch(int batchNum) throws SearchEngineException; // // public void indexTweets(List<Tweet> tweets) throws SearchEngineException; // // public void deleteTweets(List<String> deleteIds) throws SearchEngineException; // // }
import io.dropwizard.lifecycle.Managed; import java.util.Collections; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.co.flax.ukmp.api.Term; import uk.co.flax.ukmp.config.TermsConfiguration; import uk.co.flax.ukmp.search.SearchEngine;
/** * Copyright (c) 2014 Lemur Consulting Ltd. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.flax.ukmp.services; /** * Manager class for handling the terms list. */ public class TermsManager implements Managed { private static final Logger LOGGER = LoggerFactory.getLogger(TermsManager.class); private final TermsManagerThread termsThread;
// Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/api/Term.java // public class Term implements Comparable<Term> { // // private final String term; // private final long count; // // public Term(String term, long count) { // this.term = term; // this.count = count; // } // // /** // * @return the term // */ // public String getTerm() { // return term; // } // // /** // * @return the count // */ // public long getCount() { // return count; // } // // @Override // public int compareTo(Term t) { // int ret = Long.compare(count, t.count); // if (ret == 0) { // ret = term.compareTo(t.term); // } // // return ret; // } // // @Override // public String toString() { // return term + " [" + count + "]"; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/config/TermsConfiguration.java // public class TermsConfiguration { // // @Valid @NotNull // private String handler; // @Valid @NotNull // private String field; // @Valid @NotNull // private int limit; // // private String sortOrder; // // @Valid @NotNull // private int batchSize; // @Valid @NotNull // private List<String> filters; // @Valid @NotNull // private String stopWordsFile; // @Valid @NotNull // private int refreshMinutes; // // // /** // * @return the handler // */ // public String getHandler() { // return handler; // } // // /** // * @return the field // */ // public String getField() { // return field; // } // // /** // * @return the limit // */ // public int getLimit() { // return limit; // } // // public String getSortOrder() { // return sortOrder; // } // // /** // * @return the batchSize // */ // public int getBatchSize() { // return batchSize; // } // // /** // * @return the filters // */ // public List<String> getFilters() { // return filters; // } // // /** // * @return the stopWordsFile // */ // public String getStopWordsFile() { // return stopWordsFile; // } // // /** // * @return the refreshMinutes // */ // public int getRefreshMinutes() { // return refreshMinutes; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/search/SearchEngine.java // public interface SearchEngine { // // /** Enumeration to indicate return states from store/update ops */ // public enum OperationStatus { // SUCCESS, // FAILURE, // NO_OPERATION // } // // public static final String ID_FIELD = "id"; // // /** // * Test the readiness of the search engine. // * @return <code>true</code> if the search engine is available, // * <code>false</code> if not. // * @throws SearchEngineException if a problem occurs while testing the // * search engine. This does not include the search engine being off-line. // */ // public boolean isServerReady() throws SearchEngineException; // // /** // * Carry out a search and return the results. // * @param query the query details. // * @return the results of the search. // * @throws SearchEngineException if there are problems executing the // * search. // */ // public SearchResults search(Query query) throws SearchEngineException; // // /** // * Get a batch of tweets from the search engine, using a minimal handler // * that only returns the tweet text. This is expected to be used to generate // * the list of terms for the word cloud. // * // * <p>Most search parameters will be filled in from the {@link TermsConfiguration}, // * with only the batch number required to set the search start point.</p> // * @param batchNum the number of the batch to look up, starting from 0. // * @return a list of search results, comprising tweets with text only. // * @throws SearchEngineException if there are problems executing the search. // */ // public SearchResults getTextBatch(int batchNum) throws SearchEngineException; // // public void indexTweets(List<Tweet> tweets) throws SearchEngineException; // // public void deleteTweets(List<String> deleteIds) throws SearchEngineException; // // } // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/services/TermsManager.java import io.dropwizard.lifecycle.Managed; import java.util.Collections; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.co.flax.ukmp.api.Term; import uk.co.flax.ukmp.config.TermsConfiguration; import uk.co.flax.ukmp.search.SearchEngine; /** * Copyright (c) 2014 Lemur Consulting Ltd. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.flax.ukmp.services; /** * Manager class for handling the terms list. */ public class TermsManager implements Managed { private static final Logger LOGGER = LoggerFactory.getLogger(TermsManager.class); private final TermsManagerThread termsThread;
public TermsManager(SearchEngine engine, TermsConfiguration config) throws Exception {
flaxsearch/hackday
ukmp/java/indexer/src/main/java/uk/co/flax/ukmp/IndexerConfiguration.java
// Path: ukmp/java/indexer/src/main/java/uk/co/flax/ukmp/config/PartyConfiguration.java // public class PartyConfiguration { // // private String displayName; // private String twitterScreenName; // private String twitterListSlug; // // /** // * @return the displayName // */ // public String getDisplayName() { // return displayName; // } // // /** // * @param displayName the displayName to set // */ // public void setDisplayName(String displayName) { // this.displayName = displayName; // } // // /** // * @return the twitterOwnerId // */ // public String getTwitterScreenName() { // return twitterScreenName; // } // // /** // * @param twitterOwnerId the twitterOwnerId to set // */ // public void setTwitterScreenName(String twitterOwnerId) { // this.twitterScreenName = twitterOwnerId; // } // // /** // * @return the twitterSlug // */ // public String getTwitterListSlug() { // return twitterListSlug; // } // // /** // * @param twitterSlug the twitterSlug to set // */ // public void setTwitterListSlug(String twitterSlug) { // this.twitterListSlug = twitterSlug; // } // // }
import java.util.Map; import uk.co.flax.ukmp.config.PartyConfiguration;
/** * Copyright (c) 2014 Lemur Consulting Ltd. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.flax.ukmp; /** * @author Matt Pearce */ public class IndexerConfiguration { private String authenticationFile; private String dataDirectory; private String archiveDirectory; private int numListeners; private int numThreads; private int messageQueueSize;
// Path: ukmp/java/indexer/src/main/java/uk/co/flax/ukmp/config/PartyConfiguration.java // public class PartyConfiguration { // // private String displayName; // private String twitterScreenName; // private String twitterListSlug; // // /** // * @return the displayName // */ // public String getDisplayName() { // return displayName; // } // // /** // * @param displayName the displayName to set // */ // public void setDisplayName(String displayName) { // this.displayName = displayName; // } // // /** // * @return the twitterOwnerId // */ // public String getTwitterScreenName() { // return twitterScreenName; // } // // /** // * @param twitterOwnerId the twitterOwnerId to set // */ // public void setTwitterScreenName(String twitterOwnerId) { // this.twitterScreenName = twitterOwnerId; // } // // /** // * @return the twitterSlug // */ // public String getTwitterListSlug() { // return twitterListSlug; // } // // /** // * @param twitterSlug the twitterSlug to set // */ // public void setTwitterListSlug(String twitterSlug) { // this.twitterListSlug = twitterSlug; // } // // } // Path: ukmp/java/indexer/src/main/java/uk/co/flax/ukmp/IndexerConfiguration.java import java.util.Map; import uk.co.flax.ukmp.config.PartyConfiguration; /** * Copyright (c) 2014 Lemur Consulting Ltd. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.flax.ukmp; /** * @author Matt Pearce */ public class IndexerConfiguration { private String authenticationFile; private String dataDirectory; private String archiveDirectory; private int numListeners; private int numThreads; private int messageQueueSize;
private Map<String, PartyConfiguration> parties;
flaxsearch/hackday
ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/resources/SentimentAnalyzer.java
// Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/api/Sentiment.java // public class Sentiment { // // public static final int SENTIMENT_POSITIVE = 3; // public static final int SENTIMENT_NEUTRAL = 2; // public static final int SENTIMENT_NEGATIVE = 1; // // @JsonProperty("class") // private final String sentimentClass; // @JsonProperty("value") // private final int sentimentValue; // // public Sentiment(String classText, int value) { // this.sentimentClass = classText; // this.sentimentValue = value; // } // // /** // * @return the sentimentClass // */ // public String getSentimentClass() { // return sentimentClass; // } // // /** // * @return the sentimentValue // */ // public int getSentimentValue() { // return sentimentValue; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/api/StanfordData.java // public class StanfordData { // // @JsonProperty("entities") // private final Map<String, List<String>> entities; // @JsonProperty("sentiment") // private final Sentiment sentiment; // // public StanfordData(Map<String, List<String>> entities, Sentiment sentiment) { // this.entities = entities; // this.sentiment = sentiment; // } // // /** // * @return the entities // */ // public Map<String, List<String>> getEntities() { // return entities; // } // // /** // * @return the sentiment // */ // public Sentiment getSentiment() { // return sentiment; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/api/StanfordRequest.java // public class StanfordRequest { // // @JsonProperty("text") // private String text; // // public void setText(String t) { // this.text = t; // } // // public String getText() { // return text; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/services/SentimentAnalysisService.java // public class SentimentAnalysisService { // // private static final String LINK_REGEX = "(https?://\\S+)"; // private static final String USERNAME_REGEX = "(@(\\w+))"; // // private static final Logger LOGGER = LoggerFactory.getLogger(SentimentAnalysisService.class); // // private final StanfordCoreNLP pipeline; // // /** // * Create a new SentimentAnalyzer using details from the Stanford // * configuration properties. // * // * @param config the configuration. // */ // public SentimentAnalysisService(StanfordConfiguration config) { // pipeline = new StanfordCoreNLP(config.getJavaSentimentProperties()); // } // // /** // * Analyse tweet text, returning the sentiment extracted from the longest // * sentence (by character count). // * @param text the tweet text. // * @return a {@link Sentiment} object containing the sentiment value and // * its label. // */ // public Sentiment analyze(String text) { // Sentiment mainSentiment = null; // // if (text != null && text.length() > 0) { // String psText = preprocessText(text); // // int longest = 0; // Annotation annotation = pipeline.process(psText); // for (CoreMap sentence : annotation.get(CoreAnnotations.SentencesAnnotation.class)) { // String partText = sentence.toString(); // if (partText.length() > longest) { // Tree tree = sentence.get(SentimentCoreAnnotations.AnnotatedTree.class); // int sentiment = RNNCoreAnnotations.getPredictedClass(tree); // mainSentiment = new Sentiment(sentence.get(SentimentCoreAnnotations.ClassName.class), sentiment); // longest = partText.length(); // } // } // // LOGGER.trace("Got '{}' sentiment from '{}'", mainSentiment.getSentimentClass(), psText); // } // // return mainSentiment; // } // // // private String preprocessText(String text) { // String ret; // // // Convert links to LINK // ret = text.replaceAll(LINK_REGEX, "LINK"); // // // Convert usernames to USERNAME // ret = ret.replaceAll(USERNAME_REGEX, "USERNAME"); // // return ret; // } // // }
import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import uk.co.flax.ukmp.api.Sentiment; import uk.co.flax.ukmp.api.StanfordData; import uk.co.flax.ukmp.api.StanfordRequest; import uk.co.flax.ukmp.services.SentimentAnalysisService;
/** * Copyright (c) 2014 Lemur Consulting Ltd. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.flax.ukmp.resources; /** * Resource handler for extracting sentiment data from tweet text. */ @Path("/sentimentAnalyzer") public class SentimentAnalyzer {
// Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/api/Sentiment.java // public class Sentiment { // // public static final int SENTIMENT_POSITIVE = 3; // public static final int SENTIMENT_NEUTRAL = 2; // public static final int SENTIMENT_NEGATIVE = 1; // // @JsonProperty("class") // private final String sentimentClass; // @JsonProperty("value") // private final int sentimentValue; // // public Sentiment(String classText, int value) { // this.sentimentClass = classText; // this.sentimentValue = value; // } // // /** // * @return the sentimentClass // */ // public String getSentimentClass() { // return sentimentClass; // } // // /** // * @return the sentimentValue // */ // public int getSentimentValue() { // return sentimentValue; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/api/StanfordData.java // public class StanfordData { // // @JsonProperty("entities") // private final Map<String, List<String>> entities; // @JsonProperty("sentiment") // private final Sentiment sentiment; // // public StanfordData(Map<String, List<String>> entities, Sentiment sentiment) { // this.entities = entities; // this.sentiment = sentiment; // } // // /** // * @return the entities // */ // public Map<String, List<String>> getEntities() { // return entities; // } // // /** // * @return the sentiment // */ // public Sentiment getSentiment() { // return sentiment; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/api/StanfordRequest.java // public class StanfordRequest { // // @JsonProperty("text") // private String text; // // public void setText(String t) { // this.text = t; // } // // public String getText() { // return text; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/services/SentimentAnalysisService.java // public class SentimentAnalysisService { // // private static final String LINK_REGEX = "(https?://\\S+)"; // private static final String USERNAME_REGEX = "(@(\\w+))"; // // private static final Logger LOGGER = LoggerFactory.getLogger(SentimentAnalysisService.class); // // private final StanfordCoreNLP pipeline; // // /** // * Create a new SentimentAnalyzer using details from the Stanford // * configuration properties. // * // * @param config the configuration. // */ // public SentimentAnalysisService(StanfordConfiguration config) { // pipeline = new StanfordCoreNLP(config.getJavaSentimentProperties()); // } // // /** // * Analyse tweet text, returning the sentiment extracted from the longest // * sentence (by character count). // * @param text the tweet text. // * @return a {@link Sentiment} object containing the sentiment value and // * its label. // */ // public Sentiment analyze(String text) { // Sentiment mainSentiment = null; // // if (text != null && text.length() > 0) { // String psText = preprocessText(text); // // int longest = 0; // Annotation annotation = pipeline.process(psText); // for (CoreMap sentence : annotation.get(CoreAnnotations.SentencesAnnotation.class)) { // String partText = sentence.toString(); // if (partText.length() > longest) { // Tree tree = sentence.get(SentimentCoreAnnotations.AnnotatedTree.class); // int sentiment = RNNCoreAnnotations.getPredictedClass(tree); // mainSentiment = new Sentiment(sentence.get(SentimentCoreAnnotations.ClassName.class), sentiment); // longest = partText.length(); // } // } // // LOGGER.trace("Got '{}' sentiment from '{}'", mainSentiment.getSentimentClass(), psText); // } // // return mainSentiment; // } // // // private String preprocessText(String text) { // String ret; // // // Convert links to LINK // ret = text.replaceAll(LINK_REGEX, "LINK"); // // // Convert usernames to USERNAME // ret = ret.replaceAll(USERNAME_REGEX, "USERNAME"); // // return ret; // } // // } // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/resources/SentimentAnalyzer.java import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import uk.co.flax.ukmp.api.Sentiment; import uk.co.flax.ukmp.api.StanfordData; import uk.co.flax.ukmp.api.StanfordRequest; import uk.co.flax.ukmp.services.SentimentAnalysisService; /** * Copyright (c) 2014 Lemur Consulting Ltd. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.flax.ukmp.resources; /** * Resource handler for extracting sentiment data from tweet text. */ @Path("/sentimentAnalyzer") public class SentimentAnalyzer {
private final SentimentAnalysisService sentimentService;
flaxsearch/hackday
ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/resources/SentimentAnalyzer.java
// Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/api/Sentiment.java // public class Sentiment { // // public static final int SENTIMENT_POSITIVE = 3; // public static final int SENTIMENT_NEUTRAL = 2; // public static final int SENTIMENT_NEGATIVE = 1; // // @JsonProperty("class") // private final String sentimentClass; // @JsonProperty("value") // private final int sentimentValue; // // public Sentiment(String classText, int value) { // this.sentimentClass = classText; // this.sentimentValue = value; // } // // /** // * @return the sentimentClass // */ // public String getSentimentClass() { // return sentimentClass; // } // // /** // * @return the sentimentValue // */ // public int getSentimentValue() { // return sentimentValue; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/api/StanfordData.java // public class StanfordData { // // @JsonProperty("entities") // private final Map<String, List<String>> entities; // @JsonProperty("sentiment") // private final Sentiment sentiment; // // public StanfordData(Map<String, List<String>> entities, Sentiment sentiment) { // this.entities = entities; // this.sentiment = sentiment; // } // // /** // * @return the entities // */ // public Map<String, List<String>> getEntities() { // return entities; // } // // /** // * @return the sentiment // */ // public Sentiment getSentiment() { // return sentiment; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/api/StanfordRequest.java // public class StanfordRequest { // // @JsonProperty("text") // private String text; // // public void setText(String t) { // this.text = t; // } // // public String getText() { // return text; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/services/SentimentAnalysisService.java // public class SentimentAnalysisService { // // private static final String LINK_REGEX = "(https?://\\S+)"; // private static final String USERNAME_REGEX = "(@(\\w+))"; // // private static final Logger LOGGER = LoggerFactory.getLogger(SentimentAnalysisService.class); // // private final StanfordCoreNLP pipeline; // // /** // * Create a new SentimentAnalyzer using details from the Stanford // * configuration properties. // * // * @param config the configuration. // */ // public SentimentAnalysisService(StanfordConfiguration config) { // pipeline = new StanfordCoreNLP(config.getJavaSentimentProperties()); // } // // /** // * Analyse tweet text, returning the sentiment extracted from the longest // * sentence (by character count). // * @param text the tweet text. // * @return a {@link Sentiment} object containing the sentiment value and // * its label. // */ // public Sentiment analyze(String text) { // Sentiment mainSentiment = null; // // if (text != null && text.length() > 0) { // String psText = preprocessText(text); // // int longest = 0; // Annotation annotation = pipeline.process(psText); // for (CoreMap sentence : annotation.get(CoreAnnotations.SentencesAnnotation.class)) { // String partText = sentence.toString(); // if (partText.length() > longest) { // Tree tree = sentence.get(SentimentCoreAnnotations.AnnotatedTree.class); // int sentiment = RNNCoreAnnotations.getPredictedClass(tree); // mainSentiment = new Sentiment(sentence.get(SentimentCoreAnnotations.ClassName.class), sentiment); // longest = partText.length(); // } // } // // LOGGER.trace("Got '{}' sentiment from '{}'", mainSentiment.getSentimentClass(), psText); // } // // return mainSentiment; // } // // // private String preprocessText(String text) { // String ret; // // // Convert links to LINK // ret = text.replaceAll(LINK_REGEX, "LINK"); // // // Convert usernames to USERNAME // ret = ret.replaceAll(USERNAME_REGEX, "USERNAME"); // // return ret; // } // // }
import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import uk.co.flax.ukmp.api.Sentiment; import uk.co.flax.ukmp.api.StanfordData; import uk.co.flax.ukmp.api.StanfordRequest; import uk.co.flax.ukmp.services.SentimentAnalysisService;
/** * Copyright (c) 2014 Lemur Consulting Ltd. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.flax.ukmp.resources; /** * Resource handler for extracting sentiment data from tweet text. */ @Path("/sentimentAnalyzer") public class SentimentAnalyzer { private final SentimentAnalysisService sentimentService; public SentimentAnalyzer(SentimentAnalysisService svc) { this.sentimentService = svc; } @POST @Produces(MediaType.APPLICATION_JSON)
// Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/api/Sentiment.java // public class Sentiment { // // public static final int SENTIMENT_POSITIVE = 3; // public static final int SENTIMENT_NEUTRAL = 2; // public static final int SENTIMENT_NEGATIVE = 1; // // @JsonProperty("class") // private final String sentimentClass; // @JsonProperty("value") // private final int sentimentValue; // // public Sentiment(String classText, int value) { // this.sentimentClass = classText; // this.sentimentValue = value; // } // // /** // * @return the sentimentClass // */ // public String getSentimentClass() { // return sentimentClass; // } // // /** // * @return the sentimentValue // */ // public int getSentimentValue() { // return sentimentValue; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/api/StanfordData.java // public class StanfordData { // // @JsonProperty("entities") // private final Map<String, List<String>> entities; // @JsonProperty("sentiment") // private final Sentiment sentiment; // // public StanfordData(Map<String, List<String>> entities, Sentiment sentiment) { // this.entities = entities; // this.sentiment = sentiment; // } // // /** // * @return the entities // */ // public Map<String, List<String>> getEntities() { // return entities; // } // // /** // * @return the sentiment // */ // public Sentiment getSentiment() { // return sentiment; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/api/StanfordRequest.java // public class StanfordRequest { // // @JsonProperty("text") // private String text; // // public void setText(String t) { // this.text = t; // } // // public String getText() { // return text; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/services/SentimentAnalysisService.java // public class SentimentAnalysisService { // // private static final String LINK_REGEX = "(https?://\\S+)"; // private static final String USERNAME_REGEX = "(@(\\w+))"; // // private static final Logger LOGGER = LoggerFactory.getLogger(SentimentAnalysisService.class); // // private final StanfordCoreNLP pipeline; // // /** // * Create a new SentimentAnalyzer using details from the Stanford // * configuration properties. // * // * @param config the configuration. // */ // public SentimentAnalysisService(StanfordConfiguration config) { // pipeline = new StanfordCoreNLP(config.getJavaSentimentProperties()); // } // // /** // * Analyse tweet text, returning the sentiment extracted from the longest // * sentence (by character count). // * @param text the tweet text. // * @return a {@link Sentiment} object containing the sentiment value and // * its label. // */ // public Sentiment analyze(String text) { // Sentiment mainSentiment = null; // // if (text != null && text.length() > 0) { // String psText = preprocessText(text); // // int longest = 0; // Annotation annotation = pipeline.process(psText); // for (CoreMap sentence : annotation.get(CoreAnnotations.SentencesAnnotation.class)) { // String partText = sentence.toString(); // if (partText.length() > longest) { // Tree tree = sentence.get(SentimentCoreAnnotations.AnnotatedTree.class); // int sentiment = RNNCoreAnnotations.getPredictedClass(tree); // mainSentiment = new Sentiment(sentence.get(SentimentCoreAnnotations.ClassName.class), sentiment); // longest = partText.length(); // } // } // // LOGGER.trace("Got '{}' sentiment from '{}'", mainSentiment.getSentimentClass(), psText); // } // // return mainSentiment; // } // // // private String preprocessText(String text) { // String ret; // // // Convert links to LINK // ret = text.replaceAll(LINK_REGEX, "LINK"); // // // Convert usernames to USERNAME // ret = ret.replaceAll(USERNAME_REGEX, "USERNAME"); // // return ret; // } // // } // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/resources/SentimentAnalyzer.java import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import uk.co.flax.ukmp.api.Sentiment; import uk.co.flax.ukmp.api.StanfordData; import uk.co.flax.ukmp.api.StanfordRequest; import uk.co.flax.ukmp.services.SentimentAnalysisService; /** * Copyright (c) 2014 Lemur Consulting Ltd. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.flax.ukmp.resources; /** * Resource handler for extracting sentiment data from tweet text. */ @Path("/sentimentAnalyzer") public class SentimentAnalyzer { private final SentimentAnalysisService sentimentService; public SentimentAnalyzer(SentimentAnalysisService svc) { this.sentimentService = svc; } @POST @Produces(MediaType.APPLICATION_JSON)
public StanfordData handlePost(StanfordRequest req) {
flaxsearch/hackday
ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/resources/SentimentAnalyzer.java
// Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/api/Sentiment.java // public class Sentiment { // // public static final int SENTIMENT_POSITIVE = 3; // public static final int SENTIMENT_NEUTRAL = 2; // public static final int SENTIMENT_NEGATIVE = 1; // // @JsonProperty("class") // private final String sentimentClass; // @JsonProperty("value") // private final int sentimentValue; // // public Sentiment(String classText, int value) { // this.sentimentClass = classText; // this.sentimentValue = value; // } // // /** // * @return the sentimentClass // */ // public String getSentimentClass() { // return sentimentClass; // } // // /** // * @return the sentimentValue // */ // public int getSentimentValue() { // return sentimentValue; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/api/StanfordData.java // public class StanfordData { // // @JsonProperty("entities") // private final Map<String, List<String>> entities; // @JsonProperty("sentiment") // private final Sentiment sentiment; // // public StanfordData(Map<String, List<String>> entities, Sentiment sentiment) { // this.entities = entities; // this.sentiment = sentiment; // } // // /** // * @return the entities // */ // public Map<String, List<String>> getEntities() { // return entities; // } // // /** // * @return the sentiment // */ // public Sentiment getSentiment() { // return sentiment; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/api/StanfordRequest.java // public class StanfordRequest { // // @JsonProperty("text") // private String text; // // public void setText(String t) { // this.text = t; // } // // public String getText() { // return text; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/services/SentimentAnalysisService.java // public class SentimentAnalysisService { // // private static final String LINK_REGEX = "(https?://\\S+)"; // private static final String USERNAME_REGEX = "(@(\\w+))"; // // private static final Logger LOGGER = LoggerFactory.getLogger(SentimentAnalysisService.class); // // private final StanfordCoreNLP pipeline; // // /** // * Create a new SentimentAnalyzer using details from the Stanford // * configuration properties. // * // * @param config the configuration. // */ // public SentimentAnalysisService(StanfordConfiguration config) { // pipeline = new StanfordCoreNLP(config.getJavaSentimentProperties()); // } // // /** // * Analyse tweet text, returning the sentiment extracted from the longest // * sentence (by character count). // * @param text the tweet text. // * @return a {@link Sentiment} object containing the sentiment value and // * its label. // */ // public Sentiment analyze(String text) { // Sentiment mainSentiment = null; // // if (text != null && text.length() > 0) { // String psText = preprocessText(text); // // int longest = 0; // Annotation annotation = pipeline.process(psText); // for (CoreMap sentence : annotation.get(CoreAnnotations.SentencesAnnotation.class)) { // String partText = sentence.toString(); // if (partText.length() > longest) { // Tree tree = sentence.get(SentimentCoreAnnotations.AnnotatedTree.class); // int sentiment = RNNCoreAnnotations.getPredictedClass(tree); // mainSentiment = new Sentiment(sentence.get(SentimentCoreAnnotations.ClassName.class), sentiment); // longest = partText.length(); // } // } // // LOGGER.trace("Got '{}' sentiment from '{}'", mainSentiment.getSentimentClass(), psText); // } // // return mainSentiment; // } // // // private String preprocessText(String text) { // String ret; // // // Convert links to LINK // ret = text.replaceAll(LINK_REGEX, "LINK"); // // // Convert usernames to USERNAME // ret = ret.replaceAll(USERNAME_REGEX, "USERNAME"); // // return ret; // } // // }
import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import uk.co.flax.ukmp.api.Sentiment; import uk.co.flax.ukmp.api.StanfordData; import uk.co.flax.ukmp.api.StanfordRequest; import uk.co.flax.ukmp.services.SentimentAnalysisService;
/** * Copyright (c) 2014 Lemur Consulting Ltd. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.flax.ukmp.resources; /** * Resource handler for extracting sentiment data from tweet text. */ @Path("/sentimentAnalyzer") public class SentimentAnalyzer { private final SentimentAnalysisService sentimentService; public SentimentAnalyzer(SentimentAnalysisService svc) { this.sentimentService = svc; } @POST @Produces(MediaType.APPLICATION_JSON)
// Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/api/Sentiment.java // public class Sentiment { // // public static final int SENTIMENT_POSITIVE = 3; // public static final int SENTIMENT_NEUTRAL = 2; // public static final int SENTIMENT_NEGATIVE = 1; // // @JsonProperty("class") // private final String sentimentClass; // @JsonProperty("value") // private final int sentimentValue; // // public Sentiment(String classText, int value) { // this.sentimentClass = classText; // this.sentimentValue = value; // } // // /** // * @return the sentimentClass // */ // public String getSentimentClass() { // return sentimentClass; // } // // /** // * @return the sentimentValue // */ // public int getSentimentValue() { // return sentimentValue; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/api/StanfordData.java // public class StanfordData { // // @JsonProperty("entities") // private final Map<String, List<String>> entities; // @JsonProperty("sentiment") // private final Sentiment sentiment; // // public StanfordData(Map<String, List<String>> entities, Sentiment sentiment) { // this.entities = entities; // this.sentiment = sentiment; // } // // /** // * @return the entities // */ // public Map<String, List<String>> getEntities() { // return entities; // } // // /** // * @return the sentiment // */ // public Sentiment getSentiment() { // return sentiment; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/api/StanfordRequest.java // public class StanfordRequest { // // @JsonProperty("text") // private String text; // // public void setText(String t) { // this.text = t; // } // // public String getText() { // return text; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/services/SentimentAnalysisService.java // public class SentimentAnalysisService { // // private static final String LINK_REGEX = "(https?://\\S+)"; // private static final String USERNAME_REGEX = "(@(\\w+))"; // // private static final Logger LOGGER = LoggerFactory.getLogger(SentimentAnalysisService.class); // // private final StanfordCoreNLP pipeline; // // /** // * Create a new SentimentAnalyzer using details from the Stanford // * configuration properties. // * // * @param config the configuration. // */ // public SentimentAnalysisService(StanfordConfiguration config) { // pipeline = new StanfordCoreNLP(config.getJavaSentimentProperties()); // } // // /** // * Analyse tweet text, returning the sentiment extracted from the longest // * sentence (by character count). // * @param text the tweet text. // * @return a {@link Sentiment} object containing the sentiment value and // * its label. // */ // public Sentiment analyze(String text) { // Sentiment mainSentiment = null; // // if (text != null && text.length() > 0) { // String psText = preprocessText(text); // // int longest = 0; // Annotation annotation = pipeline.process(psText); // for (CoreMap sentence : annotation.get(CoreAnnotations.SentencesAnnotation.class)) { // String partText = sentence.toString(); // if (partText.length() > longest) { // Tree tree = sentence.get(SentimentCoreAnnotations.AnnotatedTree.class); // int sentiment = RNNCoreAnnotations.getPredictedClass(tree); // mainSentiment = new Sentiment(sentence.get(SentimentCoreAnnotations.ClassName.class), sentiment); // longest = partText.length(); // } // } // // LOGGER.trace("Got '{}' sentiment from '{}'", mainSentiment.getSentimentClass(), psText); // } // // return mainSentiment; // } // // // private String preprocessText(String text) { // String ret; // // // Convert links to LINK // ret = text.replaceAll(LINK_REGEX, "LINK"); // // // Convert usernames to USERNAME // ret = ret.replaceAll(USERNAME_REGEX, "USERNAME"); // // return ret; // } // // } // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/resources/SentimentAnalyzer.java import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import uk.co.flax.ukmp.api.Sentiment; import uk.co.flax.ukmp.api.StanfordData; import uk.co.flax.ukmp.api.StanfordRequest; import uk.co.flax.ukmp.services.SentimentAnalysisService; /** * Copyright (c) 2014 Lemur Consulting Ltd. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.flax.ukmp.resources; /** * Resource handler for extracting sentiment data from tweet text. */ @Path("/sentimentAnalyzer") public class SentimentAnalyzer { private final SentimentAnalysisService sentimentService; public SentimentAnalyzer(SentimentAnalysisService svc) { this.sentimentService = svc; } @POST @Produces(MediaType.APPLICATION_JSON)
public StanfordData handlePost(StanfordRequest req) {
flaxsearch/hackday
ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/resources/SentimentAnalyzer.java
// Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/api/Sentiment.java // public class Sentiment { // // public static final int SENTIMENT_POSITIVE = 3; // public static final int SENTIMENT_NEUTRAL = 2; // public static final int SENTIMENT_NEGATIVE = 1; // // @JsonProperty("class") // private final String sentimentClass; // @JsonProperty("value") // private final int sentimentValue; // // public Sentiment(String classText, int value) { // this.sentimentClass = classText; // this.sentimentValue = value; // } // // /** // * @return the sentimentClass // */ // public String getSentimentClass() { // return sentimentClass; // } // // /** // * @return the sentimentValue // */ // public int getSentimentValue() { // return sentimentValue; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/api/StanfordData.java // public class StanfordData { // // @JsonProperty("entities") // private final Map<String, List<String>> entities; // @JsonProperty("sentiment") // private final Sentiment sentiment; // // public StanfordData(Map<String, List<String>> entities, Sentiment sentiment) { // this.entities = entities; // this.sentiment = sentiment; // } // // /** // * @return the entities // */ // public Map<String, List<String>> getEntities() { // return entities; // } // // /** // * @return the sentiment // */ // public Sentiment getSentiment() { // return sentiment; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/api/StanfordRequest.java // public class StanfordRequest { // // @JsonProperty("text") // private String text; // // public void setText(String t) { // this.text = t; // } // // public String getText() { // return text; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/services/SentimentAnalysisService.java // public class SentimentAnalysisService { // // private static final String LINK_REGEX = "(https?://\\S+)"; // private static final String USERNAME_REGEX = "(@(\\w+))"; // // private static final Logger LOGGER = LoggerFactory.getLogger(SentimentAnalysisService.class); // // private final StanfordCoreNLP pipeline; // // /** // * Create a new SentimentAnalyzer using details from the Stanford // * configuration properties. // * // * @param config the configuration. // */ // public SentimentAnalysisService(StanfordConfiguration config) { // pipeline = new StanfordCoreNLP(config.getJavaSentimentProperties()); // } // // /** // * Analyse tweet text, returning the sentiment extracted from the longest // * sentence (by character count). // * @param text the tweet text. // * @return a {@link Sentiment} object containing the sentiment value and // * its label. // */ // public Sentiment analyze(String text) { // Sentiment mainSentiment = null; // // if (text != null && text.length() > 0) { // String psText = preprocessText(text); // // int longest = 0; // Annotation annotation = pipeline.process(psText); // for (CoreMap sentence : annotation.get(CoreAnnotations.SentencesAnnotation.class)) { // String partText = sentence.toString(); // if (partText.length() > longest) { // Tree tree = sentence.get(SentimentCoreAnnotations.AnnotatedTree.class); // int sentiment = RNNCoreAnnotations.getPredictedClass(tree); // mainSentiment = new Sentiment(sentence.get(SentimentCoreAnnotations.ClassName.class), sentiment); // longest = partText.length(); // } // } // // LOGGER.trace("Got '{}' sentiment from '{}'", mainSentiment.getSentimentClass(), psText); // } // // return mainSentiment; // } // // // private String preprocessText(String text) { // String ret; // // // Convert links to LINK // ret = text.replaceAll(LINK_REGEX, "LINK"); // // // Convert usernames to USERNAME // ret = ret.replaceAll(USERNAME_REGEX, "USERNAME"); // // return ret; // } // // }
import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import uk.co.flax.ukmp.api.Sentiment; import uk.co.flax.ukmp.api.StanfordData; import uk.co.flax.ukmp.api.StanfordRequest; import uk.co.flax.ukmp.services.SentimentAnalysisService;
/** * Copyright (c) 2014 Lemur Consulting Ltd. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.flax.ukmp.resources; /** * Resource handler for extracting sentiment data from tweet text. */ @Path("/sentimentAnalyzer") public class SentimentAnalyzer { private final SentimentAnalysisService sentimentService; public SentimentAnalyzer(SentimentAnalysisService svc) { this.sentimentService = svc; } @POST @Produces(MediaType.APPLICATION_JSON) public StanfordData handlePost(StanfordRequest req) { String text = req.getText();
// Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/api/Sentiment.java // public class Sentiment { // // public static final int SENTIMENT_POSITIVE = 3; // public static final int SENTIMENT_NEUTRAL = 2; // public static final int SENTIMENT_NEGATIVE = 1; // // @JsonProperty("class") // private final String sentimentClass; // @JsonProperty("value") // private final int sentimentValue; // // public Sentiment(String classText, int value) { // this.sentimentClass = classText; // this.sentimentValue = value; // } // // /** // * @return the sentimentClass // */ // public String getSentimentClass() { // return sentimentClass; // } // // /** // * @return the sentimentValue // */ // public int getSentimentValue() { // return sentimentValue; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/api/StanfordData.java // public class StanfordData { // // @JsonProperty("entities") // private final Map<String, List<String>> entities; // @JsonProperty("sentiment") // private final Sentiment sentiment; // // public StanfordData(Map<String, List<String>> entities, Sentiment sentiment) { // this.entities = entities; // this.sentiment = sentiment; // } // // /** // * @return the entities // */ // public Map<String, List<String>> getEntities() { // return entities; // } // // /** // * @return the sentiment // */ // public Sentiment getSentiment() { // return sentiment; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/api/StanfordRequest.java // public class StanfordRequest { // // @JsonProperty("text") // private String text; // // public void setText(String t) { // this.text = t; // } // // public String getText() { // return text; // } // // } // // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/services/SentimentAnalysisService.java // public class SentimentAnalysisService { // // private static final String LINK_REGEX = "(https?://\\S+)"; // private static final String USERNAME_REGEX = "(@(\\w+))"; // // private static final Logger LOGGER = LoggerFactory.getLogger(SentimentAnalysisService.class); // // private final StanfordCoreNLP pipeline; // // /** // * Create a new SentimentAnalyzer using details from the Stanford // * configuration properties. // * // * @param config the configuration. // */ // public SentimentAnalysisService(StanfordConfiguration config) { // pipeline = new StanfordCoreNLP(config.getJavaSentimentProperties()); // } // // /** // * Analyse tweet text, returning the sentiment extracted from the longest // * sentence (by character count). // * @param text the tweet text. // * @return a {@link Sentiment} object containing the sentiment value and // * its label. // */ // public Sentiment analyze(String text) { // Sentiment mainSentiment = null; // // if (text != null && text.length() > 0) { // String psText = preprocessText(text); // // int longest = 0; // Annotation annotation = pipeline.process(psText); // for (CoreMap sentence : annotation.get(CoreAnnotations.SentencesAnnotation.class)) { // String partText = sentence.toString(); // if (partText.length() > longest) { // Tree tree = sentence.get(SentimentCoreAnnotations.AnnotatedTree.class); // int sentiment = RNNCoreAnnotations.getPredictedClass(tree); // mainSentiment = new Sentiment(sentence.get(SentimentCoreAnnotations.ClassName.class), sentiment); // longest = partText.length(); // } // } // // LOGGER.trace("Got '{}' sentiment from '{}'", mainSentiment.getSentimentClass(), psText); // } // // return mainSentiment; // } // // // private String preprocessText(String text) { // String ret; // // // Convert links to LINK // ret = text.replaceAll(LINK_REGEX, "LINK"); // // // Convert usernames to USERNAME // ret = ret.replaceAll(USERNAME_REGEX, "USERNAME"); // // return ret; // } // // } // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/resources/SentimentAnalyzer.java import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import uk.co.flax.ukmp.api.Sentiment; import uk.co.flax.ukmp.api.StanfordData; import uk.co.flax.ukmp.api.StanfordRequest; import uk.co.flax.ukmp.services.SentimentAnalysisService; /** * Copyright (c) 2014 Lemur Consulting Ltd. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.flax.ukmp.resources; /** * Resource handler for extracting sentiment data from tweet text. */ @Path("/sentimentAnalyzer") public class SentimentAnalyzer { private final SentimentAnalysisService sentimentService; public SentimentAnalyzer(SentimentAnalysisService svc) { this.sentimentService = svc; } @POST @Produces(MediaType.APPLICATION_JSON) public StanfordData handlePost(StanfordRequest req) { String text = req.getText();
Sentiment sentiment = sentimentService.analyze(text);
flaxsearch/hackday
ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/twitter/AbstractTwitterClient.java
// Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/config/TwitterConfiguration.java // public class TwitterConfiguration { // // private String authConfigFile; // // private int deletionBatchSize = 50; // // private int statusBatchSize = 100; // // private boolean enabled; // // private List<TwitterListConfiguration> lists; // // private int updateCheckHours; // // @NotNull // private String dataDirectory; // // public boolean isEnabled() { // return enabled; // } // // public String getAuthConfigFile() { // return authConfigFile; // } // // public int getDeletionBatchSize() { // return deletionBatchSize; // } // // public int getStatusBatchSize() { // return statusBatchSize; // } // // public List<TwitterListConfiguration> getLists() { // return lists; // } // // public int getUpdateCheckHours() { // return updateCheckHours; // } // // /** // * @return the dataDirectory // */ // public String getDataDirectory() { // return dataDirectory; // } // // }
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang3.StringUtils; import twitter4j.conf.Configuration; import twitter4j.conf.ConfigurationBuilder; import uk.co.flax.ukmp.config.TwitterConfiguration;
/** * Copyright (c) 2015 Lemur Consulting Ltd. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.flax.ukmp.twitter; /** * Base class for the twitter handlers. * * @author Matt Pearce */ public abstract class AbstractTwitterClient { private static final String CONSUMER_KEY = "consumer_key"; private static final String CONSUMER_SECRET = "consumer_secret"; private static final String ACCESS_TOKEN = "access_token_key"; private static final String ACCESS_SECRET = "access_token_secret";
// Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/config/TwitterConfiguration.java // public class TwitterConfiguration { // // private String authConfigFile; // // private int deletionBatchSize = 50; // // private int statusBatchSize = 100; // // private boolean enabled; // // private List<TwitterListConfiguration> lists; // // private int updateCheckHours; // // @NotNull // private String dataDirectory; // // public boolean isEnabled() { // return enabled; // } // // public String getAuthConfigFile() { // return authConfigFile; // } // // public int getDeletionBatchSize() { // return deletionBatchSize; // } // // public int getStatusBatchSize() { // return statusBatchSize; // } // // public List<TwitterListConfiguration> getLists() { // return lists; // } // // public int getUpdateCheckHours() { // return updateCheckHours; // } // // /** // * @return the dataDirectory // */ // public String getDataDirectory() { // return dataDirectory; // } // // } // Path: ukmp/java/webapp/src/main/java/uk/co/flax/ukmp/twitter/AbstractTwitterClient.java import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang3.StringUtils; import twitter4j.conf.Configuration; import twitter4j.conf.ConfigurationBuilder; import uk.co.flax.ukmp.config.TwitterConfiguration; /** * Copyright (c) 2015 Lemur Consulting Ltd. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.flax.ukmp.twitter; /** * Base class for the twitter handlers. * * @author Matt Pearce */ public abstract class AbstractTwitterClient { private static final String CONSUMER_KEY = "consumer_key"; private static final String CONSUMER_SECRET = "consumer_secret"; private static final String ACCESS_TOKEN = "access_token_key"; private static final String ACCESS_SECRET = "access_token_secret";
protected abstract TwitterConfiguration getConfig();
flaxsearch/hackday
ukmp/java/indexer/src/main/java/uk/co/flax/ukmp/Indexer.java
// Path: ukmp/java/indexer/src/main/java/uk/co/flax/ukmp/twitter/PartyListHandler.java // public class PartyListHandler { // // private static final Logger LOGGER = LoggerFactory.getLogger(PartyListHandler.class); // // private static final long REFRESH_TIME = 6 * 60 * 60 * 1000; // // private final Configuration twitterConfig; // private final Map<String, PartyConfiguration> parties; // // private boolean hasChanged; // private Date updateTime; // // // private Map<String, Set<Long>> partyMemberIds = new HashMap<>(); // private Map<Long, String> memberParties = new HashMap<>(); // // public PartyListHandler(Configuration twitterConfig, Map<String, PartyConfiguration> parties) { // this.twitterConfig = twitterConfig; // this.parties = parties; // } // // // public void refreshLists() { // Map<String, Set<Long>> memberIds = new HashMap<>(); // // Authorization auth = AuthorizationFactory.getInstance(twitterConfig); // TwitterFactory tf = new TwitterFactory(twitterConfig); // Twitter twitter = tf.getInstance(auth); // for (PartyConfiguration pc : parties.values()) { // Set<Long> ids = readPartyIds(twitter, pc.getTwitterScreenName(), pc.getTwitterListSlug(), pc.getDisplayName()); // if (!ids.isEmpty()) { // memberIds.put(pc.getDisplayName(), ids); // } // } // // synchronized(partyMemberIds) { // for (String party : memberIds.keySet()) { // if (!partyMemberIds.containsKey(party) || Sets.symmetricDifference(memberIds.get(party), partyMemberIds.get(party)).size() > 0) { // hasChanged = true; // partyMemberIds.put(party, memberIds.get(party)); // LOGGER.debug("Updated list for {} with {} ids", party, memberIds.get(party).size()); // } // } // } // // if (hasChanged) { // updateTime = new Date(); // memberParties.clear(); // } // } // // private Set<Long> readPartyIds(Twitter twitter, String screenName, String slug, String party) { // Set<Long> ids = new HashSet<>(); // // try { // long cursor = -1; // PagableResponseList<User> response = null; // do { // response = twitter.getUserListMembers(screenName, slug, cursor); // for (User user : response) { // LOGGER.debug("Read id for user @{}", user.getScreenName()); // ids.add(user.getId()); // } // cursor = response.getNextCursor(); // } while (response != null && response.hasNext()); // } catch (TwitterException e) { // LOGGER.error("Twitter exception updating {} party list : {}", party, e.getMessage()); // } // // return ids; // } // // // public boolean listsChanged() { // return hasChanged; // } // // // public boolean isTimeToUpdate() { // return updateTime.before(new Date(new Date().getTime() - REFRESH_TIME)); // } // // public Collection<Long> getPartyMemberIds(String party) { // return partyMemberIds.get(party); // } // // public List<Long> getAllPartyMemberIds() { // List<Long> ids = new ArrayList<>(); // // for (Set<Long> memberIds : partyMemberIds.values()) { // ids.addAll(memberIds); // } // // return ids; // } // // public Map<Long, String> getMemberParties() { // if (memberParties == null || memberParties.size() == 0) { // synchronized (memberParties) { // // Initialise member parties map // for (String party : partyMemberIds.keySet()) { // for (Long memberId : partyMemberIds.get(party)) { // memberParties.put(memberId, party); // } // } // } // } // // return memberParties; // } // // }
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import org.yaml.snakeyaml.Yaml; import twitter4j.conf.Configuration; import twitter4j.conf.PropertyConfiguration; import uk.co.flax.ukmp.twitter.PartyListHandler;
br = new BufferedReader(new FileReader(configFile)); ret = yaml.loadAs(br, IndexerConfiguration.class); } finally { if (br != null) { br.close(); } } return ret; } private Configuration readTwitterConfiguration(String twitterConfigFile) throws IOException { Configuration twitterConfig = null; InputStream is = null; try { is = new FileInputStream(config.getAuthenticationFile()); twitterConfig = new PropertyConfiguration(is); } finally { if (is != null) { is.close(); } } return twitterConfig; } public void run() {
// Path: ukmp/java/indexer/src/main/java/uk/co/flax/ukmp/twitter/PartyListHandler.java // public class PartyListHandler { // // private static final Logger LOGGER = LoggerFactory.getLogger(PartyListHandler.class); // // private static final long REFRESH_TIME = 6 * 60 * 60 * 1000; // // private final Configuration twitterConfig; // private final Map<String, PartyConfiguration> parties; // // private boolean hasChanged; // private Date updateTime; // // // private Map<String, Set<Long>> partyMemberIds = new HashMap<>(); // private Map<Long, String> memberParties = new HashMap<>(); // // public PartyListHandler(Configuration twitterConfig, Map<String, PartyConfiguration> parties) { // this.twitterConfig = twitterConfig; // this.parties = parties; // } // // // public void refreshLists() { // Map<String, Set<Long>> memberIds = new HashMap<>(); // // Authorization auth = AuthorizationFactory.getInstance(twitterConfig); // TwitterFactory tf = new TwitterFactory(twitterConfig); // Twitter twitter = tf.getInstance(auth); // for (PartyConfiguration pc : parties.values()) { // Set<Long> ids = readPartyIds(twitter, pc.getTwitterScreenName(), pc.getTwitterListSlug(), pc.getDisplayName()); // if (!ids.isEmpty()) { // memberIds.put(pc.getDisplayName(), ids); // } // } // // synchronized(partyMemberIds) { // for (String party : memberIds.keySet()) { // if (!partyMemberIds.containsKey(party) || Sets.symmetricDifference(memberIds.get(party), partyMemberIds.get(party)).size() > 0) { // hasChanged = true; // partyMemberIds.put(party, memberIds.get(party)); // LOGGER.debug("Updated list for {} with {} ids", party, memberIds.get(party).size()); // } // } // } // // if (hasChanged) { // updateTime = new Date(); // memberParties.clear(); // } // } // // private Set<Long> readPartyIds(Twitter twitter, String screenName, String slug, String party) { // Set<Long> ids = new HashSet<>(); // // try { // long cursor = -1; // PagableResponseList<User> response = null; // do { // response = twitter.getUserListMembers(screenName, slug, cursor); // for (User user : response) { // LOGGER.debug("Read id for user @{}", user.getScreenName()); // ids.add(user.getId()); // } // cursor = response.getNextCursor(); // } while (response != null && response.hasNext()); // } catch (TwitterException e) { // LOGGER.error("Twitter exception updating {} party list : {}", party, e.getMessage()); // } // // return ids; // } // // // public boolean listsChanged() { // return hasChanged; // } // // // public boolean isTimeToUpdate() { // return updateTime.before(new Date(new Date().getTime() - REFRESH_TIME)); // } // // public Collection<Long> getPartyMemberIds(String party) { // return partyMemberIds.get(party); // } // // public List<Long> getAllPartyMemberIds() { // List<Long> ids = new ArrayList<>(); // // for (Set<Long> memberIds : partyMemberIds.values()) { // ids.addAll(memberIds); // } // // return ids; // } // // public Map<Long, String> getMemberParties() { // if (memberParties == null || memberParties.size() == 0) { // synchronized (memberParties) { // // Initialise member parties map // for (String party : partyMemberIds.keySet()) { // for (Long memberId : partyMemberIds.get(party)) { // memberParties.put(memberId, party); // } // } // } // } // // return memberParties; // } // // } // Path: ukmp/java/indexer/src/main/java/uk/co/flax/ukmp/Indexer.java import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import org.yaml.snakeyaml.Yaml; import twitter4j.conf.Configuration; import twitter4j.conf.PropertyConfiguration; import uk.co.flax.ukmp.twitter.PartyListHandler; br = new BufferedReader(new FileReader(configFile)); ret = yaml.loadAs(br, IndexerConfiguration.class); } finally { if (br != null) { br.close(); } } return ret; } private Configuration readTwitterConfiguration(String twitterConfigFile) throws IOException { Configuration twitterConfig = null; InputStream is = null; try { is = new FileInputStream(config.getAuthenticationFile()); twitterConfig = new PropertyConfiguration(is); } finally { if (is != null) { is.close(); } } return twitterConfig; } public void run() {
PartyListHandler listHandler = new PartyListHandler(twitterConfig, config.getParties());
lovejjfg/MyBlogDemo
app/src/main/java/com/lovejjfg/blogdemo/ui/HorizontalPicker.java
// Path: app/src/main/java/com/lovejjfg/blogdemo/activity/PickerActivity.java // public class PickerActivity extends AppCompatActivity { // @Bind(R.id.hor_picker) // HorizontalPicker mHorPicker; // private boolean isExband; // private static final String TAG = PickerActivity.class.getSimpleName(); // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_picker); // ButterKnife.bind(this); // mHorPicker.setPickerAdapter(new PickerItemAdapter() { // // @Override // public ItemHolder onCreatePickerHolder(ViewGroup parent, int pos) { // // LayoutInflater inflater = LayoutInflater.from(parent.getContext()); // RecyclerView recycler = (RecyclerView) inflater.inflate(R.layout.text_layout, parent, false); // View inflate = inflater.inflate(R.layout.layout_item, parent, false); // return new ItemHolder(inflate, recycler, pos + 18); // } // // // @Override // // public HorizontalPicker.PickerHolder onCreatePickerDetailView(ViewGroup parent, int pos) { // // TextView textView = new TextView(parent.getContext()); // // textView.setText(String.format("xxxxxxxx%d", pos)); // // return new ItemDetailHolder(textView); // // } // // @Override // public int getItemCount() { // return 3; // } // // @Override // public void onBindPickerHolder(ViewGroup parent, HorizontalPicker.PickerHolder holder, int pos) { // ((ItemHolder) holder).onBindHolder("这是" + pos); // // holder.onBindHolder(); // } // }); // // } // // public static class ItemHolder extends HorizontalPicker.PickerHolder<View, RecyclerView> { // @Bind(R.id.tv_title) // TextView mTextTitle; // @Bind(R.id.iv_arrow) // ImageView mIvArrow; // // // public ItemHolder(View view, RecyclerView detailView, final int i) { // super(view, detailView); // detailView.setLayoutManager(new GridLayoutManager(detailView.getContext(), 4)); // detailView.setAdapter(new RecyclerView.Adapter() { // @Override // public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // return new MyHolder(new TextView(parent.getContext())); // } // // @Override // public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) { // ((TextView) holder.itemView).setText(position == 0 ? "默认" : "点击" + position); // holder.itemView.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // onBindHolder(position == 0 ? "默认" : "点击" + position); // // } // }); // } // // @Override // public int getItemCount() { // return i; // } // }); // ButterKnife.bind(this, view); // } // // // @Override // public void notifyCheckChange(ViewGroup horizontalPicker, boolean checked, boolean toggle) { // mIvArrow.setRotation(checked ? 180 : 0); // // if (toggle) { // // com.transitionseverywhere.TransitionManager.beginDelayedTransition(horizontalPicker, new Explode()); // // } // // mItemDetailView.setVisibility(checked ? View.VISIBLE : View.GONE); // } // // // public void onBindHolder(String title) { // mTextTitle.setText(title); // } // } // // public static class MyHolder extends RecyclerView.ViewHolder { // public MyHolder(View itemView) { // super(itemView); // } // } // // // public static class ItemDetailHolder extends HorizontalPicker.PickerHolder { // // public ItemDetailHolder(View view) { // // super(view); // // ButterKnife.bind(this, view); // // } // // // // @Override // // public void notifyCheckChange(boolean checked) { // // // // } // // } // // }
import java.util.ArrayList; import android.content.Context; import android.support.v7.widget.LinearLayoutCompat; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.Checkable; import android.widget.FrameLayout; import android.widget.LinearLayout; import com.lovejjfg.blogdemo.activity.PickerActivity; import com.transitionseverywhere.Explode; import com.transitionseverywhere.TransitionManager;
// // } // // @Override // public void onChildItemShown() { // // } // // @Override // public void onChildItemClosed() { // // } // // @Override // public void setPickerItemText(CharSequence text) { // mText.setText(text); // } // // @Override // public void setPickerItemClickListener(PickerItemClick pickerItemClick) { // mPickerItemClick = pickerItemClick; // } // // @Override // public void onClick(View v) { // // } // } public interface PickerItem {
// Path: app/src/main/java/com/lovejjfg/blogdemo/activity/PickerActivity.java // public class PickerActivity extends AppCompatActivity { // @Bind(R.id.hor_picker) // HorizontalPicker mHorPicker; // private boolean isExband; // private static final String TAG = PickerActivity.class.getSimpleName(); // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_picker); // ButterKnife.bind(this); // mHorPicker.setPickerAdapter(new PickerItemAdapter() { // // @Override // public ItemHolder onCreatePickerHolder(ViewGroup parent, int pos) { // // LayoutInflater inflater = LayoutInflater.from(parent.getContext()); // RecyclerView recycler = (RecyclerView) inflater.inflate(R.layout.text_layout, parent, false); // View inflate = inflater.inflate(R.layout.layout_item, parent, false); // return new ItemHolder(inflate, recycler, pos + 18); // } // // // @Override // // public HorizontalPicker.PickerHolder onCreatePickerDetailView(ViewGroup parent, int pos) { // // TextView textView = new TextView(parent.getContext()); // // textView.setText(String.format("xxxxxxxx%d", pos)); // // return new ItemDetailHolder(textView); // // } // // @Override // public int getItemCount() { // return 3; // } // // @Override // public void onBindPickerHolder(ViewGroup parent, HorizontalPicker.PickerHolder holder, int pos) { // ((ItemHolder) holder).onBindHolder("这是" + pos); // // holder.onBindHolder(); // } // }); // // } // // public static class ItemHolder extends HorizontalPicker.PickerHolder<View, RecyclerView> { // @Bind(R.id.tv_title) // TextView mTextTitle; // @Bind(R.id.iv_arrow) // ImageView mIvArrow; // // // public ItemHolder(View view, RecyclerView detailView, final int i) { // super(view, detailView); // detailView.setLayoutManager(new GridLayoutManager(detailView.getContext(), 4)); // detailView.setAdapter(new RecyclerView.Adapter() { // @Override // public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // return new MyHolder(new TextView(parent.getContext())); // } // // @Override // public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) { // ((TextView) holder.itemView).setText(position == 0 ? "默认" : "点击" + position); // holder.itemView.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // onBindHolder(position == 0 ? "默认" : "点击" + position); // // } // }); // } // // @Override // public int getItemCount() { // return i; // } // }); // ButterKnife.bind(this, view); // } // // // @Override // public void notifyCheckChange(ViewGroup horizontalPicker, boolean checked, boolean toggle) { // mIvArrow.setRotation(checked ? 180 : 0); // // if (toggle) { // // com.transitionseverywhere.TransitionManager.beginDelayedTransition(horizontalPicker, new Explode()); // // } // // mItemDetailView.setVisibility(checked ? View.VISIBLE : View.GONE); // } // // // public void onBindHolder(String title) { // mTextTitle.setText(title); // } // } // // public static class MyHolder extends RecyclerView.ViewHolder { // public MyHolder(View itemView) { // super(itemView); // } // } // // // public static class ItemDetailHolder extends HorizontalPicker.PickerHolder { // // public ItemDetailHolder(View view) { // // super(view); // // ButterKnife.bind(this, view); // // } // // // // @Override // // public void notifyCheckChange(boolean checked) { // // // // } // // } // // } // Path: app/src/main/java/com/lovejjfg/blogdemo/ui/HorizontalPicker.java import java.util.ArrayList; import android.content.Context; import android.support.v7.widget.LinearLayoutCompat; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.Checkable; import android.widget.FrameLayout; import android.widget.LinearLayout; import com.lovejjfg.blogdemo.activity.PickerActivity; import com.transitionseverywhere.Explode; import com.transitionseverywhere.TransitionManager; // // } // // @Override // public void onChildItemShown() { // // } // // @Override // public void onChildItemClosed() { // // } // // @Override // public void setPickerItemText(CharSequence text) { // mText.setText(text); // } // // @Override // public void setPickerItemClickListener(PickerItemClick pickerItemClick) { // mPickerItemClick = pickerItemClick; // } // // @Override // public void onClick(View v) { // // } // } public interface PickerItem {
PickerActivity.ItemHolder onCreatePickerHolder(ViewGroup parent, int pos);
lovejjfg/MyBlogDemo
app/src/main/java/com/lovejjfg/blogdemo/utils/PhotoUtils.java
// Path: app/src/main/java/com/lovejjfg/blogdemo/utils/crop/Crop.java // public class Crop { // // public static final int REQUEST_CROP = 6709; // public static final int REQUEST_PICK = 9162; // public static final int RESULT_ERROR = 404; // // static interface Extra { // String ASPECT_X = "aspect_x"; // String ASPECT_Y = "aspect_y"; // String MAX_X = "max_x"; // String MAX_Y = "max_y"; // String ERROR = "error"; // } // // private Intent cropIntent; // // /** // * Create a crop Intent builder with source image // * // * @param source Source image URI // */ // public Crop(Uri source) { // cropIntent = new Intent(); // cropIntent.setData(source); // } // // /** // * Set output URI where the cropped image will be saved // * // * @param output Output image URI // */ // public Crop output(Uri output) { // cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, output); // return this; // } // // /** // * Set fixed aspect ratio for crop area // * // * @param x Aspect X // * @param y Aspect Y // */ // public Crop withAspect(int x, int y) { // cropIntent.putExtra(Extra.ASPECT_X, x); // cropIntent.putExtra(Extra.ASPECT_Y, y); // return this; // } // // /** // * Crop area with fixed 1:1 aspect ratio // */ // public Crop asSquare() { // cropIntent.putExtra(Extra.ASPECT_X, 1); // cropIntent.putExtra(Extra.ASPECT_Y, 1); // return this; // } // // /** // * Set maximum crop size // * // * @param width Max width // * @param height Max height // */ // public Crop withMaxSize(int width, int height) { // cropIntent.putExtra(Extra.MAX_X, width); // cropIntent.putExtra(Extra.MAX_Y, height); // return this; // } // // /** // * Send the crop Intent! // * // * @param activity Activity that will receive result // */ // public void start(Activity activity) { // activity.startActivityForResult(getIntent(activity), REQUEST_CROP); // } // // /** // * Send the crop Intent! // * // * @param context Context // * @param fragment Fragment that will receive result // */ // @TargetApi(Build.VERSION_CODES.HONEYCOMB) // public void start(Context context, Fragment fragment) { // fragment.startActivityForResult(getIntent(context), REQUEST_CROP); // } // // Intent getIntent(Context context) { // cropIntent.setClass(context, CropImageActivity.class); // return cropIntent; // } // // /** // * Retrieve URI for cropped image, as set in the Intent builder // * // * @param result Output Image URI // */ // public static Uri getOutput(Intent result) { // return result.getParcelableExtra(MediaStore.EXTRA_OUTPUT); // } // // /** // * Retrieve error that caused crop to fail // * // * @param result Result Intent // * @return Throwable handled in CropImageActivity // */ // public static Throwable getError(Intent result) { // return (Throwable) result.getSerializableExtra(Extra.ERROR); // } // // /** // * Utility method that starts an image picker since that often precedes a crop // * // * @param activity Activity that will receive result // */ // public static void pickImage(Activity activity) { // Intent intent = new Intent(Intent.ACTION_GET_CONTENT).setType("image/*"); // try { // activity.startActivityForResult(intent, REQUEST_PICK); // } catch (ActivityNotFoundException e) { // Toast.makeText(activity, R.string.crop__pick_error, Toast.LENGTH_SHORT).show(); // } // } // // }
import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.ExifInterface; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.os.Parcel; import android.os.Parcelable; import android.provider.MediaStore; import android.text.TextUtils; import android.util.Log; import com.lovejjfg.blogdemo.utils.crop.Crop; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream;
case ExifInterface.ORIENTATION_ROTATE_90: degree = 90; break; case ExifInterface.ORIENTATION_ROTATE_180: degree = 180; break; case ExifInterface.ORIENTATION_ROTATE_270: degree = 270; break; } } catch (IOException e) { e.printStackTrace(); } return degree; } /** * 剪裁图片 * * @param file 图片file文件 */ public void crop(File file) { // String parentPath = PhotoUtils.getImageCheDir(mContext); // String path = System.nanoTime() + "测试.jpg"; // String path = System.nanoTime() + ".jpg"; String parentPath = PhotoUtils.getImageCheDir(mContext); String path = parentPath + System.nanoTime() + ".jpg"; // String path = "jj.jpg"; // Uri outputUri = Uri.fromFile(new File(path)); Uri outputUri = Uri.fromFile(new File(path));
// Path: app/src/main/java/com/lovejjfg/blogdemo/utils/crop/Crop.java // public class Crop { // // public static final int REQUEST_CROP = 6709; // public static final int REQUEST_PICK = 9162; // public static final int RESULT_ERROR = 404; // // static interface Extra { // String ASPECT_X = "aspect_x"; // String ASPECT_Y = "aspect_y"; // String MAX_X = "max_x"; // String MAX_Y = "max_y"; // String ERROR = "error"; // } // // private Intent cropIntent; // // /** // * Create a crop Intent builder with source image // * // * @param source Source image URI // */ // public Crop(Uri source) { // cropIntent = new Intent(); // cropIntent.setData(source); // } // // /** // * Set output URI where the cropped image will be saved // * // * @param output Output image URI // */ // public Crop output(Uri output) { // cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, output); // return this; // } // // /** // * Set fixed aspect ratio for crop area // * // * @param x Aspect X // * @param y Aspect Y // */ // public Crop withAspect(int x, int y) { // cropIntent.putExtra(Extra.ASPECT_X, x); // cropIntent.putExtra(Extra.ASPECT_Y, y); // return this; // } // // /** // * Crop area with fixed 1:1 aspect ratio // */ // public Crop asSquare() { // cropIntent.putExtra(Extra.ASPECT_X, 1); // cropIntent.putExtra(Extra.ASPECT_Y, 1); // return this; // } // // /** // * Set maximum crop size // * // * @param width Max width // * @param height Max height // */ // public Crop withMaxSize(int width, int height) { // cropIntent.putExtra(Extra.MAX_X, width); // cropIntent.putExtra(Extra.MAX_Y, height); // return this; // } // // /** // * Send the crop Intent! // * // * @param activity Activity that will receive result // */ // public void start(Activity activity) { // activity.startActivityForResult(getIntent(activity), REQUEST_CROP); // } // // /** // * Send the crop Intent! // * // * @param context Context // * @param fragment Fragment that will receive result // */ // @TargetApi(Build.VERSION_CODES.HONEYCOMB) // public void start(Context context, Fragment fragment) { // fragment.startActivityForResult(getIntent(context), REQUEST_CROP); // } // // Intent getIntent(Context context) { // cropIntent.setClass(context, CropImageActivity.class); // return cropIntent; // } // // /** // * Retrieve URI for cropped image, as set in the Intent builder // * // * @param result Output Image URI // */ // public static Uri getOutput(Intent result) { // return result.getParcelableExtra(MediaStore.EXTRA_OUTPUT); // } // // /** // * Retrieve error that caused crop to fail // * // * @param result Result Intent // * @return Throwable handled in CropImageActivity // */ // public static Throwable getError(Intent result) { // return (Throwable) result.getSerializableExtra(Extra.ERROR); // } // // /** // * Utility method that starts an image picker since that often precedes a crop // * // * @param activity Activity that will receive result // */ // public static void pickImage(Activity activity) { // Intent intent = new Intent(Intent.ACTION_GET_CONTENT).setType("image/*"); // try { // activity.startActivityForResult(intent, REQUEST_PICK); // } catch (ActivityNotFoundException e) { // Toast.makeText(activity, R.string.crop__pick_error, Toast.LENGTH_SHORT).show(); // } // } // // } // Path: app/src/main/java/com/lovejjfg/blogdemo/utils/PhotoUtils.java import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.ExifInterface; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.os.Parcel; import android.os.Parcelable; import android.provider.MediaStore; import android.text.TextUtils; import android.util.Log; import com.lovejjfg.blogdemo.utils.crop.Crop; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; case ExifInterface.ORIENTATION_ROTATE_90: degree = 90; break; case ExifInterface.ORIENTATION_ROTATE_180: degree = 180; break; case ExifInterface.ORIENTATION_ROTATE_270: degree = 270; break; } } catch (IOException e) { e.printStackTrace(); } return degree; } /** * 剪裁图片 * * @param file 图片file文件 */ public void crop(File file) { // String parentPath = PhotoUtils.getImageCheDir(mContext); // String path = System.nanoTime() + "测试.jpg"; // String path = System.nanoTime() + ".jpg"; String parentPath = PhotoUtils.getImageCheDir(mContext); String path = parentPath + System.nanoTime() + ".jpg"; // String path = "jj.jpg"; // Uri outputUri = Uri.fromFile(new File(path)); Uri outputUri = Uri.fromFile(new File(path));
new Crop(Uri.fromFile(file)).output(outputUri).asSquare().withMaxSize(DEFAULT_AVATAR_SIZE, 240).start((Activity) mContext);
lovejjfg/MyBlogDemo
app/src/main/java/com/lovejjfg/blogdemo/base/BaseSlideFinishActivity.java
// Path: app/src/main/java/com/lovejjfg/blogdemo/utils/BaseUtil.java // public class BaseUtil { // public static void startActivityOnspecifiedAnimation(Activity context, Class<?> cls) { // context.startActivity(new Intent(context, cls)); // context.overridePendingTransition(R.anim.start_activity_in, R.anim.start_activity_out); // } // // // public static int getStatusHeight(Activity context) { // try { // Class c = Class.forName("com.android.internal.R$dimen"); // Object obj = c.newInstance(); // Field field = c.getField("status_bar_height"); // int x = Integer.parseInt(field.get(obj).toString()); // return context.getResources().getDimensionPixelSize(x); // } catch (Exception e) { // e.printStackTrace(); // return 0; // } // } // // //版本名 // public static String getVersionName(Context context) { // return getPackageInfo(context).versionName; // } // // //版本号 // public static int getVersionCode(Context context) { // return getPackageInfo(context).versionCode; // } // // private static PackageInfo getPackageInfo(Context context) { // PackageInfo pi = null; // // try { // PackageManager pm = context.getPackageManager(); // pi = pm.getPackageInfo(context.getPackageName(), // PackageManager.GET_CONFIGURATIONS); // // return pi; // } catch (Exception e) { // e.printStackTrace(); // } // // return pi; // } // }
import android.app.Activity; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.widget.FrameLayout; import android.widget.TextView; import com.lovejjfg.blogdemo.R; import com.lovejjfg.blogdemo.utils.BaseUtil;
} @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { finishSelf(); return true; } return super.onKeyDown(keyCode, event); } protected void init() { } @Override public void onClick(View v) { performViewClick(v); } public abstract View initView(Bundle savedInstanceState); protected abstract void performViewClick(View v); public void finishSelf() { this.finish(); this.overridePendingTransition(0, R.anim.finish_activity_out);//取消Activity的动画。 } public void startActivityOnspecifiedAnimation(Activity context, Class<?> cls) {
// Path: app/src/main/java/com/lovejjfg/blogdemo/utils/BaseUtil.java // public class BaseUtil { // public static void startActivityOnspecifiedAnimation(Activity context, Class<?> cls) { // context.startActivity(new Intent(context, cls)); // context.overridePendingTransition(R.anim.start_activity_in, R.anim.start_activity_out); // } // // // public static int getStatusHeight(Activity context) { // try { // Class c = Class.forName("com.android.internal.R$dimen"); // Object obj = c.newInstance(); // Field field = c.getField("status_bar_height"); // int x = Integer.parseInt(field.get(obj).toString()); // return context.getResources().getDimensionPixelSize(x); // } catch (Exception e) { // e.printStackTrace(); // return 0; // } // } // // //版本名 // public static String getVersionName(Context context) { // return getPackageInfo(context).versionName; // } // // //版本号 // public static int getVersionCode(Context context) { // return getPackageInfo(context).versionCode; // } // // private static PackageInfo getPackageInfo(Context context) { // PackageInfo pi = null; // // try { // PackageManager pm = context.getPackageManager(); // pi = pm.getPackageInfo(context.getPackageName(), // PackageManager.GET_CONFIGURATIONS); // // return pi; // } catch (Exception e) { // e.printStackTrace(); // } // // return pi; // } // } // Path: app/src/main/java/com/lovejjfg/blogdemo/base/BaseSlideFinishActivity.java import android.app.Activity; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.widget.FrameLayout; import android.widget.TextView; import com.lovejjfg.blogdemo.R; import com.lovejjfg.blogdemo.utils.BaseUtil; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { finishSelf(); return true; } return super.onKeyDown(keyCode, event); } protected void init() { } @Override public void onClick(View v) { performViewClick(v); } public abstract View initView(Bundle savedInstanceState); protected abstract void performViewClick(View v); public void finishSelf() { this.finish(); this.overridePendingTransition(0, R.anim.finish_activity_out);//取消Activity的动画。 } public void startActivityOnspecifiedAnimation(Activity context, Class<?> cls) {
BaseUtil.startActivityOnspecifiedAnimation(context, cls);
lovejjfg/MyBlogDemo
app/src/main/java/com/lovejjfg/blogdemo/recyclerview/adapter/MyAdapter.java
// Path: app/src/main/java/com/lovejjfg/blogdemo/utils/JumpUtil.java // public class JumpUtil { // // public static void jumpToMain(Context context) { // Intent intent = new Intent(context, MainActivity.class); // context.startActivity(intent); // } // // public static void jumpToBottome(Activity context) { // Intent intent = new Intent(context, BottomSheetActivity.class); // context.startActivity(intent); // context.overridePendingTransition(R.anim.bottom_activity_in, R.anim.bottom_activity_out); // // } // }
import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.lovejjfg.blogdemo.R; import com.lovejjfg.blogdemo.utils.JumpUtil;
package com.lovejjfg.blogdemo.recyclerview.adapter; /** * Created by Joe on 2016/4/21. * Email lovejjfg@gmail.com */ public class MyAdapter extends RecyclerView.Adapter { public MyAdapter() { } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return onViewHolder(parent); } private RecyclerView.ViewHolder onViewHolder(ViewGroup parent) { return new MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_adapter, parent, false)); } @Override public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) { ((MyViewHolder) holder).onBindView(position); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {
// Path: app/src/main/java/com/lovejjfg/blogdemo/utils/JumpUtil.java // public class JumpUtil { // // public static void jumpToMain(Context context) { // Intent intent = new Intent(context, MainActivity.class); // context.startActivity(intent); // } // // public static void jumpToBottome(Activity context) { // Intent intent = new Intent(context, BottomSheetActivity.class); // context.startActivity(intent); // context.overridePendingTransition(R.anim.bottom_activity_in, R.anim.bottom_activity_out); // // } // } // Path: app/src/main/java/com/lovejjfg/blogdemo/recyclerview/adapter/MyAdapter.java import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.lovejjfg.blogdemo.R; import com.lovejjfg.blogdemo.utils.JumpUtil; package com.lovejjfg.blogdemo.recyclerview.adapter; /** * Created by Joe on 2016/4/21. * Email lovejjfg@gmail.com */ public class MyAdapter extends RecyclerView.Adapter { public MyAdapter() { } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return onViewHolder(parent); } private RecyclerView.ViewHolder onViewHolder(ViewGroup parent) { return new MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_adapter, parent, false)); } @Override public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) { ((MyViewHolder) holder).onBindView(position); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {
JumpUtil.jumpToMain(holder.itemView.getContext());
lovejjfg/MyBlogDemo
app/src/test/java/com/lovejjfg/family/ApiTest.java
// Path: app/src/main/java/com/lovejjfg/blogdemo/utils/BaseUtil.java // public class BaseUtil { // public static void startActivityOnspecifiedAnimation(Activity context, Class<?> cls) { // context.startActivity(new Intent(context, cls)); // context.overridePendingTransition(R.anim.start_activity_in, R.anim.start_activity_out); // } // // // public static int getStatusHeight(Activity context) { // try { // Class c = Class.forName("com.android.internal.R$dimen"); // Object obj = c.newInstance(); // Field field = c.getField("status_bar_height"); // int x = Integer.parseInt(field.get(obj).toString()); // return context.getResources().getDimensionPixelSize(x); // } catch (Exception e) { // e.printStackTrace(); // return 0; // } // } // // //版本名 // public static String getVersionName(Context context) { // return getPackageInfo(context).versionName; // } // // //版本号 // public static int getVersionCode(Context context) { // return getPackageInfo(context).versionCode; // } // // private static PackageInfo getPackageInfo(Context context) { // PackageInfo pi = null; // // try { // PackageManager pm = context.getPackageManager(); // pi = pm.getPackageInfo(context.getPackageName(), // PackageManager.GET_CONFIGURATIONS); // // return pi; // } catch (Exception e) { // e.printStackTrace(); // } // // return pi; // } // }
import com.lovejjfg.blogdemo.utils.BaseUtil; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import java.io.IOException;
package com.lovejjfg.family; @RunWith(RobolectricTestRunner.class) @Config(sdk = 23, manifest = Config.NONE) public class ApiTest extends BaseTest { // private LoginApi loginApi; @Override @Before public void setUp() { super.setUp(); // activity = Robolectric.buildActivity(MainActivity.class).create().get(); // userService = BaseDataManager.getUserService(); // loginApi = BaseDataManager.getLoginApi(); } @After public void tearDown() { } @Test public void testVersion() throws Exception {
// Path: app/src/main/java/com/lovejjfg/blogdemo/utils/BaseUtil.java // public class BaseUtil { // public static void startActivityOnspecifiedAnimation(Activity context, Class<?> cls) { // context.startActivity(new Intent(context, cls)); // context.overridePendingTransition(R.anim.start_activity_in, R.anim.start_activity_out); // } // // // public static int getStatusHeight(Activity context) { // try { // Class c = Class.forName("com.android.internal.R$dimen"); // Object obj = c.newInstance(); // Field field = c.getField("status_bar_height"); // int x = Integer.parseInt(field.get(obj).toString()); // return context.getResources().getDimensionPixelSize(x); // } catch (Exception e) { // e.printStackTrace(); // return 0; // } // } // // //版本名 // public static String getVersionName(Context context) { // return getPackageInfo(context).versionName; // } // // //版本号 // public static int getVersionCode(Context context) { // return getPackageInfo(context).versionCode; // } // // private static PackageInfo getPackageInfo(Context context) { // PackageInfo pi = null; // // try { // PackageManager pm = context.getPackageManager(); // pi = pm.getPackageInfo(context.getPackageName(), // PackageManager.GET_CONFIGURATIONS); // // return pi; // } catch (Exception e) { // e.printStackTrace(); // } // // return pi; // } // } // Path: app/src/test/java/com/lovejjfg/family/ApiTest.java import com.lovejjfg.blogdemo.utils.BaseUtil; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import java.io.IOException; package com.lovejjfg.family; @RunWith(RobolectricTestRunner.class) @Config(sdk = 23, manifest = Config.NONE) public class ApiTest extends BaseTest { // private LoginApi loginApi; @Override @Before public void setUp() { super.setUp(); // activity = Robolectric.buildActivity(MainActivity.class).create().get(); // userService = BaseDataManager.getUserService(); // loginApi = BaseDataManager.getLoginApi(); } @After public void tearDown() { } @Test public void testVersion() throws Exception {
int versionCode = BaseUtil.getVersionCode(context);
lovejjfg/MyBlogDemo
app/src/main/java/com/lovejjfg/blogdemo/base/BombApiService.java
// Path: app/src/main/java/com/lovejjfg/blogdemo/model/bean/blogBean.java // public class BlogBean { // String tittle; // String url; // String time; // String times; // // public BlogBean(String tittle, String url, String time, String times) { // this.tittle = tittle; // this.url = url; // this.time = time; // this.times = times; // } // // public String getTittle() { // return tittle; // } // // public void setTittle(String tittle) { // this.tittle = tittle; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public String getTime() { // return time; // } // // public void setTime(String time) { // this.time = time; // } // // public String getTimes() { // return times; // } // // public void setTimes(String times) { // this.times = times; // } // // }
import com.lovejjfg.blogdemo.model.bean.BlogBean; import retrofit2.http.Body; import retrofit2.http.POST; import retrofit2.http.Path; import rx.Observable;
package com.lovejjfg.blogdemo.base; /** * Created by 张俊 on 2016/3/15. */ public interface BombApiService { // @Multipart // @POST("/batch") // void updateFile(@Part("photo") RequestBody photo, @Part("description") RequestBody description); @POST("files/{fileName}")
// Path: app/src/main/java/com/lovejjfg/blogdemo/model/bean/blogBean.java // public class BlogBean { // String tittle; // String url; // String time; // String times; // // public BlogBean(String tittle, String url, String time, String times) { // this.tittle = tittle; // this.url = url; // this.time = time; // this.times = times; // } // // public String getTittle() { // return tittle; // } // // public void setTittle(String tittle) { // this.tittle = tittle; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public String getTime() { // return time; // } // // public void setTime(String time) { // this.time = time; // } // // public String getTimes() { // return times; // } // // public void setTimes(String times) { // this.times = times; // } // // } // Path: app/src/main/java/com/lovejjfg/blogdemo/base/BombApiService.java import com.lovejjfg.blogdemo.model.bean.BlogBean; import retrofit2.http.Body; import retrofit2.http.POST; import retrofit2.http.Path; import rx.Observable; package com.lovejjfg.blogdemo.base; /** * Created by 张俊 on 2016/3/15. */ public interface BombApiService { // @Multipart // @POST("/batch") // void updateFile(@Part("photo") RequestBody photo, @Part("description") RequestBody description); @POST("files/{fileName}")
Observable<BlogBean> OupdateFiles(@Path("fileName") String fileName, @Body byte[] bytes);
Esaych/DDCustomPlugin
src/net/diamonddominion/esaych/global/ChatUtils.java
// Path: src/net/diamonddominion/esaych/util/SQL.java // public class SQL { // // static String url = "jdbc:mysql://localhost:3306/DiamondDom_Bungee"; // static String user = "root"; // static String password = "K2gEBBl6"; // static Connection con; // // public static Connection getConnection() { // try { // if (con != null && !con.isClosed()) { // return con; // } else { // con = DriverManager.getConnection(url, user, password); // } // } catch (SQLException e) { // e.printStackTrace(); // } // return con; // } // // public static void singleQuery(String query) { // try { // Connection con = getConnection(); // // Statement st = (Statement) con.createStatement(); // st.executeUpdate(query); // } catch (SQLException e) { // e.printStackTrace(); // } // } // // }
import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.diamonddominion.esaych.util.SQL; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.World; import org.bukkit.block.Sign; import org.bukkit.entity.Player;
package net.diamonddominion.esaych.global; public class ChatUtils { static Chat chatPlugin = null; public ChatUtils(Chat chat) { World sv = Bukkit.getWorld("Survival"); if (sv != null) {
// Path: src/net/diamonddominion/esaych/util/SQL.java // public class SQL { // // static String url = "jdbc:mysql://localhost:3306/DiamondDom_Bungee"; // static String user = "root"; // static String password = "K2gEBBl6"; // static Connection con; // // public static Connection getConnection() { // try { // if (con != null && !con.isClosed()) { // return con; // } else { // con = DriverManager.getConnection(url, user, password); // } // } catch (SQLException e) { // e.printStackTrace(); // } // return con; // } // // public static void singleQuery(String query) { // try { // Connection con = getConnection(); // // Statement st = (Statement) con.createStatement(); // st.executeUpdate(query); // } catch (SQLException e) { // e.printStackTrace(); // } // } // // } // Path: src/net/diamonddominion/esaych/global/ChatUtils.java import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.diamonddominion.esaych.util.SQL; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.World; import org.bukkit.block.Sign; import org.bukkit.entity.Player; package net.diamonddominion.esaych.global; public class ChatUtils { static Chat chatPlugin = null; public ChatUtils(Chat chat) { World sv = Bukkit.getWorld("Survival"); if (sv != null) {
SQL.singleQuery("TRUNCATE TABLE `dd-owners`;");
Esaych/DDCustomPlugin
src/net/diamonddominion/esaych/global/ChatSQL.java
// Path: src/net/diamonddominion/esaych/util/SQL.java // public class SQL { // // static String url = "jdbc:mysql://localhost:3306/DiamondDom_Bungee"; // static String user = "root"; // static String password = "K2gEBBl6"; // static Connection con; // // public static Connection getConnection() { // try { // if (con != null && !con.isClosed()) { // return con; // } else { // con = DriverManager.getConnection(url, user, password); // } // } catch (SQLException e) { // e.printStackTrace(); // } // return con; // } // // public static void singleQuery(String query) { // try { // Connection con = getConnection(); // // Statement st = (Statement) con.createStatement(); // st.executeUpdate(query); // } catch (SQLException e) { // e.printStackTrace(); // } // } // // }
import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import net.diamonddominion.esaych.util.SQL; import org.bukkit.Bukkit; import org.bukkit.entity.Player;
public String getChannel(String playerName) { return cacheChannelData.get(playerName); } public void setChannel(String playerName, String channel) { insertQuery(playerName, "channel", channel); cacheChannelData.put(playerName, channel); } public boolean getBadProfile(String playerName) { if (cacheBadProfileData.containsKey(playerName)) return cacheBadProfileData.get(playerName); return false; } public void setBadProfile(String playerName, boolean bad) { if (bad) insertQuery(playerName, "badprofile", "1"); else insertQuery(playerName, "badprofile", "0"); cacheBadProfileData.put(playerName, bad); } public String getDatingPartner(String playerName) { return cacheDatingPartner.get(playerName); } public void setDatingPartner(String player1, String player2) { if (player2 != null) {
// Path: src/net/diamonddominion/esaych/util/SQL.java // public class SQL { // // static String url = "jdbc:mysql://localhost:3306/DiamondDom_Bungee"; // static String user = "root"; // static String password = "K2gEBBl6"; // static Connection con; // // public static Connection getConnection() { // try { // if (con != null && !con.isClosed()) { // return con; // } else { // con = DriverManager.getConnection(url, user, password); // } // } catch (SQLException e) { // e.printStackTrace(); // } // return con; // } // // public static void singleQuery(String query) { // try { // Connection con = getConnection(); // // Statement st = (Statement) con.createStatement(); // st.executeUpdate(query); // } catch (SQLException e) { // e.printStackTrace(); // } // } // // } // Path: src/net/diamonddominion/esaych/global/ChatSQL.java import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import net.diamonddominion.esaych.util.SQL; import org.bukkit.Bukkit; import org.bukkit.entity.Player; public String getChannel(String playerName) { return cacheChannelData.get(playerName); } public void setChannel(String playerName, String channel) { insertQuery(playerName, "channel", channel); cacheChannelData.put(playerName, channel); } public boolean getBadProfile(String playerName) { if (cacheBadProfileData.containsKey(playerName)) return cacheBadProfileData.get(playerName); return false; } public void setBadProfile(String playerName, boolean bad) { if (bad) insertQuery(playerName, "badprofile", "1"); else insertQuery(playerName, "badprofile", "0"); cacheBadProfileData.put(playerName, bad); } public String getDatingPartner(String playerName) { return cacheDatingPartner.get(playerName); } public void setDatingPartner(String player1, String player2) { if (player2 != null) {
Connection con = SQL.getConnection();
spotify/hype
hype-submitter/src/main/java/com/spotify/hype/model/StagedContinuation.java
// Path: hype-gcs/src/main/java/com/spotify/hype/gcs/RunManifest.java // @AutoMatter // public interface RunManifest { // // String continuation(); // // List<String> classPathFiles(); // // List<String> files(); // // static RunManifest read(Path manifestPath) throws IOException { // return ManifestUtil.read(manifestPath); // } // // static void write(RunManifest manifest, Path manifestPath) throws IOException { // ManifestUtil.write(manifest, manifestPath); // } // }
import java.nio.file.Path; import com.spotify.hype.gcs.RunManifest; import io.norberg.automatter.AutoMatter;
/*- * -\-\- * hype-submitter * -- * Copyright (C) 2016 - 2017 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.hype.model; @AutoMatter public interface StagedContinuation { Path manifestPath();
// Path: hype-gcs/src/main/java/com/spotify/hype/gcs/RunManifest.java // @AutoMatter // public interface RunManifest { // // String continuation(); // // List<String> classPathFiles(); // // List<String> files(); // // static RunManifest read(Path manifestPath) throws IOException { // return ManifestUtil.read(manifestPath); // } // // static void write(RunManifest manifest, Path manifestPath) throws IOException { // ManifestUtil.write(manifest, manifestPath); // } // } // Path: hype-submitter/src/main/java/com/spotify/hype/model/StagedContinuation.java import java.nio.file.Path; import com.spotify.hype.gcs.RunManifest; import io.norberg.automatter.AutoMatter; /*- * -\-\- * hype-submitter * -- * Copyright (C) 2016 - 2017 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.hype.model; @AutoMatter public interface StagedContinuation { Path manifestPath();
RunManifest manifest();
spotify/hype
hype-submitter/src/main/java/com/spotify/hype/model/VolumeRequest.java
// Path: hype-common/src/main/java/com/spotify/hype/util/Util.java // public final class Util { // // private static final String ALPHA_NUMERIC_STRING = "abcdefghijklmnopqrstuvwxyz0123456789"; // // private Util() { // } // // public static String randomAlphaNumeric(int count) { // StringBuilder builder = new StringBuilder(); // while (count-- != 0) { // int character = (int)(Math.random() * ALPHA_NUMERIC_STRING.length()); // builder.append(ALPHA_NUMERIC_STRING.charAt(character)); // } // return builder.toString(); // } // }
import com.spotify.hype.util.Util; import io.norberg.automatter.AutoMatter;
/*- * -\-\- * hype-submitter * -- * Copyright (C) 2016 - 2017 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.hype.model; /** * A request for a volume to be created from the specified storage class, with a specific size. * * <p>see http://blog.kubernetes.io/2016/10/dynamic-provisioning-and-storage-in-kubernetes.html */ @AutoMatter public interface VolumeRequest { String VOLUME_REQUEST_PREFIX = "hype-request-"; String id(); boolean keep(); ClaimRequest spec(); @AutoMatter interface ClaimRequest { String storageClass(); String size(); boolean useExisting(); } static VolumeRequest volumeRequest(String storageClass, String size) {
// Path: hype-common/src/main/java/com/spotify/hype/util/Util.java // public final class Util { // // private static final String ALPHA_NUMERIC_STRING = "abcdefghijklmnopqrstuvwxyz0123456789"; // // private Util() { // } // // public static String randomAlphaNumeric(int count) { // StringBuilder builder = new StringBuilder(); // while (count-- != 0) { // int character = (int)(Math.random() * ALPHA_NUMERIC_STRING.length()); // builder.append(ALPHA_NUMERIC_STRING.charAt(character)); // } // return builder.toString(); // } // } // Path: hype-submitter/src/main/java/com/spotify/hype/model/VolumeRequest.java import com.spotify.hype.util.Util; import io.norberg.automatter.AutoMatter; /*- * -\-\- * hype-submitter * -- * Copyright (C) 2016 - 2017 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.hype.model; /** * A request for a volume to be created from the specified storage class, with a specific size. * * <p>see http://blog.kubernetes.io/2016/10/dynamic-provisioning-and-storage-in-kubernetes.html */ @AutoMatter public interface VolumeRequest { String VOLUME_REQUEST_PREFIX = "hype-request-"; String id(); boolean keep(); ClaimRequest spec(); @AutoMatter interface ClaimRequest { String storageClass(); String size(); boolean useExisting(); } static VolumeRequest volumeRequest(String storageClass, String size) {
final String id = VOLUME_REQUEST_PREFIX + Util.randomAlphaNumeric(8);
spotify/hype
hype-run/src/main/java/com/spotify/hype/stub/ContinuationEntryPoint.java
// Path: hype-common/src/main/java/com/spotify/hype/util/Fn.java // @FunctionalInterface // public interface Fn<T> extends Serializable { // T run(); // } // // Path: hype-common/src/main/java/com/spotify/hype/util/SerializationUtil.java // public class SerializationUtil { // // private static final String CONT_FILE = "continuation-"; // private static final String EXT = ".bin"; // // public static Path serializeContinuation(Fn<?> continuation) { // try { // final Path outputPath = Files.createTempFile(CONT_FILE, EXT); // serializeObject(continuation, outputPath); // return outputPath; // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // public static Fn<?> readContinuation(Path continuationPath) { // return (Fn) readObject(continuationPath); // } // // public static void serializeObject(Object obj, Path outputPath) { // Kryo kryo = new Kryo(); // kryo.register(java.lang.invoke.SerializedLambda.class); // kryo.register(ClosureSerializer.Closure.class, new ClosureSerializer()); // // try { // final File file = outputPath.toFile(); // try (Output output = new Output(new FileOutputStream(file))) { // kryo.writeClassAndObject(output, obj); // } // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // public static Object readObject(Path object) { // File file = object.toFile(); // // try (InputStream input = new FileInputStream(file)) { // return readObject(input); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // public static Object readObject(InputStream inputStream) { // Kryo kryo = new Kryo(); // kryo.register(java.lang.invoke.SerializedLambda.class); // kryo.register(ClosureSerializer.Closure.class, new ClosureSerializer()); // kryo.setInstantiatorStrategy(new Kryo.DefaultInstantiatorStrategy(new StdInstantiatorStrategy())); // // Input input = new Input(inputStream); // return kryo.readClassAndObject(input); // } // }
import com.spotify.hype.util.Fn; import com.spotify.hype.util.SerializationUtil; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths;
/*- * -\-\- * hype-submitter * -- * Copyright (C) 2016 - 2017 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.hype.stub; /** * TODO: document. */ public class ContinuationEntryPoint { public static void main(String[] args) throws Exception { if (args.length < 2) { throw new IllegalArgumentException("Usage: <staging-dir> <continuation-file> <output-file>"); } final Path continuationPath = Paths.get(args[0], args[1]); if (!Files.exists(continuationPath)) { throw new IllegalArgumentException(continuationPath + " does not exist"); } final Path returnValuePath = Paths.get(args[0], args[2]); if (Files.exists(returnValuePath)) { throw new IllegalArgumentException(returnValuePath + " already exists"); } System.setProperty("user.dir", args[0]);
// Path: hype-common/src/main/java/com/spotify/hype/util/Fn.java // @FunctionalInterface // public interface Fn<T> extends Serializable { // T run(); // } // // Path: hype-common/src/main/java/com/spotify/hype/util/SerializationUtil.java // public class SerializationUtil { // // private static final String CONT_FILE = "continuation-"; // private static final String EXT = ".bin"; // // public static Path serializeContinuation(Fn<?> continuation) { // try { // final Path outputPath = Files.createTempFile(CONT_FILE, EXT); // serializeObject(continuation, outputPath); // return outputPath; // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // public static Fn<?> readContinuation(Path continuationPath) { // return (Fn) readObject(continuationPath); // } // // public static void serializeObject(Object obj, Path outputPath) { // Kryo kryo = new Kryo(); // kryo.register(java.lang.invoke.SerializedLambda.class); // kryo.register(ClosureSerializer.Closure.class, new ClosureSerializer()); // // try { // final File file = outputPath.toFile(); // try (Output output = new Output(new FileOutputStream(file))) { // kryo.writeClassAndObject(output, obj); // } // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // public static Object readObject(Path object) { // File file = object.toFile(); // // try (InputStream input = new FileInputStream(file)) { // return readObject(input); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // public static Object readObject(InputStream inputStream) { // Kryo kryo = new Kryo(); // kryo.register(java.lang.invoke.SerializedLambda.class); // kryo.register(ClosureSerializer.Closure.class, new ClosureSerializer()); // kryo.setInstantiatorStrategy(new Kryo.DefaultInstantiatorStrategy(new StdInstantiatorStrategy())); // // Input input = new Input(inputStream); // return kryo.readClassAndObject(input); // } // } // Path: hype-run/src/main/java/com/spotify/hype/stub/ContinuationEntryPoint.java import com.spotify.hype.util.Fn; import com.spotify.hype.util.SerializationUtil; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; /*- * -\-\- * hype-submitter * -- * Copyright (C) 2016 - 2017 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.hype.stub; /** * TODO: document. */ public class ContinuationEntryPoint { public static void main(String[] args) throws Exception { if (args.length < 2) { throw new IllegalArgumentException("Usage: <staging-dir> <continuation-file> <output-file>"); } final Path continuationPath = Paths.get(args[0], args[1]); if (!Files.exists(continuationPath)) { throw new IllegalArgumentException(continuationPath + " does not exist"); } final Path returnValuePath = Paths.get(args[0], args[2]); if (Files.exists(returnValuePath)) { throw new IllegalArgumentException(returnValuePath + " already exists"); } System.setProperty("user.dir", args[0]);
final Fn<?> continuation = SerializationUtil.readContinuation(continuationPath);
spotify/hype
hype-run/src/main/java/com/spotify/hype/stub/ContinuationEntryPoint.java
// Path: hype-common/src/main/java/com/spotify/hype/util/Fn.java // @FunctionalInterface // public interface Fn<T> extends Serializable { // T run(); // } // // Path: hype-common/src/main/java/com/spotify/hype/util/SerializationUtil.java // public class SerializationUtil { // // private static final String CONT_FILE = "continuation-"; // private static final String EXT = ".bin"; // // public static Path serializeContinuation(Fn<?> continuation) { // try { // final Path outputPath = Files.createTempFile(CONT_FILE, EXT); // serializeObject(continuation, outputPath); // return outputPath; // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // public static Fn<?> readContinuation(Path continuationPath) { // return (Fn) readObject(continuationPath); // } // // public static void serializeObject(Object obj, Path outputPath) { // Kryo kryo = new Kryo(); // kryo.register(java.lang.invoke.SerializedLambda.class); // kryo.register(ClosureSerializer.Closure.class, new ClosureSerializer()); // // try { // final File file = outputPath.toFile(); // try (Output output = new Output(new FileOutputStream(file))) { // kryo.writeClassAndObject(output, obj); // } // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // public static Object readObject(Path object) { // File file = object.toFile(); // // try (InputStream input = new FileInputStream(file)) { // return readObject(input); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // public static Object readObject(InputStream inputStream) { // Kryo kryo = new Kryo(); // kryo.register(java.lang.invoke.SerializedLambda.class); // kryo.register(ClosureSerializer.Closure.class, new ClosureSerializer()); // kryo.setInstantiatorStrategy(new Kryo.DefaultInstantiatorStrategy(new StdInstantiatorStrategy())); // // Input input = new Input(inputStream); // return kryo.readClassAndObject(input); // } // }
import com.spotify.hype.util.Fn; import com.spotify.hype.util.SerializationUtil; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths;
/*- * -\-\- * hype-submitter * -- * Copyright (C) 2016 - 2017 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.hype.stub; /** * TODO: document. */ public class ContinuationEntryPoint { public static void main(String[] args) throws Exception { if (args.length < 2) { throw new IllegalArgumentException("Usage: <staging-dir> <continuation-file> <output-file>"); } final Path continuationPath = Paths.get(args[0], args[1]); if (!Files.exists(continuationPath)) { throw new IllegalArgumentException(continuationPath + " does not exist"); } final Path returnValuePath = Paths.get(args[0], args[2]); if (Files.exists(returnValuePath)) { throw new IllegalArgumentException(returnValuePath + " already exists"); } System.setProperty("user.dir", args[0]);
// Path: hype-common/src/main/java/com/spotify/hype/util/Fn.java // @FunctionalInterface // public interface Fn<T> extends Serializable { // T run(); // } // // Path: hype-common/src/main/java/com/spotify/hype/util/SerializationUtil.java // public class SerializationUtil { // // private static final String CONT_FILE = "continuation-"; // private static final String EXT = ".bin"; // // public static Path serializeContinuation(Fn<?> continuation) { // try { // final Path outputPath = Files.createTempFile(CONT_FILE, EXT); // serializeObject(continuation, outputPath); // return outputPath; // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // public static Fn<?> readContinuation(Path continuationPath) { // return (Fn) readObject(continuationPath); // } // // public static void serializeObject(Object obj, Path outputPath) { // Kryo kryo = new Kryo(); // kryo.register(java.lang.invoke.SerializedLambda.class); // kryo.register(ClosureSerializer.Closure.class, new ClosureSerializer()); // // try { // final File file = outputPath.toFile(); // try (Output output = new Output(new FileOutputStream(file))) { // kryo.writeClassAndObject(output, obj); // } // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // public static Object readObject(Path object) { // File file = object.toFile(); // // try (InputStream input = new FileInputStream(file)) { // return readObject(input); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // public static Object readObject(InputStream inputStream) { // Kryo kryo = new Kryo(); // kryo.register(java.lang.invoke.SerializedLambda.class); // kryo.register(ClosureSerializer.Closure.class, new ClosureSerializer()); // kryo.setInstantiatorStrategy(new Kryo.DefaultInstantiatorStrategy(new StdInstantiatorStrategy())); // // Input input = new Input(inputStream); // return kryo.readClassAndObject(input); // } // } // Path: hype-run/src/main/java/com/spotify/hype/stub/ContinuationEntryPoint.java import com.spotify.hype.util.Fn; import com.spotify.hype.util.SerializationUtil; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; /*- * -\-\- * hype-submitter * -- * Copyright (C) 2016 - 2017 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.hype.stub; /** * TODO: document. */ public class ContinuationEntryPoint { public static void main(String[] args) throws Exception { if (args.length < 2) { throw new IllegalArgumentException("Usage: <staging-dir> <continuation-file> <output-file>"); } final Path continuationPath = Paths.get(args[0], args[1]); if (!Files.exists(continuationPath)) { throw new IllegalArgumentException(continuationPath + " does not exist"); } final Path returnValuePath = Paths.get(args[0], args[2]); if (Files.exists(returnValuePath)) { throw new IllegalArgumentException(returnValuePath + " already exists"); } System.setProperty("user.dir", args[0]);
final Fn<?> continuation = SerializationUtil.readContinuation(continuationPath);
spotify/hype
hype-submitter/src/main/java/com/spotify/hype/runner/VolumeRepository.java
// Path: hype-submitter/src/main/java/com/spotify/hype/model/VolumeRequest.java // @AutoMatter // public interface VolumeRequest { // // String VOLUME_REQUEST_PREFIX = "hype-request-"; // // String id(); // boolean keep(); // ClaimRequest spec(); // // @AutoMatter // interface ClaimRequest { // String storageClass(); // String size(); // boolean useExisting(); // } // // static VolumeRequest volumeRequest(String storageClass, String size) { // final String id = VOLUME_REQUEST_PREFIX + Util.randomAlphaNumeric(8); // return new VolumeRequestBuilder() // .id(id) // .keep(false) // new claims are deleted by default // .spec(new ClaimRequestBuilder() // .storageClass(storageClass) // .size(size) // .useExisting(false) // .build()) // .build(); // } // // static VolumeRequest createIfNotExists(String name, String storageClass, String size) { // final String id = String.format("%s-%s-%s", name, storageClass, size); // return new VolumeRequestBuilder() // .id(id) // .keep(true) // .spec(new ClaimRequestBuilder() // .storageClass(storageClass) // .size(size) // .useExisting(true) // .build()) // .build(); // } // // default VolumeRequest keepOnExit() { // return VolumeRequestBuilder.from(this) // .keep(true) // .build(); // } // // /** // * Mount the requested volume in read-only mode at the specified path. // */ // default VolumeMount mountReadOnly(String mountPath) { // return VolumeMount.volumeMount(this, mountPath, true); // } // // /** // * Mount the requested volume in read-write mode at the specified path. // */ // default VolumeMount mountReadWrite(String mountPath) { // return VolumeMount.volumeMount(this, mountPath, false); // } // } // // Path: hype-submitter/src/main/java/com/spotify/hype/model/VolumeRequest.java // @AutoMatter // interface ClaimRequest { // String storageClass(); // String size(); // boolean useExisting(); // }
import java.io.Closeable; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static java.util.stream.Collectors.toList; import com.spotify.hype.model.VolumeRequest; import com.spotify.hype.model.VolumeRequest.ClaimRequest; import io.fabric8.kubernetes.api.model.PersistentVolumeClaim; import io.fabric8.kubernetes.api.model.PersistentVolumeClaimBuilder; import io.fabric8.kubernetes.api.model.Quantity; import io.fabric8.kubernetes.api.model.ResourceRequirements; import io.fabric8.kubernetes.api.model.ResourceRequirementsBuilder; import io.fabric8.kubernetes.client.KubernetesClient;
/*- * -\-\- * hype-submitter * -- * Copyright (C) 2016 - 2017 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.hype.runner; /** * A repository for creating temporary {@link PersistentVolumeClaim}s from {@link VolumeRequest}s. * * <p>The repository will delete all created claims when it is closed. */ public class VolumeRepository implements Closeable { private static final Logger LOG = LoggerFactory.getLogger(VolumeRepository.class); static final String STORAGE_CLASS_ANNOTATION = "volume.beta.kubernetes.io/storage-class"; static final String READ_WRITE_ONCE = "ReadWriteOnce"; static final String READ_ONLY_MANY = "ReadOnlyMany"; private final KubernetesClient client;
// Path: hype-submitter/src/main/java/com/spotify/hype/model/VolumeRequest.java // @AutoMatter // public interface VolumeRequest { // // String VOLUME_REQUEST_PREFIX = "hype-request-"; // // String id(); // boolean keep(); // ClaimRequest spec(); // // @AutoMatter // interface ClaimRequest { // String storageClass(); // String size(); // boolean useExisting(); // } // // static VolumeRequest volumeRequest(String storageClass, String size) { // final String id = VOLUME_REQUEST_PREFIX + Util.randomAlphaNumeric(8); // return new VolumeRequestBuilder() // .id(id) // .keep(false) // new claims are deleted by default // .spec(new ClaimRequestBuilder() // .storageClass(storageClass) // .size(size) // .useExisting(false) // .build()) // .build(); // } // // static VolumeRequest createIfNotExists(String name, String storageClass, String size) { // final String id = String.format("%s-%s-%s", name, storageClass, size); // return new VolumeRequestBuilder() // .id(id) // .keep(true) // .spec(new ClaimRequestBuilder() // .storageClass(storageClass) // .size(size) // .useExisting(true) // .build()) // .build(); // } // // default VolumeRequest keepOnExit() { // return VolumeRequestBuilder.from(this) // .keep(true) // .build(); // } // // /** // * Mount the requested volume in read-only mode at the specified path. // */ // default VolumeMount mountReadOnly(String mountPath) { // return VolumeMount.volumeMount(this, mountPath, true); // } // // /** // * Mount the requested volume in read-write mode at the specified path. // */ // default VolumeMount mountReadWrite(String mountPath) { // return VolumeMount.volumeMount(this, mountPath, false); // } // } // // Path: hype-submitter/src/main/java/com/spotify/hype/model/VolumeRequest.java // @AutoMatter // interface ClaimRequest { // String storageClass(); // String size(); // boolean useExisting(); // } // Path: hype-submitter/src/main/java/com/spotify/hype/runner/VolumeRepository.java import java.io.Closeable; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static java.util.stream.Collectors.toList; import com.spotify.hype.model.VolumeRequest; import com.spotify.hype.model.VolumeRequest.ClaimRequest; import io.fabric8.kubernetes.api.model.PersistentVolumeClaim; import io.fabric8.kubernetes.api.model.PersistentVolumeClaimBuilder; import io.fabric8.kubernetes.api.model.Quantity; import io.fabric8.kubernetes.api.model.ResourceRequirements; import io.fabric8.kubernetes.api.model.ResourceRequirementsBuilder; import io.fabric8.kubernetes.client.KubernetesClient; /*- * -\-\- * hype-submitter * -- * Copyright (C) 2016 - 2017 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.hype.runner; /** * A repository for creating temporary {@link PersistentVolumeClaim}s from {@link VolumeRequest}s. * * <p>The repository will delete all created claims when it is closed. */ public class VolumeRepository implements Closeable { private static final Logger LOG = LoggerFactory.getLogger(VolumeRepository.class); static final String STORAGE_CLASS_ANNOTATION = "volume.beta.kubernetes.io/storage-class"; static final String READ_WRITE_ONCE = "ReadWriteOnce"; static final String READ_ONLY_MANY = "ReadOnlyMany"; private final KubernetesClient client;
private final ConcurrentMap<VolumeRequest, PersistentVolumeClaim> claims =
spotify/hype
hype-submitter/src/main/java/com/spotify/hype/runner/VolumeRepository.java
// Path: hype-submitter/src/main/java/com/spotify/hype/model/VolumeRequest.java // @AutoMatter // public interface VolumeRequest { // // String VOLUME_REQUEST_PREFIX = "hype-request-"; // // String id(); // boolean keep(); // ClaimRequest spec(); // // @AutoMatter // interface ClaimRequest { // String storageClass(); // String size(); // boolean useExisting(); // } // // static VolumeRequest volumeRequest(String storageClass, String size) { // final String id = VOLUME_REQUEST_PREFIX + Util.randomAlphaNumeric(8); // return new VolumeRequestBuilder() // .id(id) // .keep(false) // new claims are deleted by default // .spec(new ClaimRequestBuilder() // .storageClass(storageClass) // .size(size) // .useExisting(false) // .build()) // .build(); // } // // static VolumeRequest createIfNotExists(String name, String storageClass, String size) { // final String id = String.format("%s-%s-%s", name, storageClass, size); // return new VolumeRequestBuilder() // .id(id) // .keep(true) // .spec(new ClaimRequestBuilder() // .storageClass(storageClass) // .size(size) // .useExisting(true) // .build()) // .build(); // } // // default VolumeRequest keepOnExit() { // return VolumeRequestBuilder.from(this) // .keep(true) // .build(); // } // // /** // * Mount the requested volume in read-only mode at the specified path. // */ // default VolumeMount mountReadOnly(String mountPath) { // return VolumeMount.volumeMount(this, mountPath, true); // } // // /** // * Mount the requested volume in read-write mode at the specified path. // */ // default VolumeMount mountReadWrite(String mountPath) { // return VolumeMount.volumeMount(this, mountPath, false); // } // } // // Path: hype-submitter/src/main/java/com/spotify/hype/model/VolumeRequest.java // @AutoMatter // interface ClaimRequest { // String storageClass(); // String size(); // boolean useExisting(); // }
import java.io.Closeable; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static java.util.stream.Collectors.toList; import com.spotify.hype.model.VolumeRequest; import com.spotify.hype.model.VolumeRequest.ClaimRequest; import io.fabric8.kubernetes.api.model.PersistentVolumeClaim; import io.fabric8.kubernetes.api.model.PersistentVolumeClaimBuilder; import io.fabric8.kubernetes.api.model.Quantity; import io.fabric8.kubernetes.api.model.ResourceRequirements; import io.fabric8.kubernetes.api.model.ResourceRequirementsBuilder; import io.fabric8.kubernetes.client.KubernetesClient;
/*- * -\-\- * hype-submitter * -- * Copyright (C) 2016 - 2017 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.hype.runner; /** * A repository for creating temporary {@link PersistentVolumeClaim}s from {@link VolumeRequest}s. * * <p>The repository will delete all created claims when it is closed. */ public class VolumeRepository implements Closeable { private static final Logger LOG = LoggerFactory.getLogger(VolumeRepository.class); static final String STORAGE_CLASS_ANNOTATION = "volume.beta.kubernetes.io/storage-class"; static final String READ_WRITE_ONCE = "ReadWriteOnce"; static final String READ_ONLY_MANY = "ReadOnlyMany"; private final KubernetesClient client; private final ConcurrentMap<VolumeRequest, PersistentVolumeClaim> claims = new ConcurrentHashMap<>(); public VolumeRepository(KubernetesClient client) { this.client = Objects.requireNonNull(client); } PersistentVolumeClaim getClaim(VolumeRequest volumeRequest) { return claims.computeIfAbsent(volumeRequest, this::createClaim); } private PersistentVolumeClaim createClaim(VolumeRequest volumeRequest) {
// Path: hype-submitter/src/main/java/com/spotify/hype/model/VolumeRequest.java // @AutoMatter // public interface VolumeRequest { // // String VOLUME_REQUEST_PREFIX = "hype-request-"; // // String id(); // boolean keep(); // ClaimRequest spec(); // // @AutoMatter // interface ClaimRequest { // String storageClass(); // String size(); // boolean useExisting(); // } // // static VolumeRequest volumeRequest(String storageClass, String size) { // final String id = VOLUME_REQUEST_PREFIX + Util.randomAlphaNumeric(8); // return new VolumeRequestBuilder() // .id(id) // .keep(false) // new claims are deleted by default // .spec(new ClaimRequestBuilder() // .storageClass(storageClass) // .size(size) // .useExisting(false) // .build()) // .build(); // } // // static VolumeRequest createIfNotExists(String name, String storageClass, String size) { // final String id = String.format("%s-%s-%s", name, storageClass, size); // return new VolumeRequestBuilder() // .id(id) // .keep(true) // .spec(new ClaimRequestBuilder() // .storageClass(storageClass) // .size(size) // .useExisting(true) // .build()) // .build(); // } // // default VolumeRequest keepOnExit() { // return VolumeRequestBuilder.from(this) // .keep(true) // .build(); // } // // /** // * Mount the requested volume in read-only mode at the specified path. // */ // default VolumeMount mountReadOnly(String mountPath) { // return VolumeMount.volumeMount(this, mountPath, true); // } // // /** // * Mount the requested volume in read-write mode at the specified path. // */ // default VolumeMount mountReadWrite(String mountPath) { // return VolumeMount.volumeMount(this, mountPath, false); // } // } // // Path: hype-submitter/src/main/java/com/spotify/hype/model/VolumeRequest.java // @AutoMatter // interface ClaimRequest { // String storageClass(); // String size(); // boolean useExisting(); // } // Path: hype-submitter/src/main/java/com/spotify/hype/runner/VolumeRepository.java import java.io.Closeable; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static java.util.stream.Collectors.toList; import com.spotify.hype.model.VolumeRequest; import com.spotify.hype.model.VolumeRequest.ClaimRequest; import io.fabric8.kubernetes.api.model.PersistentVolumeClaim; import io.fabric8.kubernetes.api.model.PersistentVolumeClaimBuilder; import io.fabric8.kubernetes.api.model.Quantity; import io.fabric8.kubernetes.api.model.ResourceRequirements; import io.fabric8.kubernetes.api.model.ResourceRequirementsBuilder; import io.fabric8.kubernetes.client.KubernetesClient; /*- * -\-\- * hype-submitter * -- * Copyright (C) 2016 - 2017 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.hype.runner; /** * A repository for creating temporary {@link PersistentVolumeClaim}s from {@link VolumeRequest}s. * * <p>The repository will delete all created claims when it is closed. */ public class VolumeRepository implements Closeable { private static final Logger LOG = LoggerFactory.getLogger(VolumeRepository.class); static final String STORAGE_CLASS_ANNOTATION = "volume.beta.kubernetes.io/storage-class"; static final String READ_WRITE_ONCE = "ReadWriteOnce"; static final String READ_ONLY_MANY = "ReadOnlyMany"; private final KubernetesClient client; private final ConcurrentMap<VolumeRequest, PersistentVolumeClaim> claims = new ConcurrentHashMap<>(); public VolumeRepository(KubernetesClient client) { this.client = Objects.requireNonNull(client); } PersistentVolumeClaim getClaim(VolumeRequest volumeRequest) { return claims.computeIfAbsent(volumeRequest, this::createClaim); } private PersistentVolumeClaim createClaim(VolumeRequest volumeRequest) {
final ClaimRequest spec = volumeRequest.spec();
spotify/hype
hype-gcs/src/test/java/com/spotify/hype/gcs/ManifestLoaderTest.java
// Path: hype-gcs/src/main/java/com/spotify/hype/gcs/StagingUtil.java // @AutoValue // public static abstract class StagedPackage { // public abstract String name(); // public abstract String location(); // public abstract long size(); // // abstract int stageCallId(); // // StagedPackage asCached() { // return stagedPackage(name(), location(), size(), -1); // } // }
import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.List; import org.junit.Before; import org.junit.Test; import static java.util.stream.Collectors.toList; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import com.spotify.hype.gcs.StagingUtil.StagedPackage; import java.io.File; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLClassLoader;
/*- * -\-\- * hype-gcs * -- * Copyright (C) 2016 - 2017 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.hype.gcs; public class ManifestLoaderTest { List<String> testFiles; Path stagingPath; String stagingLocation; @Before public void setUp() throws Exception { URLClassLoader cl = (URLClassLoader) StagingUtilTest.class.getClassLoader(); testFiles = Arrays.stream(cl.getURLs()) .map(url -> new File(toUri(url))) .map(File::getAbsolutePath) .collect(toList()); stagingPath = Files.createTempDirectory("unit-test"); stagingLocation = stagingPath.toUri().toString(); } @Test public void end2endStaging() throws Exception {
// Path: hype-gcs/src/main/java/com/spotify/hype/gcs/StagingUtil.java // @AutoValue // public static abstract class StagedPackage { // public abstract String name(); // public abstract String location(); // public abstract long size(); // // abstract int stageCallId(); // // StagedPackage asCached() { // return stagedPackage(name(), location(), size(), -1); // } // } // Path: hype-gcs/src/test/java/com/spotify/hype/gcs/ManifestLoaderTest.java import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.List; import org.junit.Before; import org.junit.Test; import static java.util.stream.Collectors.toList; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import com.spotify.hype.gcs.StagingUtil.StagedPackage; import java.io.File; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLClassLoader; /*- * -\-\- * hype-gcs * -- * Copyright (C) 2016 - 2017 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.hype.gcs; public class ManifestLoaderTest { List<String> testFiles; Path stagingPath; String stagingLocation; @Before public void setUp() throws Exception { URLClassLoader cl = (URLClassLoader) StagingUtilTest.class.getClassLoader(); testFiles = Arrays.stream(cl.getURLs()) .map(url -> new File(toUri(url))) .map(File::getAbsolutePath) .collect(toList()); stagingPath = Files.createTempDirectory("unit-test"); stagingLocation = stagingPath.toUri().toString(); } @Test public void end2endStaging() throws Exception {
List<StagedPackage> stagedPackages =
spotify/hype
hype-submitter/src/main/java/com/spotify/hype/runner/LocalDockerRunner.java
// Path: hype-submitter/src/main/java/com/spotify/hype/model/RunEnvironment.java // @AutoMatter // public interface RunEnvironment { // // Optional<Path> yamlPath(); // List<Secret> secretMounts(); // List<VolumeMount> volumeMounts(); // Map<String, String> resourceRequests(); // // static RunEnvironment environment() { // return new RunEnvironmentBuilder().build(); // } // // static RunEnvironment fromYaml(String resourcePath) { // final URI resourceUri; // try { // resourceUri = RunEnvironment.class.getResource(resourcePath).toURI(); // } catch (URISyntaxException e) { // throw new RuntimeException(e); // } // return fromYaml(Paths.get(resourceUri)); // } // // static RunEnvironment fromYaml(Path path) { // return new RunEnvironmentBuilder() // .yamlPath(path) // .build(); // } // // default RunEnvironment withSecret(String name, String mountPath) { // return RunEnvironmentBuilder.from(this) // .addSecretMount(Secret.secret(name, mountPath)) // .build(); // } // // default RunEnvironment withSecret(Secret secret) { // return RunEnvironmentBuilder.from(this) // .addSecretMount(secret) // .build(); // } // // default RunEnvironment withMount(VolumeMount volumeMount) { // return RunEnvironmentBuilder.from(this) // .addVolumeMount(volumeMount) // .build(); // } // // default RunEnvironment withRequest(String resource, String amount) { // return RunEnvironmentBuilder.from(this) // .putResourceRequest(resource, amount) // .build(); // } // // default RunEnvironment withRequest(ResourceRequest request) { // return RunEnvironmentBuilder.from(this) // .putResourceRequest(request.resource(), request.amount()) // .build(); // } // } // // Path: hype-submitter/src/main/java/com/spotify/hype/model/StagedContinuation.java // @AutoMatter // public interface StagedContinuation { // // Path manifestPath(); // RunManifest manifest(); // // static StagedContinuation stagedContinuation(Path manifestPath, RunManifest manifest) { // return new StagedContinuationBuilder() // .manifestPath(manifestPath) // .manifest(manifest) // .build(); // } // }
import static com.google.common.collect.ImmutableList.of; import com.spotify.docker.client.DockerClient; import com.spotify.docker.client.exceptions.DockerException; import com.spotify.docker.client.messages.ContainerConfig; import com.spotify.docker.client.messages.ContainerCreation; import com.spotify.docker.client.messages.ContainerInfo; import com.spotify.docker.client.messages.HostConfig; import com.spotify.docker.client.messages.Image; import com.spotify.hype.model.RunEnvironment; import com.spotify.hype.model.StagedContinuation; import java.io.File; import java.io.IOException; import java.net.URI; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/*- * -\-\- * hype-submitter * -- * Copyright (C) 2016 - 2017 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.hype.runner; public class LocalDockerRunner implements DockerRunner { private static final Logger LOG = LoggerFactory.getLogger(LocalDockerRunner.class); private static final String GCLOUD_CREDENTIALS = "GOOGLE_APPLICATION_CREDENTIALS"; private static final String STAGING_VOLUME = "/staging"; private static final String GCLOUD_CREDENTIALS_MOUNT = "/etc/gcloud/key.json"; private static final int POLL_CONTAINERS_INTERVAL_SECONDS = 1; private final DockerClient client; private final Boolean keepContainer; private final Boolean keepTerminationLog; private final Boolean keepVolumes; public LocalDockerRunner(final DockerClient client, final Boolean keepContainer, final Boolean keepTerminationLog, final Boolean keepVolumes) { this.client = client; this.keepContainer = keepContainer; this.keepTerminationLog = keepTerminationLog; this.keepVolumes = keepVolumes; } @Override public Optional<URI> run(final RunSpec runSpec) {
// Path: hype-submitter/src/main/java/com/spotify/hype/model/RunEnvironment.java // @AutoMatter // public interface RunEnvironment { // // Optional<Path> yamlPath(); // List<Secret> secretMounts(); // List<VolumeMount> volumeMounts(); // Map<String, String> resourceRequests(); // // static RunEnvironment environment() { // return new RunEnvironmentBuilder().build(); // } // // static RunEnvironment fromYaml(String resourcePath) { // final URI resourceUri; // try { // resourceUri = RunEnvironment.class.getResource(resourcePath).toURI(); // } catch (URISyntaxException e) { // throw new RuntimeException(e); // } // return fromYaml(Paths.get(resourceUri)); // } // // static RunEnvironment fromYaml(Path path) { // return new RunEnvironmentBuilder() // .yamlPath(path) // .build(); // } // // default RunEnvironment withSecret(String name, String mountPath) { // return RunEnvironmentBuilder.from(this) // .addSecretMount(Secret.secret(name, mountPath)) // .build(); // } // // default RunEnvironment withSecret(Secret secret) { // return RunEnvironmentBuilder.from(this) // .addSecretMount(secret) // .build(); // } // // default RunEnvironment withMount(VolumeMount volumeMount) { // return RunEnvironmentBuilder.from(this) // .addVolumeMount(volumeMount) // .build(); // } // // default RunEnvironment withRequest(String resource, String amount) { // return RunEnvironmentBuilder.from(this) // .putResourceRequest(resource, amount) // .build(); // } // // default RunEnvironment withRequest(ResourceRequest request) { // return RunEnvironmentBuilder.from(this) // .putResourceRequest(request.resource(), request.amount()) // .build(); // } // } // // Path: hype-submitter/src/main/java/com/spotify/hype/model/StagedContinuation.java // @AutoMatter // public interface StagedContinuation { // // Path manifestPath(); // RunManifest manifest(); // // static StagedContinuation stagedContinuation(Path manifestPath, RunManifest manifest) { // return new StagedContinuationBuilder() // .manifestPath(manifestPath) // .manifest(manifest) // .build(); // } // } // Path: hype-submitter/src/main/java/com/spotify/hype/runner/LocalDockerRunner.java import static com.google.common.collect.ImmutableList.of; import com.spotify.docker.client.DockerClient; import com.spotify.docker.client.exceptions.DockerException; import com.spotify.docker.client.messages.ContainerConfig; import com.spotify.docker.client.messages.ContainerCreation; import com.spotify.docker.client.messages.ContainerInfo; import com.spotify.docker.client.messages.HostConfig; import com.spotify.docker.client.messages.Image; import com.spotify.hype.model.RunEnvironment; import com.spotify.hype.model.StagedContinuation; import java.io.File; import java.io.IOException; import java.net.URI; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /*- * -\-\- * hype-submitter * -- * Copyright (C) 2016 - 2017 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.hype.runner; public class LocalDockerRunner implements DockerRunner { private static final Logger LOG = LoggerFactory.getLogger(LocalDockerRunner.class); private static final String GCLOUD_CREDENTIALS = "GOOGLE_APPLICATION_CREDENTIALS"; private static final String STAGING_VOLUME = "/staging"; private static final String GCLOUD_CREDENTIALS_MOUNT = "/etc/gcloud/key.json"; private static final int POLL_CONTAINERS_INTERVAL_SECONDS = 1; private final DockerClient client; private final Boolean keepContainer; private final Boolean keepTerminationLog; private final Boolean keepVolumes; public LocalDockerRunner(final DockerClient client, final Boolean keepContainer, final Boolean keepTerminationLog, final Boolean keepVolumes) { this.client = client; this.keepContainer = keepContainer; this.keepTerminationLog = keepTerminationLog; this.keepVolumes = keepVolumes; } @Override public Optional<URI> run(final RunSpec runSpec) {
final RunEnvironment env = runSpec.runEnvironment();
spotify/hype
hype-submitter/src/main/java/com/spotify/hype/runner/LocalDockerRunner.java
// Path: hype-submitter/src/main/java/com/spotify/hype/model/RunEnvironment.java // @AutoMatter // public interface RunEnvironment { // // Optional<Path> yamlPath(); // List<Secret> secretMounts(); // List<VolumeMount> volumeMounts(); // Map<String, String> resourceRequests(); // // static RunEnvironment environment() { // return new RunEnvironmentBuilder().build(); // } // // static RunEnvironment fromYaml(String resourcePath) { // final URI resourceUri; // try { // resourceUri = RunEnvironment.class.getResource(resourcePath).toURI(); // } catch (URISyntaxException e) { // throw new RuntimeException(e); // } // return fromYaml(Paths.get(resourceUri)); // } // // static RunEnvironment fromYaml(Path path) { // return new RunEnvironmentBuilder() // .yamlPath(path) // .build(); // } // // default RunEnvironment withSecret(String name, String mountPath) { // return RunEnvironmentBuilder.from(this) // .addSecretMount(Secret.secret(name, mountPath)) // .build(); // } // // default RunEnvironment withSecret(Secret secret) { // return RunEnvironmentBuilder.from(this) // .addSecretMount(secret) // .build(); // } // // default RunEnvironment withMount(VolumeMount volumeMount) { // return RunEnvironmentBuilder.from(this) // .addVolumeMount(volumeMount) // .build(); // } // // default RunEnvironment withRequest(String resource, String amount) { // return RunEnvironmentBuilder.from(this) // .putResourceRequest(resource, amount) // .build(); // } // // default RunEnvironment withRequest(ResourceRequest request) { // return RunEnvironmentBuilder.from(this) // .putResourceRequest(request.resource(), request.amount()) // .build(); // } // } // // Path: hype-submitter/src/main/java/com/spotify/hype/model/StagedContinuation.java // @AutoMatter // public interface StagedContinuation { // // Path manifestPath(); // RunManifest manifest(); // // static StagedContinuation stagedContinuation(Path manifestPath, RunManifest manifest) { // return new StagedContinuationBuilder() // .manifestPath(manifestPath) // .manifest(manifest) // .build(); // } // }
import static com.google.common.collect.ImmutableList.of; import com.spotify.docker.client.DockerClient; import com.spotify.docker.client.exceptions.DockerException; import com.spotify.docker.client.messages.ContainerConfig; import com.spotify.docker.client.messages.ContainerCreation; import com.spotify.docker.client.messages.ContainerInfo; import com.spotify.docker.client.messages.HostConfig; import com.spotify.docker.client.messages.Image; import com.spotify.hype.model.RunEnvironment; import com.spotify.hype.model.StagedContinuation; import java.io.File; import java.io.IOException; import java.net.URI; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/*- * -\-\- * hype-submitter * -- * Copyright (C) 2016 - 2017 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.hype.runner; public class LocalDockerRunner implements DockerRunner { private static final Logger LOG = LoggerFactory.getLogger(LocalDockerRunner.class); private static final String GCLOUD_CREDENTIALS = "GOOGLE_APPLICATION_CREDENTIALS"; private static final String STAGING_VOLUME = "/staging"; private static final String GCLOUD_CREDENTIALS_MOUNT = "/etc/gcloud/key.json"; private static final int POLL_CONTAINERS_INTERVAL_SECONDS = 1; private final DockerClient client; private final Boolean keepContainer; private final Boolean keepTerminationLog; private final Boolean keepVolumes; public LocalDockerRunner(final DockerClient client, final Boolean keepContainer, final Boolean keepTerminationLog, final Boolean keepVolumes) { this.client = client; this.keepContainer = keepContainer; this.keepTerminationLog = keepTerminationLog; this.keepVolumes = keepVolumes; } @Override public Optional<URI> run(final RunSpec runSpec) { final RunEnvironment env = runSpec.runEnvironment();
// Path: hype-submitter/src/main/java/com/spotify/hype/model/RunEnvironment.java // @AutoMatter // public interface RunEnvironment { // // Optional<Path> yamlPath(); // List<Secret> secretMounts(); // List<VolumeMount> volumeMounts(); // Map<String, String> resourceRequests(); // // static RunEnvironment environment() { // return new RunEnvironmentBuilder().build(); // } // // static RunEnvironment fromYaml(String resourcePath) { // final URI resourceUri; // try { // resourceUri = RunEnvironment.class.getResource(resourcePath).toURI(); // } catch (URISyntaxException e) { // throw new RuntimeException(e); // } // return fromYaml(Paths.get(resourceUri)); // } // // static RunEnvironment fromYaml(Path path) { // return new RunEnvironmentBuilder() // .yamlPath(path) // .build(); // } // // default RunEnvironment withSecret(String name, String mountPath) { // return RunEnvironmentBuilder.from(this) // .addSecretMount(Secret.secret(name, mountPath)) // .build(); // } // // default RunEnvironment withSecret(Secret secret) { // return RunEnvironmentBuilder.from(this) // .addSecretMount(secret) // .build(); // } // // default RunEnvironment withMount(VolumeMount volumeMount) { // return RunEnvironmentBuilder.from(this) // .addVolumeMount(volumeMount) // .build(); // } // // default RunEnvironment withRequest(String resource, String amount) { // return RunEnvironmentBuilder.from(this) // .putResourceRequest(resource, amount) // .build(); // } // // default RunEnvironment withRequest(ResourceRequest request) { // return RunEnvironmentBuilder.from(this) // .putResourceRequest(request.resource(), request.amount()) // .build(); // } // } // // Path: hype-submitter/src/main/java/com/spotify/hype/model/StagedContinuation.java // @AutoMatter // public interface StagedContinuation { // // Path manifestPath(); // RunManifest manifest(); // // static StagedContinuation stagedContinuation(Path manifestPath, RunManifest manifest) { // return new StagedContinuationBuilder() // .manifestPath(manifestPath) // .manifest(manifest) // .build(); // } // } // Path: hype-submitter/src/main/java/com/spotify/hype/runner/LocalDockerRunner.java import static com.google.common.collect.ImmutableList.of; import com.spotify.docker.client.DockerClient; import com.spotify.docker.client.exceptions.DockerException; import com.spotify.docker.client.messages.ContainerConfig; import com.spotify.docker.client.messages.ContainerCreation; import com.spotify.docker.client.messages.ContainerInfo; import com.spotify.docker.client.messages.HostConfig; import com.spotify.docker.client.messages.Image; import com.spotify.hype.model.RunEnvironment; import com.spotify.hype.model.StagedContinuation; import java.io.File; import java.io.IOException; import java.net.URI; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /*- * -\-\- * hype-submitter * -- * Copyright (C) 2016 - 2017 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.hype.runner; public class LocalDockerRunner implements DockerRunner { private static final Logger LOG = LoggerFactory.getLogger(LocalDockerRunner.class); private static final String GCLOUD_CREDENTIALS = "GOOGLE_APPLICATION_CREDENTIALS"; private static final String STAGING_VOLUME = "/staging"; private static final String GCLOUD_CREDENTIALS_MOUNT = "/etc/gcloud/key.json"; private static final int POLL_CONTAINERS_INTERVAL_SECONDS = 1; private final DockerClient client; private final Boolean keepContainer; private final Boolean keepTerminationLog; private final Boolean keepVolumes; public LocalDockerRunner(final DockerClient client, final Boolean keepContainer, final Boolean keepTerminationLog, final Boolean keepVolumes) { this.client = client; this.keepContainer = keepContainer; this.keepTerminationLog = keepTerminationLog; this.keepVolumes = keepVolumes; } @Override public Optional<URI> run(final RunSpec runSpec) { final RunEnvironment env = runSpec.runEnvironment();
final StagedContinuation stagedContinuation = runSpec.stagedContinuation();
spotify/hype
hype-submitter/src/main/java/com/spotify/hype/runner/DockerRunner.java
// Path: hype-submitter/src/main/java/com/spotify/hype/model/ContainerEngineCluster.java // @AutoMatter // public interface ContainerEngineCluster { // // String project(); // String zone(); // String cluster(); // // static ContainerEngineCluster containerEngineCluster(String project, String zone, String cluster) { // return new ContainerEngineClusterBuilder() // .project(project) // .zone(zone) // .cluster(cluster) // .build(); // } // } // // Path: hype-submitter/src/main/java/com/spotify/hype/model/DockerCluster.java // @AutoMatter // public interface DockerCluster { // boolean keepContainer(); // boolean keepTerminationLog(); // boolean keepVolumes(); // // static DockerCluster dockerCluster(final boolean keepContainer, // final boolean keepTerminationLog, // final boolean keepVolumes) { // return new DockerClusterBuilder() // .keepContainer(keepContainer) // .keepTerminationLog(keepTerminationLog) // .keepVolumes(keepVolumes) // .build(); // } // // static DockerCluster dockerCluster() { // return new DockerClusterBuilder() // .keepContainer(false) // .keepTerminationLog(false) // .keepVolumes(false) // .build(); // } // // }
import io.fabric8.kubernetes.client.ConfigBuilder; import io.fabric8.kubernetes.client.DefaultKubernetesClient; import io.fabric8.kubernetes.client.KubernetesClient; import java.io.IOException; import java.net.URI; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.services.container.Container; import com.google.api.services.container.ContainerScopes; import com.google.api.services.container.model.Cluster; import com.google.common.base.Throwables; import com.spotify.docker.client.DefaultDockerClient; import com.spotify.docker.client.DockerClient; import com.spotify.docker.client.exceptions.DockerCertificateException; import com.spotify.hype.model.ContainerEngineCluster; import com.spotify.hype.model.DockerCluster;
/*- * -\-\- * Spotify Styx Scheduler Service * -- * Copyright (C) 2016 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.hype.runner; /** * Defines an interface to the Docker execution environment */ public interface DockerRunner { String NAMESPACE = "default"; Logger LOG = LoggerFactory.getLogger(DockerRunner.class); /** * Runs a hype execution. Blocks until complete. * * @param runSpec Specification of what to run * @return Optionally a uri pointing to the gcs location of the return value */ Optional<URI> run(RunSpec runSpec); static DockerRunner kubernetes( KubernetesClient kubernetesClient, VolumeRepository volumeRepository) { return new KubernetesDockerRunner(kubernetesClient, volumeRepository); } static DockerRunner local(DockerClient dockerClient,
// Path: hype-submitter/src/main/java/com/spotify/hype/model/ContainerEngineCluster.java // @AutoMatter // public interface ContainerEngineCluster { // // String project(); // String zone(); // String cluster(); // // static ContainerEngineCluster containerEngineCluster(String project, String zone, String cluster) { // return new ContainerEngineClusterBuilder() // .project(project) // .zone(zone) // .cluster(cluster) // .build(); // } // } // // Path: hype-submitter/src/main/java/com/spotify/hype/model/DockerCluster.java // @AutoMatter // public interface DockerCluster { // boolean keepContainer(); // boolean keepTerminationLog(); // boolean keepVolumes(); // // static DockerCluster dockerCluster(final boolean keepContainer, // final boolean keepTerminationLog, // final boolean keepVolumes) { // return new DockerClusterBuilder() // .keepContainer(keepContainer) // .keepTerminationLog(keepTerminationLog) // .keepVolumes(keepVolumes) // .build(); // } // // static DockerCluster dockerCluster() { // return new DockerClusterBuilder() // .keepContainer(false) // .keepTerminationLog(false) // .keepVolumes(false) // .build(); // } // // } // Path: hype-submitter/src/main/java/com/spotify/hype/runner/DockerRunner.java import io.fabric8.kubernetes.client.ConfigBuilder; import io.fabric8.kubernetes.client.DefaultKubernetesClient; import io.fabric8.kubernetes.client.KubernetesClient; import java.io.IOException; import java.net.URI; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.services.container.Container; import com.google.api.services.container.ContainerScopes; import com.google.api.services.container.model.Cluster; import com.google.common.base.Throwables; import com.spotify.docker.client.DefaultDockerClient; import com.spotify.docker.client.DockerClient; import com.spotify.docker.client.exceptions.DockerCertificateException; import com.spotify.hype.model.ContainerEngineCluster; import com.spotify.hype.model.DockerCluster; /*- * -\-\- * Spotify Styx Scheduler Service * -- * Copyright (C) 2016 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.hype.runner; /** * Defines an interface to the Docker execution environment */ public interface DockerRunner { String NAMESPACE = "default"; Logger LOG = LoggerFactory.getLogger(DockerRunner.class); /** * Runs a hype execution. Blocks until complete. * * @param runSpec Specification of what to run * @return Optionally a uri pointing to the gcs location of the return value */ Optional<URI> run(RunSpec runSpec); static DockerRunner kubernetes( KubernetesClient kubernetesClient, VolumeRepository volumeRepository) { return new KubernetesDockerRunner(kubernetesClient, volumeRepository); } static DockerRunner local(DockerClient dockerClient,
DockerCluster dockerCluster) {
spotify/hype
hype-submitter/src/main/java/com/spotify/hype/runner/DockerRunner.java
// Path: hype-submitter/src/main/java/com/spotify/hype/model/ContainerEngineCluster.java // @AutoMatter // public interface ContainerEngineCluster { // // String project(); // String zone(); // String cluster(); // // static ContainerEngineCluster containerEngineCluster(String project, String zone, String cluster) { // return new ContainerEngineClusterBuilder() // .project(project) // .zone(zone) // .cluster(cluster) // .build(); // } // } // // Path: hype-submitter/src/main/java/com/spotify/hype/model/DockerCluster.java // @AutoMatter // public interface DockerCluster { // boolean keepContainer(); // boolean keepTerminationLog(); // boolean keepVolumes(); // // static DockerCluster dockerCluster(final boolean keepContainer, // final boolean keepTerminationLog, // final boolean keepVolumes) { // return new DockerClusterBuilder() // .keepContainer(keepContainer) // .keepTerminationLog(keepTerminationLog) // .keepVolumes(keepVolumes) // .build(); // } // // static DockerCluster dockerCluster() { // return new DockerClusterBuilder() // .keepContainer(false) // .keepTerminationLog(false) // .keepVolumes(false) // .build(); // } // // }
import io.fabric8.kubernetes.client.ConfigBuilder; import io.fabric8.kubernetes.client.DefaultKubernetesClient; import io.fabric8.kubernetes.client.KubernetesClient; import java.io.IOException; import java.net.URI; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.services.container.Container; import com.google.api.services.container.ContainerScopes; import com.google.api.services.container.model.Cluster; import com.google.common.base.Throwables; import com.spotify.docker.client.DefaultDockerClient; import com.spotify.docker.client.DockerClient; import com.spotify.docker.client.exceptions.DockerCertificateException; import com.spotify.hype.model.ContainerEngineCluster; import com.spotify.hype.model.DockerCluster;
/*- * -\-\- * Spotify Styx Scheduler Service * -- * Copyright (C) 2016 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.hype.runner; /** * Defines an interface to the Docker execution environment */ public interface DockerRunner { String NAMESPACE = "default"; Logger LOG = LoggerFactory.getLogger(DockerRunner.class); /** * Runs a hype execution. Blocks until complete. * * @param runSpec Specification of what to run * @return Optionally a uri pointing to the gcs location of the return value */ Optional<URI> run(RunSpec runSpec); static DockerRunner kubernetes( KubernetesClient kubernetesClient, VolumeRepository volumeRepository) { return new KubernetesDockerRunner(kubernetesClient, volumeRepository); } static DockerRunner local(DockerClient dockerClient, DockerCluster dockerCluster) { return new LocalDockerRunner( dockerClient, dockerCluster.keepContainer(), dockerCluster.keepTerminationLog(), dockerCluster.keepVolumes()); }
// Path: hype-submitter/src/main/java/com/spotify/hype/model/ContainerEngineCluster.java // @AutoMatter // public interface ContainerEngineCluster { // // String project(); // String zone(); // String cluster(); // // static ContainerEngineCluster containerEngineCluster(String project, String zone, String cluster) { // return new ContainerEngineClusterBuilder() // .project(project) // .zone(zone) // .cluster(cluster) // .build(); // } // } // // Path: hype-submitter/src/main/java/com/spotify/hype/model/DockerCluster.java // @AutoMatter // public interface DockerCluster { // boolean keepContainer(); // boolean keepTerminationLog(); // boolean keepVolumes(); // // static DockerCluster dockerCluster(final boolean keepContainer, // final boolean keepTerminationLog, // final boolean keepVolumes) { // return new DockerClusterBuilder() // .keepContainer(keepContainer) // .keepTerminationLog(keepTerminationLog) // .keepVolumes(keepVolumes) // .build(); // } // // static DockerCluster dockerCluster() { // return new DockerClusterBuilder() // .keepContainer(false) // .keepTerminationLog(false) // .keepVolumes(false) // .build(); // } // // } // Path: hype-submitter/src/main/java/com/spotify/hype/runner/DockerRunner.java import io.fabric8.kubernetes.client.ConfigBuilder; import io.fabric8.kubernetes.client.DefaultKubernetesClient; import io.fabric8.kubernetes.client.KubernetesClient; import java.io.IOException; import java.net.URI; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.services.container.Container; import com.google.api.services.container.ContainerScopes; import com.google.api.services.container.model.Cluster; import com.google.common.base.Throwables; import com.spotify.docker.client.DefaultDockerClient; import com.spotify.docker.client.DockerClient; import com.spotify.docker.client.exceptions.DockerCertificateException; import com.spotify.hype.model.ContainerEngineCluster; import com.spotify.hype.model.DockerCluster; /*- * -\-\- * Spotify Styx Scheduler Service * -- * Copyright (C) 2016 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.hype.runner; /** * Defines an interface to the Docker execution environment */ public interface DockerRunner { String NAMESPACE = "default"; Logger LOG = LoggerFactory.getLogger(DockerRunner.class); /** * Runs a hype execution. Blocks until complete. * * @param runSpec Specification of what to run * @return Optionally a uri pointing to the gcs location of the return value */ Optional<URI> run(RunSpec runSpec); static DockerRunner kubernetes( KubernetesClient kubernetesClient, VolumeRepository volumeRepository) { return new KubernetesDockerRunner(kubernetesClient, volumeRepository); } static DockerRunner local(DockerClient dockerClient, DockerCluster dockerCluster) { return new LocalDockerRunner( dockerClient, dockerCluster.keepContainer(), dockerCluster.keepTerminationLog(), dockerCluster.keepVolumes()); }
static KubernetesClient createKubernetesClient(ContainerEngineCluster gkeCluster) {
spotify/hype
hype-caplet/src/main/java/Hypelet.java
// Path: hype-common/src/main/java/com/spotify/hype/util/Util.java // public static String randomAlphaNumeric(int count) { // StringBuilder builder = new StringBuilder(); // while (count-- != 0) { // int character = (int)(Math.random() * ALPHA_NUMERIC_STRING.length()); // builder.append(ALPHA_NUMERIC_STRING.charAt(character)); // } // return builder.toString(); // } // // Path: hype-gcs/src/main/java/com/spotify/hype/gcs/ManifestLoader.java // public final class ManifestLoader { // // private static final ForkJoinPool FJP = new ForkJoinPool(32); // // public static RunManifest downloadManifest(Path manifestPath, Path destinationDir) throws IOException { // final RunManifest manifest = ManifestUtil.read(manifestPath); // // final Set<Path> manifestEntries = new LinkedHashSet<>(); // manifestEntries.add(manifestPath.resolveSibling(manifest.continuation())); // for (String file : concat(manifest.classPathFiles(), manifest.files())) { // manifestEntries.add(manifestPath.resolveSibling(file)); // } // // try { // FJP.submit(() -> manifestEntries.parallelStream() // .forEach(filePath -> downloadFile(filePath, destinationDir))) // .get(); // } catch (InterruptedException | ExecutionException e) { // throw new RuntimeException(e); // } // // return manifest; // } // // private static void downloadFile(Path filePath, Path destinationDir) { // final Path destinationFile = destinationDir.resolve(filePath.getFileName().toString()); // try { // // todo: retries // Files.copy(filePath, destinationFile, StandardCopyOption.REPLACE_EXISTING); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // // Path: hype-gcs/src/main/java/com/spotify/hype/gcs/RunManifest.java // @AutoMatter // public interface RunManifest { // // String continuation(); // // List<String> classPathFiles(); // // List<String> files(); // // static RunManifest read(Path manifestPath) throws IOException { // return ManifestUtil.read(manifestPath); // } // // static void write(RunManifest manifest, Path manifestPath) throws IOException { // ManifestUtil.write(manifest, manifestPath); // } // }
import static com.google.cloud.storage.contrib.nio.CloudStorageOptions.withMimeType; import static com.google.common.base.Charsets.UTF_8; import static com.spotify.hype.util.Util.randomAlphaNumeric; import static java.nio.file.StandardOpenOption.CREATE; import static java.nio.file.StandardOpenOption.CREATE_NEW; import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING; import static java.nio.file.StandardOpenOption.WRITE; import static java.util.Collections.emptyMap; import com.google.common.collect.Sets; import com.spotify.hype.gcs.ManifestLoader; import com.spotify.hype.gcs.RunManifest; import java.io.IOException; import java.net.URI; import java.nio.channels.Channels; import java.nio.channels.WritableByteChannel; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.OpenOption; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.spi.FileSystemProvider; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Properties; import java.util.Set;
/*- * -\-\- * hype-run * -- * Copyright (C) 2016 - 2017 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ /** * Capsule caplet that downloads a run-manifest to a temp directory and adds the included files to * the application JVM classpath. * * <p>It takes one command line arguments: {@code <run-manifest-uri>}. * * <p>After staging the manifest contents locally, it invokes the inner JVM by replacing the first * argument with a path to the local temp directory. It also adds two additional arguments to the * application JVM, pointing to 1. the continuation file, and 2. to an output file which can be * written to. If the output file is written, it will be uploaded to the staging uri when the * application JVM exits. */ public class Hypelet extends Capsule { private static final String NOOP_MODE = "noop"; private static final String STAGING_PREFIX = "hype-run-"; private static final String BINARY = "application/octet-stream"; private static final String TERMINATION_LOG = "/dev/termination-log"; private static final String HYPE_EXECUTION_ID = "HYPE_EXECUTION_ID"; private final List<Path> downloadedJars = new ArrayList<>(); private Path manifestPath; private Path stagingDir; private String returnFile; public Hypelet(Capsule pred) { super(pred); } @Override protected ProcessBuilder prelaunch(List<String> jvmArgs, List<String> args) { if (NOOP_MODE.equals(getMode())) { return super.prelaunch(jvmArgs, args); } if (args.size() < 1) { throw new IllegalArgumentException("Usage: <run-manifest-uri>"); } System.out.println("=== HYPE RUN CAPSULE (v" + getVersion() + ") ==="); try { final URI uri = URI.create(args.get(0)); manifestPath = loadFileSystemProvider(uri).getPath(uri); stagingDir = Files.createTempDirectory(STAGING_PREFIX); System.out.println("Downloading files from " + manifestPath.toUri()); // print manifest Files.copy(manifestPath, System.out);
// Path: hype-common/src/main/java/com/spotify/hype/util/Util.java // public static String randomAlphaNumeric(int count) { // StringBuilder builder = new StringBuilder(); // while (count-- != 0) { // int character = (int)(Math.random() * ALPHA_NUMERIC_STRING.length()); // builder.append(ALPHA_NUMERIC_STRING.charAt(character)); // } // return builder.toString(); // } // // Path: hype-gcs/src/main/java/com/spotify/hype/gcs/ManifestLoader.java // public final class ManifestLoader { // // private static final ForkJoinPool FJP = new ForkJoinPool(32); // // public static RunManifest downloadManifest(Path manifestPath, Path destinationDir) throws IOException { // final RunManifest manifest = ManifestUtil.read(manifestPath); // // final Set<Path> manifestEntries = new LinkedHashSet<>(); // manifestEntries.add(manifestPath.resolveSibling(manifest.continuation())); // for (String file : concat(manifest.classPathFiles(), manifest.files())) { // manifestEntries.add(manifestPath.resolveSibling(file)); // } // // try { // FJP.submit(() -> manifestEntries.parallelStream() // .forEach(filePath -> downloadFile(filePath, destinationDir))) // .get(); // } catch (InterruptedException | ExecutionException e) { // throw new RuntimeException(e); // } // // return manifest; // } // // private static void downloadFile(Path filePath, Path destinationDir) { // final Path destinationFile = destinationDir.resolve(filePath.getFileName().toString()); // try { // // todo: retries // Files.copy(filePath, destinationFile, StandardCopyOption.REPLACE_EXISTING); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // // Path: hype-gcs/src/main/java/com/spotify/hype/gcs/RunManifest.java // @AutoMatter // public interface RunManifest { // // String continuation(); // // List<String> classPathFiles(); // // List<String> files(); // // static RunManifest read(Path manifestPath) throws IOException { // return ManifestUtil.read(manifestPath); // } // // static void write(RunManifest manifest, Path manifestPath) throws IOException { // ManifestUtil.write(manifest, manifestPath); // } // } // Path: hype-caplet/src/main/java/Hypelet.java import static com.google.cloud.storage.contrib.nio.CloudStorageOptions.withMimeType; import static com.google.common.base.Charsets.UTF_8; import static com.spotify.hype.util.Util.randomAlphaNumeric; import static java.nio.file.StandardOpenOption.CREATE; import static java.nio.file.StandardOpenOption.CREATE_NEW; import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING; import static java.nio.file.StandardOpenOption.WRITE; import static java.util.Collections.emptyMap; import com.google.common.collect.Sets; import com.spotify.hype.gcs.ManifestLoader; import com.spotify.hype.gcs.RunManifest; import java.io.IOException; import java.net.URI; import java.nio.channels.Channels; import java.nio.channels.WritableByteChannel; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.OpenOption; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.spi.FileSystemProvider; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Properties; import java.util.Set; /*- * -\-\- * hype-run * -- * Copyright (C) 2016 - 2017 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ /** * Capsule caplet that downloads a run-manifest to a temp directory and adds the included files to * the application JVM classpath. * * <p>It takes one command line arguments: {@code <run-manifest-uri>}. * * <p>After staging the manifest contents locally, it invokes the inner JVM by replacing the first * argument with a path to the local temp directory. It also adds two additional arguments to the * application JVM, pointing to 1. the continuation file, and 2. to an output file which can be * written to. If the output file is written, it will be uploaded to the staging uri when the * application JVM exits. */ public class Hypelet extends Capsule { private static final String NOOP_MODE = "noop"; private static final String STAGING_PREFIX = "hype-run-"; private static final String BINARY = "application/octet-stream"; private static final String TERMINATION_LOG = "/dev/termination-log"; private static final String HYPE_EXECUTION_ID = "HYPE_EXECUTION_ID"; private final List<Path> downloadedJars = new ArrayList<>(); private Path manifestPath; private Path stagingDir; private String returnFile; public Hypelet(Capsule pred) { super(pred); } @Override protected ProcessBuilder prelaunch(List<String> jvmArgs, List<String> args) { if (NOOP_MODE.equals(getMode())) { return super.prelaunch(jvmArgs, args); } if (args.size() < 1) { throw new IllegalArgumentException("Usage: <run-manifest-uri>"); } System.out.println("=== HYPE RUN CAPSULE (v" + getVersion() + ") ==="); try { final URI uri = URI.create(args.get(0)); manifestPath = loadFileSystemProvider(uri).getPath(uri); stagingDir = Files.createTempDirectory(STAGING_PREFIX); System.out.println("Downloading files from " + manifestPath.toUri()); // print manifest Files.copy(manifestPath, System.out);
final RunManifest manifest = ManifestLoader.downloadManifest(manifestPath, stagingDir);
spotify/hype
hype-caplet/src/main/java/Hypelet.java
// Path: hype-common/src/main/java/com/spotify/hype/util/Util.java // public static String randomAlphaNumeric(int count) { // StringBuilder builder = new StringBuilder(); // while (count-- != 0) { // int character = (int)(Math.random() * ALPHA_NUMERIC_STRING.length()); // builder.append(ALPHA_NUMERIC_STRING.charAt(character)); // } // return builder.toString(); // } // // Path: hype-gcs/src/main/java/com/spotify/hype/gcs/ManifestLoader.java // public final class ManifestLoader { // // private static final ForkJoinPool FJP = new ForkJoinPool(32); // // public static RunManifest downloadManifest(Path manifestPath, Path destinationDir) throws IOException { // final RunManifest manifest = ManifestUtil.read(manifestPath); // // final Set<Path> manifestEntries = new LinkedHashSet<>(); // manifestEntries.add(manifestPath.resolveSibling(manifest.continuation())); // for (String file : concat(manifest.classPathFiles(), manifest.files())) { // manifestEntries.add(manifestPath.resolveSibling(file)); // } // // try { // FJP.submit(() -> manifestEntries.parallelStream() // .forEach(filePath -> downloadFile(filePath, destinationDir))) // .get(); // } catch (InterruptedException | ExecutionException e) { // throw new RuntimeException(e); // } // // return manifest; // } // // private static void downloadFile(Path filePath, Path destinationDir) { // final Path destinationFile = destinationDir.resolve(filePath.getFileName().toString()); // try { // // todo: retries // Files.copy(filePath, destinationFile, StandardCopyOption.REPLACE_EXISTING); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // // Path: hype-gcs/src/main/java/com/spotify/hype/gcs/RunManifest.java // @AutoMatter // public interface RunManifest { // // String continuation(); // // List<String> classPathFiles(); // // List<String> files(); // // static RunManifest read(Path manifestPath) throws IOException { // return ManifestUtil.read(manifestPath); // } // // static void write(RunManifest manifest, Path manifestPath) throws IOException { // ManifestUtil.write(manifest, manifestPath); // } // }
import static com.google.cloud.storage.contrib.nio.CloudStorageOptions.withMimeType; import static com.google.common.base.Charsets.UTF_8; import static com.spotify.hype.util.Util.randomAlphaNumeric; import static java.nio.file.StandardOpenOption.CREATE; import static java.nio.file.StandardOpenOption.CREATE_NEW; import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING; import static java.nio.file.StandardOpenOption.WRITE; import static java.util.Collections.emptyMap; import com.google.common.collect.Sets; import com.spotify.hype.gcs.ManifestLoader; import com.spotify.hype.gcs.RunManifest; import java.io.IOException; import java.net.URI; import java.nio.channels.Channels; import java.nio.channels.WritableByteChannel; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.OpenOption; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.spi.FileSystemProvider; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Properties; import java.util.Set;
/*- * -\-\- * hype-run * -- * Copyright (C) 2016 - 2017 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ /** * Capsule caplet that downloads a run-manifest to a temp directory and adds the included files to * the application JVM classpath. * * <p>It takes one command line arguments: {@code <run-manifest-uri>}. * * <p>After staging the manifest contents locally, it invokes the inner JVM by replacing the first * argument with a path to the local temp directory. It also adds two additional arguments to the * application JVM, pointing to 1. the continuation file, and 2. to an output file which can be * written to. If the output file is written, it will be uploaded to the staging uri when the * application JVM exits. */ public class Hypelet extends Capsule { private static final String NOOP_MODE = "noop"; private static final String STAGING_PREFIX = "hype-run-"; private static final String BINARY = "application/octet-stream"; private static final String TERMINATION_LOG = "/dev/termination-log"; private static final String HYPE_EXECUTION_ID = "HYPE_EXECUTION_ID"; private final List<Path> downloadedJars = new ArrayList<>(); private Path manifestPath; private Path stagingDir; private String returnFile; public Hypelet(Capsule pred) { super(pred); } @Override protected ProcessBuilder prelaunch(List<String> jvmArgs, List<String> args) { if (NOOP_MODE.equals(getMode())) { return super.prelaunch(jvmArgs, args); } if (args.size() < 1) { throw new IllegalArgumentException("Usage: <run-manifest-uri>"); } System.out.println("=== HYPE RUN CAPSULE (v" + getVersion() + ") ==="); try { final URI uri = URI.create(args.get(0)); manifestPath = loadFileSystemProvider(uri).getPath(uri); stagingDir = Files.createTempDirectory(STAGING_PREFIX); System.out.println("Downloading files from " + manifestPath.toUri()); // print manifest Files.copy(manifestPath, System.out);
// Path: hype-common/src/main/java/com/spotify/hype/util/Util.java // public static String randomAlphaNumeric(int count) { // StringBuilder builder = new StringBuilder(); // while (count-- != 0) { // int character = (int)(Math.random() * ALPHA_NUMERIC_STRING.length()); // builder.append(ALPHA_NUMERIC_STRING.charAt(character)); // } // return builder.toString(); // } // // Path: hype-gcs/src/main/java/com/spotify/hype/gcs/ManifestLoader.java // public final class ManifestLoader { // // private static final ForkJoinPool FJP = new ForkJoinPool(32); // // public static RunManifest downloadManifest(Path manifestPath, Path destinationDir) throws IOException { // final RunManifest manifest = ManifestUtil.read(manifestPath); // // final Set<Path> manifestEntries = new LinkedHashSet<>(); // manifestEntries.add(manifestPath.resolveSibling(manifest.continuation())); // for (String file : concat(manifest.classPathFiles(), manifest.files())) { // manifestEntries.add(manifestPath.resolveSibling(file)); // } // // try { // FJP.submit(() -> manifestEntries.parallelStream() // .forEach(filePath -> downloadFile(filePath, destinationDir))) // .get(); // } catch (InterruptedException | ExecutionException e) { // throw new RuntimeException(e); // } // // return manifest; // } // // private static void downloadFile(Path filePath, Path destinationDir) { // final Path destinationFile = destinationDir.resolve(filePath.getFileName().toString()); // try { // // todo: retries // Files.copy(filePath, destinationFile, StandardCopyOption.REPLACE_EXISTING); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // // Path: hype-gcs/src/main/java/com/spotify/hype/gcs/RunManifest.java // @AutoMatter // public interface RunManifest { // // String continuation(); // // List<String> classPathFiles(); // // List<String> files(); // // static RunManifest read(Path manifestPath) throws IOException { // return ManifestUtil.read(manifestPath); // } // // static void write(RunManifest manifest, Path manifestPath) throws IOException { // ManifestUtil.write(manifest, manifestPath); // } // } // Path: hype-caplet/src/main/java/Hypelet.java import static com.google.cloud.storage.contrib.nio.CloudStorageOptions.withMimeType; import static com.google.common.base.Charsets.UTF_8; import static com.spotify.hype.util.Util.randomAlphaNumeric; import static java.nio.file.StandardOpenOption.CREATE; import static java.nio.file.StandardOpenOption.CREATE_NEW; import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING; import static java.nio.file.StandardOpenOption.WRITE; import static java.util.Collections.emptyMap; import com.google.common.collect.Sets; import com.spotify.hype.gcs.ManifestLoader; import com.spotify.hype.gcs.RunManifest; import java.io.IOException; import java.net.URI; import java.nio.channels.Channels; import java.nio.channels.WritableByteChannel; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.OpenOption; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.spi.FileSystemProvider; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Properties; import java.util.Set; /*- * -\-\- * hype-run * -- * Copyright (C) 2016 - 2017 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ /** * Capsule caplet that downloads a run-manifest to a temp directory and adds the included files to * the application JVM classpath. * * <p>It takes one command line arguments: {@code <run-manifest-uri>}. * * <p>After staging the manifest contents locally, it invokes the inner JVM by replacing the first * argument with a path to the local temp directory. It also adds two additional arguments to the * application JVM, pointing to 1. the continuation file, and 2. to an output file which can be * written to. If the output file is written, it will be uploaded to the staging uri when the * application JVM exits. */ public class Hypelet extends Capsule { private static final String NOOP_MODE = "noop"; private static final String STAGING_PREFIX = "hype-run-"; private static final String BINARY = "application/octet-stream"; private static final String TERMINATION_LOG = "/dev/termination-log"; private static final String HYPE_EXECUTION_ID = "HYPE_EXECUTION_ID"; private final List<Path> downloadedJars = new ArrayList<>(); private Path manifestPath; private Path stagingDir; private String returnFile; public Hypelet(Capsule pred) { super(pred); } @Override protected ProcessBuilder prelaunch(List<String> jvmArgs, List<String> args) { if (NOOP_MODE.equals(getMode())) { return super.prelaunch(jvmArgs, args); } if (args.size() < 1) { throw new IllegalArgumentException("Usage: <run-manifest-uri>"); } System.out.println("=== HYPE RUN CAPSULE (v" + getVersion() + ") ==="); try { final URI uri = URI.create(args.get(0)); manifestPath = loadFileSystemProvider(uri).getPath(uri); stagingDir = Files.createTempDirectory(STAGING_PREFIX); System.out.println("Downloading files from " + manifestPath.toUri()); // print manifest Files.copy(manifestPath, System.out);
final RunManifest manifest = ManifestLoader.downloadManifest(manifestPath, stagingDir);
spotify/hype
hype-caplet/src/main/java/Hypelet.java
// Path: hype-common/src/main/java/com/spotify/hype/util/Util.java // public static String randomAlphaNumeric(int count) { // StringBuilder builder = new StringBuilder(); // while (count-- != 0) { // int character = (int)(Math.random() * ALPHA_NUMERIC_STRING.length()); // builder.append(ALPHA_NUMERIC_STRING.charAt(character)); // } // return builder.toString(); // } // // Path: hype-gcs/src/main/java/com/spotify/hype/gcs/ManifestLoader.java // public final class ManifestLoader { // // private static final ForkJoinPool FJP = new ForkJoinPool(32); // // public static RunManifest downloadManifest(Path manifestPath, Path destinationDir) throws IOException { // final RunManifest manifest = ManifestUtil.read(manifestPath); // // final Set<Path> manifestEntries = new LinkedHashSet<>(); // manifestEntries.add(manifestPath.resolveSibling(manifest.continuation())); // for (String file : concat(manifest.classPathFiles(), manifest.files())) { // manifestEntries.add(manifestPath.resolveSibling(file)); // } // // try { // FJP.submit(() -> manifestEntries.parallelStream() // .forEach(filePath -> downloadFile(filePath, destinationDir))) // .get(); // } catch (InterruptedException | ExecutionException e) { // throw new RuntimeException(e); // } // // return manifest; // } // // private static void downloadFile(Path filePath, Path destinationDir) { // final Path destinationFile = destinationDir.resolve(filePath.getFileName().toString()); // try { // // todo: retries // Files.copy(filePath, destinationFile, StandardCopyOption.REPLACE_EXISTING); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // // Path: hype-gcs/src/main/java/com/spotify/hype/gcs/RunManifest.java // @AutoMatter // public interface RunManifest { // // String continuation(); // // List<String> classPathFiles(); // // List<String> files(); // // static RunManifest read(Path manifestPath) throws IOException { // return ManifestUtil.read(manifestPath); // } // // static void write(RunManifest manifest, Path manifestPath) throws IOException { // ManifestUtil.write(manifest, manifestPath); // } // }
import static com.google.cloud.storage.contrib.nio.CloudStorageOptions.withMimeType; import static com.google.common.base.Charsets.UTF_8; import static com.spotify.hype.util.Util.randomAlphaNumeric; import static java.nio.file.StandardOpenOption.CREATE; import static java.nio.file.StandardOpenOption.CREATE_NEW; import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING; import static java.nio.file.StandardOpenOption.WRITE; import static java.util.Collections.emptyMap; import com.google.common.collect.Sets; import com.spotify.hype.gcs.ManifestLoader; import com.spotify.hype.gcs.RunManifest; import java.io.IOException; import java.net.URI; import java.nio.channels.Channels; import java.nio.channels.WritableByteChannel; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.OpenOption; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.spi.FileSystemProvider; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Properties; import java.util.Set;
super.cleanup(); } @Override protected Object lookup0(Object x, String type, Map.Entry<String, ?> attrContext, Object context) { final Object o = super.lookup0(x, type, attrContext, context); if ("App-Class-Path".equals(attrContext.getKey())) { final List<Path> lookup = new ArrayList<>((List<Path>) o); lookup.addAll(downloadedJars); return lookup; } return o; } private static String getVersion() { Properties props = new Properties(); try { props.load(Hypelet.class.getResourceAsStream("/version.properties")); } catch (IOException e) { throw new RuntimeException(e); } return props.getProperty("hypelet.version"); } private static String getRunId() { return System.getenv().containsKey(HYPE_EXECUTION_ID) ? System.getenv(HYPE_EXECUTION_ID)
// Path: hype-common/src/main/java/com/spotify/hype/util/Util.java // public static String randomAlphaNumeric(int count) { // StringBuilder builder = new StringBuilder(); // while (count-- != 0) { // int character = (int)(Math.random() * ALPHA_NUMERIC_STRING.length()); // builder.append(ALPHA_NUMERIC_STRING.charAt(character)); // } // return builder.toString(); // } // // Path: hype-gcs/src/main/java/com/spotify/hype/gcs/ManifestLoader.java // public final class ManifestLoader { // // private static final ForkJoinPool FJP = new ForkJoinPool(32); // // public static RunManifest downloadManifest(Path manifestPath, Path destinationDir) throws IOException { // final RunManifest manifest = ManifestUtil.read(manifestPath); // // final Set<Path> manifestEntries = new LinkedHashSet<>(); // manifestEntries.add(manifestPath.resolveSibling(manifest.continuation())); // for (String file : concat(manifest.classPathFiles(), manifest.files())) { // manifestEntries.add(manifestPath.resolveSibling(file)); // } // // try { // FJP.submit(() -> manifestEntries.parallelStream() // .forEach(filePath -> downloadFile(filePath, destinationDir))) // .get(); // } catch (InterruptedException | ExecutionException e) { // throw new RuntimeException(e); // } // // return manifest; // } // // private static void downloadFile(Path filePath, Path destinationDir) { // final Path destinationFile = destinationDir.resolve(filePath.getFileName().toString()); // try { // // todo: retries // Files.copy(filePath, destinationFile, StandardCopyOption.REPLACE_EXISTING); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // // Path: hype-gcs/src/main/java/com/spotify/hype/gcs/RunManifest.java // @AutoMatter // public interface RunManifest { // // String continuation(); // // List<String> classPathFiles(); // // List<String> files(); // // static RunManifest read(Path manifestPath) throws IOException { // return ManifestUtil.read(manifestPath); // } // // static void write(RunManifest manifest, Path manifestPath) throws IOException { // ManifestUtil.write(manifest, manifestPath); // } // } // Path: hype-caplet/src/main/java/Hypelet.java import static com.google.cloud.storage.contrib.nio.CloudStorageOptions.withMimeType; import static com.google.common.base.Charsets.UTF_8; import static com.spotify.hype.util.Util.randomAlphaNumeric; import static java.nio.file.StandardOpenOption.CREATE; import static java.nio.file.StandardOpenOption.CREATE_NEW; import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING; import static java.nio.file.StandardOpenOption.WRITE; import static java.util.Collections.emptyMap; import com.google.common.collect.Sets; import com.spotify.hype.gcs.ManifestLoader; import com.spotify.hype.gcs.RunManifest; import java.io.IOException; import java.net.URI; import java.nio.channels.Channels; import java.nio.channels.WritableByteChannel; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.OpenOption; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.spi.FileSystemProvider; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Properties; import java.util.Set; super.cleanup(); } @Override protected Object lookup0(Object x, String type, Map.Entry<String, ?> attrContext, Object context) { final Object o = super.lookup0(x, type, attrContext, context); if ("App-Class-Path".equals(attrContext.getKey())) { final List<Path> lookup = new ArrayList<>((List<Path>) o); lookup.addAll(downloadedJars); return lookup; } return o; } private static String getVersion() { Properties props = new Properties(); try { props.load(Hypelet.class.getResourceAsStream("/version.properties")); } catch (IOException e) { throw new RuntimeException(e); } return props.getProperty("hypelet.version"); } private static String getRunId() { return System.getenv().containsKey(HYPE_EXECUTION_ID) ? System.getenv(HYPE_EXECUTION_ID)
: randomAlphaNumeric(8);
spotify/hype
hype-submitter/src/main/java/com/spotify/hype/runner/RunSpec.java
// Path: hype-submitter/src/main/java/com/spotify/hype/model/RunEnvironment.java // @AutoMatter // public interface RunEnvironment { // // Optional<Path> yamlPath(); // List<Secret> secretMounts(); // List<VolumeMount> volumeMounts(); // Map<String, String> resourceRequests(); // // static RunEnvironment environment() { // return new RunEnvironmentBuilder().build(); // } // // static RunEnvironment fromYaml(String resourcePath) { // final URI resourceUri; // try { // resourceUri = RunEnvironment.class.getResource(resourcePath).toURI(); // } catch (URISyntaxException e) { // throw new RuntimeException(e); // } // return fromYaml(Paths.get(resourceUri)); // } // // static RunEnvironment fromYaml(Path path) { // return new RunEnvironmentBuilder() // .yamlPath(path) // .build(); // } // // default RunEnvironment withSecret(String name, String mountPath) { // return RunEnvironmentBuilder.from(this) // .addSecretMount(Secret.secret(name, mountPath)) // .build(); // } // // default RunEnvironment withSecret(Secret secret) { // return RunEnvironmentBuilder.from(this) // .addSecretMount(secret) // .build(); // } // // default RunEnvironment withMount(VolumeMount volumeMount) { // return RunEnvironmentBuilder.from(this) // .addVolumeMount(volumeMount) // .build(); // } // // default RunEnvironment withRequest(String resource, String amount) { // return RunEnvironmentBuilder.from(this) // .putResourceRequest(resource, amount) // .build(); // } // // default RunEnvironment withRequest(ResourceRequest request) { // return RunEnvironmentBuilder.from(this) // .putResourceRequest(request.resource(), request.amount()) // .build(); // } // } // // Path: hype-submitter/src/main/java/com/spotify/hype/model/StagedContinuation.java // @AutoMatter // public interface StagedContinuation { // // Path manifestPath(); // RunManifest manifest(); // // static StagedContinuation stagedContinuation(Path manifestPath, RunManifest manifest) { // return new StagedContinuationBuilder() // .manifestPath(manifestPath) // .manifest(manifest) // .build(); // } // }
import io.norberg.automatter.AutoMatter; import com.spotify.hype.model.RunEnvironment; import com.spotify.hype.model.StagedContinuation;
/*- * -\-\- * hype-submitter * -- * Copyright (C) 2016 - 2017 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.hype.runner; @AutoMatter public interface RunSpec {
// Path: hype-submitter/src/main/java/com/spotify/hype/model/RunEnvironment.java // @AutoMatter // public interface RunEnvironment { // // Optional<Path> yamlPath(); // List<Secret> secretMounts(); // List<VolumeMount> volumeMounts(); // Map<String, String> resourceRequests(); // // static RunEnvironment environment() { // return new RunEnvironmentBuilder().build(); // } // // static RunEnvironment fromYaml(String resourcePath) { // final URI resourceUri; // try { // resourceUri = RunEnvironment.class.getResource(resourcePath).toURI(); // } catch (URISyntaxException e) { // throw new RuntimeException(e); // } // return fromYaml(Paths.get(resourceUri)); // } // // static RunEnvironment fromYaml(Path path) { // return new RunEnvironmentBuilder() // .yamlPath(path) // .build(); // } // // default RunEnvironment withSecret(String name, String mountPath) { // return RunEnvironmentBuilder.from(this) // .addSecretMount(Secret.secret(name, mountPath)) // .build(); // } // // default RunEnvironment withSecret(Secret secret) { // return RunEnvironmentBuilder.from(this) // .addSecretMount(secret) // .build(); // } // // default RunEnvironment withMount(VolumeMount volumeMount) { // return RunEnvironmentBuilder.from(this) // .addVolumeMount(volumeMount) // .build(); // } // // default RunEnvironment withRequest(String resource, String amount) { // return RunEnvironmentBuilder.from(this) // .putResourceRequest(resource, amount) // .build(); // } // // default RunEnvironment withRequest(ResourceRequest request) { // return RunEnvironmentBuilder.from(this) // .putResourceRequest(request.resource(), request.amount()) // .build(); // } // } // // Path: hype-submitter/src/main/java/com/spotify/hype/model/StagedContinuation.java // @AutoMatter // public interface StagedContinuation { // // Path manifestPath(); // RunManifest manifest(); // // static StagedContinuation stagedContinuation(Path manifestPath, RunManifest manifest) { // return new StagedContinuationBuilder() // .manifestPath(manifestPath) // .manifest(manifest) // .build(); // } // } // Path: hype-submitter/src/main/java/com/spotify/hype/runner/RunSpec.java import io.norberg.automatter.AutoMatter; import com.spotify.hype.model.RunEnvironment; import com.spotify.hype.model.StagedContinuation; /*- * -\-\- * hype-submitter * -- * Copyright (C) 2016 - 2017 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.hype.runner; @AutoMatter public interface RunSpec {
RunEnvironment runEnvironment();
spotify/hype
hype-submitter/src/main/java/com/spotify/hype/runner/RunSpec.java
// Path: hype-submitter/src/main/java/com/spotify/hype/model/RunEnvironment.java // @AutoMatter // public interface RunEnvironment { // // Optional<Path> yamlPath(); // List<Secret> secretMounts(); // List<VolumeMount> volumeMounts(); // Map<String, String> resourceRequests(); // // static RunEnvironment environment() { // return new RunEnvironmentBuilder().build(); // } // // static RunEnvironment fromYaml(String resourcePath) { // final URI resourceUri; // try { // resourceUri = RunEnvironment.class.getResource(resourcePath).toURI(); // } catch (URISyntaxException e) { // throw new RuntimeException(e); // } // return fromYaml(Paths.get(resourceUri)); // } // // static RunEnvironment fromYaml(Path path) { // return new RunEnvironmentBuilder() // .yamlPath(path) // .build(); // } // // default RunEnvironment withSecret(String name, String mountPath) { // return RunEnvironmentBuilder.from(this) // .addSecretMount(Secret.secret(name, mountPath)) // .build(); // } // // default RunEnvironment withSecret(Secret secret) { // return RunEnvironmentBuilder.from(this) // .addSecretMount(secret) // .build(); // } // // default RunEnvironment withMount(VolumeMount volumeMount) { // return RunEnvironmentBuilder.from(this) // .addVolumeMount(volumeMount) // .build(); // } // // default RunEnvironment withRequest(String resource, String amount) { // return RunEnvironmentBuilder.from(this) // .putResourceRequest(resource, amount) // .build(); // } // // default RunEnvironment withRequest(ResourceRequest request) { // return RunEnvironmentBuilder.from(this) // .putResourceRequest(request.resource(), request.amount()) // .build(); // } // } // // Path: hype-submitter/src/main/java/com/spotify/hype/model/StagedContinuation.java // @AutoMatter // public interface StagedContinuation { // // Path manifestPath(); // RunManifest manifest(); // // static StagedContinuation stagedContinuation(Path manifestPath, RunManifest manifest) { // return new StagedContinuationBuilder() // .manifestPath(manifestPath) // .manifest(manifest) // .build(); // } // }
import io.norberg.automatter.AutoMatter; import com.spotify.hype.model.RunEnvironment; import com.spotify.hype.model.StagedContinuation;
/*- * -\-\- * hype-submitter * -- * Copyright (C) 2016 - 2017 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.hype.runner; @AutoMatter public interface RunSpec { RunEnvironment runEnvironment();
// Path: hype-submitter/src/main/java/com/spotify/hype/model/RunEnvironment.java // @AutoMatter // public interface RunEnvironment { // // Optional<Path> yamlPath(); // List<Secret> secretMounts(); // List<VolumeMount> volumeMounts(); // Map<String, String> resourceRequests(); // // static RunEnvironment environment() { // return new RunEnvironmentBuilder().build(); // } // // static RunEnvironment fromYaml(String resourcePath) { // final URI resourceUri; // try { // resourceUri = RunEnvironment.class.getResource(resourcePath).toURI(); // } catch (URISyntaxException e) { // throw new RuntimeException(e); // } // return fromYaml(Paths.get(resourceUri)); // } // // static RunEnvironment fromYaml(Path path) { // return new RunEnvironmentBuilder() // .yamlPath(path) // .build(); // } // // default RunEnvironment withSecret(String name, String mountPath) { // return RunEnvironmentBuilder.from(this) // .addSecretMount(Secret.secret(name, mountPath)) // .build(); // } // // default RunEnvironment withSecret(Secret secret) { // return RunEnvironmentBuilder.from(this) // .addSecretMount(secret) // .build(); // } // // default RunEnvironment withMount(VolumeMount volumeMount) { // return RunEnvironmentBuilder.from(this) // .addVolumeMount(volumeMount) // .build(); // } // // default RunEnvironment withRequest(String resource, String amount) { // return RunEnvironmentBuilder.from(this) // .putResourceRequest(resource, amount) // .build(); // } // // default RunEnvironment withRequest(ResourceRequest request) { // return RunEnvironmentBuilder.from(this) // .putResourceRequest(request.resource(), request.amount()) // .build(); // } // } // // Path: hype-submitter/src/main/java/com/spotify/hype/model/StagedContinuation.java // @AutoMatter // public interface StagedContinuation { // // Path manifestPath(); // RunManifest manifest(); // // static StagedContinuation stagedContinuation(Path manifestPath, RunManifest manifest) { // return new StagedContinuationBuilder() // .manifestPath(manifestPath) // .manifest(manifest) // .build(); // } // } // Path: hype-submitter/src/main/java/com/spotify/hype/runner/RunSpec.java import io.norberg.automatter.AutoMatter; import com.spotify.hype.model.RunEnvironment; import com.spotify.hype.model.StagedContinuation; /*- * -\-\- * hype-submitter * -- * Copyright (C) 2016 - 2017 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.hype.runner; @AutoMatter public interface RunSpec { RunEnvironment runEnvironment();
StagedContinuation stagedContinuation();
spotify/hype
hype-submitter/src/test/java/com/spotify/hype/runner/VolumeRepositoryTest.java
// Path: hype-submitter/src/main/java/com/spotify/hype/model/VolumeRequest.java // @AutoMatter // public interface VolumeRequest { // // String VOLUME_REQUEST_PREFIX = "hype-request-"; // // String id(); // boolean keep(); // ClaimRequest spec(); // // @AutoMatter // interface ClaimRequest { // String storageClass(); // String size(); // boolean useExisting(); // } // // static VolumeRequest volumeRequest(String storageClass, String size) { // final String id = VOLUME_REQUEST_PREFIX + Util.randomAlphaNumeric(8); // return new VolumeRequestBuilder() // .id(id) // .keep(false) // new claims are deleted by default // .spec(new ClaimRequestBuilder() // .storageClass(storageClass) // .size(size) // .useExisting(false) // .build()) // .build(); // } // // static VolumeRequest createIfNotExists(String name, String storageClass, String size) { // final String id = String.format("%s-%s-%s", name, storageClass, size); // return new VolumeRequestBuilder() // .id(id) // .keep(true) // .spec(new ClaimRequestBuilder() // .storageClass(storageClass) // .size(size) // .useExisting(true) // .build()) // .build(); // } // // default VolumeRequest keepOnExit() { // return VolumeRequestBuilder.from(this) // .keep(true) // .build(); // } // // /** // * Mount the requested volume in read-only mode at the specified path. // */ // default VolumeMount mountReadOnly(String mountPath) { // return VolumeMount.volumeMount(this, mountPath, true); // } // // /** // * Mount the requested volume in read-write mode at the specified path. // */ // default VolumeMount mountReadWrite(String mountPath) { // return VolumeMount.volumeMount(this, mountPath, false); // } // }
import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.spotify.hype.model.VolumeRequest; import io.fabric8.kubernetes.api.model.DoneablePersistentVolumeClaim; import io.fabric8.kubernetes.api.model.PersistentVolumeClaim; import io.fabric8.kubernetes.api.model.PersistentVolumeClaimList; import io.fabric8.kubernetes.api.model.Quantity; import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.Resource; import java.util.List; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner;
@Mock Resource<PersistentVolumeClaim, DoneablePersistentVolumeClaim> nonExistingPvcResource; @Mock PersistentVolumeClaim mockPvc; @Mock MixedOperation< // euw PersistentVolumeClaim, PersistentVolumeClaimList, DoneablePersistentVolumeClaim, Resource< PersistentVolumeClaim, DoneablePersistentVolumeClaim>> pvcs; @Captor ArgumentCaptor<PersistentVolumeClaim> createdPvc; @Captor ArgumentCaptor<List<PersistentVolumeClaim>> deletedPvcs; private VolumeRepository volumeRepository; @Before public void setUp() throws Exception { volumeRepository = new VolumeRepository(mockClient); when(mockClient.persistentVolumeClaims()).thenReturn(pvcs); when(pvcs.withName(any())).thenAnswer(invocation -> invocation.getArguments()[0].equals(EXISTING_CLAIM) ? existingPvcResource : nonExistingPvcResource); when(existingPvcResource.get()).thenReturn(mockPvc); when(nonExistingPvcResource.get()).thenReturn(null); when(pvcs.create(createdPvc.capture())).then(invocation -> createdPvc.getValue()); when(pvcs.delete(deletedPvcs.capture())).thenReturn(true); } @Test public void createsNewVolumeClaim() throws Exception {
// Path: hype-submitter/src/main/java/com/spotify/hype/model/VolumeRequest.java // @AutoMatter // public interface VolumeRequest { // // String VOLUME_REQUEST_PREFIX = "hype-request-"; // // String id(); // boolean keep(); // ClaimRequest spec(); // // @AutoMatter // interface ClaimRequest { // String storageClass(); // String size(); // boolean useExisting(); // } // // static VolumeRequest volumeRequest(String storageClass, String size) { // final String id = VOLUME_REQUEST_PREFIX + Util.randomAlphaNumeric(8); // return new VolumeRequestBuilder() // .id(id) // .keep(false) // new claims are deleted by default // .spec(new ClaimRequestBuilder() // .storageClass(storageClass) // .size(size) // .useExisting(false) // .build()) // .build(); // } // // static VolumeRequest createIfNotExists(String name, String storageClass, String size) { // final String id = String.format("%s-%s-%s", name, storageClass, size); // return new VolumeRequestBuilder() // .id(id) // .keep(true) // .spec(new ClaimRequestBuilder() // .storageClass(storageClass) // .size(size) // .useExisting(true) // .build()) // .build(); // } // // default VolumeRequest keepOnExit() { // return VolumeRequestBuilder.from(this) // .keep(true) // .build(); // } // // /** // * Mount the requested volume in read-only mode at the specified path. // */ // default VolumeMount mountReadOnly(String mountPath) { // return VolumeMount.volumeMount(this, mountPath, true); // } // // /** // * Mount the requested volume in read-write mode at the specified path. // */ // default VolumeMount mountReadWrite(String mountPath) { // return VolumeMount.volumeMount(this, mountPath, false); // } // } // Path: hype-submitter/src/test/java/com/spotify/hype/runner/VolumeRepositoryTest.java import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.spotify.hype.model.VolumeRequest; import io.fabric8.kubernetes.api.model.DoneablePersistentVolumeClaim; import io.fabric8.kubernetes.api.model.PersistentVolumeClaim; import io.fabric8.kubernetes.api.model.PersistentVolumeClaimList; import io.fabric8.kubernetes.api.model.Quantity; import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.Resource; import java.util.List; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; @Mock Resource<PersistentVolumeClaim, DoneablePersistentVolumeClaim> nonExistingPvcResource; @Mock PersistentVolumeClaim mockPvc; @Mock MixedOperation< // euw PersistentVolumeClaim, PersistentVolumeClaimList, DoneablePersistentVolumeClaim, Resource< PersistentVolumeClaim, DoneablePersistentVolumeClaim>> pvcs; @Captor ArgumentCaptor<PersistentVolumeClaim> createdPvc; @Captor ArgumentCaptor<List<PersistentVolumeClaim>> deletedPvcs; private VolumeRepository volumeRepository; @Before public void setUp() throws Exception { volumeRepository = new VolumeRepository(mockClient); when(mockClient.persistentVolumeClaims()).thenReturn(pvcs); when(pvcs.withName(any())).thenAnswer(invocation -> invocation.getArguments()[0].equals(EXISTING_CLAIM) ? existingPvcResource : nonExistingPvcResource); when(existingPvcResource.get()).thenReturn(mockPvc); when(nonExistingPvcResource.get()).thenReturn(null); when(pvcs.create(createdPvc.capture())).then(invocation -> createdPvc.getValue()); when(pvcs.delete(deletedPvcs.capture())).thenReturn(true); } @Test public void createsNewVolumeClaim() throws Exception {
VolumeRequest request = VolumeRequest.volumeRequest("storage-class-name", "16Gi");
dan-zx/twitt4droid
library/src/com/twitt4droid/data/source/SQLFileParser.java
// Path: library/src/com/twitt4droid/util/Strings.java // public final class Strings { // // /** Empty string "". */ // public static final String EMPTY = ""; // // /** // * Default constructor. Do NOT try to initialize this class, it is suppose // * to be an static utility. // */ // private Strings() { // throw new IllegalAccessError("This class cannot be instantiated nor extended"); // } // // /** // * Check that the given string is either null or empty. // * // * @param str the string to check. // * @return {@code true} if the given string is either null or empty; // * otherwise {@code false}. // */ // public static boolean isNullOrBlank(String str) { // return str == null || str.trim().length() == 0; // } // }
import android.util.Log; import com.twitt4droid.util.Strings; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.regex.Pattern;
/* * Copyright 2014 Daniel Pedraza-Arcega * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twitt4droid.data.source; /** * SQL file parser utility. * * @author Daniel Pedraza-Arcega * @since version 1.0 */ class SQLFileParser { private static final int END_OF_STREAM = -1; private static final String TAG = SQLFileParser.class.getSimpleName(); private static final String STATEMENT_DELIMITER = ";"; private static final Pattern COMMENT_PATTERN = Pattern.compile("(?:/\\*[^;]*?\\*/)|(?:--[^;]*?$)", Pattern.DOTALL | Pattern.MULTILINE); /** * Returns all the SQL statements contained in given stream. * * @param stream an SQL file stream. * @return SQL statements. */ static String[] getSqlStatements(InputStream stream) { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(stream)); int r; StringBuilder sb = new StringBuilder(); while ((r = reader.read()) != END_OF_STREAM) { char character = (char) r; sb.append(character); } return COMMENT_PATTERN.matcher(sb)
// Path: library/src/com/twitt4droid/util/Strings.java // public final class Strings { // // /** Empty string "". */ // public static final String EMPTY = ""; // // /** // * Default constructor. Do NOT try to initialize this class, it is suppose // * to be an static utility. // */ // private Strings() { // throw new IllegalAccessError("This class cannot be instantiated nor extended"); // } // // /** // * Check that the given string is either null or empty. // * // * @param str the string to check. // * @return {@code true} if the given string is either null or empty; // * otherwise {@code false}. // */ // public static boolean isNullOrBlank(String str) { // return str == null || str.trim().length() == 0; // } // } // Path: library/src/com/twitt4droid/data/source/SQLFileParser.java import android.util.Log; import com.twitt4droid.util.Strings; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.regex.Pattern; /* * Copyright 2014 Daniel Pedraza-Arcega * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twitt4droid.data.source; /** * SQL file parser utility. * * @author Daniel Pedraza-Arcega * @since version 1.0 */ class SQLFileParser { private static final int END_OF_STREAM = -1; private static final String TAG = SQLFileParser.class.getSimpleName(); private static final String STATEMENT_DELIMITER = ";"; private static final Pattern COMMENT_PATTERN = Pattern.compile("(?:/\\*[^;]*?\\*/)|(?:--[^;]*?$)", Pattern.DOTALL | Pattern.MULTILINE); /** * Returns all the SQL statements contained in given stream. * * @param stream an SQL file stream. * @return SQL statements. */ static String[] getSqlStatements(InputStream stream) { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(stream)); int r; StringBuilder sb = new StringBuilder(); while ((r = reader.read()) != END_OF_STREAM) { char character = (char) r; sb.append(character); } return COMMENT_PATTERN.matcher(sb)
.replaceAll(Strings.EMPTY)
dan-zx/twitt4droid
library/src/com/twitt4droid/data/dao/impl/sqlite/SQLiteUtils.java
// Path: library/src/com/twitt4droid/util/Strings.java // public final class Strings { // // /** Empty string "". */ // public static final String EMPTY = ""; // // /** // * Default constructor. Do NOT try to initialize this class, it is suppose // * to be an static utility. // */ // private Strings() { // throw new IllegalAccessError("This class cannot be instantiated nor extended"); // } // // /** // * Check that the given string is either null or empty. // * // * @param str the string to check. // * @return {@code true} if the given string is either null or empty; // * otherwise {@code false}. // */ // public static boolean isNullOrBlank(String str) { // return str == null || str.trim().length() == 0; // } // }
import android.annotation.TargetApi; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteStatement; import android.os.Build; import android.util.Log; import com.twitt4droid.util.Strings; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale;
*/ static Date getDateFromLong(Cursor cursor, String columnName) { Long value = getLong(cursor, columnName); if (value != null) return new Date(value); return null; } /** * Gets the date value of the given column when the column is unix time. * * @param cursor a Cursor. * @param columnName the column name. * @return the column value if exists; otherwise {@code null}. */ static Date getDateFromUnixTime(Cursor cursor, String columnName) { Long value = getLong(cursor, columnName); if (value != null) return new Date(value * 1000L); return null; } /** * Gets the date value of the given column when the column is string type. * * @param cursor a Cursor. * @param columnName the column name. * @param timeString the format of the date. * @return the column value if exists; otherwise {@code null}. */ static Date getDateFromString(Cursor cursor, String columnName, TimeString timeString) { String value = getString(cursor, columnName);
// Path: library/src/com/twitt4droid/util/Strings.java // public final class Strings { // // /** Empty string "". */ // public static final String EMPTY = ""; // // /** // * Default constructor. Do NOT try to initialize this class, it is suppose // * to be an static utility. // */ // private Strings() { // throw new IllegalAccessError("This class cannot be instantiated nor extended"); // } // // /** // * Check that the given string is either null or empty. // * // * @param str the string to check. // * @return {@code true} if the given string is either null or empty; // * otherwise {@code false}. // */ // public static boolean isNullOrBlank(String str) { // return str == null || str.trim().length() == 0; // } // } // Path: library/src/com/twitt4droid/data/dao/impl/sqlite/SQLiteUtils.java import android.annotation.TargetApi; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteStatement; import android.os.Build; import android.util.Log; import com.twitt4droid.util.Strings; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; */ static Date getDateFromLong(Cursor cursor, String columnName) { Long value = getLong(cursor, columnName); if (value != null) return new Date(value); return null; } /** * Gets the date value of the given column when the column is unix time. * * @param cursor a Cursor. * @param columnName the column name. * @return the column value if exists; otherwise {@code null}. */ static Date getDateFromUnixTime(Cursor cursor, String columnName) { Long value = getLong(cursor, columnName); if (value != null) return new Date(value * 1000L); return null; } /** * Gets the date value of the given column when the column is string type. * * @param cursor a Cursor. * @param columnName the column name. * @param timeString the format of the date. * @return the column value if exists; otherwise {@code null}. */ static Date getDateFromString(Cursor cursor, String columnName, TimeString timeString) { String value = getString(cursor, columnName);
if (!Strings.isNullOrBlank(value)) {
dan-zx/twitt4droid
library/src/com/twitt4droid/fragment/ListTimelineFragment.java
// Path: library/src/com/twitt4droid/data/dao/ListTimelineDAO.java // public interface ListTimelineDAO extends GenericDAO<Status, Long> { // // /** // * Returns all the statuses from the given list. // * // * @param listId the list id. // * @return statuses. // */ // List<Status> fetchListByListId(Long listId); // // /** // * Saves all the given statuses in the given list. // * // * @param statuses statuses. // * @param listId the list id. // */ // void save(List<Status> statuses, Long listId); // // /** // * Deletes all statuses in the given list. // * // * @param listId the list id. // */ // void deleteAllByListId(Long listId); // } // // Path: library/src/com/twitt4droid/data/dao/impl/DAOFactory.java // public class DAOFactory { // // private final Context context; // // /** // * Creates a DAOFactory. // * // * @param context the application context. // */ // public DAOFactory(Context context) { // this.context = context; // } // // /** @return a new HomeTimelineDAO. */ // public TimelineDAO getHomeTimelineDAO() { // TimelineSQLiteDAO dao = new TimelineSQLiteDAO(TimelineSQLiteDAO.Table.HOME); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new MentionsTimelineDAO. */ // public TimelineDAO getMentionsTimelineDAO() { // TimelineSQLiteDAO dao = new TimelineSQLiteDAO(TimelineSQLiteDAO.Table.MENTION); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new UserTimelineDAO. */ // public UserTimelineDAO getUserTimelineDAO() { // UserTimelineSQLiteDAO dao = new UserTimelineSQLiteDAO(); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new FixedQueryTimelineDAO. */ // public TimelineDAO getFixedQueryTimelineDAO() { // TimelineSQLiteDAO dao = new TimelineSQLiteDAO(TimelineSQLiteDAO.Table.FIXED_QUERY); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new QueryableTimelineDAO. */ // public TimelineDAO getQueryableTimelineDAO() { // TimelineSQLiteDAO dao = new TimelineSQLiteDAO(TimelineSQLiteDAO.Table.QUERYABLE); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new ListTimelineDAO. */ // public ListTimelineDAO getListTimelineDAO() { // ListSQLiteDAO dao = new ListSQLiteDAO(); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new UserDAO. */ // public UserDAO getUserDAO() { // UserSQLiteDAO dao = new UserSQLiteDAO(); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // }
import android.os.Bundle; import com.twitt4droid.R; import com.twitt4droid.data.dao.ListTimelineDAO; import com.twitt4droid.data.dao.impl.DAOFactory; import twitter4j.Paging; import twitter4j.TwitterException; import twitter4j.UserList; import java.util.List;
/* * Copyright 2014 Daniel Pedraza-Arcega * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twitt4droid.fragment; /** * Shows the 20 most recent statuses from the given list. * * @author Daniel Pedraza-Arcega * @since version 1.0 */ public class ListTimelineFragment extends TimelineFragment { protected static final String LIST_ARG = "LIST"; /** * Creates a ListTimelineFragment. * * @param userList a Twitter list. * @param enableDarkTheme if the dark theme is enabled. * @return a new ListTimelineFragment. */ public static ListTimelineFragment newInstance(UserList userList, boolean enableDarkTheme) { ListTimelineFragment fragment = new ListTimelineFragment(); Bundle args = new Bundle(); args.putSerializable(LIST_ARG, userList); args.putBoolean(ENABLE_DARK_THEME_ARG, enableDarkTheme); fragment.setArguments(args); return fragment; } /** * Creates a ListTimelineFragment. * * @param userList a Twitter list. * @return a new ListTimelineFragment. */ public static ListTimelineFragment newInstance(UserList userList) { return newInstance(userList, false); } /** {@inheritDoc} */ @Override protected ListStatusesLoaderTask initStatusesLoaderTask() {
// Path: library/src/com/twitt4droid/data/dao/ListTimelineDAO.java // public interface ListTimelineDAO extends GenericDAO<Status, Long> { // // /** // * Returns all the statuses from the given list. // * // * @param listId the list id. // * @return statuses. // */ // List<Status> fetchListByListId(Long listId); // // /** // * Saves all the given statuses in the given list. // * // * @param statuses statuses. // * @param listId the list id. // */ // void save(List<Status> statuses, Long listId); // // /** // * Deletes all statuses in the given list. // * // * @param listId the list id. // */ // void deleteAllByListId(Long listId); // } // // Path: library/src/com/twitt4droid/data/dao/impl/DAOFactory.java // public class DAOFactory { // // private final Context context; // // /** // * Creates a DAOFactory. // * // * @param context the application context. // */ // public DAOFactory(Context context) { // this.context = context; // } // // /** @return a new HomeTimelineDAO. */ // public TimelineDAO getHomeTimelineDAO() { // TimelineSQLiteDAO dao = new TimelineSQLiteDAO(TimelineSQLiteDAO.Table.HOME); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new MentionsTimelineDAO. */ // public TimelineDAO getMentionsTimelineDAO() { // TimelineSQLiteDAO dao = new TimelineSQLiteDAO(TimelineSQLiteDAO.Table.MENTION); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new UserTimelineDAO. */ // public UserTimelineDAO getUserTimelineDAO() { // UserTimelineSQLiteDAO dao = new UserTimelineSQLiteDAO(); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new FixedQueryTimelineDAO. */ // public TimelineDAO getFixedQueryTimelineDAO() { // TimelineSQLiteDAO dao = new TimelineSQLiteDAO(TimelineSQLiteDAO.Table.FIXED_QUERY); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new QueryableTimelineDAO. */ // public TimelineDAO getQueryableTimelineDAO() { // TimelineSQLiteDAO dao = new TimelineSQLiteDAO(TimelineSQLiteDAO.Table.QUERYABLE); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new ListTimelineDAO. */ // public ListTimelineDAO getListTimelineDAO() { // ListSQLiteDAO dao = new ListSQLiteDAO(); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new UserDAO. */ // public UserDAO getUserDAO() { // UserSQLiteDAO dao = new UserSQLiteDAO(); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // } // Path: library/src/com/twitt4droid/fragment/ListTimelineFragment.java import android.os.Bundle; import com.twitt4droid.R; import com.twitt4droid.data.dao.ListTimelineDAO; import com.twitt4droid.data.dao.impl.DAOFactory; import twitter4j.Paging; import twitter4j.TwitterException; import twitter4j.UserList; import java.util.List; /* * Copyright 2014 Daniel Pedraza-Arcega * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twitt4droid.fragment; /** * Shows the 20 most recent statuses from the given list. * * @author Daniel Pedraza-Arcega * @since version 1.0 */ public class ListTimelineFragment extends TimelineFragment { protected static final String LIST_ARG = "LIST"; /** * Creates a ListTimelineFragment. * * @param userList a Twitter list. * @param enableDarkTheme if the dark theme is enabled. * @return a new ListTimelineFragment. */ public static ListTimelineFragment newInstance(UserList userList, boolean enableDarkTheme) { ListTimelineFragment fragment = new ListTimelineFragment(); Bundle args = new Bundle(); args.putSerializable(LIST_ARG, userList); args.putBoolean(ENABLE_DARK_THEME_ARG, enableDarkTheme); fragment.setArguments(args); return fragment; } /** * Creates a ListTimelineFragment. * * @param userList a Twitter list. * @return a new ListTimelineFragment. */ public static ListTimelineFragment newInstance(UserList userList) { return newInstance(userList, false); } /** {@inheritDoc} */ @Override protected ListStatusesLoaderTask initStatusesLoaderTask() {
return new ListStatusesLoaderTask(new DAOFactory(getActivity().getApplicationContext()).getListTimelineDAO(), getList().getId());
dan-zx/twitt4droid
library/src/com/twitt4droid/fragment/FixedQueryTimelineFragment.java
// Path: library/src/com/twitt4droid/data/dao/TimelineDAO.java // public interface TimelineDAO extends GenericDAO<Status, Long> { // // /** // * Returns all statuses. // * // * @return statuses. // */ // List<Status> fetchList(); // // /** // * Saves all the given statuses. // * // * @param statuses statuses. // */ // void save(List<Status> statuses); // // /** Deletes all statuses. */ // void deleteAll(); // } // // Path: library/src/com/twitt4droid/data/dao/impl/DAOFactory.java // public class DAOFactory { // // private final Context context; // // /** // * Creates a DAOFactory. // * // * @param context the application context. // */ // public DAOFactory(Context context) { // this.context = context; // } // // /** @return a new HomeTimelineDAO. */ // public TimelineDAO getHomeTimelineDAO() { // TimelineSQLiteDAO dao = new TimelineSQLiteDAO(TimelineSQLiteDAO.Table.HOME); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new MentionsTimelineDAO. */ // public TimelineDAO getMentionsTimelineDAO() { // TimelineSQLiteDAO dao = new TimelineSQLiteDAO(TimelineSQLiteDAO.Table.MENTION); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new UserTimelineDAO. */ // public UserTimelineDAO getUserTimelineDAO() { // UserTimelineSQLiteDAO dao = new UserTimelineSQLiteDAO(); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new FixedQueryTimelineDAO. */ // public TimelineDAO getFixedQueryTimelineDAO() { // TimelineSQLiteDAO dao = new TimelineSQLiteDAO(TimelineSQLiteDAO.Table.FIXED_QUERY); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new QueryableTimelineDAO. */ // public TimelineDAO getQueryableTimelineDAO() { // TimelineSQLiteDAO dao = new TimelineSQLiteDAO(TimelineSQLiteDAO.Table.QUERYABLE); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new ListTimelineDAO. */ // public ListTimelineDAO getListTimelineDAO() { // ListSQLiteDAO dao = new ListSQLiteDAO(); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new UserDAO. */ // public UserDAO getUserDAO() { // UserSQLiteDAO dao = new UserSQLiteDAO(); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // }
import android.os.Bundle; import com.twitt4droid.R; import com.twitt4droid.data.dao.TimelineDAO; import com.twitt4droid.data.dao.impl.DAOFactory; import twitter4j.Query; import twitter4j.TwitterException; import java.util.List;
/* * Copyright 2014 Daniel Pedraza-Arcega * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twitt4droid.fragment; /** * Shows the 20 most recent statuses that match a given query. * * @author Daniel Pedraza-Arcega * @since version 1.0 */ public class FixedQueryTimelineFragment extends TimelineFragment { protected static final String QUERY_ARG = "QUERY"; /** * Creates a FixedQueryTimelineFragment. * * @param query a search query. * @param enableDarkTheme if the dark theme is enabled. * @return a new FixedQueryTimelineFragment. */ public static FixedQueryTimelineFragment newInstance(String query, boolean enableDarkTheme) { FixedQueryTimelineFragment fragment = new FixedQueryTimelineFragment(); Bundle args = new Bundle(); args.putString(QUERY_ARG, query); args.putBoolean(ENABLE_DARK_THEME_ARG, enableDarkTheme); fragment.setArguments(args); return fragment; } /** * Creates a FixedQueryTimelineFragment. * * @param query a search query. * @return a new FixedQueryTimelineFragment. */ public static FixedQueryTimelineFragment newInstance(String query) { return newInstance(query, false); } /** {@inheritDoc} */ @Override protected QueryStatusesLoaderTask initStatusesLoaderTask() {
// Path: library/src/com/twitt4droid/data/dao/TimelineDAO.java // public interface TimelineDAO extends GenericDAO<Status, Long> { // // /** // * Returns all statuses. // * // * @return statuses. // */ // List<Status> fetchList(); // // /** // * Saves all the given statuses. // * // * @param statuses statuses. // */ // void save(List<Status> statuses); // // /** Deletes all statuses. */ // void deleteAll(); // } // // Path: library/src/com/twitt4droid/data/dao/impl/DAOFactory.java // public class DAOFactory { // // private final Context context; // // /** // * Creates a DAOFactory. // * // * @param context the application context. // */ // public DAOFactory(Context context) { // this.context = context; // } // // /** @return a new HomeTimelineDAO. */ // public TimelineDAO getHomeTimelineDAO() { // TimelineSQLiteDAO dao = new TimelineSQLiteDAO(TimelineSQLiteDAO.Table.HOME); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new MentionsTimelineDAO. */ // public TimelineDAO getMentionsTimelineDAO() { // TimelineSQLiteDAO dao = new TimelineSQLiteDAO(TimelineSQLiteDAO.Table.MENTION); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new UserTimelineDAO. */ // public UserTimelineDAO getUserTimelineDAO() { // UserTimelineSQLiteDAO dao = new UserTimelineSQLiteDAO(); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new FixedQueryTimelineDAO. */ // public TimelineDAO getFixedQueryTimelineDAO() { // TimelineSQLiteDAO dao = new TimelineSQLiteDAO(TimelineSQLiteDAO.Table.FIXED_QUERY); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new QueryableTimelineDAO. */ // public TimelineDAO getQueryableTimelineDAO() { // TimelineSQLiteDAO dao = new TimelineSQLiteDAO(TimelineSQLiteDAO.Table.QUERYABLE); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new ListTimelineDAO. */ // public ListTimelineDAO getListTimelineDAO() { // ListSQLiteDAO dao = new ListSQLiteDAO(); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new UserDAO. */ // public UserDAO getUserDAO() { // UserSQLiteDAO dao = new UserSQLiteDAO(); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // } // Path: library/src/com/twitt4droid/fragment/FixedQueryTimelineFragment.java import android.os.Bundle; import com.twitt4droid.R; import com.twitt4droid.data.dao.TimelineDAO; import com.twitt4droid.data.dao.impl.DAOFactory; import twitter4j.Query; import twitter4j.TwitterException; import java.util.List; /* * Copyright 2014 Daniel Pedraza-Arcega * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twitt4droid.fragment; /** * Shows the 20 most recent statuses that match a given query. * * @author Daniel Pedraza-Arcega * @since version 1.0 */ public class FixedQueryTimelineFragment extends TimelineFragment { protected static final String QUERY_ARG = "QUERY"; /** * Creates a FixedQueryTimelineFragment. * * @param query a search query. * @param enableDarkTheme if the dark theme is enabled. * @return a new FixedQueryTimelineFragment. */ public static FixedQueryTimelineFragment newInstance(String query, boolean enableDarkTheme) { FixedQueryTimelineFragment fragment = new FixedQueryTimelineFragment(); Bundle args = new Bundle(); args.putString(QUERY_ARG, query); args.putBoolean(ENABLE_DARK_THEME_ARG, enableDarkTheme); fragment.setArguments(args); return fragment; } /** * Creates a FixedQueryTimelineFragment. * * @param query a search query. * @return a new FixedQueryTimelineFragment. */ public static FixedQueryTimelineFragment newInstance(String query) { return newInstance(query, false); } /** {@inheritDoc} */ @Override protected QueryStatusesLoaderTask initStatusesLoaderTask() {
return new QueryStatusesLoaderTask(new DAOFactory(getActivity().getApplicationContext()).getFixedQueryTimelineDAO(), getQuery());
dan-zx/twitt4droid
library/src/com/twitt4droid/fragment/HomeTimelineFragment.java
// Path: library/src/com/twitt4droid/data/dao/TimelineDAO.java // public interface TimelineDAO extends GenericDAO<Status, Long> { // // /** // * Returns all statuses. // * // * @return statuses. // */ // List<Status> fetchList(); // // /** // * Saves all the given statuses. // * // * @param statuses statuses. // */ // void save(List<Status> statuses); // // /** Deletes all statuses. */ // void deleteAll(); // } // // Path: library/src/com/twitt4droid/data/dao/impl/DAOFactory.java // public class DAOFactory { // // private final Context context; // // /** // * Creates a DAOFactory. // * // * @param context the application context. // */ // public DAOFactory(Context context) { // this.context = context; // } // // /** @return a new HomeTimelineDAO. */ // public TimelineDAO getHomeTimelineDAO() { // TimelineSQLiteDAO dao = new TimelineSQLiteDAO(TimelineSQLiteDAO.Table.HOME); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new MentionsTimelineDAO. */ // public TimelineDAO getMentionsTimelineDAO() { // TimelineSQLiteDAO dao = new TimelineSQLiteDAO(TimelineSQLiteDAO.Table.MENTION); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new UserTimelineDAO. */ // public UserTimelineDAO getUserTimelineDAO() { // UserTimelineSQLiteDAO dao = new UserTimelineSQLiteDAO(); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new FixedQueryTimelineDAO. */ // public TimelineDAO getFixedQueryTimelineDAO() { // TimelineSQLiteDAO dao = new TimelineSQLiteDAO(TimelineSQLiteDAO.Table.FIXED_QUERY); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new QueryableTimelineDAO. */ // public TimelineDAO getQueryableTimelineDAO() { // TimelineSQLiteDAO dao = new TimelineSQLiteDAO(TimelineSQLiteDAO.Table.QUERYABLE); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new ListTimelineDAO. */ // public ListTimelineDAO getListTimelineDAO() { // ListSQLiteDAO dao = new ListSQLiteDAO(); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new UserDAO. */ // public UserDAO getUserDAO() { // UserSQLiteDAO dao = new UserSQLiteDAO(); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // }
import android.os.Bundle; import com.twitt4droid.R; import com.twitt4droid.data.dao.TimelineDAO; import com.twitt4droid.data.dao.impl.DAOFactory; import twitter4j.TwitterException; import java.util.List;
/* * Copyright 2014 Daniel Pedraza-Arcega * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twitt4droid.fragment; /** * Shows the 20 most recent statuses, including retweets, posted by the authenticating user and that * user's friends. * * @author Daniel Pedraza-Arcega * @since version 1.0 */ public class HomeTimelineFragment extends TimelineFragment { /** * Creates a HomeTimelineFragment. * * @param enableDarkTheme if the dark theme is enabled. * @return a new HomeTimelineFragment. */ public static HomeTimelineFragment newInstance(boolean enableDarkTheme) { HomeTimelineFragment fragment = new HomeTimelineFragment(); Bundle args = new Bundle(); args.putBoolean(ENABLE_DARK_THEME_ARG, enableDarkTheme); fragment.setArguments(args); return fragment; } /** * Creates a HomeTimelineFragment. * * @return a new HomeTimelineFragment. */ public static HomeTimelineFragment newInstance() { return newInstance(false); } /** {@inheritDoc} */ @Override protected HomeStatusesLoaderTask initStatusesLoaderTask() {
// Path: library/src/com/twitt4droid/data/dao/TimelineDAO.java // public interface TimelineDAO extends GenericDAO<Status, Long> { // // /** // * Returns all statuses. // * // * @return statuses. // */ // List<Status> fetchList(); // // /** // * Saves all the given statuses. // * // * @param statuses statuses. // */ // void save(List<Status> statuses); // // /** Deletes all statuses. */ // void deleteAll(); // } // // Path: library/src/com/twitt4droid/data/dao/impl/DAOFactory.java // public class DAOFactory { // // private final Context context; // // /** // * Creates a DAOFactory. // * // * @param context the application context. // */ // public DAOFactory(Context context) { // this.context = context; // } // // /** @return a new HomeTimelineDAO. */ // public TimelineDAO getHomeTimelineDAO() { // TimelineSQLiteDAO dao = new TimelineSQLiteDAO(TimelineSQLiteDAO.Table.HOME); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new MentionsTimelineDAO. */ // public TimelineDAO getMentionsTimelineDAO() { // TimelineSQLiteDAO dao = new TimelineSQLiteDAO(TimelineSQLiteDAO.Table.MENTION); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new UserTimelineDAO. */ // public UserTimelineDAO getUserTimelineDAO() { // UserTimelineSQLiteDAO dao = new UserTimelineSQLiteDAO(); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new FixedQueryTimelineDAO. */ // public TimelineDAO getFixedQueryTimelineDAO() { // TimelineSQLiteDAO dao = new TimelineSQLiteDAO(TimelineSQLiteDAO.Table.FIXED_QUERY); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new QueryableTimelineDAO. */ // public TimelineDAO getQueryableTimelineDAO() { // TimelineSQLiteDAO dao = new TimelineSQLiteDAO(TimelineSQLiteDAO.Table.QUERYABLE); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new ListTimelineDAO. */ // public ListTimelineDAO getListTimelineDAO() { // ListSQLiteDAO dao = new ListSQLiteDAO(); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new UserDAO. */ // public UserDAO getUserDAO() { // UserSQLiteDAO dao = new UserSQLiteDAO(); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // } // Path: library/src/com/twitt4droid/fragment/HomeTimelineFragment.java import android.os.Bundle; import com.twitt4droid.R; import com.twitt4droid.data.dao.TimelineDAO; import com.twitt4droid.data.dao.impl.DAOFactory; import twitter4j.TwitterException; import java.util.List; /* * Copyright 2014 Daniel Pedraza-Arcega * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twitt4droid.fragment; /** * Shows the 20 most recent statuses, including retweets, posted by the authenticating user and that * user's friends. * * @author Daniel Pedraza-Arcega * @since version 1.0 */ public class HomeTimelineFragment extends TimelineFragment { /** * Creates a HomeTimelineFragment. * * @param enableDarkTheme if the dark theme is enabled. * @return a new HomeTimelineFragment. */ public static HomeTimelineFragment newInstance(boolean enableDarkTheme) { HomeTimelineFragment fragment = new HomeTimelineFragment(); Bundle args = new Bundle(); args.putBoolean(ENABLE_DARK_THEME_ARG, enableDarkTheme); fragment.setArguments(args); return fragment; } /** * Creates a HomeTimelineFragment. * * @return a new HomeTimelineFragment. */ public static HomeTimelineFragment newInstance() { return newInstance(false); } /** {@inheritDoc} */ @Override protected HomeStatusesLoaderTask initStatusesLoaderTask() {
return new HomeStatusesLoaderTask(new DAOFactory(getActivity().getApplicationContext()).getHomeTimelineDAO());
dan-zx/twitt4droid
library/src/com/twitt4droid/fragment/MentionsTimelineFragment.java
// Path: library/src/com/twitt4droid/data/dao/TimelineDAO.java // public interface TimelineDAO extends GenericDAO<Status, Long> { // // /** // * Returns all statuses. // * // * @return statuses. // */ // List<Status> fetchList(); // // /** // * Saves all the given statuses. // * // * @param statuses statuses. // */ // void save(List<Status> statuses); // // /** Deletes all statuses. */ // void deleteAll(); // } // // Path: library/src/com/twitt4droid/data/dao/impl/DAOFactory.java // public class DAOFactory { // // private final Context context; // // /** // * Creates a DAOFactory. // * // * @param context the application context. // */ // public DAOFactory(Context context) { // this.context = context; // } // // /** @return a new HomeTimelineDAO. */ // public TimelineDAO getHomeTimelineDAO() { // TimelineSQLiteDAO dao = new TimelineSQLiteDAO(TimelineSQLiteDAO.Table.HOME); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new MentionsTimelineDAO. */ // public TimelineDAO getMentionsTimelineDAO() { // TimelineSQLiteDAO dao = new TimelineSQLiteDAO(TimelineSQLiteDAO.Table.MENTION); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new UserTimelineDAO. */ // public UserTimelineDAO getUserTimelineDAO() { // UserTimelineSQLiteDAO dao = new UserTimelineSQLiteDAO(); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new FixedQueryTimelineDAO. */ // public TimelineDAO getFixedQueryTimelineDAO() { // TimelineSQLiteDAO dao = new TimelineSQLiteDAO(TimelineSQLiteDAO.Table.FIXED_QUERY); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new QueryableTimelineDAO. */ // public TimelineDAO getQueryableTimelineDAO() { // TimelineSQLiteDAO dao = new TimelineSQLiteDAO(TimelineSQLiteDAO.Table.QUERYABLE); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new ListTimelineDAO. */ // public ListTimelineDAO getListTimelineDAO() { // ListSQLiteDAO dao = new ListSQLiteDAO(); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new UserDAO. */ // public UserDAO getUserDAO() { // UserSQLiteDAO dao = new UserSQLiteDAO(); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // }
import android.os.Bundle; import com.twitt4droid.R; import com.twitt4droid.data.dao.TimelineDAO; import com.twitt4droid.data.dao.impl.DAOFactory; import twitter4j.TwitterException; import java.util.List;
/* * Copyright 2014 Daniel Pedraza-Arcega * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twitt4droid.fragment; /** * Shows the 20 most recent mentions (tweets containing a users's \@screen_name) for the * authenticating user. * * @author Daniel Pedraza-Arcega * @since version 1.0 */ public class MentionsTimelineFragment extends TimelineFragment { /** * Creates a MentionsTimelineFragment. * * @param enableDarkTheme if the dark theme is enabled. * @return a new MentionsTimelineFragment. */ public static MentionsTimelineFragment newInstance(boolean enableDarkTheme) { MentionsTimelineFragment fragment = new MentionsTimelineFragment(); Bundle args = new Bundle(); args.putBoolean(ENABLE_DARK_THEME_ARG, enableDarkTheme); fragment.setArguments(args); return fragment; } /** * Creates a MentionsTimelineFragment. * * @return a new MentionsTimelineFragment. */ public static MentionsTimelineFragment newInstance() { return newInstance(false); } /** {@inheritDoc} */ @Override protected MentionsStatusesLoaderTask initStatusesLoaderTask() {
// Path: library/src/com/twitt4droid/data/dao/TimelineDAO.java // public interface TimelineDAO extends GenericDAO<Status, Long> { // // /** // * Returns all statuses. // * // * @return statuses. // */ // List<Status> fetchList(); // // /** // * Saves all the given statuses. // * // * @param statuses statuses. // */ // void save(List<Status> statuses); // // /** Deletes all statuses. */ // void deleteAll(); // } // // Path: library/src/com/twitt4droid/data/dao/impl/DAOFactory.java // public class DAOFactory { // // private final Context context; // // /** // * Creates a DAOFactory. // * // * @param context the application context. // */ // public DAOFactory(Context context) { // this.context = context; // } // // /** @return a new HomeTimelineDAO. */ // public TimelineDAO getHomeTimelineDAO() { // TimelineSQLiteDAO dao = new TimelineSQLiteDAO(TimelineSQLiteDAO.Table.HOME); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new MentionsTimelineDAO. */ // public TimelineDAO getMentionsTimelineDAO() { // TimelineSQLiteDAO dao = new TimelineSQLiteDAO(TimelineSQLiteDAO.Table.MENTION); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new UserTimelineDAO. */ // public UserTimelineDAO getUserTimelineDAO() { // UserTimelineSQLiteDAO dao = new UserTimelineSQLiteDAO(); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new FixedQueryTimelineDAO. */ // public TimelineDAO getFixedQueryTimelineDAO() { // TimelineSQLiteDAO dao = new TimelineSQLiteDAO(TimelineSQLiteDAO.Table.FIXED_QUERY); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new QueryableTimelineDAO. */ // public TimelineDAO getQueryableTimelineDAO() { // TimelineSQLiteDAO dao = new TimelineSQLiteDAO(TimelineSQLiteDAO.Table.QUERYABLE); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new ListTimelineDAO. */ // public ListTimelineDAO getListTimelineDAO() { // ListSQLiteDAO dao = new ListSQLiteDAO(); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // // /** @return a new UserDAO. */ // public UserDAO getUserDAO() { // UserSQLiteDAO dao = new UserSQLiteDAO(); // dao.setContext(context); // dao.setSQLiteOpenHelper(new Twitt4droidDatabaseHelper(context)); // return dao; // } // } // Path: library/src/com/twitt4droid/fragment/MentionsTimelineFragment.java import android.os.Bundle; import com.twitt4droid.R; import com.twitt4droid.data.dao.TimelineDAO; import com.twitt4droid.data.dao.impl.DAOFactory; import twitter4j.TwitterException; import java.util.List; /* * Copyright 2014 Daniel Pedraza-Arcega * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twitt4droid.fragment; /** * Shows the 20 most recent mentions (tweets containing a users's \@screen_name) for the * authenticating user. * * @author Daniel Pedraza-Arcega * @since version 1.0 */ public class MentionsTimelineFragment extends TimelineFragment { /** * Creates a MentionsTimelineFragment. * * @param enableDarkTheme if the dark theme is enabled. * @return a new MentionsTimelineFragment. */ public static MentionsTimelineFragment newInstance(boolean enableDarkTheme) { MentionsTimelineFragment fragment = new MentionsTimelineFragment(); Bundle args = new Bundle(); args.putBoolean(ENABLE_DARK_THEME_ARG, enableDarkTheme); fragment.setArguments(args); return fragment; } /** * Creates a MentionsTimelineFragment. * * @return a new MentionsTimelineFragment. */ public static MentionsTimelineFragment newInstance() { return newInstance(false); } /** {@inheritDoc} */ @Override protected MentionsStatusesLoaderTask initStatusesLoaderTask() {
return new MentionsStatusesLoaderTask(new DAOFactory(getActivity().getApplicationContext()).getMentionsTimelineDAO());
funktionio/funktion-connectors
funktion-model/src/main/java/io/fabric8/funktion/model/steps/Otherwise.java
// Path: funktion-model/src/main/java/io/fabric8/funktion/model/StepKinds.java // public class StepKinds { // public static final String CHOICE = "choice"; // public static final String ENDPOINT = "endpoint"; // public static final String FILTER = "filter"; // public static final String FUNCTION = "function"; // public static final String FLOW = "flow"; // public static final String OTHERWISE = "otherwise"; // public static final String SET_BODY = "setBody"; // public static final String SET_HEADERS = "setHeaders"; // public static final String SPLIT = "split"; // public static final String THROTTLE = "throttle"; // public static final String LOG = "log"; // }
import io.fabric8.funktion.model.StepKinds; import java.util.List;
/* * Copyright 2016 Red Hat, Inc. * <p> * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * */ package io.fabric8.funktion.model.steps; /** * Represents the otherwise clause in a {@link Choice} */ public class Otherwise extends ChildSteps<Otherwise> { public Otherwise() {
// Path: funktion-model/src/main/java/io/fabric8/funktion/model/StepKinds.java // public class StepKinds { // public static final String CHOICE = "choice"; // public static final String ENDPOINT = "endpoint"; // public static final String FILTER = "filter"; // public static final String FUNCTION = "function"; // public static final String FLOW = "flow"; // public static final String OTHERWISE = "otherwise"; // public static final String SET_BODY = "setBody"; // public static final String SET_HEADERS = "setHeaders"; // public static final String SPLIT = "split"; // public static final String THROTTLE = "throttle"; // public static final String LOG = "log"; // } // Path: funktion-model/src/main/java/io/fabric8/funktion/model/steps/Otherwise.java import io.fabric8.funktion.model.StepKinds; import java.util.List; /* * Copyright 2016 Red Hat, Inc. * <p> * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * */ package io.fabric8.funktion.model.steps; /** * Represents the otherwise clause in a {@link Choice} */ public class Otherwise extends ChildSteps<Otherwise> { public Otherwise() {
super(StepKinds.OTHERWISE);
funktionio/funktion-connectors
funktion-model/src/main/java/io/fabric8/funktion/model/steps/SetBody.java
// Path: funktion-model/src/main/java/io/fabric8/funktion/model/StepKinds.java // public class StepKinds { // public static final String CHOICE = "choice"; // public static final String ENDPOINT = "endpoint"; // public static final String FILTER = "filter"; // public static final String FUNCTION = "function"; // public static final String FLOW = "flow"; // public static final String OTHERWISE = "otherwise"; // public static final String SET_BODY = "setBody"; // public static final String SET_HEADERS = "setHeaders"; // public static final String SPLIT = "split"; // public static final String THROTTLE = "throttle"; // public static final String LOG = "log"; // }
import io.fabric8.funktion.model.StepKinds;
/* * Copyright 2016 Red Hat, Inc. * <p> * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * */ package io.fabric8.funktion.model.steps; /** * Sets the payload body */ public class SetBody extends Step { private String body; public SetBody() {
// Path: funktion-model/src/main/java/io/fabric8/funktion/model/StepKinds.java // public class StepKinds { // public static final String CHOICE = "choice"; // public static final String ENDPOINT = "endpoint"; // public static final String FILTER = "filter"; // public static final String FUNCTION = "function"; // public static final String FLOW = "flow"; // public static final String OTHERWISE = "otherwise"; // public static final String SET_BODY = "setBody"; // public static final String SET_HEADERS = "setHeaders"; // public static final String SPLIT = "split"; // public static final String THROTTLE = "throttle"; // public static final String LOG = "log"; // } // Path: funktion-model/src/main/java/io/fabric8/funktion/model/steps/SetBody.java import io.fabric8.funktion.model.StepKinds; /* * Copyright 2016 Red Hat, Inc. * <p> * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * */ package io.fabric8.funktion.model.steps; /** * Sets the payload body */ public class SetBody extends Step { private String body; public SetBody() {
super(StepKinds.SET_BODY);
funktionio/funktion-connectors
funktion-model/src/main/java/io/fabric8/funktion/model/steps/Split.java
// Path: funktion-model/src/main/java/io/fabric8/funktion/model/StepKinds.java // public class StepKinds { // public static final String CHOICE = "choice"; // public static final String ENDPOINT = "endpoint"; // public static final String FILTER = "filter"; // public static final String FUNCTION = "function"; // public static final String FLOW = "flow"; // public static final String OTHERWISE = "otherwise"; // public static final String SET_BODY = "setBody"; // public static final String SET_HEADERS = "setHeaders"; // public static final String SPLIT = "split"; // public static final String THROTTLE = "throttle"; // public static final String LOG = "log"; // }
import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.fabric8.funktion.model.StepKinds;
/* * Copyright 2016 Red Hat, Inc. * <p> * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * */ package io.fabric8.funktion.model.steps; /** * Splits the payload into multiple messages */ @JsonPropertyOrder({"expression", "language", "steps"}) public class Split extends ChildSteps<Split> { private String expression; private String language; public Split() {
// Path: funktion-model/src/main/java/io/fabric8/funktion/model/StepKinds.java // public class StepKinds { // public static final String CHOICE = "choice"; // public static final String ENDPOINT = "endpoint"; // public static final String FILTER = "filter"; // public static final String FUNCTION = "function"; // public static final String FLOW = "flow"; // public static final String OTHERWISE = "otherwise"; // public static final String SET_BODY = "setBody"; // public static final String SET_HEADERS = "setHeaders"; // public static final String SPLIT = "split"; // public static final String THROTTLE = "throttle"; // public static final String LOG = "log"; // } // Path: funktion-model/src/main/java/io/fabric8/funktion/model/steps/Split.java import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.fabric8.funktion.model.StepKinds; /* * Copyright 2016 Red Hat, Inc. * <p> * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * */ package io.fabric8.funktion.model.steps; /** * Splits the payload into multiple messages */ @JsonPropertyOrder({"expression", "language", "steps"}) public class Split extends ChildSteps<Split> { private String expression; private String language; public Split() {
super(StepKinds.SPLIT);
funktionio/funktion-connectors
funktion-runtime/src/test/java/io/fabric8/funktion/runtime/components/HttpsTest.java
// Path: funktion-runtime/src/test/java/io/fabric8/funktion/FunktionTestSupport.java // public abstract class FunktionTestSupport extends CamelTestSupport { // private static final transient Logger LOG = LoggerFactory.getLogger(FunktionTestSupport.class); // // public static File getBaseDir() { // String basedir = System.getProperty("basedir", System.getProperty("user.dir", ".")); // File answer = new File(basedir); // return answer; // } // // @Override // protected RoutesBuilder createRouteBuilder() throws Exception { // final Funktion funktion = createFunktion(); // if (isDumpFlowYAML()) { // String fileNamePrefix = "target/funktion-tests/" + getClassNameAsPath() + "-" + getTestMethodName(); // File file = new File(getBaseDir(), fileNamePrefix + ".yml"); // file.getParentFile().mkdirs(); // Funktions.saveConfig(funktion, file); // Funktions.saveConfigJSON(funktion, new File(getBaseDir(), fileNamePrefix + ".json")); // } // return new FunktionRouteBuilder() { // @Override // protected Funktion loadFunktion() throws IOException { // return funktion; // } // }; // // } // // protected Funktion loadTestYaml() throws IOException { // String path = getClassNameAsPath() + "-" + getTestMethodName() + ".yml"; // LOG.info("Loading Funktion flows from classpath at: " + path); // URL resource = getClass().getClassLoader().getResource(path); // Assertions.assertThat(resource).describedAs("Could not find " + path + " on the classpath!").isNotNull(); // return Funktions.loadFromURL(resource); // } // // private String getClassNameAsPath() { // return getClass().getName().replace('.', '/'); // } // // // @Override // public boolean isDumpRouteCoverage() { // return true; // } // // /** // * Factory method to create the funktion flows for the test case // */ // protected Funktion createFunktion() throws Exception { // Funktion funktion = new Funktion(); // addFunktionFlows(funktion); // return funktion; // } // // protected void logMessagesReceived(MockEndpoint... mockEndpoints) { // System.out.println(); // for (MockEndpoint mockEndpoint : mockEndpoints) { // System.out.println("Messages received on endpoint " + mockEndpoint.getEndpointUri()); // List<Exchange> exchanges = mockEndpoint.getExchanges(); // Assertions.assertThat(exchanges).describedAs("exchanges on " + mockEndpoint).isNotNull(); // int count = 0; // for (Exchange exchange : exchanges) { // System.out.println(" " + count++ + " = " + exchange.getIn().getBody(String.class)); // } // System.out.println(); // } // } // // /** // * Adds the flows to this funktion using the Funktion DSL // */ // protected void addFunktionFlows(Funktion funktion) { // } // // protected boolean isDumpFlowYAML() { // return true; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/model/Funktion.java // public class Funktion extends DtoSupport { // private List<Flow> flows = new ArrayList<>(); // // public List<Flow> getFlows() { // return flows; // } // // public void setFlows(List<Flow> flows) { // this.flows = flows; // } // // public Flow createFlow() { // return addFlow(new Flow()); // } // // public Flow addFlow(Flow flow) { // flows.add(flow); // return flow; // } // }
import io.fabric8.funktion.FunktionTestSupport; import io.fabric8.funktion.model.Funktion; import org.apache.camel.EndpointInject; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.component.mock.MockEndpoint; import org.assertj.core.api.Assertions; import org.junit.Ignore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List;
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.fabric8.funktion.runtime.components; /** */ public class HttpsTest extends FunktionTestSupport { private static final transient Logger LOG = LoggerFactory.getLogger(HttpsTest.class); @EndpointInject(uri = "mock:results") protected MockEndpoint results; @Override public boolean isDumpRouteCoverage() { return true; } // TODO @Ignore public void testInvokeHTTPS() throws Exception { results.expectedMessageCount(1); results.assertIsSatisfied(); List<Exchange> exchanges = results.getExchanges(); Assertions.assertThat(exchanges.size()).isGreaterThan(0); Exchange exchange = exchanges.get(0); Message in = exchange.getIn(); String json = in.getBody(String.class); LOG.info("Received: " + json); } @Override
// Path: funktion-runtime/src/test/java/io/fabric8/funktion/FunktionTestSupport.java // public abstract class FunktionTestSupport extends CamelTestSupport { // private static final transient Logger LOG = LoggerFactory.getLogger(FunktionTestSupport.class); // // public static File getBaseDir() { // String basedir = System.getProperty("basedir", System.getProperty("user.dir", ".")); // File answer = new File(basedir); // return answer; // } // // @Override // protected RoutesBuilder createRouteBuilder() throws Exception { // final Funktion funktion = createFunktion(); // if (isDumpFlowYAML()) { // String fileNamePrefix = "target/funktion-tests/" + getClassNameAsPath() + "-" + getTestMethodName(); // File file = new File(getBaseDir(), fileNamePrefix + ".yml"); // file.getParentFile().mkdirs(); // Funktions.saveConfig(funktion, file); // Funktions.saveConfigJSON(funktion, new File(getBaseDir(), fileNamePrefix + ".json")); // } // return new FunktionRouteBuilder() { // @Override // protected Funktion loadFunktion() throws IOException { // return funktion; // } // }; // // } // // protected Funktion loadTestYaml() throws IOException { // String path = getClassNameAsPath() + "-" + getTestMethodName() + ".yml"; // LOG.info("Loading Funktion flows from classpath at: " + path); // URL resource = getClass().getClassLoader().getResource(path); // Assertions.assertThat(resource).describedAs("Could not find " + path + " on the classpath!").isNotNull(); // return Funktions.loadFromURL(resource); // } // // private String getClassNameAsPath() { // return getClass().getName().replace('.', '/'); // } // // // @Override // public boolean isDumpRouteCoverage() { // return true; // } // // /** // * Factory method to create the funktion flows for the test case // */ // protected Funktion createFunktion() throws Exception { // Funktion funktion = new Funktion(); // addFunktionFlows(funktion); // return funktion; // } // // protected void logMessagesReceived(MockEndpoint... mockEndpoints) { // System.out.println(); // for (MockEndpoint mockEndpoint : mockEndpoints) { // System.out.println("Messages received on endpoint " + mockEndpoint.getEndpointUri()); // List<Exchange> exchanges = mockEndpoint.getExchanges(); // Assertions.assertThat(exchanges).describedAs("exchanges on " + mockEndpoint).isNotNull(); // int count = 0; // for (Exchange exchange : exchanges) { // System.out.println(" " + count++ + " = " + exchange.getIn().getBody(String.class)); // } // System.out.println(); // } // } // // /** // * Adds the flows to this funktion using the Funktion DSL // */ // protected void addFunktionFlows(Funktion funktion) { // } // // protected boolean isDumpFlowYAML() { // return true; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/model/Funktion.java // public class Funktion extends DtoSupport { // private List<Flow> flows = new ArrayList<>(); // // public List<Flow> getFlows() { // return flows; // } // // public void setFlows(List<Flow> flows) { // this.flows = flows; // } // // public Flow createFlow() { // return addFlow(new Flow()); // } // // public Flow addFlow(Flow flow) { // flows.add(flow); // return flow; // } // } // Path: funktion-runtime/src/test/java/io/fabric8/funktion/runtime/components/HttpsTest.java import io.fabric8.funktion.FunktionTestSupport; import io.fabric8.funktion.model.Funktion; import org.apache.camel.EndpointInject; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.component.mock.MockEndpoint; import org.assertj.core.api.Assertions; import org.junit.Ignore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.fabric8.funktion.runtime.components; /** */ public class HttpsTest extends FunktionTestSupport { private static final transient Logger LOG = LoggerFactory.getLogger(HttpsTest.class); @EndpointInject(uri = "mock:results") protected MockEndpoint results; @Override public boolean isDumpRouteCoverage() { return true; } // TODO @Ignore public void testInvokeHTTPS() throws Exception { results.expectedMessageCount(1); results.assertIsSatisfied(); List<Exchange> exchanges = results.getExchanges(); Assertions.assertThat(exchanges.size()).isGreaterThan(0); Exchange exchange = exchanges.get(0); Message in = exchange.getIn(); String json = in.getBody(String.class); LOG.info("Received: " + json); } @Override
protected void addFunktionFlows(Funktion funktion) {
funktionio/funktion-connectors
funktion-model/src/main/java/io/fabric8/funktion/model/Flow.java
// Path: funktion-model/src/main/java/io/fabric8/funktion/support/Strings.java // public class Strings { // // public static boolean isEmpty(String value) { // return value == null || value.length() == 0 || value.trim().length() == 0; // } // // }
import com.fasterxml.jackson.annotation.JsonIgnore; import io.fabric8.funktion.model.steps.*; import io.fabric8.funktion.support.Strings; import java.util.ArrayList; import java.util.List; import java.util.Map;
/* * Copyright 2016 Red Hat, Inc. * <p> * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * */ package io.fabric8.funktion.model; public class Flow extends DtoSupport { private String name; private Boolean trace; private Boolean logResult; private Boolean singleMessageMode; private List<Step> steps = new ArrayList<>(); public Flow addStep(Step step) { steps.add(step); return this; } public Flow name(String value) { setName(value); return this; } public Flow logResult(boolean value) { setLogResult(value); return this; } public Flow trace(boolean value) { setTrace(value); return this; } public Flow singleMessageMode(boolean value) { setSingleMessageMode(value); return this; } @Override public String toString() { StringBuilder builder = new StringBuilder("Flow ");
// Path: funktion-model/src/main/java/io/fabric8/funktion/support/Strings.java // public class Strings { // // public static boolean isEmpty(String value) { // return value == null || value.length() == 0 || value.trim().length() == 0; // } // // } // Path: funktion-model/src/main/java/io/fabric8/funktion/model/Flow.java import com.fasterxml.jackson.annotation.JsonIgnore; import io.fabric8.funktion.model.steps.*; import io.fabric8.funktion.support.Strings; import java.util.ArrayList; import java.util.List; import java.util.Map; /* * Copyright 2016 Red Hat, Inc. * <p> * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * */ package io.fabric8.funktion.model; public class Flow extends DtoSupport { private String name; private Boolean trace; private Boolean logResult; private Boolean singleMessageMode; private List<Step> steps = new ArrayList<>(); public Flow addStep(Step step) { steps.add(step); return this; } public Flow name(String value) { setName(value); return this; } public Flow logResult(boolean value) { setLogResult(value); return this; } public Flow trace(boolean value) { setTrace(value); return this; } public Flow singleMessageMode(boolean value) { setSingleMessageMode(value); return this; } @Override public String toString() { StringBuilder builder = new StringBuilder("Flow ");
if (!Strings.isEmpty(name)) {
funktionio/funktion-connectors
funktion-runtime/src/test/java/io/fabric8/funktion/runtime/steps/SplitTest.java
// Path: funktion-runtime/src/test/java/io/fabric8/funktion/FunktionTestSupport.java // public abstract class FunktionTestSupport extends CamelTestSupport { // private static final transient Logger LOG = LoggerFactory.getLogger(FunktionTestSupport.class); // // public static File getBaseDir() { // String basedir = System.getProperty("basedir", System.getProperty("user.dir", ".")); // File answer = new File(basedir); // return answer; // } // // @Override // protected RoutesBuilder createRouteBuilder() throws Exception { // final Funktion funktion = createFunktion(); // if (isDumpFlowYAML()) { // String fileNamePrefix = "target/funktion-tests/" + getClassNameAsPath() + "-" + getTestMethodName(); // File file = new File(getBaseDir(), fileNamePrefix + ".yml"); // file.getParentFile().mkdirs(); // Funktions.saveConfig(funktion, file); // Funktions.saveConfigJSON(funktion, new File(getBaseDir(), fileNamePrefix + ".json")); // } // return new FunktionRouteBuilder() { // @Override // protected Funktion loadFunktion() throws IOException { // return funktion; // } // }; // // } // // protected Funktion loadTestYaml() throws IOException { // String path = getClassNameAsPath() + "-" + getTestMethodName() + ".yml"; // LOG.info("Loading Funktion flows from classpath at: " + path); // URL resource = getClass().getClassLoader().getResource(path); // Assertions.assertThat(resource).describedAs("Could not find " + path + " on the classpath!").isNotNull(); // return Funktions.loadFromURL(resource); // } // // private String getClassNameAsPath() { // return getClass().getName().replace('.', '/'); // } // // // @Override // public boolean isDumpRouteCoverage() { // return true; // } // // /** // * Factory method to create the funktion flows for the test case // */ // protected Funktion createFunktion() throws Exception { // Funktion funktion = new Funktion(); // addFunktionFlows(funktion); // return funktion; // } // // protected void logMessagesReceived(MockEndpoint... mockEndpoints) { // System.out.println(); // for (MockEndpoint mockEndpoint : mockEndpoints) { // System.out.println("Messages received on endpoint " + mockEndpoint.getEndpointUri()); // List<Exchange> exchanges = mockEndpoint.getExchanges(); // Assertions.assertThat(exchanges).describedAs("exchanges on " + mockEndpoint).isNotNull(); // int count = 0; // for (Exchange exchange : exchanges) { // System.out.println(" " + count++ + " = " + exchange.getIn().getBody(String.class)); // } // System.out.println(); // } // } // // /** // * Adds the flows to this funktion using the Funktion DSL // */ // protected void addFunktionFlows(Funktion funktion) { // } // // protected boolean isDumpFlowYAML() { // return true; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/model/Funktion.java // public class Funktion extends DtoSupport { // private List<Flow> flows = new ArrayList<>(); // // public List<Flow> getFlows() { // return flows; // } // // public void setFlows(List<Flow> flows) { // this.flows = flows; // } // // public Flow createFlow() { // return addFlow(new Flow()); // } // // public Flow addFlow(Flow flow) { // flows.add(flow); // return flow; // } // }
import io.fabric8.funktion.FunktionTestSupport; import io.fabric8.funktion.model.Funktion; import org.apache.camel.EndpointInject; import org.apache.camel.component.mock.MockEndpoint; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.List;
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.fabric8.funktion.runtime.steps; /** */ public class SplitTest extends FunktionTestSupport { public static final String START_URI = "direct:start"; public static final String RESULTS_URI = "mock:results"; private static final transient Logger LOG = LoggerFactory.getLogger(SplitTest.class); @EndpointInject(uri = RESULTS_URI) protected MockEndpoint resultsEndpoint; protected List<String> messages = Arrays.asList( "{ \"orderId\": \"ABC\", \"lineItems\": [{\"id\":123,\"name\":\"beer\"},{\"id\":456,\"name\":\"wine\"}] }" ); protected List<String> expectedMessages = Arrays.asList( "{\"id\":123,\"name\":\"beer\"}", "{\"id\":456,\"name\":\"wine\"}" ); @Test public void testStep() throws Exception { resultsEndpoint.expectedBodiesReceived(expectedMessages); for (Object body : messages) { template.sendBody(START_URI, body); } MockEndpoint.assertIsSatisfied(resultsEndpoint); logMessagesReceived(resultsEndpoint); } @Override
// Path: funktion-runtime/src/test/java/io/fabric8/funktion/FunktionTestSupport.java // public abstract class FunktionTestSupport extends CamelTestSupport { // private static final transient Logger LOG = LoggerFactory.getLogger(FunktionTestSupport.class); // // public static File getBaseDir() { // String basedir = System.getProperty("basedir", System.getProperty("user.dir", ".")); // File answer = new File(basedir); // return answer; // } // // @Override // protected RoutesBuilder createRouteBuilder() throws Exception { // final Funktion funktion = createFunktion(); // if (isDumpFlowYAML()) { // String fileNamePrefix = "target/funktion-tests/" + getClassNameAsPath() + "-" + getTestMethodName(); // File file = new File(getBaseDir(), fileNamePrefix + ".yml"); // file.getParentFile().mkdirs(); // Funktions.saveConfig(funktion, file); // Funktions.saveConfigJSON(funktion, new File(getBaseDir(), fileNamePrefix + ".json")); // } // return new FunktionRouteBuilder() { // @Override // protected Funktion loadFunktion() throws IOException { // return funktion; // } // }; // // } // // protected Funktion loadTestYaml() throws IOException { // String path = getClassNameAsPath() + "-" + getTestMethodName() + ".yml"; // LOG.info("Loading Funktion flows from classpath at: " + path); // URL resource = getClass().getClassLoader().getResource(path); // Assertions.assertThat(resource).describedAs("Could not find " + path + " on the classpath!").isNotNull(); // return Funktions.loadFromURL(resource); // } // // private String getClassNameAsPath() { // return getClass().getName().replace('.', '/'); // } // // // @Override // public boolean isDumpRouteCoverage() { // return true; // } // // /** // * Factory method to create the funktion flows for the test case // */ // protected Funktion createFunktion() throws Exception { // Funktion funktion = new Funktion(); // addFunktionFlows(funktion); // return funktion; // } // // protected void logMessagesReceived(MockEndpoint... mockEndpoints) { // System.out.println(); // for (MockEndpoint mockEndpoint : mockEndpoints) { // System.out.println("Messages received on endpoint " + mockEndpoint.getEndpointUri()); // List<Exchange> exchanges = mockEndpoint.getExchanges(); // Assertions.assertThat(exchanges).describedAs("exchanges on " + mockEndpoint).isNotNull(); // int count = 0; // for (Exchange exchange : exchanges) { // System.out.println(" " + count++ + " = " + exchange.getIn().getBody(String.class)); // } // System.out.println(); // } // } // // /** // * Adds the flows to this funktion using the Funktion DSL // */ // protected void addFunktionFlows(Funktion funktion) { // } // // protected boolean isDumpFlowYAML() { // return true; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/model/Funktion.java // public class Funktion extends DtoSupport { // private List<Flow> flows = new ArrayList<>(); // // public List<Flow> getFlows() { // return flows; // } // // public void setFlows(List<Flow> flows) { // this.flows = flows; // } // // public Flow createFlow() { // return addFlow(new Flow()); // } // // public Flow addFlow(Flow flow) { // flows.add(flow); // return flow; // } // } // Path: funktion-runtime/src/test/java/io/fabric8/funktion/runtime/steps/SplitTest.java import io.fabric8.funktion.FunktionTestSupport; import io.fabric8.funktion.model.Funktion; import org.apache.camel.EndpointInject; import org.apache.camel.component.mock.MockEndpoint; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.List; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.fabric8.funktion.runtime.steps; /** */ public class SplitTest extends FunktionTestSupport { public static final String START_URI = "direct:start"; public static final String RESULTS_URI = "mock:results"; private static final transient Logger LOG = LoggerFactory.getLogger(SplitTest.class); @EndpointInject(uri = RESULTS_URI) protected MockEndpoint resultsEndpoint; protected List<String> messages = Arrays.asList( "{ \"orderId\": \"ABC\", \"lineItems\": [{\"id\":123,\"name\":\"beer\"},{\"id\":456,\"name\":\"wine\"}] }" ); protected List<String> expectedMessages = Arrays.asList( "{\"id\":123,\"name\":\"beer\"}", "{\"id\":456,\"name\":\"wine\"}" ); @Test public void testStep() throws Exception { resultsEndpoint.expectedBodiesReceived(expectedMessages); for (Object body : messages) { template.sendBody(START_URI, body); } MockEndpoint.assertIsSatisfied(resultsEndpoint); logMessagesReceived(resultsEndpoint); } @Override
protected void addFunktionFlows(Funktion funktion) {
funktionio/funktion-connectors
funktion-runtime/src/main/java/io/fabric8/funktion/runtime/components/json/JsonEndpoint.java
// Path: funktion-model/src/main/java/io/fabric8/funktion/support/Strings.java // public class Strings { // // public static boolean isEmpty(String value) { // return value == null || value.length() == 0 || value.trim().length() == 0; // } // // }
import java.util.Arrays; import java.util.HashSet; import java.util.Objects; import java.util.Set; import io.fabric8.funktion.support.Strings; import org.apache.camel.Component; import org.apache.camel.Consumer; import org.apache.camel.Endpoint; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.Processor; import org.apache.camel.Producer; import org.apache.camel.impl.DefaultEndpoint; import org.apache.camel.util.ServiceHelper; import java.io.InputStream; import java.io.Reader; import java.nio.ByteBuffer;
@Override protected void doStart() throws Exception { jsonMarshalEndpoint = getCamelContext().getEndpoint("dataformat:json-jackson:marshal"); Objects.requireNonNull(jsonMarshalEndpoint, "jsonMarshalEndpoint"); jsonMarshalProducer = jsonMarshalEndpoint.createProducer(); Objects.requireNonNull(jsonMarshalProducer, "jsonMarshalProducer"); ServiceHelper.startServices(jsonMarshalEndpoint, jsonMarshalProducer); super.doStart(); } @Override protected void doStop() throws Exception { ServiceHelper.stopServices(jsonMarshalProducer, jsonMarshalEndpoint); super.doStop(); } /** * Lets marshal the body to JSON using Jackson if we require it. * <br> * The current rules are to only marshal to JSON if we don't have a {@link Exchange#CONTENT_TYPE} header. * If we can convert the body to a String then we test if its already JSON and if not we marshal it using the JSON * data format with the Jackson library */ public void jsonMarshalIfRequired(Exchange exchange) throws Exception { Message in = exchange.getIn(); if (in == null) { return; } String contentType = in.getHeader(Exchange.CONTENT_TYPE, String.class);
// Path: funktion-model/src/main/java/io/fabric8/funktion/support/Strings.java // public class Strings { // // public static boolean isEmpty(String value) { // return value == null || value.length() == 0 || value.trim().length() == 0; // } // // } // Path: funktion-runtime/src/main/java/io/fabric8/funktion/runtime/components/json/JsonEndpoint.java import java.util.Arrays; import java.util.HashSet; import java.util.Objects; import java.util.Set; import io.fabric8.funktion.support.Strings; import org.apache.camel.Component; import org.apache.camel.Consumer; import org.apache.camel.Endpoint; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.Processor; import org.apache.camel.Producer; import org.apache.camel.impl.DefaultEndpoint; import org.apache.camel.util.ServiceHelper; import java.io.InputStream; import java.io.Reader; import java.nio.ByteBuffer; @Override protected void doStart() throws Exception { jsonMarshalEndpoint = getCamelContext().getEndpoint("dataformat:json-jackson:marshal"); Objects.requireNonNull(jsonMarshalEndpoint, "jsonMarshalEndpoint"); jsonMarshalProducer = jsonMarshalEndpoint.createProducer(); Objects.requireNonNull(jsonMarshalProducer, "jsonMarshalProducer"); ServiceHelper.startServices(jsonMarshalEndpoint, jsonMarshalProducer); super.doStart(); } @Override protected void doStop() throws Exception { ServiceHelper.stopServices(jsonMarshalProducer, jsonMarshalEndpoint); super.doStop(); } /** * Lets marshal the body to JSON using Jackson if we require it. * <br> * The current rules are to only marshal to JSON if we don't have a {@link Exchange#CONTENT_TYPE} header. * If we can convert the body to a String then we test if its already JSON and if not we marshal it using the JSON * data format with the Jackson library */ public void jsonMarshalIfRequired(Exchange exchange) throws Exception { Message in = exchange.getIn(); if (in == null) { return; } String contentType = in.getHeader(Exchange.CONTENT_TYPE, String.class);
if (!Strings.isEmpty(contentType)) {
funktionio/funktion-connectors
funktion-model/src/test/java/io/fabric8/funktion/model/FunktionAssertions.java
// Path: funktion-model/src/main/java/io/fabric8/funktion/model/steps/Endpoint.java // public class Endpoint extends Step { // private String uri; // // public Endpoint() { // super(StepKinds.ENDPOINT); // } // // public Endpoint(String uri) { // this(); // this.uri = uri; // } // // @Override // public String toString() { // return "Endpoint: " + uri; // } // // public String getUri() { // return uri; // } // // public void setUri(String uri) { // this.uri = uri; // } // // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/model/steps/Function.java // public class Function extends Step { // private String name; // // public Function() { // super(StepKinds.FUNCTION); // } // // public Function(String name) { // this(); // this.name = name; // } // // @Override // public String toString() { // return "Function: " + name; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/model/steps/Step.java // @JsonInclude(JsonInclude.Include.NON_EMPTY) // @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "kind") // @JsonSubTypes({ // @JsonSubTypes.Type(value = Choice.class, name = StepKinds.CHOICE), // @JsonSubTypes.Type(value = Endpoint.class, name = StepKinds.ENDPOINT), // @JsonSubTypes.Type(value = Filter.class, name = StepKinds.FILTER), // @JsonSubTypes.Type(value = Function.class, name = StepKinds.FUNCTION), // @JsonSubTypes.Type(value = Otherwise.class, name = StepKinds.OTHERWISE), // @JsonSubTypes.Type(value = SetBody.class, name = StepKinds.SET_BODY), // @JsonSubTypes.Type(value = SetHeaders.class, name = StepKinds.SET_HEADERS), // @JsonSubTypes.Type(value = Split.class, name = StepKinds.SPLIT), // @JsonSubTypes.Type(value = Throttle.class, name = StepKinds.THROTTLE), // @JsonSubTypes.Type(value = Log.class, name = StepKinds.LOG)} // ) // public abstract class Step { // private String kind; // // public Step() { // } // // public Step(String kind) { // this.kind = kind; // } // // @JsonIgnore // public String getKind() { // return kind; // } // // public void setKind(String kind) { // this.kind = kind; // } // // }
import io.fabric8.funktion.model.steps.Endpoint; import io.fabric8.funktion.model.steps.Function; import io.fabric8.funktion.model.steps.Step; import java.util.List; import static org.assertj.core.api.Assertions.assertThat;
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.fabric8.funktion.model; /** */ public class FunktionAssertions { public static Flow assertFlow(Funktion model, int index) { List<Flow> flows = model.getFlows(); String message = "" + model + " flows"; assertThat(flows).describedAs(message).isNotEmpty(); int size = flows.size(); assertThat(size).describedAs(message + " size").isGreaterThan(index); return flows.get(index); }
// Path: funktion-model/src/main/java/io/fabric8/funktion/model/steps/Endpoint.java // public class Endpoint extends Step { // private String uri; // // public Endpoint() { // super(StepKinds.ENDPOINT); // } // // public Endpoint(String uri) { // this(); // this.uri = uri; // } // // @Override // public String toString() { // return "Endpoint: " + uri; // } // // public String getUri() { // return uri; // } // // public void setUri(String uri) { // this.uri = uri; // } // // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/model/steps/Function.java // public class Function extends Step { // private String name; // // public Function() { // super(StepKinds.FUNCTION); // } // // public Function(String name) { // this(); // this.name = name; // } // // @Override // public String toString() { // return "Function: " + name; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/model/steps/Step.java // @JsonInclude(JsonInclude.Include.NON_EMPTY) // @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "kind") // @JsonSubTypes({ // @JsonSubTypes.Type(value = Choice.class, name = StepKinds.CHOICE), // @JsonSubTypes.Type(value = Endpoint.class, name = StepKinds.ENDPOINT), // @JsonSubTypes.Type(value = Filter.class, name = StepKinds.FILTER), // @JsonSubTypes.Type(value = Function.class, name = StepKinds.FUNCTION), // @JsonSubTypes.Type(value = Otherwise.class, name = StepKinds.OTHERWISE), // @JsonSubTypes.Type(value = SetBody.class, name = StepKinds.SET_BODY), // @JsonSubTypes.Type(value = SetHeaders.class, name = StepKinds.SET_HEADERS), // @JsonSubTypes.Type(value = Split.class, name = StepKinds.SPLIT), // @JsonSubTypes.Type(value = Throttle.class, name = StepKinds.THROTTLE), // @JsonSubTypes.Type(value = Log.class, name = StepKinds.LOG)} // ) // public abstract class Step { // private String kind; // // public Step() { // } // // public Step(String kind) { // this.kind = kind; // } // // @JsonIgnore // public String getKind() { // return kind; // } // // public void setKind(String kind) { // this.kind = kind; // } // // } // Path: funktion-model/src/test/java/io/fabric8/funktion/model/FunktionAssertions.java import io.fabric8.funktion.model.steps.Endpoint; import io.fabric8.funktion.model.steps.Function; import io.fabric8.funktion.model.steps.Step; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.fabric8.funktion.model; /** */ public class FunktionAssertions { public static Flow assertFlow(Funktion model, int index) { List<Flow> flows = model.getFlows(); String message = "" + model + " flows"; assertThat(flows).describedAs(message).isNotEmpty(); int size = flows.size(); assertThat(size).describedAs(message + " size").isGreaterThan(index); return flows.get(index); }
public static Endpoint assertEndpointStep(Flow flow, int index, String expectedUri) {
funktionio/funktion-connectors
funktion-model/src/test/java/io/fabric8/funktion/model/FunktionAssertions.java
// Path: funktion-model/src/main/java/io/fabric8/funktion/model/steps/Endpoint.java // public class Endpoint extends Step { // private String uri; // // public Endpoint() { // super(StepKinds.ENDPOINT); // } // // public Endpoint(String uri) { // this(); // this.uri = uri; // } // // @Override // public String toString() { // return "Endpoint: " + uri; // } // // public String getUri() { // return uri; // } // // public void setUri(String uri) { // this.uri = uri; // } // // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/model/steps/Function.java // public class Function extends Step { // private String name; // // public Function() { // super(StepKinds.FUNCTION); // } // // public Function(String name) { // this(); // this.name = name; // } // // @Override // public String toString() { // return "Function: " + name; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/model/steps/Step.java // @JsonInclude(JsonInclude.Include.NON_EMPTY) // @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "kind") // @JsonSubTypes({ // @JsonSubTypes.Type(value = Choice.class, name = StepKinds.CHOICE), // @JsonSubTypes.Type(value = Endpoint.class, name = StepKinds.ENDPOINT), // @JsonSubTypes.Type(value = Filter.class, name = StepKinds.FILTER), // @JsonSubTypes.Type(value = Function.class, name = StepKinds.FUNCTION), // @JsonSubTypes.Type(value = Otherwise.class, name = StepKinds.OTHERWISE), // @JsonSubTypes.Type(value = SetBody.class, name = StepKinds.SET_BODY), // @JsonSubTypes.Type(value = SetHeaders.class, name = StepKinds.SET_HEADERS), // @JsonSubTypes.Type(value = Split.class, name = StepKinds.SPLIT), // @JsonSubTypes.Type(value = Throttle.class, name = StepKinds.THROTTLE), // @JsonSubTypes.Type(value = Log.class, name = StepKinds.LOG)} // ) // public abstract class Step { // private String kind; // // public Step() { // } // // public Step(String kind) { // this.kind = kind; // } // // @JsonIgnore // public String getKind() { // return kind; // } // // public void setKind(String kind) { // this.kind = kind; // } // // }
import io.fabric8.funktion.model.steps.Endpoint; import io.fabric8.funktion.model.steps.Function; import io.fabric8.funktion.model.steps.Step; import java.util.List; import static org.assertj.core.api.Assertions.assertThat;
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.fabric8.funktion.model; /** */ public class FunktionAssertions { public static Flow assertFlow(Funktion model, int index) { List<Flow> flows = model.getFlows(); String message = "" + model + " flows"; assertThat(flows).describedAs(message).isNotEmpty(); int size = flows.size(); assertThat(size).describedAs(message + " size").isGreaterThan(index); return flows.get(index); } public static Endpoint assertEndpointStep(Flow flow, int index, String expectedUri) { Endpoint step = assertFlowHasStep(flow, index, Endpoint.class); assertThat(step.getUri()).describedAs("flow " + flow + " step " + index + " endpoint " + step + " URI").isEqualTo(expectedUri); assertThat(step.getKind()).describedAs("flow " + flow + " step " + index + " endpoint " + step + " kind").isEqualTo(StepKinds.ENDPOINT); return step; }
// Path: funktion-model/src/main/java/io/fabric8/funktion/model/steps/Endpoint.java // public class Endpoint extends Step { // private String uri; // // public Endpoint() { // super(StepKinds.ENDPOINT); // } // // public Endpoint(String uri) { // this(); // this.uri = uri; // } // // @Override // public String toString() { // return "Endpoint: " + uri; // } // // public String getUri() { // return uri; // } // // public void setUri(String uri) { // this.uri = uri; // } // // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/model/steps/Function.java // public class Function extends Step { // private String name; // // public Function() { // super(StepKinds.FUNCTION); // } // // public Function(String name) { // this(); // this.name = name; // } // // @Override // public String toString() { // return "Function: " + name; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/model/steps/Step.java // @JsonInclude(JsonInclude.Include.NON_EMPTY) // @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "kind") // @JsonSubTypes({ // @JsonSubTypes.Type(value = Choice.class, name = StepKinds.CHOICE), // @JsonSubTypes.Type(value = Endpoint.class, name = StepKinds.ENDPOINT), // @JsonSubTypes.Type(value = Filter.class, name = StepKinds.FILTER), // @JsonSubTypes.Type(value = Function.class, name = StepKinds.FUNCTION), // @JsonSubTypes.Type(value = Otherwise.class, name = StepKinds.OTHERWISE), // @JsonSubTypes.Type(value = SetBody.class, name = StepKinds.SET_BODY), // @JsonSubTypes.Type(value = SetHeaders.class, name = StepKinds.SET_HEADERS), // @JsonSubTypes.Type(value = Split.class, name = StepKinds.SPLIT), // @JsonSubTypes.Type(value = Throttle.class, name = StepKinds.THROTTLE), // @JsonSubTypes.Type(value = Log.class, name = StepKinds.LOG)} // ) // public abstract class Step { // private String kind; // // public Step() { // } // // public Step(String kind) { // this.kind = kind; // } // // @JsonIgnore // public String getKind() { // return kind; // } // // public void setKind(String kind) { // this.kind = kind; // } // // } // Path: funktion-model/src/test/java/io/fabric8/funktion/model/FunktionAssertions.java import io.fabric8.funktion.model.steps.Endpoint; import io.fabric8.funktion.model.steps.Function; import io.fabric8.funktion.model.steps.Step; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.fabric8.funktion.model; /** */ public class FunktionAssertions { public static Flow assertFlow(Funktion model, int index) { List<Flow> flows = model.getFlows(); String message = "" + model + " flows"; assertThat(flows).describedAs(message).isNotEmpty(); int size = flows.size(); assertThat(size).describedAs(message + " size").isGreaterThan(index); return flows.get(index); } public static Endpoint assertEndpointStep(Flow flow, int index, String expectedUri) { Endpoint step = assertFlowHasStep(flow, index, Endpoint.class); assertThat(step.getUri()).describedAs("flow " + flow + " step " + index + " endpoint " + step + " URI").isEqualTo(expectedUri); assertThat(step.getKind()).describedAs("flow " + flow + " step " + index + " endpoint " + step + " kind").isEqualTo(StepKinds.ENDPOINT); return step; }
public static Function assertFunctionStep(Flow flow, int index, String expectedName) {
funktionio/funktion-connectors
funktion-model/src/test/java/io/fabric8/funktion/model/FunktionAssertions.java
// Path: funktion-model/src/main/java/io/fabric8/funktion/model/steps/Endpoint.java // public class Endpoint extends Step { // private String uri; // // public Endpoint() { // super(StepKinds.ENDPOINT); // } // // public Endpoint(String uri) { // this(); // this.uri = uri; // } // // @Override // public String toString() { // return "Endpoint: " + uri; // } // // public String getUri() { // return uri; // } // // public void setUri(String uri) { // this.uri = uri; // } // // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/model/steps/Function.java // public class Function extends Step { // private String name; // // public Function() { // super(StepKinds.FUNCTION); // } // // public Function(String name) { // this(); // this.name = name; // } // // @Override // public String toString() { // return "Function: " + name; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/model/steps/Step.java // @JsonInclude(JsonInclude.Include.NON_EMPTY) // @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "kind") // @JsonSubTypes({ // @JsonSubTypes.Type(value = Choice.class, name = StepKinds.CHOICE), // @JsonSubTypes.Type(value = Endpoint.class, name = StepKinds.ENDPOINT), // @JsonSubTypes.Type(value = Filter.class, name = StepKinds.FILTER), // @JsonSubTypes.Type(value = Function.class, name = StepKinds.FUNCTION), // @JsonSubTypes.Type(value = Otherwise.class, name = StepKinds.OTHERWISE), // @JsonSubTypes.Type(value = SetBody.class, name = StepKinds.SET_BODY), // @JsonSubTypes.Type(value = SetHeaders.class, name = StepKinds.SET_HEADERS), // @JsonSubTypes.Type(value = Split.class, name = StepKinds.SPLIT), // @JsonSubTypes.Type(value = Throttle.class, name = StepKinds.THROTTLE), // @JsonSubTypes.Type(value = Log.class, name = StepKinds.LOG)} // ) // public abstract class Step { // private String kind; // // public Step() { // } // // public Step(String kind) { // this.kind = kind; // } // // @JsonIgnore // public String getKind() { // return kind; // } // // public void setKind(String kind) { // this.kind = kind; // } // // }
import io.fabric8.funktion.model.steps.Endpoint; import io.fabric8.funktion.model.steps.Function; import io.fabric8.funktion.model.steps.Step; import java.util.List; import static org.assertj.core.api.Assertions.assertThat;
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.fabric8.funktion.model; /** */ public class FunktionAssertions { public static Flow assertFlow(Funktion model, int index) { List<Flow> flows = model.getFlows(); String message = "" + model + " flows"; assertThat(flows).describedAs(message).isNotEmpty(); int size = flows.size(); assertThat(size).describedAs(message + " size").isGreaterThan(index); return flows.get(index); } public static Endpoint assertEndpointStep(Flow flow, int index, String expectedUri) { Endpoint step = assertFlowHasStep(flow, index, Endpoint.class); assertThat(step.getUri()).describedAs("flow " + flow + " step " + index + " endpoint " + step + " URI").isEqualTo(expectedUri); assertThat(step.getKind()).describedAs("flow " + flow + " step " + index + " endpoint " + step + " kind").isEqualTo(StepKinds.ENDPOINT); return step; } public static Function assertFunctionStep(Flow flow, int index, String expectedName) { Function step = assertFlowHasStep(flow, index, Function.class); assertThat(step.getName()).describedAs("flow " + flow + " step " + index + " endpoint " + step + " name").isEqualTo(expectedName); assertThat(step.getKind()).describedAs("flow " + flow + " step " + index + " endpoint " + step + " kind").isEqualTo(StepKinds.FUNCTION); return step; } /** * Asserts that the given flow has a step at the given index of the given type */
// Path: funktion-model/src/main/java/io/fabric8/funktion/model/steps/Endpoint.java // public class Endpoint extends Step { // private String uri; // // public Endpoint() { // super(StepKinds.ENDPOINT); // } // // public Endpoint(String uri) { // this(); // this.uri = uri; // } // // @Override // public String toString() { // return "Endpoint: " + uri; // } // // public String getUri() { // return uri; // } // // public void setUri(String uri) { // this.uri = uri; // } // // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/model/steps/Function.java // public class Function extends Step { // private String name; // // public Function() { // super(StepKinds.FUNCTION); // } // // public Function(String name) { // this(); // this.name = name; // } // // @Override // public String toString() { // return "Function: " + name; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/model/steps/Step.java // @JsonInclude(JsonInclude.Include.NON_EMPTY) // @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "kind") // @JsonSubTypes({ // @JsonSubTypes.Type(value = Choice.class, name = StepKinds.CHOICE), // @JsonSubTypes.Type(value = Endpoint.class, name = StepKinds.ENDPOINT), // @JsonSubTypes.Type(value = Filter.class, name = StepKinds.FILTER), // @JsonSubTypes.Type(value = Function.class, name = StepKinds.FUNCTION), // @JsonSubTypes.Type(value = Otherwise.class, name = StepKinds.OTHERWISE), // @JsonSubTypes.Type(value = SetBody.class, name = StepKinds.SET_BODY), // @JsonSubTypes.Type(value = SetHeaders.class, name = StepKinds.SET_HEADERS), // @JsonSubTypes.Type(value = Split.class, name = StepKinds.SPLIT), // @JsonSubTypes.Type(value = Throttle.class, name = StepKinds.THROTTLE), // @JsonSubTypes.Type(value = Log.class, name = StepKinds.LOG)} // ) // public abstract class Step { // private String kind; // // public Step() { // } // // public Step(String kind) { // this.kind = kind; // } // // @JsonIgnore // public String getKind() { // return kind; // } // // public void setKind(String kind) { // this.kind = kind; // } // // } // Path: funktion-model/src/test/java/io/fabric8/funktion/model/FunktionAssertions.java import io.fabric8.funktion.model.steps.Endpoint; import io.fabric8.funktion.model.steps.Function; import io.fabric8.funktion.model.steps.Step; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.fabric8.funktion.model; /** */ public class FunktionAssertions { public static Flow assertFlow(Funktion model, int index) { List<Flow> flows = model.getFlows(); String message = "" + model + " flows"; assertThat(flows).describedAs(message).isNotEmpty(); int size = flows.size(); assertThat(size).describedAs(message + " size").isGreaterThan(index); return flows.get(index); } public static Endpoint assertEndpointStep(Flow flow, int index, String expectedUri) { Endpoint step = assertFlowHasStep(flow, index, Endpoint.class); assertThat(step.getUri()).describedAs("flow " + flow + " step " + index + " endpoint " + step + " URI").isEqualTo(expectedUri); assertThat(step.getKind()).describedAs("flow " + flow + " step " + index + " endpoint " + step + " kind").isEqualTo(StepKinds.ENDPOINT); return step; } public static Function assertFunctionStep(Flow flow, int index, String expectedName) { Function step = assertFlowHasStep(flow, index, Function.class); assertThat(step.getName()).describedAs("flow " + flow + " step " + index + " endpoint " + step + " name").isEqualTo(expectedName); assertThat(step.getKind()).describedAs("flow " + flow + " step " + index + " endpoint " + step + " kind").isEqualTo(StepKinds.FUNCTION); return step; } /** * Asserts that the given flow has a step at the given index of the given type */
public static <T extends Step> T assertFlowHasStep(Flow flow, int index, Class<T> clazz) {
funktionio/funktion-connectors
funktion-agent/src/main/java/io/fabric8/funktion/agent/Agent.java
// Path: funktion-model/src/main/java/io/fabric8/funktion/DataKeys.java // public class DataKeys { // public static class Connector { // public static final String SCHEMA_YAML = "schema.yml"; // public static final String ASCIIDOC = "documentation.adoc"; // public static final String DEPLOYMENT_YAML = "deployment.yml"; // public static final String APPLICATION_PROPERTIES = Subscription.APPLICATION_PROPERTIES; // } // // public static class Subscription { // public static final String APPLICATION_PROPERTIES = "application.properties"; // public static final String FUNKTION_YAML = "funktion.yml"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public class Labels { // public static final String KIND = "funktion.fabric8.io/kind"; // public static final String CONNECTOR = "connector"; // // public static class Kind { // public static final String CONNECTOR = "Connector"; // public static final String SUBSCRIPTION = "Subscription"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/model/Funktion.java // public class Funktion extends DtoSupport { // private List<Flow> flows = new ArrayList<>(); // // public List<Flow> getFlows() { // return flows; // } // // public void setFlows(List<Flow> flows) { // this.flows = flows; // } // // public Flow createFlow() { // return addFlow(new Flow()); // } // // public Flow addFlow(Flow flow) { // flows.add(flow); // return flow; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/ApplicationProperties.java // public static String toPropertiesString(Map<String, String> applicationProperties, String comments) throws IOException { // Properties properties = toProperties(applicationProperties); // StringWriter writer = new StringWriter(); // properties.store(writer, comments); // return writer.toString(); // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public static final String SUBSCRIPTION = "Subscription"; // // Path: funktion-model/src/main/java/io/fabric8/funktion/support/YamlHelper.java // public static ObjectMapper createYamlMapper() { // ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory() // .configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true) // .configure(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS, true) // .configure(YAMLGenerator.Feature.USE_NATIVE_OBJECT_ID, false) // .configure(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID, false) // ); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY). // enable(SerializationFeature.INDENT_OUTPUT). // disable(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS). // disable(SerializationFeature.WRITE_NULL_MAP_VALUES); // return objectMapper; // // }
import com.fasterxml.jackson.core.JsonProcessingException; import io.fabric8.funktion.DataKeys; import io.fabric8.funktion.Labels; import io.fabric8.funktion.model.Funktion; import io.fabric8.kubernetes.api.KubernetesHelper; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ConfigMapBuilder; import io.fabric8.kubernetes.api.model.ConfigMapList; import io.fabric8.kubernetes.client.DefaultKubernetesClient; import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.utils.Objects; import io.fabric8.utils.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import static io.fabric8.funktion.ApplicationProperties.toPropertiesString; import static io.fabric8.funktion.Labels.Kind.SUBSCRIPTION; import static io.fabric8.funktion.support.YamlHelper.createYamlMapper; import static io.fabric8.utils.Lists.notNullList;
Objects.notNull(namespace, "namespace"); ConfigMap configMap = createSubscriptionResource(request, namespace); kubernetesClient.configMaps().inNamespace(namespace).create(configMap); return new SubscribeResponse(namespace, KubernetesHelper.getName(configMap)); } public void unsubscribe(String namespace, String name) { kubernetesClient.configMaps().inNamespace(namespace).withName(name).delete(); } public String getCurrentNamespace() { String answer = kubernetesClient.getNamespace(); if (Strings.isNullOrBlank(answer)) { answer = KubernetesHelper.defaultNamespace(); } if (Strings.isNullOrBlank(answer)) { answer = System.getenv("KUBERNETES_NAMESPACE"); } if (Strings.isNullOrBlank(answer)) { answer = "default"; } return answer; } protected ConfigMap createSubscriptionResource(SubscribeRequest request, String namespace) throws InternalException { Map<String, String> annotations = new LinkedHashMap<>(); Map<String, String> data = new LinkedHashMap<>(); Map<String, String> labels = new HashMap<>();
// Path: funktion-model/src/main/java/io/fabric8/funktion/DataKeys.java // public class DataKeys { // public static class Connector { // public static final String SCHEMA_YAML = "schema.yml"; // public static final String ASCIIDOC = "documentation.adoc"; // public static final String DEPLOYMENT_YAML = "deployment.yml"; // public static final String APPLICATION_PROPERTIES = Subscription.APPLICATION_PROPERTIES; // } // // public static class Subscription { // public static final String APPLICATION_PROPERTIES = "application.properties"; // public static final String FUNKTION_YAML = "funktion.yml"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public class Labels { // public static final String KIND = "funktion.fabric8.io/kind"; // public static final String CONNECTOR = "connector"; // // public static class Kind { // public static final String CONNECTOR = "Connector"; // public static final String SUBSCRIPTION = "Subscription"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/model/Funktion.java // public class Funktion extends DtoSupport { // private List<Flow> flows = new ArrayList<>(); // // public List<Flow> getFlows() { // return flows; // } // // public void setFlows(List<Flow> flows) { // this.flows = flows; // } // // public Flow createFlow() { // return addFlow(new Flow()); // } // // public Flow addFlow(Flow flow) { // flows.add(flow); // return flow; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/ApplicationProperties.java // public static String toPropertiesString(Map<String, String> applicationProperties, String comments) throws IOException { // Properties properties = toProperties(applicationProperties); // StringWriter writer = new StringWriter(); // properties.store(writer, comments); // return writer.toString(); // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public static final String SUBSCRIPTION = "Subscription"; // // Path: funktion-model/src/main/java/io/fabric8/funktion/support/YamlHelper.java // public static ObjectMapper createYamlMapper() { // ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory() // .configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true) // .configure(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS, true) // .configure(YAMLGenerator.Feature.USE_NATIVE_OBJECT_ID, false) // .configure(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID, false) // ); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY). // enable(SerializationFeature.INDENT_OUTPUT). // disable(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS). // disable(SerializationFeature.WRITE_NULL_MAP_VALUES); // return objectMapper; // // } // Path: funktion-agent/src/main/java/io/fabric8/funktion/agent/Agent.java import com.fasterxml.jackson.core.JsonProcessingException; import io.fabric8.funktion.DataKeys; import io.fabric8.funktion.Labels; import io.fabric8.funktion.model.Funktion; import io.fabric8.kubernetes.api.KubernetesHelper; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ConfigMapBuilder; import io.fabric8.kubernetes.api.model.ConfigMapList; import io.fabric8.kubernetes.client.DefaultKubernetesClient; import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.utils.Objects; import io.fabric8.utils.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import static io.fabric8.funktion.ApplicationProperties.toPropertiesString; import static io.fabric8.funktion.Labels.Kind.SUBSCRIPTION; import static io.fabric8.funktion.support.YamlHelper.createYamlMapper; import static io.fabric8.utils.Lists.notNullList; Objects.notNull(namespace, "namespace"); ConfigMap configMap = createSubscriptionResource(request, namespace); kubernetesClient.configMaps().inNamespace(namespace).create(configMap); return new SubscribeResponse(namespace, KubernetesHelper.getName(configMap)); } public void unsubscribe(String namespace, String name) { kubernetesClient.configMaps().inNamespace(namespace).withName(name).delete(); } public String getCurrentNamespace() { String answer = kubernetesClient.getNamespace(); if (Strings.isNullOrBlank(answer)) { answer = KubernetesHelper.defaultNamespace(); } if (Strings.isNullOrBlank(answer)) { answer = System.getenv("KUBERNETES_NAMESPACE"); } if (Strings.isNullOrBlank(answer)) { answer = "default"; } return answer; } protected ConfigMap createSubscriptionResource(SubscribeRequest request, String namespace) throws InternalException { Map<String, String> annotations = new LinkedHashMap<>(); Map<String, String> data = new LinkedHashMap<>(); Map<String, String> labels = new HashMap<>();
labels.put(Labels.KIND, SUBSCRIPTION);
funktionio/funktion-connectors
funktion-agent/src/main/java/io/fabric8/funktion/agent/Agent.java
// Path: funktion-model/src/main/java/io/fabric8/funktion/DataKeys.java // public class DataKeys { // public static class Connector { // public static final String SCHEMA_YAML = "schema.yml"; // public static final String ASCIIDOC = "documentation.adoc"; // public static final String DEPLOYMENT_YAML = "deployment.yml"; // public static final String APPLICATION_PROPERTIES = Subscription.APPLICATION_PROPERTIES; // } // // public static class Subscription { // public static final String APPLICATION_PROPERTIES = "application.properties"; // public static final String FUNKTION_YAML = "funktion.yml"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public class Labels { // public static final String KIND = "funktion.fabric8.io/kind"; // public static final String CONNECTOR = "connector"; // // public static class Kind { // public static final String CONNECTOR = "Connector"; // public static final String SUBSCRIPTION = "Subscription"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/model/Funktion.java // public class Funktion extends DtoSupport { // private List<Flow> flows = new ArrayList<>(); // // public List<Flow> getFlows() { // return flows; // } // // public void setFlows(List<Flow> flows) { // this.flows = flows; // } // // public Flow createFlow() { // return addFlow(new Flow()); // } // // public Flow addFlow(Flow flow) { // flows.add(flow); // return flow; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/ApplicationProperties.java // public static String toPropertiesString(Map<String, String> applicationProperties, String comments) throws IOException { // Properties properties = toProperties(applicationProperties); // StringWriter writer = new StringWriter(); // properties.store(writer, comments); // return writer.toString(); // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public static final String SUBSCRIPTION = "Subscription"; // // Path: funktion-model/src/main/java/io/fabric8/funktion/support/YamlHelper.java // public static ObjectMapper createYamlMapper() { // ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory() // .configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true) // .configure(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS, true) // .configure(YAMLGenerator.Feature.USE_NATIVE_OBJECT_ID, false) // .configure(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID, false) // ); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY). // enable(SerializationFeature.INDENT_OUTPUT). // disable(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS). // disable(SerializationFeature.WRITE_NULL_MAP_VALUES); // return objectMapper; // // }
import com.fasterxml.jackson.core.JsonProcessingException; import io.fabric8.funktion.DataKeys; import io.fabric8.funktion.Labels; import io.fabric8.funktion.model.Funktion; import io.fabric8.kubernetes.api.KubernetesHelper; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ConfigMapBuilder; import io.fabric8.kubernetes.api.model.ConfigMapList; import io.fabric8.kubernetes.client.DefaultKubernetesClient; import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.utils.Objects; import io.fabric8.utils.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import static io.fabric8.funktion.ApplicationProperties.toPropertiesString; import static io.fabric8.funktion.Labels.Kind.SUBSCRIPTION; import static io.fabric8.funktion.support.YamlHelper.createYamlMapper; import static io.fabric8.utils.Lists.notNullList;
Objects.notNull(namespace, "namespace"); ConfigMap configMap = createSubscriptionResource(request, namespace); kubernetesClient.configMaps().inNamespace(namespace).create(configMap); return new SubscribeResponse(namespace, KubernetesHelper.getName(configMap)); } public void unsubscribe(String namespace, String name) { kubernetesClient.configMaps().inNamespace(namespace).withName(name).delete(); } public String getCurrentNamespace() { String answer = kubernetesClient.getNamespace(); if (Strings.isNullOrBlank(answer)) { answer = KubernetesHelper.defaultNamespace(); } if (Strings.isNullOrBlank(answer)) { answer = System.getenv("KUBERNETES_NAMESPACE"); } if (Strings.isNullOrBlank(answer)) { answer = "default"; } return answer; } protected ConfigMap createSubscriptionResource(SubscribeRequest request, String namespace) throws InternalException { Map<String, String> annotations = new LinkedHashMap<>(); Map<String, String> data = new LinkedHashMap<>(); Map<String, String> labels = new HashMap<>();
// Path: funktion-model/src/main/java/io/fabric8/funktion/DataKeys.java // public class DataKeys { // public static class Connector { // public static final String SCHEMA_YAML = "schema.yml"; // public static final String ASCIIDOC = "documentation.adoc"; // public static final String DEPLOYMENT_YAML = "deployment.yml"; // public static final String APPLICATION_PROPERTIES = Subscription.APPLICATION_PROPERTIES; // } // // public static class Subscription { // public static final String APPLICATION_PROPERTIES = "application.properties"; // public static final String FUNKTION_YAML = "funktion.yml"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public class Labels { // public static final String KIND = "funktion.fabric8.io/kind"; // public static final String CONNECTOR = "connector"; // // public static class Kind { // public static final String CONNECTOR = "Connector"; // public static final String SUBSCRIPTION = "Subscription"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/model/Funktion.java // public class Funktion extends DtoSupport { // private List<Flow> flows = new ArrayList<>(); // // public List<Flow> getFlows() { // return flows; // } // // public void setFlows(List<Flow> flows) { // this.flows = flows; // } // // public Flow createFlow() { // return addFlow(new Flow()); // } // // public Flow addFlow(Flow flow) { // flows.add(flow); // return flow; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/ApplicationProperties.java // public static String toPropertiesString(Map<String, String> applicationProperties, String comments) throws IOException { // Properties properties = toProperties(applicationProperties); // StringWriter writer = new StringWriter(); // properties.store(writer, comments); // return writer.toString(); // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public static final String SUBSCRIPTION = "Subscription"; // // Path: funktion-model/src/main/java/io/fabric8/funktion/support/YamlHelper.java // public static ObjectMapper createYamlMapper() { // ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory() // .configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true) // .configure(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS, true) // .configure(YAMLGenerator.Feature.USE_NATIVE_OBJECT_ID, false) // .configure(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID, false) // ); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY). // enable(SerializationFeature.INDENT_OUTPUT). // disable(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS). // disable(SerializationFeature.WRITE_NULL_MAP_VALUES); // return objectMapper; // // } // Path: funktion-agent/src/main/java/io/fabric8/funktion/agent/Agent.java import com.fasterxml.jackson.core.JsonProcessingException; import io.fabric8.funktion.DataKeys; import io.fabric8.funktion.Labels; import io.fabric8.funktion.model.Funktion; import io.fabric8.kubernetes.api.KubernetesHelper; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ConfigMapBuilder; import io.fabric8.kubernetes.api.model.ConfigMapList; import io.fabric8.kubernetes.client.DefaultKubernetesClient; import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.utils.Objects; import io.fabric8.utils.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import static io.fabric8.funktion.ApplicationProperties.toPropertiesString; import static io.fabric8.funktion.Labels.Kind.SUBSCRIPTION; import static io.fabric8.funktion.support.YamlHelper.createYamlMapper; import static io.fabric8.utils.Lists.notNullList; Objects.notNull(namespace, "namespace"); ConfigMap configMap = createSubscriptionResource(request, namespace); kubernetesClient.configMaps().inNamespace(namespace).create(configMap); return new SubscribeResponse(namespace, KubernetesHelper.getName(configMap)); } public void unsubscribe(String namespace, String name) { kubernetesClient.configMaps().inNamespace(namespace).withName(name).delete(); } public String getCurrentNamespace() { String answer = kubernetesClient.getNamespace(); if (Strings.isNullOrBlank(answer)) { answer = KubernetesHelper.defaultNamespace(); } if (Strings.isNullOrBlank(answer)) { answer = System.getenv("KUBERNETES_NAMESPACE"); } if (Strings.isNullOrBlank(answer)) { answer = "default"; } return answer; } protected ConfigMap createSubscriptionResource(SubscribeRequest request, String namespace) throws InternalException { Map<String, String> annotations = new LinkedHashMap<>(); Map<String, String> data = new LinkedHashMap<>(); Map<String, String> labels = new HashMap<>();
labels.put(Labels.KIND, SUBSCRIPTION);
funktionio/funktion-connectors
funktion-agent/src/main/java/io/fabric8/funktion/agent/Agent.java
// Path: funktion-model/src/main/java/io/fabric8/funktion/DataKeys.java // public class DataKeys { // public static class Connector { // public static final String SCHEMA_YAML = "schema.yml"; // public static final String ASCIIDOC = "documentation.adoc"; // public static final String DEPLOYMENT_YAML = "deployment.yml"; // public static final String APPLICATION_PROPERTIES = Subscription.APPLICATION_PROPERTIES; // } // // public static class Subscription { // public static final String APPLICATION_PROPERTIES = "application.properties"; // public static final String FUNKTION_YAML = "funktion.yml"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public class Labels { // public static final String KIND = "funktion.fabric8.io/kind"; // public static final String CONNECTOR = "connector"; // // public static class Kind { // public static final String CONNECTOR = "Connector"; // public static final String SUBSCRIPTION = "Subscription"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/model/Funktion.java // public class Funktion extends DtoSupport { // private List<Flow> flows = new ArrayList<>(); // // public List<Flow> getFlows() { // return flows; // } // // public void setFlows(List<Flow> flows) { // this.flows = flows; // } // // public Flow createFlow() { // return addFlow(new Flow()); // } // // public Flow addFlow(Flow flow) { // flows.add(flow); // return flow; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/ApplicationProperties.java // public static String toPropertiesString(Map<String, String> applicationProperties, String comments) throws IOException { // Properties properties = toProperties(applicationProperties); // StringWriter writer = new StringWriter(); // properties.store(writer, comments); // return writer.toString(); // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public static final String SUBSCRIPTION = "Subscription"; // // Path: funktion-model/src/main/java/io/fabric8/funktion/support/YamlHelper.java // public static ObjectMapper createYamlMapper() { // ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory() // .configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true) // .configure(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS, true) // .configure(YAMLGenerator.Feature.USE_NATIVE_OBJECT_ID, false) // .configure(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID, false) // ); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY). // enable(SerializationFeature.INDENT_OUTPUT). // disable(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS). // disable(SerializationFeature.WRITE_NULL_MAP_VALUES); // return objectMapper; // // }
import com.fasterxml.jackson.core.JsonProcessingException; import io.fabric8.funktion.DataKeys; import io.fabric8.funktion.Labels; import io.fabric8.funktion.model.Funktion; import io.fabric8.kubernetes.api.KubernetesHelper; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ConfigMapBuilder; import io.fabric8.kubernetes.api.model.ConfigMapList; import io.fabric8.kubernetes.client.DefaultKubernetesClient; import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.utils.Objects; import io.fabric8.utils.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import static io.fabric8.funktion.ApplicationProperties.toPropertiesString; import static io.fabric8.funktion.Labels.Kind.SUBSCRIPTION; import static io.fabric8.funktion.support.YamlHelper.createYamlMapper; import static io.fabric8.utils.Lists.notNullList;
} public String getCurrentNamespace() { String answer = kubernetesClient.getNamespace(); if (Strings.isNullOrBlank(answer)) { answer = KubernetesHelper.defaultNamespace(); } if (Strings.isNullOrBlank(answer)) { answer = System.getenv("KUBERNETES_NAMESPACE"); } if (Strings.isNullOrBlank(answer)) { answer = "default"; } return answer; } protected ConfigMap createSubscriptionResource(SubscribeRequest request, String namespace) throws InternalException { Map<String, String> annotations = new LinkedHashMap<>(); Map<String, String> data = new LinkedHashMap<>(); Map<String, String> labels = new HashMap<>(); labels.put(Labels.KIND, SUBSCRIPTION); String connectorName = request.findConnectorName(); String namePrefix = "design"; if (Strings.isNotBlank(connectorName)) { namePrefix += "-" + connectorName; labels.put(Labels.CONNECTOR, connectorName); } String name = createSubscriptionName(request, namespace, namePrefix);
// Path: funktion-model/src/main/java/io/fabric8/funktion/DataKeys.java // public class DataKeys { // public static class Connector { // public static final String SCHEMA_YAML = "schema.yml"; // public static final String ASCIIDOC = "documentation.adoc"; // public static final String DEPLOYMENT_YAML = "deployment.yml"; // public static final String APPLICATION_PROPERTIES = Subscription.APPLICATION_PROPERTIES; // } // // public static class Subscription { // public static final String APPLICATION_PROPERTIES = "application.properties"; // public static final String FUNKTION_YAML = "funktion.yml"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public class Labels { // public static final String KIND = "funktion.fabric8.io/kind"; // public static final String CONNECTOR = "connector"; // // public static class Kind { // public static final String CONNECTOR = "Connector"; // public static final String SUBSCRIPTION = "Subscription"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/model/Funktion.java // public class Funktion extends DtoSupport { // private List<Flow> flows = new ArrayList<>(); // // public List<Flow> getFlows() { // return flows; // } // // public void setFlows(List<Flow> flows) { // this.flows = flows; // } // // public Flow createFlow() { // return addFlow(new Flow()); // } // // public Flow addFlow(Flow flow) { // flows.add(flow); // return flow; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/ApplicationProperties.java // public static String toPropertiesString(Map<String, String> applicationProperties, String comments) throws IOException { // Properties properties = toProperties(applicationProperties); // StringWriter writer = new StringWriter(); // properties.store(writer, comments); // return writer.toString(); // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public static final String SUBSCRIPTION = "Subscription"; // // Path: funktion-model/src/main/java/io/fabric8/funktion/support/YamlHelper.java // public static ObjectMapper createYamlMapper() { // ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory() // .configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true) // .configure(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS, true) // .configure(YAMLGenerator.Feature.USE_NATIVE_OBJECT_ID, false) // .configure(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID, false) // ); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY). // enable(SerializationFeature.INDENT_OUTPUT). // disable(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS). // disable(SerializationFeature.WRITE_NULL_MAP_VALUES); // return objectMapper; // // } // Path: funktion-agent/src/main/java/io/fabric8/funktion/agent/Agent.java import com.fasterxml.jackson.core.JsonProcessingException; import io.fabric8.funktion.DataKeys; import io.fabric8.funktion.Labels; import io.fabric8.funktion.model.Funktion; import io.fabric8.kubernetes.api.KubernetesHelper; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ConfigMapBuilder; import io.fabric8.kubernetes.api.model.ConfigMapList; import io.fabric8.kubernetes.client.DefaultKubernetesClient; import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.utils.Objects; import io.fabric8.utils.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import static io.fabric8.funktion.ApplicationProperties.toPropertiesString; import static io.fabric8.funktion.Labels.Kind.SUBSCRIPTION; import static io.fabric8.funktion.support.YamlHelper.createYamlMapper; import static io.fabric8.utils.Lists.notNullList; } public String getCurrentNamespace() { String answer = kubernetesClient.getNamespace(); if (Strings.isNullOrBlank(answer)) { answer = KubernetesHelper.defaultNamespace(); } if (Strings.isNullOrBlank(answer)) { answer = System.getenv("KUBERNETES_NAMESPACE"); } if (Strings.isNullOrBlank(answer)) { answer = "default"; } return answer; } protected ConfigMap createSubscriptionResource(SubscribeRequest request, String namespace) throws InternalException { Map<String, String> annotations = new LinkedHashMap<>(); Map<String, String> data = new LinkedHashMap<>(); Map<String, String> labels = new HashMap<>(); labels.put(Labels.KIND, SUBSCRIPTION); String connectorName = request.findConnectorName(); String namePrefix = "design"; if (Strings.isNotBlank(connectorName)) { namePrefix += "-" + connectorName; labels.put(Labels.CONNECTOR, connectorName); } String name = createSubscriptionName(request, namespace, namePrefix);
Funktion funktion = request.getFunktion();
funktionio/funktion-connectors
funktion-agent/src/main/java/io/fabric8/funktion/agent/Agent.java
// Path: funktion-model/src/main/java/io/fabric8/funktion/DataKeys.java // public class DataKeys { // public static class Connector { // public static final String SCHEMA_YAML = "schema.yml"; // public static final String ASCIIDOC = "documentation.adoc"; // public static final String DEPLOYMENT_YAML = "deployment.yml"; // public static final String APPLICATION_PROPERTIES = Subscription.APPLICATION_PROPERTIES; // } // // public static class Subscription { // public static final String APPLICATION_PROPERTIES = "application.properties"; // public static final String FUNKTION_YAML = "funktion.yml"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public class Labels { // public static final String KIND = "funktion.fabric8.io/kind"; // public static final String CONNECTOR = "connector"; // // public static class Kind { // public static final String CONNECTOR = "Connector"; // public static final String SUBSCRIPTION = "Subscription"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/model/Funktion.java // public class Funktion extends DtoSupport { // private List<Flow> flows = new ArrayList<>(); // // public List<Flow> getFlows() { // return flows; // } // // public void setFlows(List<Flow> flows) { // this.flows = flows; // } // // public Flow createFlow() { // return addFlow(new Flow()); // } // // public Flow addFlow(Flow flow) { // flows.add(flow); // return flow; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/ApplicationProperties.java // public static String toPropertiesString(Map<String, String> applicationProperties, String comments) throws IOException { // Properties properties = toProperties(applicationProperties); // StringWriter writer = new StringWriter(); // properties.store(writer, comments); // return writer.toString(); // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public static final String SUBSCRIPTION = "Subscription"; // // Path: funktion-model/src/main/java/io/fabric8/funktion/support/YamlHelper.java // public static ObjectMapper createYamlMapper() { // ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory() // .configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true) // .configure(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS, true) // .configure(YAMLGenerator.Feature.USE_NATIVE_OBJECT_ID, false) // .configure(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID, false) // ); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY). // enable(SerializationFeature.INDENT_OUTPUT). // disable(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS). // disable(SerializationFeature.WRITE_NULL_MAP_VALUES); // return objectMapper; // // }
import com.fasterxml.jackson.core.JsonProcessingException; import io.fabric8.funktion.DataKeys; import io.fabric8.funktion.Labels; import io.fabric8.funktion.model.Funktion; import io.fabric8.kubernetes.api.KubernetesHelper; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ConfigMapBuilder; import io.fabric8.kubernetes.api.model.ConfigMapList; import io.fabric8.kubernetes.client.DefaultKubernetesClient; import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.utils.Objects; import io.fabric8.utils.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import static io.fabric8.funktion.ApplicationProperties.toPropertiesString; import static io.fabric8.funktion.Labels.Kind.SUBSCRIPTION; import static io.fabric8.funktion.support.YamlHelper.createYamlMapper; import static io.fabric8.utils.Lists.notNullList;
String answer = kubernetesClient.getNamespace(); if (Strings.isNullOrBlank(answer)) { answer = KubernetesHelper.defaultNamespace(); } if (Strings.isNullOrBlank(answer)) { answer = System.getenv("KUBERNETES_NAMESPACE"); } if (Strings.isNullOrBlank(answer)) { answer = "default"; } return answer; } protected ConfigMap createSubscriptionResource(SubscribeRequest request, String namespace) throws InternalException { Map<String, String> annotations = new LinkedHashMap<>(); Map<String, String> data = new LinkedHashMap<>(); Map<String, String> labels = new HashMap<>(); labels.put(Labels.KIND, SUBSCRIPTION); String connectorName = request.findConnectorName(); String namePrefix = "design"; if (Strings.isNotBlank(connectorName)) { namePrefix += "-" + connectorName; labels.put(Labels.CONNECTOR, connectorName); } String name = createSubscriptionName(request, namespace, namePrefix); Funktion funktion = request.getFunktion(); Objects.notNull(funktion, "funktion"); try {
// Path: funktion-model/src/main/java/io/fabric8/funktion/DataKeys.java // public class DataKeys { // public static class Connector { // public static final String SCHEMA_YAML = "schema.yml"; // public static final String ASCIIDOC = "documentation.adoc"; // public static final String DEPLOYMENT_YAML = "deployment.yml"; // public static final String APPLICATION_PROPERTIES = Subscription.APPLICATION_PROPERTIES; // } // // public static class Subscription { // public static final String APPLICATION_PROPERTIES = "application.properties"; // public static final String FUNKTION_YAML = "funktion.yml"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public class Labels { // public static final String KIND = "funktion.fabric8.io/kind"; // public static final String CONNECTOR = "connector"; // // public static class Kind { // public static final String CONNECTOR = "Connector"; // public static final String SUBSCRIPTION = "Subscription"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/model/Funktion.java // public class Funktion extends DtoSupport { // private List<Flow> flows = new ArrayList<>(); // // public List<Flow> getFlows() { // return flows; // } // // public void setFlows(List<Flow> flows) { // this.flows = flows; // } // // public Flow createFlow() { // return addFlow(new Flow()); // } // // public Flow addFlow(Flow flow) { // flows.add(flow); // return flow; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/ApplicationProperties.java // public static String toPropertiesString(Map<String, String> applicationProperties, String comments) throws IOException { // Properties properties = toProperties(applicationProperties); // StringWriter writer = new StringWriter(); // properties.store(writer, comments); // return writer.toString(); // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public static final String SUBSCRIPTION = "Subscription"; // // Path: funktion-model/src/main/java/io/fabric8/funktion/support/YamlHelper.java // public static ObjectMapper createYamlMapper() { // ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory() // .configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true) // .configure(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS, true) // .configure(YAMLGenerator.Feature.USE_NATIVE_OBJECT_ID, false) // .configure(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID, false) // ); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY). // enable(SerializationFeature.INDENT_OUTPUT). // disable(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS). // disable(SerializationFeature.WRITE_NULL_MAP_VALUES); // return objectMapper; // // } // Path: funktion-agent/src/main/java/io/fabric8/funktion/agent/Agent.java import com.fasterxml.jackson.core.JsonProcessingException; import io.fabric8.funktion.DataKeys; import io.fabric8.funktion.Labels; import io.fabric8.funktion.model.Funktion; import io.fabric8.kubernetes.api.KubernetesHelper; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ConfigMapBuilder; import io.fabric8.kubernetes.api.model.ConfigMapList; import io.fabric8.kubernetes.client.DefaultKubernetesClient; import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.utils.Objects; import io.fabric8.utils.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import static io.fabric8.funktion.ApplicationProperties.toPropertiesString; import static io.fabric8.funktion.Labels.Kind.SUBSCRIPTION; import static io.fabric8.funktion.support.YamlHelper.createYamlMapper; import static io.fabric8.utils.Lists.notNullList; String answer = kubernetesClient.getNamespace(); if (Strings.isNullOrBlank(answer)) { answer = KubernetesHelper.defaultNamespace(); } if (Strings.isNullOrBlank(answer)) { answer = System.getenv("KUBERNETES_NAMESPACE"); } if (Strings.isNullOrBlank(answer)) { answer = "default"; } return answer; } protected ConfigMap createSubscriptionResource(SubscribeRequest request, String namespace) throws InternalException { Map<String, String> annotations = new LinkedHashMap<>(); Map<String, String> data = new LinkedHashMap<>(); Map<String, String> labels = new HashMap<>(); labels.put(Labels.KIND, SUBSCRIPTION); String connectorName = request.findConnectorName(); String namePrefix = "design"; if (Strings.isNotBlank(connectorName)) { namePrefix += "-" + connectorName; labels.put(Labels.CONNECTOR, connectorName); } String name = createSubscriptionName(request, namespace, namePrefix); Funktion funktion = request.getFunktion(); Objects.notNull(funktion, "funktion"); try {
String yaml = createYamlMapper().writeValueAsString(funktion);
funktionio/funktion-connectors
funktion-agent/src/main/java/io/fabric8/funktion/agent/Agent.java
// Path: funktion-model/src/main/java/io/fabric8/funktion/DataKeys.java // public class DataKeys { // public static class Connector { // public static final String SCHEMA_YAML = "schema.yml"; // public static final String ASCIIDOC = "documentation.adoc"; // public static final String DEPLOYMENT_YAML = "deployment.yml"; // public static final String APPLICATION_PROPERTIES = Subscription.APPLICATION_PROPERTIES; // } // // public static class Subscription { // public static final String APPLICATION_PROPERTIES = "application.properties"; // public static final String FUNKTION_YAML = "funktion.yml"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public class Labels { // public static final String KIND = "funktion.fabric8.io/kind"; // public static final String CONNECTOR = "connector"; // // public static class Kind { // public static final String CONNECTOR = "Connector"; // public static final String SUBSCRIPTION = "Subscription"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/model/Funktion.java // public class Funktion extends DtoSupport { // private List<Flow> flows = new ArrayList<>(); // // public List<Flow> getFlows() { // return flows; // } // // public void setFlows(List<Flow> flows) { // this.flows = flows; // } // // public Flow createFlow() { // return addFlow(new Flow()); // } // // public Flow addFlow(Flow flow) { // flows.add(flow); // return flow; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/ApplicationProperties.java // public static String toPropertiesString(Map<String, String> applicationProperties, String comments) throws IOException { // Properties properties = toProperties(applicationProperties); // StringWriter writer = new StringWriter(); // properties.store(writer, comments); // return writer.toString(); // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public static final String SUBSCRIPTION = "Subscription"; // // Path: funktion-model/src/main/java/io/fabric8/funktion/support/YamlHelper.java // public static ObjectMapper createYamlMapper() { // ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory() // .configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true) // .configure(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS, true) // .configure(YAMLGenerator.Feature.USE_NATIVE_OBJECT_ID, false) // .configure(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID, false) // ); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY). // enable(SerializationFeature.INDENT_OUTPUT). // disable(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS). // disable(SerializationFeature.WRITE_NULL_MAP_VALUES); // return objectMapper; // // }
import com.fasterxml.jackson.core.JsonProcessingException; import io.fabric8.funktion.DataKeys; import io.fabric8.funktion.Labels; import io.fabric8.funktion.model.Funktion; import io.fabric8.kubernetes.api.KubernetesHelper; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ConfigMapBuilder; import io.fabric8.kubernetes.api.model.ConfigMapList; import io.fabric8.kubernetes.client.DefaultKubernetesClient; import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.utils.Objects; import io.fabric8.utils.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import static io.fabric8.funktion.ApplicationProperties.toPropertiesString; import static io.fabric8.funktion.Labels.Kind.SUBSCRIPTION; import static io.fabric8.funktion.support.YamlHelper.createYamlMapper; import static io.fabric8.utils.Lists.notNullList;
if (Strings.isNullOrBlank(answer)) { answer = KubernetesHelper.defaultNamespace(); } if (Strings.isNullOrBlank(answer)) { answer = System.getenv("KUBERNETES_NAMESPACE"); } if (Strings.isNullOrBlank(answer)) { answer = "default"; } return answer; } protected ConfigMap createSubscriptionResource(SubscribeRequest request, String namespace) throws InternalException { Map<String, String> annotations = new LinkedHashMap<>(); Map<String, String> data = new LinkedHashMap<>(); Map<String, String> labels = new HashMap<>(); labels.put(Labels.KIND, SUBSCRIPTION); String connectorName = request.findConnectorName(); String namePrefix = "design"; if (Strings.isNotBlank(connectorName)) { namePrefix += "-" + connectorName; labels.put(Labels.CONNECTOR, connectorName); } String name = createSubscriptionName(request, namespace, namePrefix); Funktion funktion = request.getFunktion(); Objects.notNull(funktion, "funktion"); try { String yaml = createYamlMapper().writeValueAsString(funktion);
// Path: funktion-model/src/main/java/io/fabric8/funktion/DataKeys.java // public class DataKeys { // public static class Connector { // public static final String SCHEMA_YAML = "schema.yml"; // public static final String ASCIIDOC = "documentation.adoc"; // public static final String DEPLOYMENT_YAML = "deployment.yml"; // public static final String APPLICATION_PROPERTIES = Subscription.APPLICATION_PROPERTIES; // } // // public static class Subscription { // public static final String APPLICATION_PROPERTIES = "application.properties"; // public static final String FUNKTION_YAML = "funktion.yml"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public class Labels { // public static final String KIND = "funktion.fabric8.io/kind"; // public static final String CONNECTOR = "connector"; // // public static class Kind { // public static final String CONNECTOR = "Connector"; // public static final String SUBSCRIPTION = "Subscription"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/model/Funktion.java // public class Funktion extends DtoSupport { // private List<Flow> flows = new ArrayList<>(); // // public List<Flow> getFlows() { // return flows; // } // // public void setFlows(List<Flow> flows) { // this.flows = flows; // } // // public Flow createFlow() { // return addFlow(new Flow()); // } // // public Flow addFlow(Flow flow) { // flows.add(flow); // return flow; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/ApplicationProperties.java // public static String toPropertiesString(Map<String, String> applicationProperties, String comments) throws IOException { // Properties properties = toProperties(applicationProperties); // StringWriter writer = new StringWriter(); // properties.store(writer, comments); // return writer.toString(); // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public static final String SUBSCRIPTION = "Subscription"; // // Path: funktion-model/src/main/java/io/fabric8/funktion/support/YamlHelper.java // public static ObjectMapper createYamlMapper() { // ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory() // .configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true) // .configure(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS, true) // .configure(YAMLGenerator.Feature.USE_NATIVE_OBJECT_ID, false) // .configure(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID, false) // ); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY). // enable(SerializationFeature.INDENT_OUTPUT). // disable(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS). // disable(SerializationFeature.WRITE_NULL_MAP_VALUES); // return objectMapper; // // } // Path: funktion-agent/src/main/java/io/fabric8/funktion/agent/Agent.java import com.fasterxml.jackson.core.JsonProcessingException; import io.fabric8.funktion.DataKeys; import io.fabric8.funktion.Labels; import io.fabric8.funktion.model.Funktion; import io.fabric8.kubernetes.api.KubernetesHelper; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ConfigMapBuilder; import io.fabric8.kubernetes.api.model.ConfigMapList; import io.fabric8.kubernetes.client.DefaultKubernetesClient; import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.utils.Objects; import io.fabric8.utils.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import static io.fabric8.funktion.ApplicationProperties.toPropertiesString; import static io.fabric8.funktion.Labels.Kind.SUBSCRIPTION; import static io.fabric8.funktion.support.YamlHelper.createYamlMapper; import static io.fabric8.utils.Lists.notNullList; if (Strings.isNullOrBlank(answer)) { answer = KubernetesHelper.defaultNamespace(); } if (Strings.isNullOrBlank(answer)) { answer = System.getenv("KUBERNETES_NAMESPACE"); } if (Strings.isNullOrBlank(answer)) { answer = "default"; } return answer; } protected ConfigMap createSubscriptionResource(SubscribeRequest request, String namespace) throws InternalException { Map<String, String> annotations = new LinkedHashMap<>(); Map<String, String> data = new LinkedHashMap<>(); Map<String, String> labels = new HashMap<>(); labels.put(Labels.KIND, SUBSCRIPTION); String connectorName = request.findConnectorName(); String namePrefix = "design"; if (Strings.isNotBlank(connectorName)) { namePrefix += "-" + connectorName; labels.put(Labels.CONNECTOR, connectorName); } String name = createSubscriptionName(request, namespace, namePrefix); Funktion funktion = request.getFunktion(); Objects.notNull(funktion, "funktion"); try { String yaml = createYamlMapper().writeValueAsString(funktion);
data.put(DataKeys.Subscription.FUNKTION_YAML, yaml);
funktionio/funktion-connectors
funktion-agent/src/main/java/io/fabric8/funktion/agent/Agent.java
// Path: funktion-model/src/main/java/io/fabric8/funktion/DataKeys.java // public class DataKeys { // public static class Connector { // public static final String SCHEMA_YAML = "schema.yml"; // public static final String ASCIIDOC = "documentation.adoc"; // public static final String DEPLOYMENT_YAML = "deployment.yml"; // public static final String APPLICATION_PROPERTIES = Subscription.APPLICATION_PROPERTIES; // } // // public static class Subscription { // public static final String APPLICATION_PROPERTIES = "application.properties"; // public static final String FUNKTION_YAML = "funktion.yml"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public class Labels { // public static final String KIND = "funktion.fabric8.io/kind"; // public static final String CONNECTOR = "connector"; // // public static class Kind { // public static final String CONNECTOR = "Connector"; // public static final String SUBSCRIPTION = "Subscription"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/model/Funktion.java // public class Funktion extends DtoSupport { // private List<Flow> flows = new ArrayList<>(); // // public List<Flow> getFlows() { // return flows; // } // // public void setFlows(List<Flow> flows) { // this.flows = flows; // } // // public Flow createFlow() { // return addFlow(new Flow()); // } // // public Flow addFlow(Flow flow) { // flows.add(flow); // return flow; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/ApplicationProperties.java // public static String toPropertiesString(Map<String, String> applicationProperties, String comments) throws IOException { // Properties properties = toProperties(applicationProperties); // StringWriter writer = new StringWriter(); // properties.store(writer, comments); // return writer.toString(); // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public static final String SUBSCRIPTION = "Subscription"; // // Path: funktion-model/src/main/java/io/fabric8/funktion/support/YamlHelper.java // public static ObjectMapper createYamlMapper() { // ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory() // .configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true) // .configure(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS, true) // .configure(YAMLGenerator.Feature.USE_NATIVE_OBJECT_ID, false) // .configure(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID, false) // ); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY). // enable(SerializationFeature.INDENT_OUTPUT). // disable(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS). // disable(SerializationFeature.WRITE_NULL_MAP_VALUES); // return objectMapper; // // }
import com.fasterxml.jackson.core.JsonProcessingException; import io.fabric8.funktion.DataKeys; import io.fabric8.funktion.Labels; import io.fabric8.funktion.model.Funktion; import io.fabric8.kubernetes.api.KubernetesHelper; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ConfigMapBuilder; import io.fabric8.kubernetes.api.model.ConfigMapList; import io.fabric8.kubernetes.client.DefaultKubernetesClient; import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.utils.Objects; import io.fabric8.utils.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import static io.fabric8.funktion.ApplicationProperties.toPropertiesString; import static io.fabric8.funktion.Labels.Kind.SUBSCRIPTION; import static io.fabric8.funktion.support.YamlHelper.createYamlMapper; import static io.fabric8.utils.Lists.notNullList;
return answer; } protected ConfigMap createSubscriptionResource(SubscribeRequest request, String namespace) throws InternalException { Map<String, String> annotations = new LinkedHashMap<>(); Map<String, String> data = new LinkedHashMap<>(); Map<String, String> labels = new HashMap<>(); labels.put(Labels.KIND, SUBSCRIPTION); String connectorName = request.findConnectorName(); String namePrefix = "design"; if (Strings.isNotBlank(connectorName)) { namePrefix += "-" + connectorName; labels.put(Labels.CONNECTOR, connectorName); } String name = createSubscriptionName(request, namespace, namePrefix); Funktion funktion = request.getFunktion(); Objects.notNull(funktion, "funktion"); try { String yaml = createYamlMapper().writeValueAsString(funktion); data.put(DataKeys.Subscription.FUNKTION_YAML, yaml); } catch (JsonProcessingException e) { throw new InternalException("Failed to marshal Funktion " + funktion + ". " + e, e); } Map<String, String> applicationProperties = request.getApplicationProperties(); if (applicationProperties != null) { String comments = null; String applicationPropertiesText = null; try {
// Path: funktion-model/src/main/java/io/fabric8/funktion/DataKeys.java // public class DataKeys { // public static class Connector { // public static final String SCHEMA_YAML = "schema.yml"; // public static final String ASCIIDOC = "documentation.adoc"; // public static final String DEPLOYMENT_YAML = "deployment.yml"; // public static final String APPLICATION_PROPERTIES = Subscription.APPLICATION_PROPERTIES; // } // // public static class Subscription { // public static final String APPLICATION_PROPERTIES = "application.properties"; // public static final String FUNKTION_YAML = "funktion.yml"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public class Labels { // public static final String KIND = "funktion.fabric8.io/kind"; // public static final String CONNECTOR = "connector"; // // public static class Kind { // public static final String CONNECTOR = "Connector"; // public static final String SUBSCRIPTION = "Subscription"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/model/Funktion.java // public class Funktion extends DtoSupport { // private List<Flow> flows = new ArrayList<>(); // // public List<Flow> getFlows() { // return flows; // } // // public void setFlows(List<Flow> flows) { // this.flows = flows; // } // // public Flow createFlow() { // return addFlow(new Flow()); // } // // public Flow addFlow(Flow flow) { // flows.add(flow); // return flow; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/ApplicationProperties.java // public static String toPropertiesString(Map<String, String> applicationProperties, String comments) throws IOException { // Properties properties = toProperties(applicationProperties); // StringWriter writer = new StringWriter(); // properties.store(writer, comments); // return writer.toString(); // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public static final String SUBSCRIPTION = "Subscription"; // // Path: funktion-model/src/main/java/io/fabric8/funktion/support/YamlHelper.java // public static ObjectMapper createYamlMapper() { // ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory() // .configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true) // .configure(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS, true) // .configure(YAMLGenerator.Feature.USE_NATIVE_OBJECT_ID, false) // .configure(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID, false) // ); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY). // enable(SerializationFeature.INDENT_OUTPUT). // disable(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS). // disable(SerializationFeature.WRITE_NULL_MAP_VALUES); // return objectMapper; // // } // Path: funktion-agent/src/main/java/io/fabric8/funktion/agent/Agent.java import com.fasterxml.jackson.core.JsonProcessingException; import io.fabric8.funktion.DataKeys; import io.fabric8.funktion.Labels; import io.fabric8.funktion.model.Funktion; import io.fabric8.kubernetes.api.KubernetesHelper; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ConfigMapBuilder; import io.fabric8.kubernetes.api.model.ConfigMapList; import io.fabric8.kubernetes.client.DefaultKubernetesClient; import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.utils.Objects; import io.fabric8.utils.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import static io.fabric8.funktion.ApplicationProperties.toPropertiesString; import static io.fabric8.funktion.Labels.Kind.SUBSCRIPTION; import static io.fabric8.funktion.support.YamlHelper.createYamlMapper; import static io.fabric8.utils.Lists.notNullList; return answer; } protected ConfigMap createSubscriptionResource(SubscribeRequest request, String namespace) throws InternalException { Map<String, String> annotations = new LinkedHashMap<>(); Map<String, String> data = new LinkedHashMap<>(); Map<String, String> labels = new HashMap<>(); labels.put(Labels.KIND, SUBSCRIPTION); String connectorName = request.findConnectorName(); String namePrefix = "design"; if (Strings.isNotBlank(connectorName)) { namePrefix += "-" + connectorName; labels.put(Labels.CONNECTOR, connectorName); } String name = createSubscriptionName(request, namespace, namePrefix); Funktion funktion = request.getFunktion(); Objects.notNull(funktion, "funktion"); try { String yaml = createYamlMapper().writeValueAsString(funktion); data.put(DataKeys.Subscription.FUNKTION_YAML, yaml); } catch (JsonProcessingException e) { throw new InternalException("Failed to marshal Funktion " + funktion + ". " + e, e); } Map<String, String> applicationProperties = request.getApplicationProperties(); if (applicationProperties != null) { String comments = null; String applicationPropertiesText = null; try {
applicationPropertiesText = toPropertiesString(applicationProperties, comments);
funktionio/funktion-connectors
connector-generator/src/main/java/io/fabric8/funktion/connector/generator/ConnectorGenerator.java
// Path: funktion-model/src/main/java/io/fabric8/funktion/support/Strings.java // public class Strings { // // public static boolean isEmpty(String value) { // return value == null || value.length() == 0 || value.trim().length() == 0; // } // // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/support/YamlHelper.java // public static ObjectMapper createYamlMapper() { // ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory() // .configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true) // .configure(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS, true) // .configure(YAMLGenerator.Feature.USE_NATIVE_OBJECT_ID, false) // .configure(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID, false) // ); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY). // enable(SerializationFeature.INDENT_OUTPUT). // disable(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS). // disable(SerializationFeature.WRITE_NULL_MAP_VALUES); // return objectMapper; // // }
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.MappingIterator; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Predicate; import io.fabric8.funktion.support.Strings; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.utils.DomHelper; import io.fabric8.utils.IOHelpers; import io.fabric8.utils.XmlUtils; import org.apache.camel.catalog.CamelCatalog; import org.apache.camel.catalog.DefaultCamelCatalog; import org.reflections.Reflections; import org.reflections.scanners.ResourcesScanner; import org.reflections.util.ClasspathHelper; import org.reflections.util.ConfigurationBuilder; import org.reflections.util.FilterBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.TreeSet; import java.util.regex.Pattern; import static io.fabric8.funktion.support.YamlHelper.createYamlMapper; import static io.fabric8.utils.DomHelper.firstChild;
Element modules = firstChild(componentsPom.getDocumentElement(), "modules"); if (modules == null) { modules = DomHelper.addChildElement(componentsPom.getDocumentElement(), "modules"); } File componentPackagePomFile = new File(getBaseDir(), "../funktion-connectors/pom.xml"); Document componentPackagePom = parseDocument(componentPackagePomFile); Element packageBuild = getOrCreateFirstChild(componentPackagePom.getDocumentElement(), "build"); Element packagePlugins = getOrCreateFirstChild(packageBuild, "plugins"); Element packagePlugin = firstChild(packagePlugins, "plugin"); Element packageDependencies = null; if (packagePlugin == null) { LOG.error("No <plugin> element inside <build><plugins> for " + componentPackagePomFile); } else { packageDependencies = firstChild(packagePlugin, "dependencies"); if (packageDependencies == null) { LOG.error("No <dependencies> element inside <build><plugins><plugin> for " + componentPackagePomFile); } } boolean updatedComponentPackagePom = false; Set<String> moduleNames = new TreeSet<>(); int count = 0; for (ComponentModel component : components) { String componentName = component.getScheme(); String groupId = component.getGroupId(); String artifactId = component.getArtifactId(); String version = component.getVersion(); String componentTitle = component.getTitle();
// Path: funktion-model/src/main/java/io/fabric8/funktion/support/Strings.java // public class Strings { // // public static boolean isEmpty(String value) { // return value == null || value.length() == 0 || value.trim().length() == 0; // } // // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/support/YamlHelper.java // public static ObjectMapper createYamlMapper() { // ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory() // .configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true) // .configure(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS, true) // .configure(YAMLGenerator.Feature.USE_NATIVE_OBJECT_ID, false) // .configure(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID, false) // ); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY). // enable(SerializationFeature.INDENT_OUTPUT). // disable(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS). // disable(SerializationFeature.WRITE_NULL_MAP_VALUES); // return objectMapper; // // } // Path: connector-generator/src/main/java/io/fabric8/funktion/connector/generator/ConnectorGenerator.java import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.MappingIterator; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Predicate; import io.fabric8.funktion.support.Strings; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.utils.DomHelper; import io.fabric8.utils.IOHelpers; import io.fabric8.utils.XmlUtils; import org.apache.camel.catalog.CamelCatalog; import org.apache.camel.catalog.DefaultCamelCatalog; import org.reflections.Reflections; import org.reflections.scanners.ResourcesScanner; import org.reflections.util.ClasspathHelper; import org.reflections.util.ConfigurationBuilder; import org.reflections.util.FilterBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.TreeSet; import java.util.regex.Pattern; import static io.fabric8.funktion.support.YamlHelper.createYamlMapper; import static io.fabric8.utils.DomHelper.firstChild; Element modules = firstChild(componentsPom.getDocumentElement(), "modules"); if (modules == null) { modules = DomHelper.addChildElement(componentsPom.getDocumentElement(), "modules"); } File componentPackagePomFile = new File(getBaseDir(), "../funktion-connectors/pom.xml"); Document componentPackagePom = parseDocument(componentPackagePomFile); Element packageBuild = getOrCreateFirstChild(componentPackagePom.getDocumentElement(), "build"); Element packagePlugins = getOrCreateFirstChild(packageBuild, "plugins"); Element packagePlugin = firstChild(packagePlugins, "plugin"); Element packageDependencies = null; if (packagePlugin == null) { LOG.error("No <plugin> element inside <build><plugins> for " + componentPackagePomFile); } else { packageDependencies = firstChild(packagePlugin, "dependencies"); if (packageDependencies == null) { LOG.error("No <dependencies> element inside <build><plugins><plugin> for " + componentPackagePomFile); } } boolean updatedComponentPackagePom = false; Set<String> moduleNames = new TreeSet<>(); int count = 0; for (ComponentModel component : components) { String componentName = component.getScheme(); String groupId = component.getGroupId(); String artifactId = component.getArtifactId(); String version = component.getVersion(); String componentTitle = component.getTitle();
if (Strings.isEmpty(componentTitle)) {
funktionio/funktion-connectors
connector-generator/src/main/java/io/fabric8/funktion/connector/generator/ConnectorGenerator.java
// Path: funktion-model/src/main/java/io/fabric8/funktion/support/Strings.java // public class Strings { // // public static boolean isEmpty(String value) { // return value == null || value.length() == 0 || value.trim().length() == 0; // } // // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/support/YamlHelper.java // public static ObjectMapper createYamlMapper() { // ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory() // .configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true) // .configure(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS, true) // .configure(YAMLGenerator.Feature.USE_NATIVE_OBJECT_ID, false) // .configure(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID, false) // ); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY). // enable(SerializationFeature.INDENT_OUTPUT). // disable(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS). // disable(SerializationFeature.WRITE_NULL_MAP_VALUES); // return objectMapper; // // }
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.MappingIterator; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Predicate; import io.fabric8.funktion.support.Strings; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.utils.DomHelper; import io.fabric8.utils.IOHelpers; import io.fabric8.utils.XmlUtils; import org.apache.camel.catalog.CamelCatalog; import org.apache.camel.catalog.DefaultCamelCatalog; import org.reflections.Reflections; import org.reflections.scanners.ResourcesScanner; import org.reflections.util.ClasspathHelper; import org.reflections.util.ConfigurationBuilder; import org.reflections.util.FilterBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.TreeSet; import java.util.regex.Pattern; import static io.fabric8.funktion.support.YamlHelper.createYamlMapper; import static io.fabric8.utils.DomHelper.firstChild;
" </enricher>\n" + " </configuration>\n" + " </plugin>\n" + " <plugin>\n" + " <groupId>org.springframework.boot</groupId>\n" + " <artifactId>spring-boot-maven-plugin</artifactId>\n" + " </plugin>\n" + " </plugins>\n" + " </build>\n" + "</project>"; IOHelpers.writeFully(new File(projectDir, "pom.xml"), pomXml); String dummyJavaClass = "package io.fabric8.funktion.connector;\n" + "\n" + "public class ConnectorMarker{}\n"; File dummyJavaFile = new File(projectDir, "src/main/java/io/fabric8/funktion/connector/ConnectorMarker.java"); dummyJavaFile.getParentFile().mkdirs(); IOHelpers.writeFully(dummyJavaFile, dummyJavaClass); String jSonSchema = camelCatalog.componentJSonSchema(componentName); String asciiDoc = camelCatalog.componentAsciiDoc(componentName); String image = "funktion/" + moduleName + ":${project.version}"; File applicationPropertiesFile = new File(projectDir, "src/main/funktion/application.properties"); ConfigMap configMap = Connectors.createConnector(component, jSonSchema, asciiDoc, image, applicationPropertiesFile); File configMapFile = new File(projectDir, "src/main/fabric8/" + componentName + "-cm.yml"); configMapFile.getParentFile().mkdirs();
// Path: funktion-model/src/main/java/io/fabric8/funktion/support/Strings.java // public class Strings { // // public static boolean isEmpty(String value) { // return value == null || value.length() == 0 || value.trim().length() == 0; // } // // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/support/YamlHelper.java // public static ObjectMapper createYamlMapper() { // ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory() // .configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true) // .configure(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS, true) // .configure(YAMLGenerator.Feature.USE_NATIVE_OBJECT_ID, false) // .configure(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID, false) // ); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY). // enable(SerializationFeature.INDENT_OUTPUT). // disable(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS). // disable(SerializationFeature.WRITE_NULL_MAP_VALUES); // return objectMapper; // // } // Path: connector-generator/src/main/java/io/fabric8/funktion/connector/generator/ConnectorGenerator.java import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.MappingIterator; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Predicate; import io.fabric8.funktion.support.Strings; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.utils.DomHelper; import io.fabric8.utils.IOHelpers; import io.fabric8.utils.XmlUtils; import org.apache.camel.catalog.CamelCatalog; import org.apache.camel.catalog.DefaultCamelCatalog; import org.reflections.Reflections; import org.reflections.scanners.ResourcesScanner; import org.reflections.util.ClasspathHelper; import org.reflections.util.ConfigurationBuilder; import org.reflections.util.FilterBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.TreeSet; import java.util.regex.Pattern; import static io.fabric8.funktion.support.YamlHelper.createYamlMapper; import static io.fabric8.utils.DomHelper.firstChild; " </enricher>\n" + " </configuration>\n" + " </plugin>\n" + " <plugin>\n" + " <groupId>org.springframework.boot</groupId>\n" + " <artifactId>spring-boot-maven-plugin</artifactId>\n" + " </plugin>\n" + " </plugins>\n" + " </build>\n" + "</project>"; IOHelpers.writeFully(new File(projectDir, "pom.xml"), pomXml); String dummyJavaClass = "package io.fabric8.funktion.connector;\n" + "\n" + "public class ConnectorMarker{}\n"; File dummyJavaFile = new File(projectDir, "src/main/java/io/fabric8/funktion/connector/ConnectorMarker.java"); dummyJavaFile.getParentFile().mkdirs(); IOHelpers.writeFully(dummyJavaFile, dummyJavaClass); String jSonSchema = camelCatalog.componentJSonSchema(componentName); String asciiDoc = camelCatalog.componentAsciiDoc(componentName); String image = "funktion/" + moduleName + ":${project.version}"; File applicationPropertiesFile = new File(projectDir, "src/main/funktion/application.properties"); ConfigMap configMap = Connectors.createConnector(component, jSonSchema, asciiDoc, image, applicationPropertiesFile); File configMapFile = new File(projectDir, "src/main/fabric8/" + componentName + "-cm.yml"); configMapFile.getParentFile().mkdirs();
ObjectMapper yamlMapper = createYamlMapper();
funktionio/funktion-connectors
funktion-model/src/main/java/io/fabric8/funktion/model/steps/Step.java
// Path: funktion-model/src/main/java/io/fabric8/funktion/model/StepKinds.java // public class StepKinds { // public static final String CHOICE = "choice"; // public static final String ENDPOINT = "endpoint"; // public static final String FILTER = "filter"; // public static final String FUNCTION = "function"; // public static final String FLOW = "flow"; // public static final String OTHERWISE = "otherwise"; // public static final String SET_BODY = "setBody"; // public static final String SET_HEADERS = "setHeaders"; // public static final String SPLIT = "split"; // public static final String THROTTLE = "throttle"; // public static final String LOG = "log"; // }
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import io.fabric8.funktion.model.StepKinds;
/* * Copyright 2016 Red Hat, Inc. * <p> * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * */ package io.fabric8.funktion.model.steps; /** * Defines the a step in a funktion flow */ @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "kind") @JsonSubTypes({
// Path: funktion-model/src/main/java/io/fabric8/funktion/model/StepKinds.java // public class StepKinds { // public static final String CHOICE = "choice"; // public static final String ENDPOINT = "endpoint"; // public static final String FILTER = "filter"; // public static final String FUNCTION = "function"; // public static final String FLOW = "flow"; // public static final String OTHERWISE = "otherwise"; // public static final String SET_BODY = "setBody"; // public static final String SET_HEADERS = "setHeaders"; // public static final String SPLIT = "split"; // public static final String THROTTLE = "throttle"; // public static final String LOG = "log"; // } // Path: funktion-model/src/main/java/io/fabric8/funktion/model/steps/Step.java import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import io.fabric8.funktion.model.StepKinds; /* * Copyright 2016 Red Hat, Inc. * <p> * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * */ package io.fabric8.funktion.model.steps; /** * Defines the a step in a funktion flow */ @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "kind") @JsonSubTypes({
@JsonSubTypes.Type(value = Choice.class, name = StepKinds.CHOICE),
funktionio/funktion-connectors
funktion-runtime/src/test/java/io/fabric8/funktion/runtime/steps/ThrottleYamlTest.java
// Path: funktion-model/src/main/java/io/fabric8/funktion/model/Funktion.java // public class Funktion extends DtoSupport { // private List<Flow> flows = new ArrayList<>(); // // public List<Flow> getFlows() { // return flows; // } // // public void setFlows(List<Flow> flows) { // this.flows = flows; // } // // public Flow createFlow() { // return addFlow(new Flow()); // } // // public Flow addFlow(Flow flow) { // flows.add(flow); // return flow; // } // }
import io.fabric8.funktion.model.Funktion; import java.io.IOException;
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.fabric8.funktion.runtime.steps; /** * Loads the test flow YAML file from src/test/resources/*.yml on the classpath */ public class ThrottleYamlTest extends ThrottleTest { @Override
// Path: funktion-model/src/main/java/io/fabric8/funktion/model/Funktion.java // public class Funktion extends DtoSupport { // private List<Flow> flows = new ArrayList<>(); // // public List<Flow> getFlows() { // return flows; // } // // public void setFlows(List<Flow> flows) { // this.flows = flows; // } // // public Flow createFlow() { // return addFlow(new Flow()); // } // // public Flow addFlow(Flow flow) { // flows.add(flow); // return flow; // } // } // Path: funktion-runtime/src/test/java/io/fabric8/funktion/runtime/steps/ThrottleYamlTest.java import io.fabric8.funktion.model.Funktion; import java.io.IOException; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.fabric8.funktion.runtime.steps; /** * Loads the test flow YAML file from src/test/resources/*.yml on the classpath */ public class ThrottleYamlTest extends ThrottleTest { @Override
protected Funktion createFunktion() throws IOException {
funktionio/funktion-connectors
funktion-model/src/main/java/io/fabric8/funktion/model/steps/Throttle.java
// Path: funktion-model/src/main/java/io/fabric8/funktion/model/StepKinds.java // public class StepKinds { // public static final String CHOICE = "choice"; // public static final String ENDPOINT = "endpoint"; // public static final String FILTER = "filter"; // public static final String FUNCTION = "function"; // public static final String FLOW = "flow"; // public static final String OTHERWISE = "otherwise"; // public static final String SET_BODY = "setBody"; // public static final String SET_HEADERS = "setHeaders"; // public static final String SPLIT = "split"; // public static final String THROTTLE = "throttle"; // public static final String LOG = "log"; // }
import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.fabric8.funktion.model.StepKinds;
/* * Copyright 2016 Red Hat, Inc. * <p> * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * */ package io.fabric8.funktion.model.steps; /** * Throttles the flow */ @JsonPropertyOrder({"maximumRequests", "periodMillis"}) public class Throttle extends ChildSteps<Throttle> { private long maximumRequests; private Long periodMillis; public Throttle() {
// Path: funktion-model/src/main/java/io/fabric8/funktion/model/StepKinds.java // public class StepKinds { // public static final String CHOICE = "choice"; // public static final String ENDPOINT = "endpoint"; // public static final String FILTER = "filter"; // public static final String FUNCTION = "function"; // public static final String FLOW = "flow"; // public static final String OTHERWISE = "otherwise"; // public static final String SET_BODY = "setBody"; // public static final String SET_HEADERS = "setHeaders"; // public static final String SPLIT = "split"; // public static final String THROTTLE = "throttle"; // public static final String LOG = "log"; // } // Path: funktion-model/src/main/java/io/fabric8/funktion/model/steps/Throttle.java import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.fabric8.funktion.model.StepKinds; /* * Copyright 2016 Red Hat, Inc. * <p> * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * */ package io.fabric8.funktion.model.steps; /** * Throttles the flow */ @JsonPropertyOrder({"maximumRequests", "periodMillis"}) public class Throttle extends ChildSteps<Throttle> { private long maximumRequests; private Long periodMillis; public Throttle() {
super(StepKinds.THROTTLE);
funktionio/funktion-connectors
funktion-runtime/src/test/java/io/fabric8/funktion/runtime/steps/ChoiceYamlTest.java
// Path: funktion-model/src/main/java/io/fabric8/funktion/model/Funktion.java // public class Funktion extends DtoSupport { // private List<Flow> flows = new ArrayList<>(); // // public List<Flow> getFlows() { // return flows; // } // // public void setFlows(List<Flow> flows) { // this.flows = flows; // } // // public Flow createFlow() { // return addFlow(new Flow()); // } // // public Flow addFlow(Flow flow) { // flows.add(flow); // return flow; // } // }
import io.fabric8.funktion.model.Funktion; import java.io.IOException;
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.fabric8.funktion.runtime.steps; /** * Loads the test flow YAML file from src/test/resources/*.yml on the classpath */ public class ChoiceYamlTest extends ChoiceTest { @Override
// Path: funktion-model/src/main/java/io/fabric8/funktion/model/Funktion.java // public class Funktion extends DtoSupport { // private List<Flow> flows = new ArrayList<>(); // // public List<Flow> getFlows() { // return flows; // } // // public void setFlows(List<Flow> flows) { // this.flows = flows; // } // // public Flow createFlow() { // return addFlow(new Flow()); // } // // public Flow addFlow(Flow flow) { // flows.add(flow); // return flow; // } // } // Path: funktion-runtime/src/test/java/io/fabric8/funktion/runtime/steps/ChoiceYamlTest.java import io.fabric8.funktion.model.Funktion; import java.io.IOException; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.fabric8.funktion.runtime.steps; /** * Loads the test flow YAML file from src/test/resources/*.yml on the classpath */ public class ChoiceYamlTest extends ChoiceTest { @Override
protected Funktion createFunktion() throws IOException {
funktionio/funktion-connectors
funktion-model/src/main/java/io/fabric8/funktion/model/steps/Choice.java
// Path: funktion-model/src/main/java/io/fabric8/funktion/model/StepKinds.java // public class StepKinds { // public static final String CHOICE = "choice"; // public static final String ENDPOINT = "endpoint"; // public static final String FILTER = "filter"; // public static final String FUNCTION = "function"; // public static final String FLOW = "flow"; // public static final String OTHERWISE = "otherwise"; // public static final String SET_BODY = "setBody"; // public static final String SET_HEADERS = "setHeaders"; // public static final String SPLIT = "split"; // public static final String THROTTLE = "throttle"; // public static final String LOG = "log"; // }
import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.fabric8.funktion.model.StepKinds; import java.util.ArrayList; import java.util.List;
/* * Copyright 2016 Red Hat, Inc. * <p> * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * */ package io.fabric8.funktion.model.steps; /** * Performs a content based routing. * <p> * Finds and evaluates the first {@link Filter} or invokes the otherwise steps */ @JsonPropertyOrder({"filters", "otherwise"}) public class Choice extends Step { private List<Filter> filters = new ArrayList<>(); private Otherwise otherwise; public Choice() {
// Path: funktion-model/src/main/java/io/fabric8/funktion/model/StepKinds.java // public class StepKinds { // public static final String CHOICE = "choice"; // public static final String ENDPOINT = "endpoint"; // public static final String FILTER = "filter"; // public static final String FUNCTION = "function"; // public static final String FLOW = "flow"; // public static final String OTHERWISE = "otherwise"; // public static final String SET_BODY = "setBody"; // public static final String SET_HEADERS = "setHeaders"; // public static final String SPLIT = "split"; // public static final String THROTTLE = "throttle"; // public static final String LOG = "log"; // } // Path: funktion-model/src/main/java/io/fabric8/funktion/model/steps/Choice.java import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.fabric8.funktion.model.StepKinds; import java.util.ArrayList; import java.util.List; /* * Copyright 2016 Red Hat, Inc. * <p> * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * */ package io.fabric8.funktion.model.steps; /** * Performs a content based routing. * <p> * Finds and evaluates the first {@link Filter} or invokes the otherwise steps */ @JsonPropertyOrder({"filters", "otherwise"}) public class Choice extends Step { private List<Filter> filters = new ArrayList<>(); private Otherwise otherwise; public Choice() {
super(StepKinds.CHOICE);
funktionio/funktion-connectors
connector-generator/src/main/java/io/fabric8/funktion/connector/generator/Connectors.java
// Path: funktion-model/src/main/java/io/fabric8/funktion/DataKeys.java // public class DataKeys { // public static class Connector { // public static final String SCHEMA_YAML = "schema.yml"; // public static final String ASCIIDOC = "documentation.adoc"; // public static final String DEPLOYMENT_YAML = "deployment.yml"; // public static final String APPLICATION_PROPERTIES = Subscription.APPLICATION_PROPERTIES; // } // // public static class Subscription { // public static final String APPLICATION_PROPERTIES = "application.properties"; // public static final String FUNKTION_YAML = "funktion.yml"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public class Labels { // public static final String KIND = "funktion.fabric8.io/kind"; // public static final String CONNECTOR = "connector"; // // public static class Kind { // public static final String CONNECTOR = "Connector"; // public static final String SUBSCRIPTION = "Subscription"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/support/YamlHelper.java // public class YamlHelper { // public static ObjectMapper createYamlMapper() { // ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory() // .configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true) // .configure(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS, true) // .configure(YAMLGenerator.Feature.USE_NATIVE_OBJECT_ID, false) // .configure(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID, false) // ); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY). // enable(SerializationFeature.INDENT_OUTPUT). // disable(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS). // disable(SerializationFeature.WRITE_NULL_MAP_VALUES); // return objectMapper; // // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public static final String CONNECTOR = "Connector"; // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public static final String SUBSCRIPTION = "Subscription";
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import io.fabric8.funktion.DataKeys; import io.fabric8.funktion.Labels; import io.fabric8.funktion.support.YamlHelper; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ConfigMapBuilder; import io.fabric8.kubernetes.api.model.extensions.Deployment; import io.fabric8.kubernetes.api.model.extensions.DeploymentBuilder; import io.fabric8.utils.IOHelpers; import io.fabric8.utils.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import static io.fabric8.funktion.Labels.Kind.CONNECTOR; import static io.fabric8.funktion.Labels.Kind.SUBSCRIPTION;
/* * Copyright 2016 Red Hat, Inc. * <p> * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * */ package io.fabric8.funktion.connector.generator; /** */ public class Connectors { private static final transient Logger LOG = LoggerFactory.getLogger(Connectors.class); public static ConfigMap createConnector(ComponentModel component, String jSonSchema, String asciiDoc, String image, File applicationPropertiesFile) { String componentName = component.getScheme().toLowerCase(); Map<String, String> annotations = new LinkedHashMap<>(); Map<String, String> labels = new LinkedHashMap<>();
// Path: funktion-model/src/main/java/io/fabric8/funktion/DataKeys.java // public class DataKeys { // public static class Connector { // public static final String SCHEMA_YAML = "schema.yml"; // public static final String ASCIIDOC = "documentation.adoc"; // public static final String DEPLOYMENT_YAML = "deployment.yml"; // public static final String APPLICATION_PROPERTIES = Subscription.APPLICATION_PROPERTIES; // } // // public static class Subscription { // public static final String APPLICATION_PROPERTIES = "application.properties"; // public static final String FUNKTION_YAML = "funktion.yml"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public class Labels { // public static final String KIND = "funktion.fabric8.io/kind"; // public static final String CONNECTOR = "connector"; // // public static class Kind { // public static final String CONNECTOR = "Connector"; // public static final String SUBSCRIPTION = "Subscription"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/support/YamlHelper.java // public class YamlHelper { // public static ObjectMapper createYamlMapper() { // ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory() // .configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true) // .configure(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS, true) // .configure(YAMLGenerator.Feature.USE_NATIVE_OBJECT_ID, false) // .configure(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID, false) // ); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY). // enable(SerializationFeature.INDENT_OUTPUT). // disable(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS). // disable(SerializationFeature.WRITE_NULL_MAP_VALUES); // return objectMapper; // // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public static final String CONNECTOR = "Connector"; // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public static final String SUBSCRIPTION = "Subscription"; // Path: connector-generator/src/main/java/io/fabric8/funktion/connector/generator/Connectors.java import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import io.fabric8.funktion.DataKeys; import io.fabric8.funktion.Labels; import io.fabric8.funktion.support.YamlHelper; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ConfigMapBuilder; import io.fabric8.kubernetes.api.model.extensions.Deployment; import io.fabric8.kubernetes.api.model.extensions.DeploymentBuilder; import io.fabric8.utils.IOHelpers; import io.fabric8.utils.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import static io.fabric8.funktion.Labels.Kind.CONNECTOR; import static io.fabric8.funktion.Labels.Kind.SUBSCRIPTION; /* * Copyright 2016 Red Hat, Inc. * <p> * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * */ package io.fabric8.funktion.connector.generator; /** */ public class Connectors { private static final transient Logger LOG = LoggerFactory.getLogger(Connectors.class); public static ConfigMap createConnector(ComponentModel component, String jSonSchema, String asciiDoc, String image, File applicationPropertiesFile) { String componentName = component.getScheme().toLowerCase(); Map<String, String> annotations = new LinkedHashMap<>(); Map<String, String> labels = new LinkedHashMap<>();
labels.put(Labels.KIND, CONNECTOR);
funktionio/funktion-connectors
connector-generator/src/main/java/io/fabric8/funktion/connector/generator/Connectors.java
// Path: funktion-model/src/main/java/io/fabric8/funktion/DataKeys.java // public class DataKeys { // public static class Connector { // public static final String SCHEMA_YAML = "schema.yml"; // public static final String ASCIIDOC = "documentation.adoc"; // public static final String DEPLOYMENT_YAML = "deployment.yml"; // public static final String APPLICATION_PROPERTIES = Subscription.APPLICATION_PROPERTIES; // } // // public static class Subscription { // public static final String APPLICATION_PROPERTIES = "application.properties"; // public static final String FUNKTION_YAML = "funktion.yml"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public class Labels { // public static final String KIND = "funktion.fabric8.io/kind"; // public static final String CONNECTOR = "connector"; // // public static class Kind { // public static final String CONNECTOR = "Connector"; // public static final String SUBSCRIPTION = "Subscription"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/support/YamlHelper.java // public class YamlHelper { // public static ObjectMapper createYamlMapper() { // ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory() // .configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true) // .configure(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS, true) // .configure(YAMLGenerator.Feature.USE_NATIVE_OBJECT_ID, false) // .configure(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID, false) // ); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY). // enable(SerializationFeature.INDENT_OUTPUT). // disable(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS). // disable(SerializationFeature.WRITE_NULL_MAP_VALUES); // return objectMapper; // // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public static final String CONNECTOR = "Connector"; // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public static final String SUBSCRIPTION = "Subscription";
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import io.fabric8.funktion.DataKeys; import io.fabric8.funktion.Labels; import io.fabric8.funktion.support.YamlHelper; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ConfigMapBuilder; import io.fabric8.kubernetes.api.model.extensions.Deployment; import io.fabric8.kubernetes.api.model.extensions.DeploymentBuilder; import io.fabric8.utils.IOHelpers; import io.fabric8.utils.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import static io.fabric8.funktion.Labels.Kind.CONNECTOR; import static io.fabric8.funktion.Labels.Kind.SUBSCRIPTION;
/* * Copyright 2016 Red Hat, Inc. * <p> * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * */ package io.fabric8.funktion.connector.generator; /** */ public class Connectors { private static final transient Logger LOG = LoggerFactory.getLogger(Connectors.class); public static ConfigMap createConnector(ComponentModel component, String jSonSchema, String asciiDoc, String image, File applicationPropertiesFile) { String componentName = component.getScheme().toLowerCase(); Map<String, String> annotations = new LinkedHashMap<>(); Map<String, String> labels = new LinkedHashMap<>();
// Path: funktion-model/src/main/java/io/fabric8/funktion/DataKeys.java // public class DataKeys { // public static class Connector { // public static final String SCHEMA_YAML = "schema.yml"; // public static final String ASCIIDOC = "documentation.adoc"; // public static final String DEPLOYMENT_YAML = "deployment.yml"; // public static final String APPLICATION_PROPERTIES = Subscription.APPLICATION_PROPERTIES; // } // // public static class Subscription { // public static final String APPLICATION_PROPERTIES = "application.properties"; // public static final String FUNKTION_YAML = "funktion.yml"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public class Labels { // public static final String KIND = "funktion.fabric8.io/kind"; // public static final String CONNECTOR = "connector"; // // public static class Kind { // public static final String CONNECTOR = "Connector"; // public static final String SUBSCRIPTION = "Subscription"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/support/YamlHelper.java // public class YamlHelper { // public static ObjectMapper createYamlMapper() { // ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory() // .configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true) // .configure(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS, true) // .configure(YAMLGenerator.Feature.USE_NATIVE_OBJECT_ID, false) // .configure(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID, false) // ); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY). // enable(SerializationFeature.INDENT_OUTPUT). // disable(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS). // disable(SerializationFeature.WRITE_NULL_MAP_VALUES); // return objectMapper; // // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public static final String CONNECTOR = "Connector"; // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public static final String SUBSCRIPTION = "Subscription"; // Path: connector-generator/src/main/java/io/fabric8/funktion/connector/generator/Connectors.java import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import io.fabric8.funktion.DataKeys; import io.fabric8.funktion.Labels; import io.fabric8.funktion.support.YamlHelper; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ConfigMapBuilder; import io.fabric8.kubernetes.api.model.extensions.Deployment; import io.fabric8.kubernetes.api.model.extensions.DeploymentBuilder; import io.fabric8.utils.IOHelpers; import io.fabric8.utils.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import static io.fabric8.funktion.Labels.Kind.CONNECTOR; import static io.fabric8.funktion.Labels.Kind.SUBSCRIPTION; /* * Copyright 2016 Red Hat, Inc. * <p> * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * */ package io.fabric8.funktion.connector.generator; /** */ public class Connectors { private static final transient Logger LOG = LoggerFactory.getLogger(Connectors.class); public static ConfigMap createConnector(ComponentModel component, String jSonSchema, String asciiDoc, String image, File applicationPropertiesFile) { String componentName = component.getScheme().toLowerCase(); Map<String, String> annotations = new LinkedHashMap<>(); Map<String, String> labels = new LinkedHashMap<>();
labels.put(Labels.KIND, CONNECTOR);
funktionio/funktion-connectors
connector-generator/src/main/java/io/fabric8/funktion/connector/generator/Connectors.java
// Path: funktion-model/src/main/java/io/fabric8/funktion/DataKeys.java // public class DataKeys { // public static class Connector { // public static final String SCHEMA_YAML = "schema.yml"; // public static final String ASCIIDOC = "documentation.adoc"; // public static final String DEPLOYMENT_YAML = "deployment.yml"; // public static final String APPLICATION_PROPERTIES = Subscription.APPLICATION_PROPERTIES; // } // // public static class Subscription { // public static final String APPLICATION_PROPERTIES = "application.properties"; // public static final String FUNKTION_YAML = "funktion.yml"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public class Labels { // public static final String KIND = "funktion.fabric8.io/kind"; // public static final String CONNECTOR = "connector"; // // public static class Kind { // public static final String CONNECTOR = "Connector"; // public static final String SUBSCRIPTION = "Subscription"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/support/YamlHelper.java // public class YamlHelper { // public static ObjectMapper createYamlMapper() { // ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory() // .configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true) // .configure(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS, true) // .configure(YAMLGenerator.Feature.USE_NATIVE_OBJECT_ID, false) // .configure(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID, false) // ); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY). // enable(SerializationFeature.INDENT_OUTPUT). // disable(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS). // disable(SerializationFeature.WRITE_NULL_MAP_VALUES); // return objectMapper; // // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public static final String CONNECTOR = "Connector"; // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public static final String SUBSCRIPTION = "Subscription";
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import io.fabric8.funktion.DataKeys; import io.fabric8.funktion.Labels; import io.fabric8.funktion.support.YamlHelper; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ConfigMapBuilder; import io.fabric8.kubernetes.api.model.extensions.Deployment; import io.fabric8.kubernetes.api.model.extensions.DeploymentBuilder; import io.fabric8.utils.IOHelpers; import io.fabric8.utils.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import static io.fabric8.funktion.Labels.Kind.CONNECTOR; import static io.fabric8.funktion.Labels.Kind.SUBSCRIPTION;
/* * Copyright 2016 Red Hat, Inc. * <p> * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * */ package io.fabric8.funktion.connector.generator; /** */ public class Connectors { private static final transient Logger LOG = LoggerFactory.getLogger(Connectors.class); public static ConfigMap createConnector(ComponentModel component, String jSonSchema, String asciiDoc, String image, File applicationPropertiesFile) { String componentName = component.getScheme().toLowerCase(); Map<String, String> annotations = new LinkedHashMap<>(); Map<String, String> labels = new LinkedHashMap<>(); labels.put(Labels.KIND, CONNECTOR); Map<String, String> data = new LinkedHashMap<>(); Map<String, String> subscriptionLabels = new HashMap<>();
// Path: funktion-model/src/main/java/io/fabric8/funktion/DataKeys.java // public class DataKeys { // public static class Connector { // public static final String SCHEMA_YAML = "schema.yml"; // public static final String ASCIIDOC = "documentation.adoc"; // public static final String DEPLOYMENT_YAML = "deployment.yml"; // public static final String APPLICATION_PROPERTIES = Subscription.APPLICATION_PROPERTIES; // } // // public static class Subscription { // public static final String APPLICATION_PROPERTIES = "application.properties"; // public static final String FUNKTION_YAML = "funktion.yml"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public class Labels { // public static final String KIND = "funktion.fabric8.io/kind"; // public static final String CONNECTOR = "connector"; // // public static class Kind { // public static final String CONNECTOR = "Connector"; // public static final String SUBSCRIPTION = "Subscription"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/support/YamlHelper.java // public class YamlHelper { // public static ObjectMapper createYamlMapper() { // ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory() // .configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true) // .configure(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS, true) // .configure(YAMLGenerator.Feature.USE_NATIVE_OBJECT_ID, false) // .configure(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID, false) // ); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY). // enable(SerializationFeature.INDENT_OUTPUT). // disable(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS). // disable(SerializationFeature.WRITE_NULL_MAP_VALUES); // return objectMapper; // // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public static final String CONNECTOR = "Connector"; // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public static final String SUBSCRIPTION = "Subscription"; // Path: connector-generator/src/main/java/io/fabric8/funktion/connector/generator/Connectors.java import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import io.fabric8.funktion.DataKeys; import io.fabric8.funktion.Labels; import io.fabric8.funktion.support.YamlHelper; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ConfigMapBuilder; import io.fabric8.kubernetes.api.model.extensions.Deployment; import io.fabric8.kubernetes.api.model.extensions.DeploymentBuilder; import io.fabric8.utils.IOHelpers; import io.fabric8.utils.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import static io.fabric8.funktion.Labels.Kind.CONNECTOR; import static io.fabric8.funktion.Labels.Kind.SUBSCRIPTION; /* * Copyright 2016 Red Hat, Inc. * <p> * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * */ package io.fabric8.funktion.connector.generator; /** */ public class Connectors { private static final transient Logger LOG = LoggerFactory.getLogger(Connectors.class); public static ConfigMap createConnector(ComponentModel component, String jSonSchema, String asciiDoc, String image, File applicationPropertiesFile) { String componentName = component.getScheme().toLowerCase(); Map<String, String> annotations = new LinkedHashMap<>(); Map<String, String> labels = new LinkedHashMap<>(); labels.put(Labels.KIND, CONNECTOR); Map<String, String> data = new LinkedHashMap<>(); Map<String, String> subscriptionLabels = new HashMap<>();
subscriptionLabels.put(Labels.KIND, SUBSCRIPTION);
funktionio/funktion-connectors
connector-generator/src/main/java/io/fabric8/funktion/connector/generator/Connectors.java
// Path: funktion-model/src/main/java/io/fabric8/funktion/DataKeys.java // public class DataKeys { // public static class Connector { // public static final String SCHEMA_YAML = "schema.yml"; // public static final String ASCIIDOC = "documentation.adoc"; // public static final String DEPLOYMENT_YAML = "deployment.yml"; // public static final String APPLICATION_PROPERTIES = Subscription.APPLICATION_PROPERTIES; // } // // public static class Subscription { // public static final String APPLICATION_PROPERTIES = "application.properties"; // public static final String FUNKTION_YAML = "funktion.yml"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public class Labels { // public static final String KIND = "funktion.fabric8.io/kind"; // public static final String CONNECTOR = "connector"; // // public static class Kind { // public static final String CONNECTOR = "Connector"; // public static final String SUBSCRIPTION = "Subscription"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/support/YamlHelper.java // public class YamlHelper { // public static ObjectMapper createYamlMapper() { // ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory() // .configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true) // .configure(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS, true) // .configure(YAMLGenerator.Feature.USE_NATIVE_OBJECT_ID, false) // .configure(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID, false) // ); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY). // enable(SerializationFeature.INDENT_OUTPUT). // disable(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS). // disable(SerializationFeature.WRITE_NULL_MAP_VALUES); // return objectMapper; // // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public static final String CONNECTOR = "Connector"; // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public static final String SUBSCRIPTION = "Subscription";
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import io.fabric8.funktion.DataKeys; import io.fabric8.funktion.Labels; import io.fabric8.funktion.support.YamlHelper; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ConfigMapBuilder; import io.fabric8.kubernetes.api.model.extensions.Deployment; import io.fabric8.kubernetes.api.model.extensions.DeploymentBuilder; import io.fabric8.utils.IOHelpers; import io.fabric8.utils.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import static io.fabric8.funktion.Labels.Kind.CONNECTOR; import static io.fabric8.funktion.Labels.Kind.SUBSCRIPTION;
/* * Copyright 2016 Red Hat, Inc. * <p> * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * */ package io.fabric8.funktion.connector.generator; /** */ public class Connectors { private static final transient Logger LOG = LoggerFactory.getLogger(Connectors.class); public static ConfigMap createConnector(ComponentModel component, String jSonSchema, String asciiDoc, String image, File applicationPropertiesFile) { String componentName = component.getScheme().toLowerCase(); Map<String, String> annotations = new LinkedHashMap<>(); Map<String, String> labels = new LinkedHashMap<>(); labels.put(Labels.KIND, CONNECTOR); Map<String, String> data = new LinkedHashMap<>(); Map<String, String> subscriptionLabels = new HashMap<>(); subscriptionLabels.put(Labels.KIND, SUBSCRIPTION); subscriptionLabels.put(Labels.CONNECTOR, componentName); Deployment deployment = new DeploymentBuilder(). withNewMetadata().withLabels(subscriptionLabels).endMetadata(). withNewSpec().withReplicas(1). withNewTemplate().withNewMetadata().withLabels(subscriptionLabels).endMetadata(). withNewSpec().addNewContainer().withName("connector").withImage(image).endContainer(). endSpec().endTemplate().endSpec().build(); try {
// Path: funktion-model/src/main/java/io/fabric8/funktion/DataKeys.java // public class DataKeys { // public static class Connector { // public static final String SCHEMA_YAML = "schema.yml"; // public static final String ASCIIDOC = "documentation.adoc"; // public static final String DEPLOYMENT_YAML = "deployment.yml"; // public static final String APPLICATION_PROPERTIES = Subscription.APPLICATION_PROPERTIES; // } // // public static class Subscription { // public static final String APPLICATION_PROPERTIES = "application.properties"; // public static final String FUNKTION_YAML = "funktion.yml"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public class Labels { // public static final String KIND = "funktion.fabric8.io/kind"; // public static final String CONNECTOR = "connector"; // // public static class Kind { // public static final String CONNECTOR = "Connector"; // public static final String SUBSCRIPTION = "Subscription"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/support/YamlHelper.java // public class YamlHelper { // public static ObjectMapper createYamlMapper() { // ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory() // .configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true) // .configure(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS, true) // .configure(YAMLGenerator.Feature.USE_NATIVE_OBJECT_ID, false) // .configure(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID, false) // ); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY). // enable(SerializationFeature.INDENT_OUTPUT). // disable(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS). // disable(SerializationFeature.WRITE_NULL_MAP_VALUES); // return objectMapper; // // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public static final String CONNECTOR = "Connector"; // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public static final String SUBSCRIPTION = "Subscription"; // Path: connector-generator/src/main/java/io/fabric8/funktion/connector/generator/Connectors.java import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import io.fabric8.funktion.DataKeys; import io.fabric8.funktion.Labels; import io.fabric8.funktion.support.YamlHelper; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ConfigMapBuilder; import io.fabric8.kubernetes.api.model.extensions.Deployment; import io.fabric8.kubernetes.api.model.extensions.DeploymentBuilder; import io.fabric8.utils.IOHelpers; import io.fabric8.utils.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import static io.fabric8.funktion.Labels.Kind.CONNECTOR; import static io.fabric8.funktion.Labels.Kind.SUBSCRIPTION; /* * Copyright 2016 Red Hat, Inc. * <p> * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * */ package io.fabric8.funktion.connector.generator; /** */ public class Connectors { private static final transient Logger LOG = LoggerFactory.getLogger(Connectors.class); public static ConfigMap createConnector(ComponentModel component, String jSonSchema, String asciiDoc, String image, File applicationPropertiesFile) { String componentName = component.getScheme().toLowerCase(); Map<String, String> annotations = new LinkedHashMap<>(); Map<String, String> labels = new LinkedHashMap<>(); labels.put(Labels.KIND, CONNECTOR); Map<String, String> data = new LinkedHashMap<>(); Map<String, String> subscriptionLabels = new HashMap<>(); subscriptionLabels.put(Labels.KIND, SUBSCRIPTION); subscriptionLabels.put(Labels.CONNECTOR, componentName); Deployment deployment = new DeploymentBuilder(). withNewMetadata().withLabels(subscriptionLabels).endMetadata(). withNewSpec().withReplicas(1). withNewTemplate().withNewMetadata().withLabels(subscriptionLabels).endMetadata(). withNewSpec().addNewContainer().withName("connector").withImage(image).endContainer(). endSpec().endTemplate().endSpec().build(); try {
String deploymentYaml = YamlHelper.createYamlMapper().writeValueAsString(deployment);
funktionio/funktion-connectors
connector-generator/src/main/java/io/fabric8/funktion/connector/generator/Connectors.java
// Path: funktion-model/src/main/java/io/fabric8/funktion/DataKeys.java // public class DataKeys { // public static class Connector { // public static final String SCHEMA_YAML = "schema.yml"; // public static final String ASCIIDOC = "documentation.adoc"; // public static final String DEPLOYMENT_YAML = "deployment.yml"; // public static final String APPLICATION_PROPERTIES = Subscription.APPLICATION_PROPERTIES; // } // // public static class Subscription { // public static final String APPLICATION_PROPERTIES = "application.properties"; // public static final String FUNKTION_YAML = "funktion.yml"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public class Labels { // public static final String KIND = "funktion.fabric8.io/kind"; // public static final String CONNECTOR = "connector"; // // public static class Kind { // public static final String CONNECTOR = "Connector"; // public static final String SUBSCRIPTION = "Subscription"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/support/YamlHelper.java // public class YamlHelper { // public static ObjectMapper createYamlMapper() { // ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory() // .configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true) // .configure(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS, true) // .configure(YAMLGenerator.Feature.USE_NATIVE_OBJECT_ID, false) // .configure(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID, false) // ); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY). // enable(SerializationFeature.INDENT_OUTPUT). // disable(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS). // disable(SerializationFeature.WRITE_NULL_MAP_VALUES); // return objectMapper; // // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public static final String CONNECTOR = "Connector"; // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public static final String SUBSCRIPTION = "Subscription";
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import io.fabric8.funktion.DataKeys; import io.fabric8.funktion.Labels; import io.fabric8.funktion.support.YamlHelper; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ConfigMapBuilder; import io.fabric8.kubernetes.api.model.extensions.Deployment; import io.fabric8.kubernetes.api.model.extensions.DeploymentBuilder; import io.fabric8.utils.IOHelpers; import io.fabric8.utils.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import static io.fabric8.funktion.Labels.Kind.CONNECTOR; import static io.fabric8.funktion.Labels.Kind.SUBSCRIPTION;
/* * Copyright 2016 Red Hat, Inc. * <p> * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * */ package io.fabric8.funktion.connector.generator; /** */ public class Connectors { private static final transient Logger LOG = LoggerFactory.getLogger(Connectors.class); public static ConfigMap createConnector(ComponentModel component, String jSonSchema, String asciiDoc, String image, File applicationPropertiesFile) { String componentName = component.getScheme().toLowerCase(); Map<String, String> annotations = new LinkedHashMap<>(); Map<String, String> labels = new LinkedHashMap<>(); labels.put(Labels.KIND, CONNECTOR); Map<String, String> data = new LinkedHashMap<>(); Map<String, String> subscriptionLabels = new HashMap<>(); subscriptionLabels.put(Labels.KIND, SUBSCRIPTION); subscriptionLabels.put(Labels.CONNECTOR, componentName); Deployment deployment = new DeploymentBuilder(). withNewMetadata().withLabels(subscriptionLabels).endMetadata(). withNewSpec().withReplicas(1). withNewTemplate().withNewMetadata().withLabels(subscriptionLabels).endMetadata(). withNewSpec().addNewContainer().withName("connector").withImage(image).endContainer(). endSpec().endTemplate().endSpec().build(); try { String deploymentYaml = YamlHelper.createYamlMapper().writeValueAsString(deployment);
// Path: funktion-model/src/main/java/io/fabric8/funktion/DataKeys.java // public class DataKeys { // public static class Connector { // public static final String SCHEMA_YAML = "schema.yml"; // public static final String ASCIIDOC = "documentation.adoc"; // public static final String DEPLOYMENT_YAML = "deployment.yml"; // public static final String APPLICATION_PROPERTIES = Subscription.APPLICATION_PROPERTIES; // } // // public static class Subscription { // public static final String APPLICATION_PROPERTIES = "application.properties"; // public static final String FUNKTION_YAML = "funktion.yml"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public class Labels { // public static final String KIND = "funktion.fabric8.io/kind"; // public static final String CONNECTOR = "connector"; // // public static class Kind { // public static final String CONNECTOR = "Connector"; // public static final String SUBSCRIPTION = "Subscription"; // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/support/YamlHelper.java // public class YamlHelper { // public static ObjectMapper createYamlMapper() { // ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory() // .configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true) // .configure(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS, true) // .configure(YAMLGenerator.Feature.USE_NATIVE_OBJECT_ID, false) // .configure(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID, false) // ); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY). // enable(SerializationFeature.INDENT_OUTPUT). // disable(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS). // disable(SerializationFeature.WRITE_NULL_MAP_VALUES); // return objectMapper; // // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public static final String CONNECTOR = "Connector"; // // Path: funktion-model/src/main/java/io/fabric8/funktion/Labels.java // public static final String SUBSCRIPTION = "Subscription"; // Path: connector-generator/src/main/java/io/fabric8/funktion/connector/generator/Connectors.java import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import io.fabric8.funktion.DataKeys; import io.fabric8.funktion.Labels; import io.fabric8.funktion.support.YamlHelper; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ConfigMapBuilder; import io.fabric8.kubernetes.api.model.extensions.Deployment; import io.fabric8.kubernetes.api.model.extensions.DeploymentBuilder; import io.fabric8.utils.IOHelpers; import io.fabric8.utils.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import static io.fabric8.funktion.Labels.Kind.CONNECTOR; import static io.fabric8.funktion.Labels.Kind.SUBSCRIPTION; /* * Copyright 2016 Red Hat, Inc. * <p> * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * */ package io.fabric8.funktion.connector.generator; /** */ public class Connectors { private static final transient Logger LOG = LoggerFactory.getLogger(Connectors.class); public static ConfigMap createConnector(ComponentModel component, String jSonSchema, String asciiDoc, String image, File applicationPropertiesFile) { String componentName = component.getScheme().toLowerCase(); Map<String, String> annotations = new LinkedHashMap<>(); Map<String, String> labels = new LinkedHashMap<>(); labels.put(Labels.KIND, CONNECTOR); Map<String, String> data = new LinkedHashMap<>(); Map<String, String> subscriptionLabels = new HashMap<>(); subscriptionLabels.put(Labels.KIND, SUBSCRIPTION); subscriptionLabels.put(Labels.CONNECTOR, componentName); Deployment deployment = new DeploymentBuilder(). withNewMetadata().withLabels(subscriptionLabels).endMetadata(). withNewSpec().withReplicas(1). withNewTemplate().withNewMetadata().withLabels(subscriptionLabels).endMetadata(). withNewSpec().addNewContainer().withName("connector").withImage(image).endContainer(). endSpec().endTemplate().endSpec().build(); try { String deploymentYaml = YamlHelper.createYamlMapper().writeValueAsString(deployment);
data.put(DataKeys.Connector.DEPLOYMENT_YAML, deploymentYaml);
funktionio/funktion-connectors
funktion-model/src/main/java/io/fabric8/funktion/model/steps/SetHeaders.java
// Path: funktion-model/src/main/java/io/fabric8/funktion/model/StepKinds.java // public class StepKinds { // public static final String CHOICE = "choice"; // public static final String ENDPOINT = "endpoint"; // public static final String FILTER = "filter"; // public static final String FUNCTION = "function"; // public static final String FLOW = "flow"; // public static final String OTHERWISE = "otherwise"; // public static final String SET_BODY = "setBody"; // public static final String SET_HEADERS = "setHeaders"; // public static final String SPLIT = "split"; // public static final String THROTTLE = "throttle"; // public static final String LOG = "log"; // }
import io.fabric8.funktion.model.StepKinds; import java.util.HashMap; import java.util.Map;
/* * Copyright 2016 Red Hat, Inc. * <p> * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * */ package io.fabric8.funktion.model.steps; /** * Sets headers on the payload */ public class SetHeaders extends Step { private Map<String, Object> headers; public SetHeaders() {
// Path: funktion-model/src/main/java/io/fabric8/funktion/model/StepKinds.java // public class StepKinds { // public static final String CHOICE = "choice"; // public static final String ENDPOINT = "endpoint"; // public static final String FILTER = "filter"; // public static final String FUNCTION = "function"; // public static final String FLOW = "flow"; // public static final String OTHERWISE = "otherwise"; // public static final String SET_BODY = "setBody"; // public static final String SET_HEADERS = "setHeaders"; // public static final String SPLIT = "split"; // public static final String THROTTLE = "throttle"; // public static final String LOG = "log"; // } // Path: funktion-model/src/main/java/io/fabric8/funktion/model/steps/SetHeaders.java import io.fabric8.funktion.model.StepKinds; import java.util.HashMap; import java.util.Map; /* * Copyright 2016 Red Hat, Inc. * <p> * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * */ package io.fabric8.funktion.model.steps; /** * Sets headers on the payload */ public class SetHeaders extends Step { private Map<String, Object> headers; public SetHeaders() {
super(StepKinds.SET_HEADERS);
funktionio/funktion-connectors
funktion-model/src/main/java/io/fabric8/funktion/model/steps/Filter.java
// Path: funktion-model/src/main/java/io/fabric8/funktion/model/StepKinds.java // public class StepKinds { // public static final String CHOICE = "choice"; // public static final String ENDPOINT = "endpoint"; // public static final String FILTER = "filter"; // public static final String FUNCTION = "function"; // public static final String FLOW = "flow"; // public static final String OTHERWISE = "otherwise"; // public static final String SET_BODY = "setBody"; // public static final String SET_HEADERS = "setHeaders"; // public static final String SPLIT = "split"; // public static final String THROTTLE = "throttle"; // public static final String LOG = "log"; // }
import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.fabric8.funktion.model.StepKinds;
/* * Copyright 2016 Red Hat, Inc. * <p> * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * */ package io.fabric8.funktion.model.steps; /** * If a filter expression is matched then it invokes the child steps */ @JsonPropertyOrder({"expression", "language", "steps"}) public class Filter extends ChildSteps<Filter> { private String expression; private String language; public Filter() {
// Path: funktion-model/src/main/java/io/fabric8/funktion/model/StepKinds.java // public class StepKinds { // public static final String CHOICE = "choice"; // public static final String ENDPOINT = "endpoint"; // public static final String FILTER = "filter"; // public static final String FUNCTION = "function"; // public static final String FLOW = "flow"; // public static final String OTHERWISE = "otherwise"; // public static final String SET_BODY = "setBody"; // public static final String SET_HEADERS = "setHeaders"; // public static final String SPLIT = "split"; // public static final String THROTTLE = "throttle"; // public static final String LOG = "log"; // } // Path: funktion-model/src/main/java/io/fabric8/funktion/model/steps/Filter.java import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.fabric8.funktion.model.StepKinds; /* * Copyright 2016 Red Hat, Inc. * <p> * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * */ package io.fabric8.funktion.model.steps; /** * If a filter expression is matched then it invokes the child steps */ @JsonPropertyOrder({"expression", "language", "steps"}) public class Filter extends ChildSteps<Filter> { private String expression; private String language; public Filter() {
super(StepKinds.FILTER);
funktionio/funktion-connectors
funktion-agent/src/test/java/io/fabric8/funktion/agent/AgentKT.java
// Path: funktion-agent/src/test/java/io/fabric8/funktion/agent/support/CamelTester.java // public class CamelTester { // private static final transient Logger LOG = LoggerFactory.getLogger(CamelTester.class); // // protected final TestRouteBuilder routeBuilder; // protected final CamelContext camelContext; // // public CamelTester(TestRouteBuilder routeBuilder) { // this(routeBuilder, new DefaultCamelContext()); // } // // public CamelTester(TestRouteBuilder routeBuilder, CamelContext camelContext) { // this.routeBuilder = routeBuilder; // this.camelContext = camelContext; // } // // public static void assertIsSatisfied(TestRouteBuilder routeBuilder) throws Exception { // CamelTester tester = new CamelTester(routeBuilder); // tester.assertIsSatisfied(); // } // // public static void assertIsSatisfied(TestRouteBuilder routeBuilder, CamelContext camelContext) throws Exception { // CamelTester tester = new CamelTester(routeBuilder, camelContext); // tester.assertIsSatisfied(); // } // // /** // * Asserts that the expectations in the <code>routeBuilder</code> are satisfied // * // * @return the result exchanges // * @throws Exception if the assertions could not be satisfied // */ // public List<Exchange> assertIsSatisfied() throws Exception { // camelContext.addRoutes(routeBuilder); // // try { // camelContext.start(); // return routeBuilder.assertIsSatisfied(); // } catch (Throwable e) { // LOG.error("Failed: " + e, e); // throw e; // } finally { // camelContext.stop(); // } // } // } // // Path: funktion-agent/src/test/java/io/fabric8/funktion/agent/support/TestRouteBuilder.java // public abstract class TestRouteBuilder extends RouteBuilder { // private static final transient Logger LOG = LoggerFactory.getLogger(TestRouteBuilder.class); // // protected MockEndpoint results; // protected MockEndpoint errors; // // public MockEndpoint getResults() { // return results; // } // // public MockEndpoint getErrors() { // return errors; // } // // @Override // public void configure() throws Exception { // this.results = endpoint("mock:results", MockEndpoint.class); // this.errors = endpoint("mock:errors", MockEndpoint.class); // // configureTest(); // } // // protected abstract void configureTest() throws Exception; // // /** // * Asserts that all the expectations on the <code>results</code> and <code>errors</code> endpoints are met // * // * @return the results exchanges // * @throws Exception if the assertion fails // */ // public List<Exchange> assertIsSatisfied() throws Exception { // results.assertIsSatisfied(); // errors.assertIsSatisfied(); // List<Exchange> results = this.results.getExchanges(); // logResults(results); // return results; // } // // protected void logResults(List<Exchange> results) { // int idx = 0; // for (Exchange result : results) { // Message in = result.getIn(); // LOG.info("=> Result exchange: " + idx++ + " " + in.getBody() + " headers: " + in.getHeaders()); // } // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/model/Funktion.java // public class Funktion extends DtoSupport { // private List<Flow> flows = new ArrayList<>(); // // public List<Flow> getFlows() { // return flows; // } // // public void setFlows(List<Flow> flows) { // this.flows = flows; // } // // public Flow createFlow() { // return addFlow(new Flow()); // } // // public Flow addFlow(Flow flow) { // flows.add(flow); // return flow; // } // }
import java.util.HashMap; import java.util.Map; import static io.fabric8.utils.URLUtils.pathJoin; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Fail.fail; import io.fabric8.funktion.agent.support.CamelTester; import io.fabric8.funktion.agent.support.TestRouteBuilder; import io.fabric8.funktion.model.Funktion; import io.fabric8.kubernetes.api.KubernetesHelper; import org.apache.camel.model.dataformat.JsonLibrary; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.ResponseEntity; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import java.util.Date;
/* * Copyright 2016 Red Hat, Inc. * <p> * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * */ package io.fabric8.funktion.agent; /** * This test case will spin up a new Funktion Subscription with a YAML file in a new Deployment then assert * that the Funktion flow writes the correct data to Elasticsearch running inside Kubernetes then ensure the * subscription is torn down again */ public class AgentKT { private static final transient Logger LOG = LoggerFactory.getLogger(AgentKT.class); protected Agent agent = new Agent(); @Test public void testAgentSubscribe() throws Throwable { String elasticSearchPath = "/testagent/funktion/1"; String namespace = agent.getCurrentNamespace(); String elasticsearchURL = getHttpServiceURL(namespace, "elasticsearch"); String elasticSearchResource = pathJoin(elasticsearchURL, elasticSearchPath); deleteResource(elasticSearchResource); LOG.info("Creating a subscription in namespace: " + namespace); String expectedName = getClass().getName(); SamplePayload payload = new SamplePayload(expectedName, new Date()); String body = KubernetesHelper.toJson(payload); LOG.info("Sending JSON: " + body); SubscribeResponse response = null; try {
// Path: funktion-agent/src/test/java/io/fabric8/funktion/agent/support/CamelTester.java // public class CamelTester { // private static final transient Logger LOG = LoggerFactory.getLogger(CamelTester.class); // // protected final TestRouteBuilder routeBuilder; // protected final CamelContext camelContext; // // public CamelTester(TestRouteBuilder routeBuilder) { // this(routeBuilder, new DefaultCamelContext()); // } // // public CamelTester(TestRouteBuilder routeBuilder, CamelContext camelContext) { // this.routeBuilder = routeBuilder; // this.camelContext = camelContext; // } // // public static void assertIsSatisfied(TestRouteBuilder routeBuilder) throws Exception { // CamelTester tester = new CamelTester(routeBuilder); // tester.assertIsSatisfied(); // } // // public static void assertIsSatisfied(TestRouteBuilder routeBuilder, CamelContext camelContext) throws Exception { // CamelTester tester = new CamelTester(routeBuilder, camelContext); // tester.assertIsSatisfied(); // } // // /** // * Asserts that the expectations in the <code>routeBuilder</code> are satisfied // * // * @return the result exchanges // * @throws Exception if the assertions could not be satisfied // */ // public List<Exchange> assertIsSatisfied() throws Exception { // camelContext.addRoutes(routeBuilder); // // try { // camelContext.start(); // return routeBuilder.assertIsSatisfied(); // } catch (Throwable e) { // LOG.error("Failed: " + e, e); // throw e; // } finally { // camelContext.stop(); // } // } // } // // Path: funktion-agent/src/test/java/io/fabric8/funktion/agent/support/TestRouteBuilder.java // public abstract class TestRouteBuilder extends RouteBuilder { // private static final transient Logger LOG = LoggerFactory.getLogger(TestRouteBuilder.class); // // protected MockEndpoint results; // protected MockEndpoint errors; // // public MockEndpoint getResults() { // return results; // } // // public MockEndpoint getErrors() { // return errors; // } // // @Override // public void configure() throws Exception { // this.results = endpoint("mock:results", MockEndpoint.class); // this.errors = endpoint("mock:errors", MockEndpoint.class); // // configureTest(); // } // // protected abstract void configureTest() throws Exception; // // /** // * Asserts that all the expectations on the <code>results</code> and <code>errors</code> endpoints are met // * // * @return the results exchanges // * @throws Exception if the assertion fails // */ // public List<Exchange> assertIsSatisfied() throws Exception { // results.assertIsSatisfied(); // errors.assertIsSatisfied(); // List<Exchange> results = this.results.getExchanges(); // logResults(results); // return results; // } // // protected void logResults(List<Exchange> results) { // int idx = 0; // for (Exchange result : results) { // Message in = result.getIn(); // LOG.info("=> Result exchange: " + idx++ + " " + in.getBody() + " headers: " + in.getHeaders()); // } // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/model/Funktion.java // public class Funktion extends DtoSupport { // private List<Flow> flows = new ArrayList<>(); // // public List<Flow> getFlows() { // return flows; // } // // public void setFlows(List<Flow> flows) { // this.flows = flows; // } // // public Flow createFlow() { // return addFlow(new Flow()); // } // // public Flow addFlow(Flow flow) { // flows.add(flow); // return flow; // } // } // Path: funktion-agent/src/test/java/io/fabric8/funktion/agent/AgentKT.java import java.util.HashMap; import java.util.Map; import static io.fabric8.utils.URLUtils.pathJoin; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Fail.fail; import io.fabric8.funktion.agent.support.CamelTester; import io.fabric8.funktion.agent.support.TestRouteBuilder; import io.fabric8.funktion.model.Funktion; import io.fabric8.kubernetes.api.KubernetesHelper; import org.apache.camel.model.dataformat.JsonLibrary; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.ResponseEntity; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import java.util.Date; /* * Copyright 2016 Red Hat, Inc. * <p> * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * */ package io.fabric8.funktion.agent; /** * This test case will spin up a new Funktion Subscription with a YAML file in a new Deployment then assert * that the Funktion flow writes the correct data to Elasticsearch running inside Kubernetes then ensure the * subscription is torn down again */ public class AgentKT { private static final transient Logger LOG = LoggerFactory.getLogger(AgentKT.class); protected Agent agent = new Agent(); @Test public void testAgentSubscribe() throws Throwable { String elasticSearchPath = "/testagent/funktion/1"; String namespace = agent.getCurrentNamespace(); String elasticsearchURL = getHttpServiceURL(namespace, "elasticsearch"); String elasticSearchResource = pathJoin(elasticsearchURL, elasticSearchPath); deleteResource(elasticSearchResource); LOG.info("Creating a subscription in namespace: " + namespace); String expectedName = getClass().getName(); SamplePayload payload = new SamplePayload(expectedName, new Date()); String body = KubernetesHelper.toJson(payload); LOG.info("Sending JSON: " + body); SubscribeResponse response = null; try {
Funktion funktion = new Funktion();
funktionio/funktion-connectors
funktion-agent/src/test/java/io/fabric8/funktion/agent/AgentKT.java
// Path: funktion-agent/src/test/java/io/fabric8/funktion/agent/support/CamelTester.java // public class CamelTester { // private static final transient Logger LOG = LoggerFactory.getLogger(CamelTester.class); // // protected final TestRouteBuilder routeBuilder; // protected final CamelContext camelContext; // // public CamelTester(TestRouteBuilder routeBuilder) { // this(routeBuilder, new DefaultCamelContext()); // } // // public CamelTester(TestRouteBuilder routeBuilder, CamelContext camelContext) { // this.routeBuilder = routeBuilder; // this.camelContext = camelContext; // } // // public static void assertIsSatisfied(TestRouteBuilder routeBuilder) throws Exception { // CamelTester tester = new CamelTester(routeBuilder); // tester.assertIsSatisfied(); // } // // public static void assertIsSatisfied(TestRouteBuilder routeBuilder, CamelContext camelContext) throws Exception { // CamelTester tester = new CamelTester(routeBuilder, camelContext); // tester.assertIsSatisfied(); // } // // /** // * Asserts that the expectations in the <code>routeBuilder</code> are satisfied // * // * @return the result exchanges // * @throws Exception if the assertions could not be satisfied // */ // public List<Exchange> assertIsSatisfied() throws Exception { // camelContext.addRoutes(routeBuilder); // // try { // camelContext.start(); // return routeBuilder.assertIsSatisfied(); // } catch (Throwable e) { // LOG.error("Failed: " + e, e); // throw e; // } finally { // camelContext.stop(); // } // } // } // // Path: funktion-agent/src/test/java/io/fabric8/funktion/agent/support/TestRouteBuilder.java // public abstract class TestRouteBuilder extends RouteBuilder { // private static final transient Logger LOG = LoggerFactory.getLogger(TestRouteBuilder.class); // // protected MockEndpoint results; // protected MockEndpoint errors; // // public MockEndpoint getResults() { // return results; // } // // public MockEndpoint getErrors() { // return errors; // } // // @Override // public void configure() throws Exception { // this.results = endpoint("mock:results", MockEndpoint.class); // this.errors = endpoint("mock:errors", MockEndpoint.class); // // configureTest(); // } // // protected abstract void configureTest() throws Exception; // // /** // * Asserts that all the expectations on the <code>results</code> and <code>errors</code> endpoints are met // * // * @return the results exchanges // * @throws Exception if the assertion fails // */ // public List<Exchange> assertIsSatisfied() throws Exception { // results.assertIsSatisfied(); // errors.assertIsSatisfied(); // List<Exchange> results = this.results.getExchanges(); // logResults(results); // return results; // } // // protected void logResults(List<Exchange> results) { // int idx = 0; // for (Exchange result : results) { // Message in = result.getIn(); // LOG.info("=> Result exchange: " + idx++ + " " + in.getBody() + " headers: " + in.getHeaders()); // } // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/model/Funktion.java // public class Funktion extends DtoSupport { // private List<Flow> flows = new ArrayList<>(); // // public List<Flow> getFlows() { // return flows; // } // // public void setFlows(List<Flow> flows) { // this.flows = flows; // } // // public Flow createFlow() { // return addFlow(new Flow()); // } // // public Flow addFlow(Flow flow) { // flows.add(flow); // return flow; // } // }
import java.util.HashMap; import java.util.Map; import static io.fabric8.utils.URLUtils.pathJoin; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Fail.fail; import io.fabric8.funktion.agent.support.CamelTester; import io.fabric8.funktion.agent.support.TestRouteBuilder; import io.fabric8.funktion.model.Funktion; import io.fabric8.kubernetes.api.KubernetesHelper; import org.apache.camel.model.dataformat.JsonLibrary; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.ResponseEntity; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import java.util.Date;
} } } private void deleteResource(String resource) { LOG.info("trying to delete " + resource); RestTemplate restTemplate = new RestTemplate(); try { restTemplate.delete(resource); } catch (RestClientException e) { LOG.info("Ignoring delete exception on resource: " + resource + " as it may not exist: " + e); } // lets assert it does not exist any more try { ResponseEntity<String> response = restTemplate.getForEntity(resource, String.class); fail("Should not have found resource: " + resource + " with: " + response.getBody()); } catch (HttpClientErrorException e) { String responseBody = e.getResponseBodyAsString(); int statusCode = e.getRawStatusCode(); LOG.info("As expected we could not find resource " + resource + " and got status: " + statusCode + " with: " + responseBody); assertThat(statusCode).describedAs("Response code after getting " + resource + " with result: " + responseBody).isGreaterThanOrEqualTo(400); } } private void assertWaitForResults(String namespace, String elasticSearchResource, SamplePayload payload) throws Throwable { final String pollUrl = pathJoin(elasticSearchResource, "/_source"); LOG.info("Querying elasticsearch URL: " + pollUrl);
// Path: funktion-agent/src/test/java/io/fabric8/funktion/agent/support/CamelTester.java // public class CamelTester { // private static final transient Logger LOG = LoggerFactory.getLogger(CamelTester.class); // // protected final TestRouteBuilder routeBuilder; // protected final CamelContext camelContext; // // public CamelTester(TestRouteBuilder routeBuilder) { // this(routeBuilder, new DefaultCamelContext()); // } // // public CamelTester(TestRouteBuilder routeBuilder, CamelContext camelContext) { // this.routeBuilder = routeBuilder; // this.camelContext = camelContext; // } // // public static void assertIsSatisfied(TestRouteBuilder routeBuilder) throws Exception { // CamelTester tester = new CamelTester(routeBuilder); // tester.assertIsSatisfied(); // } // // public static void assertIsSatisfied(TestRouteBuilder routeBuilder, CamelContext camelContext) throws Exception { // CamelTester tester = new CamelTester(routeBuilder, camelContext); // tester.assertIsSatisfied(); // } // // /** // * Asserts that the expectations in the <code>routeBuilder</code> are satisfied // * // * @return the result exchanges // * @throws Exception if the assertions could not be satisfied // */ // public List<Exchange> assertIsSatisfied() throws Exception { // camelContext.addRoutes(routeBuilder); // // try { // camelContext.start(); // return routeBuilder.assertIsSatisfied(); // } catch (Throwable e) { // LOG.error("Failed: " + e, e); // throw e; // } finally { // camelContext.stop(); // } // } // } // // Path: funktion-agent/src/test/java/io/fabric8/funktion/agent/support/TestRouteBuilder.java // public abstract class TestRouteBuilder extends RouteBuilder { // private static final transient Logger LOG = LoggerFactory.getLogger(TestRouteBuilder.class); // // protected MockEndpoint results; // protected MockEndpoint errors; // // public MockEndpoint getResults() { // return results; // } // // public MockEndpoint getErrors() { // return errors; // } // // @Override // public void configure() throws Exception { // this.results = endpoint("mock:results", MockEndpoint.class); // this.errors = endpoint("mock:errors", MockEndpoint.class); // // configureTest(); // } // // protected abstract void configureTest() throws Exception; // // /** // * Asserts that all the expectations on the <code>results</code> and <code>errors</code> endpoints are met // * // * @return the results exchanges // * @throws Exception if the assertion fails // */ // public List<Exchange> assertIsSatisfied() throws Exception { // results.assertIsSatisfied(); // errors.assertIsSatisfied(); // List<Exchange> results = this.results.getExchanges(); // logResults(results); // return results; // } // // protected void logResults(List<Exchange> results) { // int idx = 0; // for (Exchange result : results) { // Message in = result.getIn(); // LOG.info("=> Result exchange: " + idx++ + " " + in.getBody() + " headers: " + in.getHeaders()); // } // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/model/Funktion.java // public class Funktion extends DtoSupport { // private List<Flow> flows = new ArrayList<>(); // // public List<Flow> getFlows() { // return flows; // } // // public void setFlows(List<Flow> flows) { // this.flows = flows; // } // // public Flow createFlow() { // return addFlow(new Flow()); // } // // public Flow addFlow(Flow flow) { // flows.add(flow); // return flow; // } // } // Path: funktion-agent/src/test/java/io/fabric8/funktion/agent/AgentKT.java import java.util.HashMap; import java.util.Map; import static io.fabric8.utils.URLUtils.pathJoin; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Fail.fail; import io.fabric8.funktion.agent.support.CamelTester; import io.fabric8.funktion.agent.support.TestRouteBuilder; import io.fabric8.funktion.model.Funktion; import io.fabric8.kubernetes.api.KubernetesHelper; import org.apache.camel.model.dataformat.JsonLibrary; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.ResponseEntity; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import java.util.Date; } } } private void deleteResource(String resource) { LOG.info("trying to delete " + resource); RestTemplate restTemplate = new RestTemplate(); try { restTemplate.delete(resource); } catch (RestClientException e) { LOG.info("Ignoring delete exception on resource: " + resource + " as it may not exist: " + e); } // lets assert it does not exist any more try { ResponseEntity<String> response = restTemplate.getForEntity(resource, String.class); fail("Should not have found resource: " + resource + " with: " + response.getBody()); } catch (HttpClientErrorException e) { String responseBody = e.getResponseBodyAsString(); int statusCode = e.getRawStatusCode(); LOG.info("As expected we could not find resource " + resource + " and got status: " + statusCode + " with: " + responseBody); assertThat(statusCode).describedAs("Response code after getting " + resource + " with result: " + responseBody).isGreaterThanOrEqualTo(400); } } private void assertWaitForResults(String namespace, String elasticSearchResource, SamplePayload payload) throws Throwable { final String pollUrl = pathJoin(elasticSearchResource, "/_source"); LOG.info("Querying elasticsearch URL: " + pollUrl);
CamelTester.assertIsSatisfied(new TestRouteBuilder() {
funktionio/funktion-connectors
funktion-agent/src/test/java/io/fabric8/funktion/agent/AgentKT.java
// Path: funktion-agent/src/test/java/io/fabric8/funktion/agent/support/CamelTester.java // public class CamelTester { // private static final transient Logger LOG = LoggerFactory.getLogger(CamelTester.class); // // protected final TestRouteBuilder routeBuilder; // protected final CamelContext camelContext; // // public CamelTester(TestRouteBuilder routeBuilder) { // this(routeBuilder, new DefaultCamelContext()); // } // // public CamelTester(TestRouteBuilder routeBuilder, CamelContext camelContext) { // this.routeBuilder = routeBuilder; // this.camelContext = camelContext; // } // // public static void assertIsSatisfied(TestRouteBuilder routeBuilder) throws Exception { // CamelTester tester = new CamelTester(routeBuilder); // tester.assertIsSatisfied(); // } // // public static void assertIsSatisfied(TestRouteBuilder routeBuilder, CamelContext camelContext) throws Exception { // CamelTester tester = new CamelTester(routeBuilder, camelContext); // tester.assertIsSatisfied(); // } // // /** // * Asserts that the expectations in the <code>routeBuilder</code> are satisfied // * // * @return the result exchanges // * @throws Exception if the assertions could not be satisfied // */ // public List<Exchange> assertIsSatisfied() throws Exception { // camelContext.addRoutes(routeBuilder); // // try { // camelContext.start(); // return routeBuilder.assertIsSatisfied(); // } catch (Throwable e) { // LOG.error("Failed: " + e, e); // throw e; // } finally { // camelContext.stop(); // } // } // } // // Path: funktion-agent/src/test/java/io/fabric8/funktion/agent/support/TestRouteBuilder.java // public abstract class TestRouteBuilder extends RouteBuilder { // private static final transient Logger LOG = LoggerFactory.getLogger(TestRouteBuilder.class); // // protected MockEndpoint results; // protected MockEndpoint errors; // // public MockEndpoint getResults() { // return results; // } // // public MockEndpoint getErrors() { // return errors; // } // // @Override // public void configure() throws Exception { // this.results = endpoint("mock:results", MockEndpoint.class); // this.errors = endpoint("mock:errors", MockEndpoint.class); // // configureTest(); // } // // protected abstract void configureTest() throws Exception; // // /** // * Asserts that all the expectations on the <code>results</code> and <code>errors</code> endpoints are met // * // * @return the results exchanges // * @throws Exception if the assertion fails // */ // public List<Exchange> assertIsSatisfied() throws Exception { // results.assertIsSatisfied(); // errors.assertIsSatisfied(); // List<Exchange> results = this.results.getExchanges(); // logResults(results); // return results; // } // // protected void logResults(List<Exchange> results) { // int idx = 0; // for (Exchange result : results) { // Message in = result.getIn(); // LOG.info("=> Result exchange: " + idx++ + " " + in.getBody() + " headers: " + in.getHeaders()); // } // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/model/Funktion.java // public class Funktion extends DtoSupport { // private List<Flow> flows = new ArrayList<>(); // // public List<Flow> getFlows() { // return flows; // } // // public void setFlows(List<Flow> flows) { // this.flows = flows; // } // // public Flow createFlow() { // return addFlow(new Flow()); // } // // public Flow addFlow(Flow flow) { // flows.add(flow); // return flow; // } // }
import java.util.HashMap; import java.util.Map; import static io.fabric8.utils.URLUtils.pathJoin; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Fail.fail; import io.fabric8.funktion.agent.support.CamelTester; import io.fabric8.funktion.agent.support.TestRouteBuilder; import io.fabric8.funktion.model.Funktion; import io.fabric8.kubernetes.api.KubernetesHelper; import org.apache.camel.model.dataformat.JsonLibrary; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.ResponseEntity; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import java.util.Date;
} } } private void deleteResource(String resource) { LOG.info("trying to delete " + resource); RestTemplate restTemplate = new RestTemplate(); try { restTemplate.delete(resource); } catch (RestClientException e) { LOG.info("Ignoring delete exception on resource: " + resource + " as it may not exist: " + e); } // lets assert it does not exist any more try { ResponseEntity<String> response = restTemplate.getForEntity(resource, String.class); fail("Should not have found resource: " + resource + " with: " + response.getBody()); } catch (HttpClientErrorException e) { String responseBody = e.getResponseBodyAsString(); int statusCode = e.getRawStatusCode(); LOG.info("As expected we could not find resource " + resource + " and got status: " + statusCode + " with: " + responseBody); assertThat(statusCode).describedAs("Response code after getting " + resource + " with result: " + responseBody).isGreaterThanOrEqualTo(400); } } private void assertWaitForResults(String namespace, String elasticSearchResource, SamplePayload payload) throws Throwable { final String pollUrl = pathJoin(elasticSearchResource, "/_source"); LOG.info("Querying elasticsearch URL: " + pollUrl);
// Path: funktion-agent/src/test/java/io/fabric8/funktion/agent/support/CamelTester.java // public class CamelTester { // private static final transient Logger LOG = LoggerFactory.getLogger(CamelTester.class); // // protected final TestRouteBuilder routeBuilder; // protected final CamelContext camelContext; // // public CamelTester(TestRouteBuilder routeBuilder) { // this(routeBuilder, new DefaultCamelContext()); // } // // public CamelTester(TestRouteBuilder routeBuilder, CamelContext camelContext) { // this.routeBuilder = routeBuilder; // this.camelContext = camelContext; // } // // public static void assertIsSatisfied(TestRouteBuilder routeBuilder) throws Exception { // CamelTester tester = new CamelTester(routeBuilder); // tester.assertIsSatisfied(); // } // // public static void assertIsSatisfied(TestRouteBuilder routeBuilder, CamelContext camelContext) throws Exception { // CamelTester tester = new CamelTester(routeBuilder, camelContext); // tester.assertIsSatisfied(); // } // // /** // * Asserts that the expectations in the <code>routeBuilder</code> are satisfied // * // * @return the result exchanges // * @throws Exception if the assertions could not be satisfied // */ // public List<Exchange> assertIsSatisfied() throws Exception { // camelContext.addRoutes(routeBuilder); // // try { // camelContext.start(); // return routeBuilder.assertIsSatisfied(); // } catch (Throwable e) { // LOG.error("Failed: " + e, e); // throw e; // } finally { // camelContext.stop(); // } // } // } // // Path: funktion-agent/src/test/java/io/fabric8/funktion/agent/support/TestRouteBuilder.java // public abstract class TestRouteBuilder extends RouteBuilder { // private static final transient Logger LOG = LoggerFactory.getLogger(TestRouteBuilder.class); // // protected MockEndpoint results; // protected MockEndpoint errors; // // public MockEndpoint getResults() { // return results; // } // // public MockEndpoint getErrors() { // return errors; // } // // @Override // public void configure() throws Exception { // this.results = endpoint("mock:results", MockEndpoint.class); // this.errors = endpoint("mock:errors", MockEndpoint.class); // // configureTest(); // } // // protected abstract void configureTest() throws Exception; // // /** // * Asserts that all the expectations on the <code>results</code> and <code>errors</code> endpoints are met // * // * @return the results exchanges // * @throws Exception if the assertion fails // */ // public List<Exchange> assertIsSatisfied() throws Exception { // results.assertIsSatisfied(); // errors.assertIsSatisfied(); // List<Exchange> results = this.results.getExchanges(); // logResults(results); // return results; // } // // protected void logResults(List<Exchange> results) { // int idx = 0; // for (Exchange result : results) { // Message in = result.getIn(); // LOG.info("=> Result exchange: " + idx++ + " " + in.getBody() + " headers: " + in.getHeaders()); // } // } // } // // Path: funktion-model/src/main/java/io/fabric8/funktion/model/Funktion.java // public class Funktion extends DtoSupport { // private List<Flow> flows = new ArrayList<>(); // // public List<Flow> getFlows() { // return flows; // } // // public void setFlows(List<Flow> flows) { // this.flows = flows; // } // // public Flow createFlow() { // return addFlow(new Flow()); // } // // public Flow addFlow(Flow flow) { // flows.add(flow); // return flow; // } // } // Path: funktion-agent/src/test/java/io/fabric8/funktion/agent/AgentKT.java import java.util.HashMap; import java.util.Map; import static io.fabric8.utils.URLUtils.pathJoin; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Fail.fail; import io.fabric8.funktion.agent.support.CamelTester; import io.fabric8.funktion.agent.support.TestRouteBuilder; import io.fabric8.funktion.model.Funktion; import io.fabric8.kubernetes.api.KubernetesHelper; import org.apache.camel.model.dataformat.JsonLibrary; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.ResponseEntity; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import java.util.Date; } } } private void deleteResource(String resource) { LOG.info("trying to delete " + resource); RestTemplate restTemplate = new RestTemplate(); try { restTemplate.delete(resource); } catch (RestClientException e) { LOG.info("Ignoring delete exception on resource: " + resource + " as it may not exist: " + e); } // lets assert it does not exist any more try { ResponseEntity<String> response = restTemplate.getForEntity(resource, String.class); fail("Should not have found resource: " + resource + " with: " + response.getBody()); } catch (HttpClientErrorException e) { String responseBody = e.getResponseBodyAsString(); int statusCode = e.getRawStatusCode(); LOG.info("As expected we could not find resource " + resource + " and got status: " + statusCode + " with: " + responseBody); assertThat(statusCode).describedAs("Response code after getting " + resource + " with result: " + responseBody).isGreaterThanOrEqualTo(400); } } private void assertWaitForResults(String namespace, String elasticSearchResource, SamplePayload payload) throws Throwable { final String pollUrl = pathJoin(elasticSearchResource, "/_source"); LOG.info("Querying elasticsearch URL: " + pollUrl);
CamelTester.assertIsSatisfied(new TestRouteBuilder() {
funktionio/funktion-connectors
funktion-runtime/src/test/java/io/fabric8/funktion/runtime/steps/FilterYamlTest.java
// Path: funktion-model/src/main/java/io/fabric8/funktion/model/Funktion.java // public class Funktion extends DtoSupport { // private List<Flow> flows = new ArrayList<>(); // // public List<Flow> getFlows() { // return flows; // } // // public void setFlows(List<Flow> flows) { // this.flows = flows; // } // // public Flow createFlow() { // return addFlow(new Flow()); // } // // public Flow addFlow(Flow flow) { // flows.add(flow); // return flow; // } // }
import io.fabric8.funktion.model.Funktion; import java.io.IOException;
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.fabric8.funktion.runtime.steps; /** * Loads the test flow YAML file from src/test/resources/*.yml on the classpath */ public class FilterYamlTest extends FilterTest { @Override
// Path: funktion-model/src/main/java/io/fabric8/funktion/model/Funktion.java // public class Funktion extends DtoSupport { // private List<Flow> flows = new ArrayList<>(); // // public List<Flow> getFlows() { // return flows; // } // // public void setFlows(List<Flow> flows) { // this.flows = flows; // } // // public Flow createFlow() { // return addFlow(new Flow()); // } // // public Flow addFlow(Flow flow) { // flows.add(flow); // return flow; // } // } // Path: funktion-runtime/src/test/java/io/fabric8/funktion/runtime/steps/FilterYamlTest.java import io.fabric8.funktion.model.Funktion; import java.io.IOException; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.fabric8.funktion.runtime.steps; /** * Loads the test flow YAML file from src/test/resources/*.yml on the classpath */ public class FilterYamlTest extends FilterTest { @Override
protected Funktion createFunktion() throws IOException {
funktionio/funktion-connectors
funktion-model/src/main/java/io/fabric8/funktion/model/steps/Log.java
// Path: funktion-model/src/main/java/io/fabric8/funktion/model/StepKinds.java // public class StepKinds { // public static final String CHOICE = "choice"; // public static final String ENDPOINT = "endpoint"; // public static final String FILTER = "filter"; // public static final String FUNCTION = "function"; // public static final String FLOW = "flow"; // public static final String OTHERWISE = "otherwise"; // public static final String SET_BODY = "setBody"; // public static final String SET_HEADERS = "setHeaders"; // public static final String SPLIT = "split"; // public static final String THROTTLE = "throttle"; // public static final String LOG = "log"; // }
import io.fabric8.funktion.model.StepKinds;
/* * Copyright 2016 Red Hat, Inc. * <p> * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * */ package io.fabric8.funktion.model.steps; /** * Sets the payload body */ public class Log extends Step { private String message; private String marker; private String logger; private String loggingLevel = "INFO"; public Log() {
// Path: funktion-model/src/main/java/io/fabric8/funktion/model/StepKinds.java // public class StepKinds { // public static final String CHOICE = "choice"; // public static final String ENDPOINT = "endpoint"; // public static final String FILTER = "filter"; // public static final String FUNCTION = "function"; // public static final String FLOW = "flow"; // public static final String OTHERWISE = "otherwise"; // public static final String SET_BODY = "setBody"; // public static final String SET_HEADERS = "setHeaders"; // public static final String SPLIT = "split"; // public static final String THROTTLE = "throttle"; // public static final String LOG = "log"; // } // Path: funktion-model/src/main/java/io/fabric8/funktion/model/steps/Log.java import io.fabric8.funktion.model.StepKinds; /* * Copyright 2016 Red Hat, Inc. * <p> * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * */ package io.fabric8.funktion.model.steps; /** * Sets the payload body */ public class Log extends Step { private String message; private String marker; private String logger; private String loggingLevel = "INFO"; public Log() {
super(StepKinds.LOG);
funktionio/funktion-connectors
funktion-runtime/src/test/java/io/fabric8/funktion/runtime/steps/LogYamlTest.java
// Path: funktion-model/src/main/java/io/fabric8/funktion/model/Funktion.java // public class Funktion extends DtoSupport { // private List<Flow> flows = new ArrayList<>(); // // public List<Flow> getFlows() { // return flows; // } // // public void setFlows(List<Flow> flows) { // this.flows = flows; // } // // public Flow createFlow() { // return addFlow(new Flow()); // } // // public Flow addFlow(Flow flow) { // flows.add(flow); // return flow; // } // }
import io.fabric8.funktion.model.Funktion; import java.io.IOException;
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.fabric8.funktion.runtime.steps; /** * Loads the test flow YAML file from src/test/resources/*.yml on the classpath */ public class LogYamlTest extends LogTest { @Override
// Path: funktion-model/src/main/java/io/fabric8/funktion/model/Funktion.java // public class Funktion extends DtoSupport { // private List<Flow> flows = new ArrayList<>(); // // public List<Flow> getFlows() { // return flows; // } // // public void setFlows(List<Flow> flows) { // this.flows = flows; // } // // public Flow createFlow() { // return addFlow(new Flow()); // } // // public Flow addFlow(Flow flow) { // flows.add(flow); // return flow; // } // } // Path: funktion-runtime/src/test/java/io/fabric8/funktion/runtime/steps/LogYamlTest.java import io.fabric8.funktion.model.Funktion; import java.io.IOException; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.fabric8.funktion.runtime.steps; /** * Loads the test flow YAML file from src/test/resources/*.yml on the classpath */ public class LogYamlTest extends LogTest { @Override
protected Funktion createFunktion() throws IOException {
funktionio/funktion-connectors
funktion-model/src/main/java/io/fabric8/funktion/model/steps/Function.java
// Path: funktion-model/src/main/java/io/fabric8/funktion/model/StepKinds.java // public class StepKinds { // public static final String CHOICE = "choice"; // public static final String ENDPOINT = "endpoint"; // public static final String FILTER = "filter"; // public static final String FUNCTION = "function"; // public static final String FLOW = "flow"; // public static final String OTHERWISE = "otherwise"; // public static final String SET_BODY = "setBody"; // public static final String SET_HEADERS = "setHeaders"; // public static final String SPLIT = "split"; // public static final String THROTTLE = "throttle"; // public static final String LOG = "log"; // }
import io.fabric8.funktion.model.StepKinds;
/* * Copyright 2016 Red Hat, Inc. * <p> * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * */ package io.fabric8.funktion.model.steps; /** * Invokes a function with the current payload */ public class Function extends Step { private String name; public Function() {
// Path: funktion-model/src/main/java/io/fabric8/funktion/model/StepKinds.java // public class StepKinds { // public static final String CHOICE = "choice"; // public static final String ENDPOINT = "endpoint"; // public static final String FILTER = "filter"; // public static final String FUNCTION = "function"; // public static final String FLOW = "flow"; // public static final String OTHERWISE = "otherwise"; // public static final String SET_BODY = "setBody"; // public static final String SET_HEADERS = "setHeaders"; // public static final String SPLIT = "split"; // public static final String THROTTLE = "throttle"; // public static final String LOG = "log"; // } // Path: funktion-model/src/main/java/io/fabric8/funktion/model/steps/Function.java import io.fabric8.funktion.model.StepKinds; /* * Copyright 2016 Red Hat, Inc. * <p> * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * */ package io.fabric8.funktion.model.steps; /** * Invokes a function with the current payload */ public class Function extends Step { private String name; public Function() {
super(StepKinds.FUNCTION);
funktionio/funktion-connectors
funktion-runtime/src/test/java/io/fabric8/funktion/runtime/steps/SplitYamlTest.java
// Path: funktion-model/src/main/java/io/fabric8/funktion/model/Funktion.java // public class Funktion extends DtoSupport { // private List<Flow> flows = new ArrayList<>(); // // public List<Flow> getFlows() { // return flows; // } // // public void setFlows(List<Flow> flows) { // this.flows = flows; // } // // public Flow createFlow() { // return addFlow(new Flow()); // } // // public Flow addFlow(Flow flow) { // flows.add(flow); // return flow; // } // }
import io.fabric8.funktion.model.Funktion; import java.io.IOException;
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.fabric8.funktion.runtime.steps; /** * Loads the test flow YAML file from src/test/resources/*.yml on the classpath */ public class SplitYamlTest extends SplitTest { @Override
// Path: funktion-model/src/main/java/io/fabric8/funktion/model/Funktion.java // public class Funktion extends DtoSupport { // private List<Flow> flows = new ArrayList<>(); // // public List<Flow> getFlows() { // return flows; // } // // public void setFlows(List<Flow> flows) { // this.flows = flows; // } // // public Flow createFlow() { // return addFlow(new Flow()); // } // // public Flow addFlow(Flow flow) { // flows.add(flow); // return flow; // } // } // Path: funktion-runtime/src/test/java/io/fabric8/funktion/runtime/steps/SplitYamlTest.java import io.fabric8.funktion.model.Funktion; import java.io.IOException; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.fabric8.funktion.runtime.steps; /** * Loads the test flow YAML file from src/test/resources/*.yml on the classpath */ public class SplitYamlTest extends SplitTest { @Override
protected Funktion createFunktion() throws IOException {
funktionio/funktion-connectors
funktion-model/src/main/java/io/fabric8/funktion/model/steps/Endpoint.java
// Path: funktion-model/src/main/java/io/fabric8/funktion/model/StepKinds.java // public class StepKinds { // public static final String CHOICE = "choice"; // public static final String ENDPOINT = "endpoint"; // public static final String FILTER = "filter"; // public static final String FUNCTION = "function"; // public static final String FLOW = "flow"; // public static final String OTHERWISE = "otherwise"; // public static final String SET_BODY = "setBody"; // public static final String SET_HEADERS = "setHeaders"; // public static final String SPLIT = "split"; // public static final String THROTTLE = "throttle"; // public static final String LOG = "log"; // }
import io.fabric8.funktion.model.StepKinds;
/* * Copyright 2016 Red Hat, Inc. * <p> * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * */ package io.fabric8.funktion.model.steps; /** * Invokes an endpoint URI (typically HTTP or HTTPS) with the current payload */ public class Endpoint extends Step { private String uri; public Endpoint() {
// Path: funktion-model/src/main/java/io/fabric8/funktion/model/StepKinds.java // public class StepKinds { // public static final String CHOICE = "choice"; // public static final String ENDPOINT = "endpoint"; // public static final String FILTER = "filter"; // public static final String FUNCTION = "function"; // public static final String FLOW = "flow"; // public static final String OTHERWISE = "otherwise"; // public static final String SET_BODY = "setBody"; // public static final String SET_HEADERS = "setHeaders"; // public static final String SPLIT = "split"; // public static final String THROTTLE = "throttle"; // public static final String LOG = "log"; // } // Path: funktion-model/src/main/java/io/fabric8/funktion/model/steps/Endpoint.java import io.fabric8.funktion.model.StepKinds; /* * Copyright 2016 Red Hat, Inc. * <p> * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * */ package io.fabric8.funktion.model.steps; /** * Invokes an endpoint URI (typically HTTP or HTTPS) with the current payload */ public class Endpoint extends Step { private String uri; public Endpoint() {
super(StepKinds.ENDPOINT);
Pivopil/spring-boot-oauth2-rest-service-password-encoding
rest/src/main/java/io/github/pivopil/rest/controllers/CompanyController.java
// Path: rest/src/main/java/io/github/pivopil/rest/constants/REST_API.java // public class REST_API { // // private REST_API() { // } // // public static final String ME = "/me"; // public static final String USERS = "/api/users"; // public static final String CLIENTS = "/api/clients"; // public static final String COMPANIES = "/api/companies"; // public static final String CONTENT = "/api/content"; // public static final String ID_PATH_VARIABLE = "/{id}"; // } // // Path: rest/src/main/java/io/github/pivopil/rest/services/CompanyService.java // @Service // @DependsOn("ovalValidator") // public class CompanyService { // // private final CompanyRepository companyRepository; // // private final RoleRepository roleRepository; // // private final Validator ovalValidator; // // @Autowired // public CompanyService(CompanyRepository companyRepository, RoleRepository roleRepository, Validator ovalValidator) { // this.companyRepository = companyRepository; // this.roleRepository = roleRepository; // this.ovalValidator = ovalValidator; // } // // public Iterable<Company> list() { // return companyRepository.findAll(); // } // // public Company getSingle(Long id) { // return companyRepository.findOne(id); // } // // @Transactional // public Company save(Company company) { // // Company currentCompany = company; // // CompanyBuilder companyBuilder = Builders.of(currentCompany); // // currentCompany = companyBuilder.withOvalValidator(ovalValidator).build(); // // currentCompany = companyRepository.save(currentCompany); // // String upperCase = currentCompany.getRoleAlias().toUpperCase(); // // Role roleUser = new Role(); // String roleUserName = String.format("ROLE_%s_LOCAL_USER", upperCase); // roleUser.setName(roleUserName); // // Role roleAdmin = new Role(); // String roleAdminName = String.format("ROLE_%s_LOCAL_ADMIN", upperCase); // roleAdmin.setName(roleAdminName); // // roleRepository.save(Arrays.asList(roleAdmin, roleUser)); // // return currentCompany; // } // // @Transactional // public void update(Company company) { // Company currentCompany = company; // // Company companyFromRepository = companyRepository.findOne(currentCompany.getId()); // // if (!companyFromRepository.getRoleAlias().equals(currentCompany.getRoleAlias())) { // throw new IllegalArgumentException("You can not change Role Alias of the company"); // } // // CompanyBuilder companyBuilder = Builders.of(currentCompany); // // currentCompany = companyBuilder.withOvalValidator(ovalValidator).build(); // // companyRepository.save(currentCompany); // } // // @Transactional // public void delete(Long id) { // companyRepository.delete(id); // } // } // // Path: share/src/main/java/io/github/pivopil/share/entities/impl/Company.java // @Entity // public class Company extends BasicEntity { // // @NotEmpty // @Column(unique = true, nullable = false) // private String name; // // @NotEmpty // @Column(unique = true, nullable = false) // private String roleAlias; // // private String description; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getRoleAlias() { // return roleAlias; // } // // public void setRoleAlias(String roleAlias) { // this.roleAlias = roleAlias; // } // }
import io.github.pivopil.rest.constants.REST_API; import io.github.pivopil.rest.services.CompanyService; import io.github.pivopil.share.entities.impl.Company; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*;
package io.github.pivopil.rest.controllers; /** * Created on 08.01.17. */ @RestController @RequestMapping(REST_API.COMPANIES) public class CompanyController {
// Path: rest/src/main/java/io/github/pivopil/rest/constants/REST_API.java // public class REST_API { // // private REST_API() { // } // // public static final String ME = "/me"; // public static final String USERS = "/api/users"; // public static final String CLIENTS = "/api/clients"; // public static final String COMPANIES = "/api/companies"; // public static final String CONTENT = "/api/content"; // public static final String ID_PATH_VARIABLE = "/{id}"; // } // // Path: rest/src/main/java/io/github/pivopil/rest/services/CompanyService.java // @Service // @DependsOn("ovalValidator") // public class CompanyService { // // private final CompanyRepository companyRepository; // // private final RoleRepository roleRepository; // // private final Validator ovalValidator; // // @Autowired // public CompanyService(CompanyRepository companyRepository, RoleRepository roleRepository, Validator ovalValidator) { // this.companyRepository = companyRepository; // this.roleRepository = roleRepository; // this.ovalValidator = ovalValidator; // } // // public Iterable<Company> list() { // return companyRepository.findAll(); // } // // public Company getSingle(Long id) { // return companyRepository.findOne(id); // } // // @Transactional // public Company save(Company company) { // // Company currentCompany = company; // // CompanyBuilder companyBuilder = Builders.of(currentCompany); // // currentCompany = companyBuilder.withOvalValidator(ovalValidator).build(); // // currentCompany = companyRepository.save(currentCompany); // // String upperCase = currentCompany.getRoleAlias().toUpperCase(); // // Role roleUser = new Role(); // String roleUserName = String.format("ROLE_%s_LOCAL_USER", upperCase); // roleUser.setName(roleUserName); // // Role roleAdmin = new Role(); // String roleAdminName = String.format("ROLE_%s_LOCAL_ADMIN", upperCase); // roleAdmin.setName(roleAdminName); // // roleRepository.save(Arrays.asList(roleAdmin, roleUser)); // // return currentCompany; // } // // @Transactional // public void update(Company company) { // Company currentCompany = company; // // Company companyFromRepository = companyRepository.findOne(currentCompany.getId()); // // if (!companyFromRepository.getRoleAlias().equals(currentCompany.getRoleAlias())) { // throw new IllegalArgumentException("You can not change Role Alias of the company"); // } // // CompanyBuilder companyBuilder = Builders.of(currentCompany); // // currentCompany = companyBuilder.withOvalValidator(ovalValidator).build(); // // companyRepository.save(currentCompany); // } // // @Transactional // public void delete(Long id) { // companyRepository.delete(id); // } // } // // Path: share/src/main/java/io/github/pivopil/share/entities/impl/Company.java // @Entity // public class Company extends BasicEntity { // // @NotEmpty // @Column(unique = true, nullable = false) // private String name; // // @NotEmpty // @Column(unique = true, nullable = false) // private String roleAlias; // // private String description; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getRoleAlias() { // return roleAlias; // } // // public void setRoleAlias(String roleAlias) { // this.roleAlias = roleAlias; // } // } // Path: rest/src/main/java/io/github/pivopil/rest/controllers/CompanyController.java import io.github.pivopil.rest.constants.REST_API; import io.github.pivopil.rest.services.CompanyService; import io.github.pivopil.share.entities.impl.Company; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; package io.github.pivopil.rest.controllers; /** * Created on 08.01.17. */ @RestController @RequestMapping(REST_API.COMPANIES) public class CompanyController {
private final CompanyService companyService;
Pivopil/spring-boot-oauth2-rest-service-password-encoding
rest/src/main/java/io/github/pivopil/rest/controllers/CompanyController.java
// Path: rest/src/main/java/io/github/pivopil/rest/constants/REST_API.java // public class REST_API { // // private REST_API() { // } // // public static final String ME = "/me"; // public static final String USERS = "/api/users"; // public static final String CLIENTS = "/api/clients"; // public static final String COMPANIES = "/api/companies"; // public static final String CONTENT = "/api/content"; // public static final String ID_PATH_VARIABLE = "/{id}"; // } // // Path: rest/src/main/java/io/github/pivopil/rest/services/CompanyService.java // @Service // @DependsOn("ovalValidator") // public class CompanyService { // // private final CompanyRepository companyRepository; // // private final RoleRepository roleRepository; // // private final Validator ovalValidator; // // @Autowired // public CompanyService(CompanyRepository companyRepository, RoleRepository roleRepository, Validator ovalValidator) { // this.companyRepository = companyRepository; // this.roleRepository = roleRepository; // this.ovalValidator = ovalValidator; // } // // public Iterable<Company> list() { // return companyRepository.findAll(); // } // // public Company getSingle(Long id) { // return companyRepository.findOne(id); // } // // @Transactional // public Company save(Company company) { // // Company currentCompany = company; // // CompanyBuilder companyBuilder = Builders.of(currentCompany); // // currentCompany = companyBuilder.withOvalValidator(ovalValidator).build(); // // currentCompany = companyRepository.save(currentCompany); // // String upperCase = currentCompany.getRoleAlias().toUpperCase(); // // Role roleUser = new Role(); // String roleUserName = String.format("ROLE_%s_LOCAL_USER", upperCase); // roleUser.setName(roleUserName); // // Role roleAdmin = new Role(); // String roleAdminName = String.format("ROLE_%s_LOCAL_ADMIN", upperCase); // roleAdmin.setName(roleAdminName); // // roleRepository.save(Arrays.asList(roleAdmin, roleUser)); // // return currentCompany; // } // // @Transactional // public void update(Company company) { // Company currentCompany = company; // // Company companyFromRepository = companyRepository.findOne(currentCompany.getId()); // // if (!companyFromRepository.getRoleAlias().equals(currentCompany.getRoleAlias())) { // throw new IllegalArgumentException("You can not change Role Alias of the company"); // } // // CompanyBuilder companyBuilder = Builders.of(currentCompany); // // currentCompany = companyBuilder.withOvalValidator(ovalValidator).build(); // // companyRepository.save(currentCompany); // } // // @Transactional // public void delete(Long id) { // companyRepository.delete(id); // } // } // // Path: share/src/main/java/io/github/pivopil/share/entities/impl/Company.java // @Entity // public class Company extends BasicEntity { // // @NotEmpty // @Column(unique = true, nullable = false) // private String name; // // @NotEmpty // @Column(unique = true, nullable = false) // private String roleAlias; // // private String description; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getRoleAlias() { // return roleAlias; // } // // public void setRoleAlias(String roleAlias) { // this.roleAlias = roleAlias; // } // }
import io.github.pivopil.rest.constants.REST_API; import io.github.pivopil.rest.services.CompanyService; import io.github.pivopil.share.entities.impl.Company; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*;
package io.github.pivopil.rest.controllers; /** * Created on 08.01.17. */ @RestController @RequestMapping(REST_API.COMPANIES) public class CompanyController { private final CompanyService companyService; @Autowired public CompanyController(CompanyService companyService) { this.companyService = companyService; } @GetMapping
// Path: rest/src/main/java/io/github/pivopil/rest/constants/REST_API.java // public class REST_API { // // private REST_API() { // } // // public static final String ME = "/me"; // public static final String USERS = "/api/users"; // public static final String CLIENTS = "/api/clients"; // public static final String COMPANIES = "/api/companies"; // public static final String CONTENT = "/api/content"; // public static final String ID_PATH_VARIABLE = "/{id}"; // } // // Path: rest/src/main/java/io/github/pivopil/rest/services/CompanyService.java // @Service // @DependsOn("ovalValidator") // public class CompanyService { // // private final CompanyRepository companyRepository; // // private final RoleRepository roleRepository; // // private final Validator ovalValidator; // // @Autowired // public CompanyService(CompanyRepository companyRepository, RoleRepository roleRepository, Validator ovalValidator) { // this.companyRepository = companyRepository; // this.roleRepository = roleRepository; // this.ovalValidator = ovalValidator; // } // // public Iterable<Company> list() { // return companyRepository.findAll(); // } // // public Company getSingle(Long id) { // return companyRepository.findOne(id); // } // // @Transactional // public Company save(Company company) { // // Company currentCompany = company; // // CompanyBuilder companyBuilder = Builders.of(currentCompany); // // currentCompany = companyBuilder.withOvalValidator(ovalValidator).build(); // // currentCompany = companyRepository.save(currentCompany); // // String upperCase = currentCompany.getRoleAlias().toUpperCase(); // // Role roleUser = new Role(); // String roleUserName = String.format("ROLE_%s_LOCAL_USER", upperCase); // roleUser.setName(roleUserName); // // Role roleAdmin = new Role(); // String roleAdminName = String.format("ROLE_%s_LOCAL_ADMIN", upperCase); // roleAdmin.setName(roleAdminName); // // roleRepository.save(Arrays.asList(roleAdmin, roleUser)); // // return currentCompany; // } // // @Transactional // public void update(Company company) { // Company currentCompany = company; // // Company companyFromRepository = companyRepository.findOne(currentCompany.getId()); // // if (!companyFromRepository.getRoleAlias().equals(currentCompany.getRoleAlias())) { // throw new IllegalArgumentException("You can not change Role Alias of the company"); // } // // CompanyBuilder companyBuilder = Builders.of(currentCompany); // // currentCompany = companyBuilder.withOvalValidator(ovalValidator).build(); // // companyRepository.save(currentCompany); // } // // @Transactional // public void delete(Long id) { // companyRepository.delete(id); // } // } // // Path: share/src/main/java/io/github/pivopil/share/entities/impl/Company.java // @Entity // public class Company extends BasicEntity { // // @NotEmpty // @Column(unique = true, nullable = false) // private String name; // // @NotEmpty // @Column(unique = true, nullable = false) // private String roleAlias; // // private String description; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getRoleAlias() { // return roleAlias; // } // // public void setRoleAlias(String roleAlias) { // this.roleAlias = roleAlias; // } // } // Path: rest/src/main/java/io/github/pivopil/rest/controllers/CompanyController.java import io.github.pivopil.rest.constants.REST_API; import io.github.pivopil.rest.services.CompanyService; import io.github.pivopil.share.entities.impl.Company; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; package io.github.pivopil.rest.controllers; /** * Created on 08.01.17. */ @RestController @RequestMapping(REST_API.COMPANIES) public class CompanyController { private final CompanyService companyService; @Autowired public CompanyController(CompanyService companyService) { this.companyService = companyService; } @GetMapping
public Iterable<Company> list() {
Pivopil/spring-boot-oauth2-rest-service-password-encoding
rest/src/main/java/io/github/pivopil/rest/config/WebSocketHandlersConfig.java
// Path: rest/src/main/java/io/github/pivopil/rest/handlers/WebSocketConnectHandler.java // public class WebSocketConnectHandler<S> // implements ApplicationListener<SessionConnectEvent> { // // private ActiveWebSocketUserRepository repository; // private SimpMessageSendingOperations messagingTemplate; // // public WebSocketConnectHandler(SimpMessageSendingOperations messagingTemplate, // ActiveWebSocketUserRepository repository) { // super(); // this.messagingTemplate = messagingTemplate; // this.repository = repository; // } // // public void onApplicationEvent(SessionConnectEvent event) { // MessageHeaders headers = event.getMessage().getHeaders(); // Principal user = SimpMessageHeaderAccessor.getUser(headers); // if (user == null) { // return; // } // String id = SimpMessageHeaderAccessor.getSessionId(headers); // this.repository.save( // new ActiveWebSocketUser(id, user.getName(), Calendar.getInstance())); // this.messagingTemplate.convertAndSend(WS_API.TOPIC_FRIENDS_SIGNIN, // Arrays.asList(user.getName())); // } // } // // Path: rest/src/main/java/io/github/pivopil/rest/handlers/WebSocketDisconnectHandler.java // public class WebSocketDisconnectHandler<S> // implements ApplicationListener<SessionDisconnectEvent> { // private ActiveWebSocketUserRepository repository; // private SimpMessageSendingOperations messagingTemplate; // // public WebSocketDisconnectHandler(SimpMessageSendingOperations messagingTemplate, // ActiveWebSocketUserRepository repository) { // super(); // this.messagingTemplate = messagingTemplate; // this.repository = repository; // } // // public void onApplicationEvent(SessionDisconnectEvent event) { // String id = event.getSessionId(); // if (id == null) { // return; // } // ActiveWebSocketUser user = this.repository.findOne(id); // if (user == null) { // return; // } // // this.repository.delete(id); // this.messagingTemplate.convertAndSend(WS_API.TOPIC_FRIENDS_SIGNOUT, // Collections.singletonList(user.getUsername())); // // } // } // // Path: share/src/main/java/io/github/pivopil/share/persistence/ActiveWebSocketUserRepository.java // @Repository // public interface ActiveWebSocketUserRepository // extends CrudRepository<ActiveWebSocketUser, String> { // // @Query("select DISTINCT(u.username) from ActiveWebSocketUser u where u.username != :username") // List<String> findAllActiveUsers(@Param("username") String username); // }
import io.github.pivopil.rest.handlers.WebSocketConnectHandler; import io.github.pivopil.rest.handlers.WebSocketDisconnectHandler; import io.github.pivopil.share.persistence.ActiveWebSocketUserRepository; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.SimpMessageSendingOperations; import org.springframework.session.ExpiringSession;
package io.github.pivopil.rest.config; @Configuration public class WebSocketHandlersConfig<S extends ExpiringSession> { @Bean
// Path: rest/src/main/java/io/github/pivopil/rest/handlers/WebSocketConnectHandler.java // public class WebSocketConnectHandler<S> // implements ApplicationListener<SessionConnectEvent> { // // private ActiveWebSocketUserRepository repository; // private SimpMessageSendingOperations messagingTemplate; // // public WebSocketConnectHandler(SimpMessageSendingOperations messagingTemplate, // ActiveWebSocketUserRepository repository) { // super(); // this.messagingTemplate = messagingTemplate; // this.repository = repository; // } // // public void onApplicationEvent(SessionConnectEvent event) { // MessageHeaders headers = event.getMessage().getHeaders(); // Principal user = SimpMessageHeaderAccessor.getUser(headers); // if (user == null) { // return; // } // String id = SimpMessageHeaderAccessor.getSessionId(headers); // this.repository.save( // new ActiveWebSocketUser(id, user.getName(), Calendar.getInstance())); // this.messagingTemplate.convertAndSend(WS_API.TOPIC_FRIENDS_SIGNIN, // Arrays.asList(user.getName())); // } // } // // Path: rest/src/main/java/io/github/pivopil/rest/handlers/WebSocketDisconnectHandler.java // public class WebSocketDisconnectHandler<S> // implements ApplicationListener<SessionDisconnectEvent> { // private ActiveWebSocketUserRepository repository; // private SimpMessageSendingOperations messagingTemplate; // // public WebSocketDisconnectHandler(SimpMessageSendingOperations messagingTemplate, // ActiveWebSocketUserRepository repository) { // super(); // this.messagingTemplate = messagingTemplate; // this.repository = repository; // } // // public void onApplicationEvent(SessionDisconnectEvent event) { // String id = event.getSessionId(); // if (id == null) { // return; // } // ActiveWebSocketUser user = this.repository.findOne(id); // if (user == null) { // return; // } // // this.repository.delete(id); // this.messagingTemplate.convertAndSend(WS_API.TOPIC_FRIENDS_SIGNOUT, // Collections.singletonList(user.getUsername())); // // } // } // // Path: share/src/main/java/io/github/pivopil/share/persistence/ActiveWebSocketUserRepository.java // @Repository // public interface ActiveWebSocketUserRepository // extends CrudRepository<ActiveWebSocketUser, String> { // // @Query("select DISTINCT(u.username) from ActiveWebSocketUser u where u.username != :username") // List<String> findAllActiveUsers(@Param("username") String username); // } // Path: rest/src/main/java/io/github/pivopil/rest/config/WebSocketHandlersConfig.java import io.github.pivopil.rest.handlers.WebSocketConnectHandler; import io.github.pivopil.rest.handlers.WebSocketDisconnectHandler; import io.github.pivopil.share.persistence.ActiveWebSocketUserRepository; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.SimpMessageSendingOperations; import org.springframework.session.ExpiringSession; package io.github.pivopil.rest.config; @Configuration public class WebSocketHandlersConfig<S extends ExpiringSession> { @Bean
public WebSocketConnectHandler<S> webSocketConnectHandler(
Pivopil/spring-boot-oauth2-rest-service-password-encoding
rest/src/main/java/io/github/pivopil/rest/config/WebSocketHandlersConfig.java
// Path: rest/src/main/java/io/github/pivopil/rest/handlers/WebSocketConnectHandler.java // public class WebSocketConnectHandler<S> // implements ApplicationListener<SessionConnectEvent> { // // private ActiveWebSocketUserRepository repository; // private SimpMessageSendingOperations messagingTemplate; // // public WebSocketConnectHandler(SimpMessageSendingOperations messagingTemplate, // ActiveWebSocketUserRepository repository) { // super(); // this.messagingTemplate = messagingTemplate; // this.repository = repository; // } // // public void onApplicationEvent(SessionConnectEvent event) { // MessageHeaders headers = event.getMessage().getHeaders(); // Principal user = SimpMessageHeaderAccessor.getUser(headers); // if (user == null) { // return; // } // String id = SimpMessageHeaderAccessor.getSessionId(headers); // this.repository.save( // new ActiveWebSocketUser(id, user.getName(), Calendar.getInstance())); // this.messagingTemplate.convertAndSend(WS_API.TOPIC_FRIENDS_SIGNIN, // Arrays.asList(user.getName())); // } // } // // Path: rest/src/main/java/io/github/pivopil/rest/handlers/WebSocketDisconnectHandler.java // public class WebSocketDisconnectHandler<S> // implements ApplicationListener<SessionDisconnectEvent> { // private ActiveWebSocketUserRepository repository; // private SimpMessageSendingOperations messagingTemplate; // // public WebSocketDisconnectHandler(SimpMessageSendingOperations messagingTemplate, // ActiveWebSocketUserRepository repository) { // super(); // this.messagingTemplate = messagingTemplate; // this.repository = repository; // } // // public void onApplicationEvent(SessionDisconnectEvent event) { // String id = event.getSessionId(); // if (id == null) { // return; // } // ActiveWebSocketUser user = this.repository.findOne(id); // if (user == null) { // return; // } // // this.repository.delete(id); // this.messagingTemplate.convertAndSend(WS_API.TOPIC_FRIENDS_SIGNOUT, // Collections.singletonList(user.getUsername())); // // } // } // // Path: share/src/main/java/io/github/pivopil/share/persistence/ActiveWebSocketUserRepository.java // @Repository // public interface ActiveWebSocketUserRepository // extends CrudRepository<ActiveWebSocketUser, String> { // // @Query("select DISTINCT(u.username) from ActiveWebSocketUser u where u.username != :username") // List<String> findAllActiveUsers(@Param("username") String username); // }
import io.github.pivopil.rest.handlers.WebSocketConnectHandler; import io.github.pivopil.rest.handlers.WebSocketDisconnectHandler; import io.github.pivopil.share.persistence.ActiveWebSocketUserRepository; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.SimpMessageSendingOperations; import org.springframework.session.ExpiringSession;
package io.github.pivopil.rest.config; @Configuration public class WebSocketHandlersConfig<S extends ExpiringSession> { @Bean public WebSocketConnectHandler<S> webSocketConnectHandler( SimpMessageSendingOperations messagingTemplate,
// Path: rest/src/main/java/io/github/pivopil/rest/handlers/WebSocketConnectHandler.java // public class WebSocketConnectHandler<S> // implements ApplicationListener<SessionConnectEvent> { // // private ActiveWebSocketUserRepository repository; // private SimpMessageSendingOperations messagingTemplate; // // public WebSocketConnectHandler(SimpMessageSendingOperations messagingTemplate, // ActiveWebSocketUserRepository repository) { // super(); // this.messagingTemplate = messagingTemplate; // this.repository = repository; // } // // public void onApplicationEvent(SessionConnectEvent event) { // MessageHeaders headers = event.getMessage().getHeaders(); // Principal user = SimpMessageHeaderAccessor.getUser(headers); // if (user == null) { // return; // } // String id = SimpMessageHeaderAccessor.getSessionId(headers); // this.repository.save( // new ActiveWebSocketUser(id, user.getName(), Calendar.getInstance())); // this.messagingTemplate.convertAndSend(WS_API.TOPIC_FRIENDS_SIGNIN, // Arrays.asList(user.getName())); // } // } // // Path: rest/src/main/java/io/github/pivopil/rest/handlers/WebSocketDisconnectHandler.java // public class WebSocketDisconnectHandler<S> // implements ApplicationListener<SessionDisconnectEvent> { // private ActiveWebSocketUserRepository repository; // private SimpMessageSendingOperations messagingTemplate; // // public WebSocketDisconnectHandler(SimpMessageSendingOperations messagingTemplate, // ActiveWebSocketUserRepository repository) { // super(); // this.messagingTemplate = messagingTemplate; // this.repository = repository; // } // // public void onApplicationEvent(SessionDisconnectEvent event) { // String id = event.getSessionId(); // if (id == null) { // return; // } // ActiveWebSocketUser user = this.repository.findOne(id); // if (user == null) { // return; // } // // this.repository.delete(id); // this.messagingTemplate.convertAndSend(WS_API.TOPIC_FRIENDS_SIGNOUT, // Collections.singletonList(user.getUsername())); // // } // } // // Path: share/src/main/java/io/github/pivopil/share/persistence/ActiveWebSocketUserRepository.java // @Repository // public interface ActiveWebSocketUserRepository // extends CrudRepository<ActiveWebSocketUser, String> { // // @Query("select DISTINCT(u.username) from ActiveWebSocketUser u where u.username != :username") // List<String> findAllActiveUsers(@Param("username") String username); // } // Path: rest/src/main/java/io/github/pivopil/rest/config/WebSocketHandlersConfig.java import io.github.pivopil.rest.handlers.WebSocketConnectHandler; import io.github.pivopil.rest.handlers.WebSocketDisconnectHandler; import io.github.pivopil.share.persistence.ActiveWebSocketUserRepository; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.SimpMessageSendingOperations; import org.springframework.session.ExpiringSession; package io.github.pivopil.rest.config; @Configuration public class WebSocketHandlersConfig<S extends ExpiringSession> { @Bean public WebSocketConnectHandler<S> webSocketConnectHandler( SimpMessageSendingOperations messagingTemplate,
ActiveWebSocketUserRepository repository) {
Pivopil/spring-boot-oauth2-rest-service-password-encoding
rest/src/main/java/io/github/pivopil/rest/config/WebSocketHandlersConfig.java
// Path: rest/src/main/java/io/github/pivopil/rest/handlers/WebSocketConnectHandler.java // public class WebSocketConnectHandler<S> // implements ApplicationListener<SessionConnectEvent> { // // private ActiveWebSocketUserRepository repository; // private SimpMessageSendingOperations messagingTemplate; // // public WebSocketConnectHandler(SimpMessageSendingOperations messagingTemplate, // ActiveWebSocketUserRepository repository) { // super(); // this.messagingTemplate = messagingTemplate; // this.repository = repository; // } // // public void onApplicationEvent(SessionConnectEvent event) { // MessageHeaders headers = event.getMessage().getHeaders(); // Principal user = SimpMessageHeaderAccessor.getUser(headers); // if (user == null) { // return; // } // String id = SimpMessageHeaderAccessor.getSessionId(headers); // this.repository.save( // new ActiveWebSocketUser(id, user.getName(), Calendar.getInstance())); // this.messagingTemplate.convertAndSend(WS_API.TOPIC_FRIENDS_SIGNIN, // Arrays.asList(user.getName())); // } // } // // Path: rest/src/main/java/io/github/pivopil/rest/handlers/WebSocketDisconnectHandler.java // public class WebSocketDisconnectHandler<S> // implements ApplicationListener<SessionDisconnectEvent> { // private ActiveWebSocketUserRepository repository; // private SimpMessageSendingOperations messagingTemplate; // // public WebSocketDisconnectHandler(SimpMessageSendingOperations messagingTemplate, // ActiveWebSocketUserRepository repository) { // super(); // this.messagingTemplate = messagingTemplate; // this.repository = repository; // } // // public void onApplicationEvent(SessionDisconnectEvent event) { // String id = event.getSessionId(); // if (id == null) { // return; // } // ActiveWebSocketUser user = this.repository.findOne(id); // if (user == null) { // return; // } // // this.repository.delete(id); // this.messagingTemplate.convertAndSend(WS_API.TOPIC_FRIENDS_SIGNOUT, // Collections.singletonList(user.getUsername())); // // } // } // // Path: share/src/main/java/io/github/pivopil/share/persistence/ActiveWebSocketUserRepository.java // @Repository // public interface ActiveWebSocketUserRepository // extends CrudRepository<ActiveWebSocketUser, String> { // // @Query("select DISTINCT(u.username) from ActiveWebSocketUser u where u.username != :username") // List<String> findAllActiveUsers(@Param("username") String username); // }
import io.github.pivopil.rest.handlers.WebSocketConnectHandler; import io.github.pivopil.rest.handlers.WebSocketDisconnectHandler; import io.github.pivopil.share.persistence.ActiveWebSocketUserRepository; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.SimpMessageSendingOperations; import org.springframework.session.ExpiringSession;
package io.github.pivopil.rest.config; @Configuration public class WebSocketHandlersConfig<S extends ExpiringSession> { @Bean public WebSocketConnectHandler<S> webSocketConnectHandler( SimpMessageSendingOperations messagingTemplate, ActiveWebSocketUserRepository repository) { return new WebSocketConnectHandler<S>(messagingTemplate, repository); } @Bean
// Path: rest/src/main/java/io/github/pivopil/rest/handlers/WebSocketConnectHandler.java // public class WebSocketConnectHandler<S> // implements ApplicationListener<SessionConnectEvent> { // // private ActiveWebSocketUserRepository repository; // private SimpMessageSendingOperations messagingTemplate; // // public WebSocketConnectHandler(SimpMessageSendingOperations messagingTemplate, // ActiveWebSocketUserRepository repository) { // super(); // this.messagingTemplate = messagingTemplate; // this.repository = repository; // } // // public void onApplicationEvent(SessionConnectEvent event) { // MessageHeaders headers = event.getMessage().getHeaders(); // Principal user = SimpMessageHeaderAccessor.getUser(headers); // if (user == null) { // return; // } // String id = SimpMessageHeaderAccessor.getSessionId(headers); // this.repository.save( // new ActiveWebSocketUser(id, user.getName(), Calendar.getInstance())); // this.messagingTemplate.convertAndSend(WS_API.TOPIC_FRIENDS_SIGNIN, // Arrays.asList(user.getName())); // } // } // // Path: rest/src/main/java/io/github/pivopil/rest/handlers/WebSocketDisconnectHandler.java // public class WebSocketDisconnectHandler<S> // implements ApplicationListener<SessionDisconnectEvent> { // private ActiveWebSocketUserRepository repository; // private SimpMessageSendingOperations messagingTemplate; // // public WebSocketDisconnectHandler(SimpMessageSendingOperations messagingTemplate, // ActiveWebSocketUserRepository repository) { // super(); // this.messagingTemplate = messagingTemplate; // this.repository = repository; // } // // public void onApplicationEvent(SessionDisconnectEvent event) { // String id = event.getSessionId(); // if (id == null) { // return; // } // ActiveWebSocketUser user = this.repository.findOne(id); // if (user == null) { // return; // } // // this.repository.delete(id); // this.messagingTemplate.convertAndSend(WS_API.TOPIC_FRIENDS_SIGNOUT, // Collections.singletonList(user.getUsername())); // // } // } // // Path: share/src/main/java/io/github/pivopil/share/persistence/ActiveWebSocketUserRepository.java // @Repository // public interface ActiveWebSocketUserRepository // extends CrudRepository<ActiveWebSocketUser, String> { // // @Query("select DISTINCT(u.username) from ActiveWebSocketUser u where u.username != :username") // List<String> findAllActiveUsers(@Param("username") String username); // } // Path: rest/src/main/java/io/github/pivopil/rest/config/WebSocketHandlersConfig.java import io.github.pivopil.rest.handlers.WebSocketConnectHandler; import io.github.pivopil.rest.handlers.WebSocketDisconnectHandler; import io.github.pivopil.share.persistence.ActiveWebSocketUserRepository; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.SimpMessageSendingOperations; import org.springframework.session.ExpiringSession; package io.github.pivopil.rest.config; @Configuration public class WebSocketHandlersConfig<S extends ExpiringSession> { @Bean public WebSocketConnectHandler<S> webSocketConnectHandler( SimpMessageSendingOperations messagingTemplate, ActiveWebSocketUserRepository repository) { return new WebSocketConnectHandler<S>(messagingTemplate, repository); } @Bean
public WebSocketDisconnectHandler<S> webSocketDisconnectHandler(
Pivopil/spring-boot-oauth2-rest-service-password-encoding
share/src/main/java/io/github/pivopil/share/persistence/ActiveWebSocketUserRepository.java
// Path: share/src/main/java/io/github/pivopil/share/entities/ActiveWebSocketUser.java // @Entity // public class ActiveWebSocketUser { // @Id // private String id; // // private String username; // // private Calendar connectionTime; // // public ActiveWebSocketUser() { // } // // public ActiveWebSocketUser(String id, String username, Calendar connectionTime) { // super(); // this.id = id; // this.username = username; // this.connectionTime = connectionTime; // } // // public String getUsername() { // return this.username; // } // // public void setUsername(String username) { // this.username = username; // } // // public Calendar getConnectionTime() { // return this.connectionTime; // } // // public void setConnectionTime(Calendar connectionTime) { // this.connectionTime = connectionTime; // } // // }
import io.github.pivopil.share.entities.ActiveWebSocketUser; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import java.util.List;
package io.github.pivopil.share.persistence; @Repository public interface ActiveWebSocketUserRepository
// Path: share/src/main/java/io/github/pivopil/share/entities/ActiveWebSocketUser.java // @Entity // public class ActiveWebSocketUser { // @Id // private String id; // // private String username; // // private Calendar connectionTime; // // public ActiveWebSocketUser() { // } // // public ActiveWebSocketUser(String id, String username, Calendar connectionTime) { // super(); // this.id = id; // this.username = username; // this.connectionTime = connectionTime; // } // // public String getUsername() { // return this.username; // } // // public void setUsername(String username) { // this.username = username; // } // // public Calendar getConnectionTime() { // return this.connectionTime; // } // // public void setConnectionTime(Calendar connectionTime) { // this.connectionTime = connectionTime; // } // // } // Path: share/src/main/java/io/github/pivopil/share/persistence/ActiveWebSocketUserRepository.java import io.github.pivopil.share.entities.ActiveWebSocketUser; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import java.util.List; package io.github.pivopil.share.persistence; @Repository public interface ActiveWebSocketUserRepository
extends CrudRepository<ActiveWebSocketUser, String> {
Pivopil/spring-boot-oauth2-rest-service-password-encoding
share/src/main/java/io/github/pivopil/share/entities/impl/User.java
// Path: share/src/main/java/io/github/pivopil/share/entities/BasicEntity.java // @MappedSuperclass // public class BasicEntity extends EntityWithId { // // private Date created; // // private Date updated; // // public Date getCreated() { // return created; // } // // public void setCreated(Date created) { // this.created = created; // } // // public Date getUpdated() { // return updated; // } // // public void setUpdated(Date updated) { // this.updated = updated; // } // // @PrePersist // protected void onCreate() { // this.created = new Date(); // } // // @PreUpdate // protected void onUpdate() { // this.updated = new Date(); // } // // }
import com.fasterxml.jackson.annotation.JsonIgnore; import io.github.pivopil.share.entities.BasicEntity; import org.hibernate.validator.constraints.NotEmpty; import javax.persistence.*; import java.io.Serializable; import java.util.HashSet; import java.util.Set;
package io.github.pivopil.share.entities.impl; @Entity @Table(name = "user_table")
// Path: share/src/main/java/io/github/pivopil/share/entities/BasicEntity.java // @MappedSuperclass // public class BasicEntity extends EntityWithId { // // private Date created; // // private Date updated; // // public Date getCreated() { // return created; // } // // public void setCreated(Date created) { // this.created = created; // } // // public Date getUpdated() { // return updated; // } // // public void setUpdated(Date updated) { // this.updated = updated; // } // // @PrePersist // protected void onCreate() { // this.created = new Date(); // } // // @PreUpdate // protected void onUpdate() { // this.updated = new Date(); // } // // } // Path: share/src/main/java/io/github/pivopil/share/entities/impl/User.java import com.fasterxml.jackson.annotation.JsonIgnore; import io.github.pivopil.share.entities.BasicEntity; import org.hibernate.validator.constraints.NotEmpty; import javax.persistence.*; import java.io.Serializable; import java.util.HashSet; import java.util.Set; package io.github.pivopil.share.entities.impl; @Entity @Table(name = "user_table")
public class User extends BasicEntity implements Serializable {
Pivopil/spring-boot-oauth2-rest-service-password-encoding
rest/src/main/java/io/github/pivopil/rest/handlers/WebSocketConnectHandler.java
// Path: rest/src/main/java/io/github/pivopil/rest/constants/WS_API.java // public class WS_API { // private WS_API() { // // } // // public static final String HANDSHAKE = "/messages"; // public static final String INSTANT_MESSAGE = "/im"; // public static final String ACTIVE_USERS = "/users"; // public static final String QUEUE_MESSAGES = "/queue/messages"; // // public static final String QUEUE_DESTINATION_PREFIX = "/queue/"; // public static final String TOPIC_DESTINATION_PREFIX = "/topic/"; // public static final String APP_PREFIX = "/app"; // public static final String TOPIC_FRIENDS_SIGNIN = "/topic/friends/signin"; // public static final String TOPIC_FRIENDS_SIGNOUT = "/topic/friends/signout"; // } // // Path: share/src/main/java/io/github/pivopil/share/entities/ActiveWebSocketUser.java // @Entity // public class ActiveWebSocketUser { // @Id // private String id; // // private String username; // // private Calendar connectionTime; // // public ActiveWebSocketUser() { // } // // public ActiveWebSocketUser(String id, String username, Calendar connectionTime) { // super(); // this.id = id; // this.username = username; // this.connectionTime = connectionTime; // } // // public String getUsername() { // return this.username; // } // // public void setUsername(String username) { // this.username = username; // } // // public Calendar getConnectionTime() { // return this.connectionTime; // } // // public void setConnectionTime(Calendar connectionTime) { // this.connectionTime = connectionTime; // } // // } // // Path: share/src/main/java/io/github/pivopil/share/persistence/ActiveWebSocketUserRepository.java // @Repository // public interface ActiveWebSocketUserRepository // extends CrudRepository<ActiveWebSocketUser, String> { // // @Query("select DISTINCT(u.username) from ActiveWebSocketUser u where u.username != :username") // List<String> findAllActiveUsers(@Param("username") String username); // }
import io.github.pivopil.rest.constants.WS_API; import io.github.pivopil.share.entities.ActiveWebSocketUser; import io.github.pivopil.share.persistence.ActiveWebSocketUserRepository; import org.springframework.context.ApplicationListener; import org.springframework.messaging.MessageHeaders; import org.springframework.messaging.simp.SimpMessageHeaderAccessor; import org.springframework.messaging.simp.SimpMessageSendingOperations; import org.springframework.web.socket.messaging.SessionConnectEvent; import java.security.Principal; import java.util.Arrays; import java.util.Calendar;
package io.github.pivopil.rest.handlers; public class WebSocketConnectHandler<S> implements ApplicationListener<SessionConnectEvent> {
// Path: rest/src/main/java/io/github/pivopil/rest/constants/WS_API.java // public class WS_API { // private WS_API() { // // } // // public static final String HANDSHAKE = "/messages"; // public static final String INSTANT_MESSAGE = "/im"; // public static final String ACTIVE_USERS = "/users"; // public static final String QUEUE_MESSAGES = "/queue/messages"; // // public static final String QUEUE_DESTINATION_PREFIX = "/queue/"; // public static final String TOPIC_DESTINATION_PREFIX = "/topic/"; // public static final String APP_PREFIX = "/app"; // public static final String TOPIC_FRIENDS_SIGNIN = "/topic/friends/signin"; // public static final String TOPIC_FRIENDS_SIGNOUT = "/topic/friends/signout"; // } // // Path: share/src/main/java/io/github/pivopil/share/entities/ActiveWebSocketUser.java // @Entity // public class ActiveWebSocketUser { // @Id // private String id; // // private String username; // // private Calendar connectionTime; // // public ActiveWebSocketUser() { // } // // public ActiveWebSocketUser(String id, String username, Calendar connectionTime) { // super(); // this.id = id; // this.username = username; // this.connectionTime = connectionTime; // } // // public String getUsername() { // return this.username; // } // // public void setUsername(String username) { // this.username = username; // } // // public Calendar getConnectionTime() { // return this.connectionTime; // } // // public void setConnectionTime(Calendar connectionTime) { // this.connectionTime = connectionTime; // } // // } // // Path: share/src/main/java/io/github/pivopil/share/persistence/ActiveWebSocketUserRepository.java // @Repository // public interface ActiveWebSocketUserRepository // extends CrudRepository<ActiveWebSocketUser, String> { // // @Query("select DISTINCT(u.username) from ActiveWebSocketUser u where u.username != :username") // List<String> findAllActiveUsers(@Param("username") String username); // } // Path: rest/src/main/java/io/github/pivopil/rest/handlers/WebSocketConnectHandler.java import io.github.pivopil.rest.constants.WS_API; import io.github.pivopil.share.entities.ActiveWebSocketUser; import io.github.pivopil.share.persistence.ActiveWebSocketUserRepository; import org.springframework.context.ApplicationListener; import org.springframework.messaging.MessageHeaders; import org.springframework.messaging.simp.SimpMessageHeaderAccessor; import org.springframework.messaging.simp.SimpMessageSendingOperations; import org.springframework.web.socket.messaging.SessionConnectEvent; import java.security.Principal; import java.util.Arrays; import java.util.Calendar; package io.github.pivopil.rest.handlers; public class WebSocketConnectHandler<S> implements ApplicationListener<SessionConnectEvent> {
private ActiveWebSocketUserRepository repository;
Pivopil/spring-boot-oauth2-rest-service-password-encoding
rest/src/main/java/io/github/pivopil/rest/handlers/WebSocketConnectHandler.java
// Path: rest/src/main/java/io/github/pivopil/rest/constants/WS_API.java // public class WS_API { // private WS_API() { // // } // // public static final String HANDSHAKE = "/messages"; // public static final String INSTANT_MESSAGE = "/im"; // public static final String ACTIVE_USERS = "/users"; // public static final String QUEUE_MESSAGES = "/queue/messages"; // // public static final String QUEUE_DESTINATION_PREFIX = "/queue/"; // public static final String TOPIC_DESTINATION_PREFIX = "/topic/"; // public static final String APP_PREFIX = "/app"; // public static final String TOPIC_FRIENDS_SIGNIN = "/topic/friends/signin"; // public static final String TOPIC_FRIENDS_SIGNOUT = "/topic/friends/signout"; // } // // Path: share/src/main/java/io/github/pivopil/share/entities/ActiveWebSocketUser.java // @Entity // public class ActiveWebSocketUser { // @Id // private String id; // // private String username; // // private Calendar connectionTime; // // public ActiveWebSocketUser() { // } // // public ActiveWebSocketUser(String id, String username, Calendar connectionTime) { // super(); // this.id = id; // this.username = username; // this.connectionTime = connectionTime; // } // // public String getUsername() { // return this.username; // } // // public void setUsername(String username) { // this.username = username; // } // // public Calendar getConnectionTime() { // return this.connectionTime; // } // // public void setConnectionTime(Calendar connectionTime) { // this.connectionTime = connectionTime; // } // // } // // Path: share/src/main/java/io/github/pivopil/share/persistence/ActiveWebSocketUserRepository.java // @Repository // public interface ActiveWebSocketUserRepository // extends CrudRepository<ActiveWebSocketUser, String> { // // @Query("select DISTINCT(u.username) from ActiveWebSocketUser u where u.username != :username") // List<String> findAllActiveUsers(@Param("username") String username); // }
import io.github.pivopil.rest.constants.WS_API; import io.github.pivopil.share.entities.ActiveWebSocketUser; import io.github.pivopil.share.persistence.ActiveWebSocketUserRepository; import org.springframework.context.ApplicationListener; import org.springframework.messaging.MessageHeaders; import org.springframework.messaging.simp.SimpMessageHeaderAccessor; import org.springframework.messaging.simp.SimpMessageSendingOperations; import org.springframework.web.socket.messaging.SessionConnectEvent; import java.security.Principal; import java.util.Arrays; import java.util.Calendar;
package io.github.pivopil.rest.handlers; public class WebSocketConnectHandler<S> implements ApplicationListener<SessionConnectEvent> { private ActiveWebSocketUserRepository repository; private SimpMessageSendingOperations messagingTemplate; public WebSocketConnectHandler(SimpMessageSendingOperations messagingTemplate, ActiveWebSocketUserRepository repository) { super(); this.messagingTemplate = messagingTemplate; this.repository = repository; } public void onApplicationEvent(SessionConnectEvent event) { MessageHeaders headers = event.getMessage().getHeaders(); Principal user = SimpMessageHeaderAccessor.getUser(headers); if (user == null) { return; } String id = SimpMessageHeaderAccessor.getSessionId(headers); this.repository.save(
// Path: rest/src/main/java/io/github/pivopil/rest/constants/WS_API.java // public class WS_API { // private WS_API() { // // } // // public static final String HANDSHAKE = "/messages"; // public static final String INSTANT_MESSAGE = "/im"; // public static final String ACTIVE_USERS = "/users"; // public static final String QUEUE_MESSAGES = "/queue/messages"; // // public static final String QUEUE_DESTINATION_PREFIX = "/queue/"; // public static final String TOPIC_DESTINATION_PREFIX = "/topic/"; // public static final String APP_PREFIX = "/app"; // public static final String TOPIC_FRIENDS_SIGNIN = "/topic/friends/signin"; // public static final String TOPIC_FRIENDS_SIGNOUT = "/topic/friends/signout"; // } // // Path: share/src/main/java/io/github/pivopil/share/entities/ActiveWebSocketUser.java // @Entity // public class ActiveWebSocketUser { // @Id // private String id; // // private String username; // // private Calendar connectionTime; // // public ActiveWebSocketUser() { // } // // public ActiveWebSocketUser(String id, String username, Calendar connectionTime) { // super(); // this.id = id; // this.username = username; // this.connectionTime = connectionTime; // } // // public String getUsername() { // return this.username; // } // // public void setUsername(String username) { // this.username = username; // } // // public Calendar getConnectionTime() { // return this.connectionTime; // } // // public void setConnectionTime(Calendar connectionTime) { // this.connectionTime = connectionTime; // } // // } // // Path: share/src/main/java/io/github/pivopil/share/persistence/ActiveWebSocketUserRepository.java // @Repository // public interface ActiveWebSocketUserRepository // extends CrudRepository<ActiveWebSocketUser, String> { // // @Query("select DISTINCT(u.username) from ActiveWebSocketUser u where u.username != :username") // List<String> findAllActiveUsers(@Param("username") String username); // } // Path: rest/src/main/java/io/github/pivopil/rest/handlers/WebSocketConnectHandler.java import io.github.pivopil.rest.constants.WS_API; import io.github.pivopil.share.entities.ActiveWebSocketUser; import io.github.pivopil.share.persistence.ActiveWebSocketUserRepository; import org.springframework.context.ApplicationListener; import org.springframework.messaging.MessageHeaders; import org.springframework.messaging.simp.SimpMessageHeaderAccessor; import org.springframework.messaging.simp.SimpMessageSendingOperations; import org.springframework.web.socket.messaging.SessionConnectEvent; import java.security.Principal; import java.util.Arrays; import java.util.Calendar; package io.github.pivopil.rest.handlers; public class WebSocketConnectHandler<S> implements ApplicationListener<SessionConnectEvent> { private ActiveWebSocketUserRepository repository; private SimpMessageSendingOperations messagingTemplate; public WebSocketConnectHandler(SimpMessageSendingOperations messagingTemplate, ActiveWebSocketUserRepository repository) { super(); this.messagingTemplate = messagingTemplate; this.repository = repository; } public void onApplicationEvent(SessionConnectEvent event) { MessageHeaders headers = event.getMessage().getHeaders(); Principal user = SimpMessageHeaderAccessor.getUser(headers); if (user == null) { return; } String id = SimpMessageHeaderAccessor.getSessionId(headers); this.repository.save(
new ActiveWebSocketUser(id, user.getName(), Calendar.getInstance()));
Pivopil/spring-boot-oauth2-rest-service-password-encoding
rest/src/main/java/io/github/pivopil/rest/handlers/WebSocketConnectHandler.java
// Path: rest/src/main/java/io/github/pivopil/rest/constants/WS_API.java // public class WS_API { // private WS_API() { // // } // // public static final String HANDSHAKE = "/messages"; // public static final String INSTANT_MESSAGE = "/im"; // public static final String ACTIVE_USERS = "/users"; // public static final String QUEUE_MESSAGES = "/queue/messages"; // // public static final String QUEUE_DESTINATION_PREFIX = "/queue/"; // public static final String TOPIC_DESTINATION_PREFIX = "/topic/"; // public static final String APP_PREFIX = "/app"; // public static final String TOPIC_FRIENDS_SIGNIN = "/topic/friends/signin"; // public static final String TOPIC_FRIENDS_SIGNOUT = "/topic/friends/signout"; // } // // Path: share/src/main/java/io/github/pivopil/share/entities/ActiveWebSocketUser.java // @Entity // public class ActiveWebSocketUser { // @Id // private String id; // // private String username; // // private Calendar connectionTime; // // public ActiveWebSocketUser() { // } // // public ActiveWebSocketUser(String id, String username, Calendar connectionTime) { // super(); // this.id = id; // this.username = username; // this.connectionTime = connectionTime; // } // // public String getUsername() { // return this.username; // } // // public void setUsername(String username) { // this.username = username; // } // // public Calendar getConnectionTime() { // return this.connectionTime; // } // // public void setConnectionTime(Calendar connectionTime) { // this.connectionTime = connectionTime; // } // // } // // Path: share/src/main/java/io/github/pivopil/share/persistence/ActiveWebSocketUserRepository.java // @Repository // public interface ActiveWebSocketUserRepository // extends CrudRepository<ActiveWebSocketUser, String> { // // @Query("select DISTINCT(u.username) from ActiveWebSocketUser u where u.username != :username") // List<String> findAllActiveUsers(@Param("username") String username); // }
import io.github.pivopil.rest.constants.WS_API; import io.github.pivopil.share.entities.ActiveWebSocketUser; import io.github.pivopil.share.persistence.ActiveWebSocketUserRepository; import org.springframework.context.ApplicationListener; import org.springframework.messaging.MessageHeaders; import org.springframework.messaging.simp.SimpMessageHeaderAccessor; import org.springframework.messaging.simp.SimpMessageSendingOperations; import org.springframework.web.socket.messaging.SessionConnectEvent; import java.security.Principal; import java.util.Arrays; import java.util.Calendar;
package io.github.pivopil.rest.handlers; public class WebSocketConnectHandler<S> implements ApplicationListener<SessionConnectEvent> { private ActiveWebSocketUserRepository repository; private SimpMessageSendingOperations messagingTemplate; public WebSocketConnectHandler(SimpMessageSendingOperations messagingTemplate, ActiveWebSocketUserRepository repository) { super(); this.messagingTemplate = messagingTemplate; this.repository = repository; } public void onApplicationEvent(SessionConnectEvent event) { MessageHeaders headers = event.getMessage().getHeaders(); Principal user = SimpMessageHeaderAccessor.getUser(headers); if (user == null) { return; } String id = SimpMessageHeaderAccessor.getSessionId(headers); this.repository.save( new ActiveWebSocketUser(id, user.getName(), Calendar.getInstance()));
// Path: rest/src/main/java/io/github/pivopil/rest/constants/WS_API.java // public class WS_API { // private WS_API() { // // } // // public static final String HANDSHAKE = "/messages"; // public static final String INSTANT_MESSAGE = "/im"; // public static final String ACTIVE_USERS = "/users"; // public static final String QUEUE_MESSAGES = "/queue/messages"; // // public static final String QUEUE_DESTINATION_PREFIX = "/queue/"; // public static final String TOPIC_DESTINATION_PREFIX = "/topic/"; // public static final String APP_PREFIX = "/app"; // public static final String TOPIC_FRIENDS_SIGNIN = "/topic/friends/signin"; // public static final String TOPIC_FRIENDS_SIGNOUT = "/topic/friends/signout"; // } // // Path: share/src/main/java/io/github/pivopil/share/entities/ActiveWebSocketUser.java // @Entity // public class ActiveWebSocketUser { // @Id // private String id; // // private String username; // // private Calendar connectionTime; // // public ActiveWebSocketUser() { // } // // public ActiveWebSocketUser(String id, String username, Calendar connectionTime) { // super(); // this.id = id; // this.username = username; // this.connectionTime = connectionTime; // } // // public String getUsername() { // return this.username; // } // // public void setUsername(String username) { // this.username = username; // } // // public Calendar getConnectionTime() { // return this.connectionTime; // } // // public void setConnectionTime(Calendar connectionTime) { // this.connectionTime = connectionTime; // } // // } // // Path: share/src/main/java/io/github/pivopil/share/persistence/ActiveWebSocketUserRepository.java // @Repository // public interface ActiveWebSocketUserRepository // extends CrudRepository<ActiveWebSocketUser, String> { // // @Query("select DISTINCT(u.username) from ActiveWebSocketUser u where u.username != :username") // List<String> findAllActiveUsers(@Param("username") String username); // } // Path: rest/src/main/java/io/github/pivopil/rest/handlers/WebSocketConnectHandler.java import io.github.pivopil.rest.constants.WS_API; import io.github.pivopil.share.entities.ActiveWebSocketUser; import io.github.pivopil.share.persistence.ActiveWebSocketUserRepository; import org.springframework.context.ApplicationListener; import org.springframework.messaging.MessageHeaders; import org.springframework.messaging.simp.SimpMessageHeaderAccessor; import org.springframework.messaging.simp.SimpMessageSendingOperations; import org.springframework.web.socket.messaging.SessionConnectEvent; import java.security.Principal; import java.util.Arrays; import java.util.Calendar; package io.github.pivopil.rest.handlers; public class WebSocketConnectHandler<S> implements ApplicationListener<SessionConnectEvent> { private ActiveWebSocketUserRepository repository; private SimpMessageSendingOperations messagingTemplate; public WebSocketConnectHandler(SimpMessageSendingOperations messagingTemplate, ActiveWebSocketUserRepository repository) { super(); this.messagingTemplate = messagingTemplate; this.repository = repository; } public void onApplicationEvent(SessionConnectEvent event) { MessageHeaders headers = event.getMessage().getHeaders(); Principal user = SimpMessageHeaderAccessor.getUser(headers); if (user == null) { return; } String id = SimpMessageHeaderAccessor.getSessionId(headers); this.repository.save( new ActiveWebSocketUser(id, user.getName(), Calendar.getInstance()));
this.messagingTemplate.convertAndSend(WS_API.TOPIC_FRIENDS_SIGNIN,
Pivopil/spring-boot-oauth2-rest-service-password-encoding
rest/src/main/java/io/github/pivopil/rest/config/WebSocketMessageBrokerConfig.java
// Path: rest/src/main/java/io/github/pivopil/rest/constants/WS_API.java // public class WS_API { // private WS_API() { // // } // // public static final String HANDSHAKE = "/messages"; // public static final String INSTANT_MESSAGE = "/im"; // public static final String ACTIVE_USERS = "/users"; // public static final String QUEUE_MESSAGES = "/queue/messages"; // // public static final String QUEUE_DESTINATION_PREFIX = "/queue/"; // public static final String TOPIC_DESTINATION_PREFIX = "/topic/"; // public static final String APP_PREFIX = "/app"; // public static final String TOPIC_FRIENDS_SIGNIN = "/topic/friends/signin"; // public static final String TOPIC_FRIENDS_SIGNOUT = "/topic/friends/signout"; // } // // Path: rest/src/main/java/io/github/pivopil/rest/handlers/CustomHandshakeInterceptor.java // public class CustomHandshakeInterceptor implements HandshakeInterceptor { // // @Override // public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception { // if (request.getURI().getQuery().split("access_token=").length == 2) { // String token = "Bearer " + request.getURI().getQuery().split("access_token=")[0]; // attributes.put("SPRING.SESSION.ID", token); // attributes.put(HTTP_SESSION_ID_ATTR_NAME, token); // } // return true; // } // // @Override // public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) { // // } // }
import io.github.pivopil.rest.constants.WS_API; import io.github.pivopil.rest.handlers.CustomHandshakeInterceptor; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.session.ExpiringSession; import org.springframework.session.web.socket.config.annotation.AbstractSessionWebSocketMessageBrokerConfigurer; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
package io.github.pivopil.rest.config; /** * Created on 02.11.16. */ @Configuration @EnableScheduling @EnableWebSocketMessageBroker public class WebSocketMessageBrokerConfig extends AbstractSessionWebSocketMessageBrokerConfigurer<ExpiringSession> { protected void configureStompEndpoints(StompEndpointRegistry registry) {
// Path: rest/src/main/java/io/github/pivopil/rest/constants/WS_API.java // public class WS_API { // private WS_API() { // // } // // public static final String HANDSHAKE = "/messages"; // public static final String INSTANT_MESSAGE = "/im"; // public static final String ACTIVE_USERS = "/users"; // public static final String QUEUE_MESSAGES = "/queue/messages"; // // public static final String QUEUE_DESTINATION_PREFIX = "/queue/"; // public static final String TOPIC_DESTINATION_PREFIX = "/topic/"; // public static final String APP_PREFIX = "/app"; // public static final String TOPIC_FRIENDS_SIGNIN = "/topic/friends/signin"; // public static final String TOPIC_FRIENDS_SIGNOUT = "/topic/friends/signout"; // } // // Path: rest/src/main/java/io/github/pivopil/rest/handlers/CustomHandshakeInterceptor.java // public class CustomHandshakeInterceptor implements HandshakeInterceptor { // // @Override // public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception { // if (request.getURI().getQuery().split("access_token=").length == 2) { // String token = "Bearer " + request.getURI().getQuery().split("access_token=")[0]; // attributes.put("SPRING.SESSION.ID", token); // attributes.put(HTTP_SESSION_ID_ATTR_NAME, token); // } // return true; // } // // @Override // public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) { // // } // } // Path: rest/src/main/java/io/github/pivopil/rest/config/WebSocketMessageBrokerConfig.java import io.github.pivopil.rest.constants.WS_API; import io.github.pivopil.rest.handlers.CustomHandshakeInterceptor; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.session.ExpiringSession; import org.springframework.session.web.socket.config.annotation.AbstractSessionWebSocketMessageBrokerConfigurer; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; package io.github.pivopil.rest.config; /** * Created on 02.11.16. */ @Configuration @EnableScheduling @EnableWebSocketMessageBroker public class WebSocketMessageBrokerConfig extends AbstractSessionWebSocketMessageBrokerConfigurer<ExpiringSession> { protected void configureStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint(WS_API.HANDSHAKE)
Pivopil/spring-boot-oauth2-rest-service-password-encoding
rest/src/main/java/io/github/pivopil/rest/config/WebSocketMessageBrokerConfig.java
// Path: rest/src/main/java/io/github/pivopil/rest/constants/WS_API.java // public class WS_API { // private WS_API() { // // } // // public static final String HANDSHAKE = "/messages"; // public static final String INSTANT_MESSAGE = "/im"; // public static final String ACTIVE_USERS = "/users"; // public static final String QUEUE_MESSAGES = "/queue/messages"; // // public static final String QUEUE_DESTINATION_PREFIX = "/queue/"; // public static final String TOPIC_DESTINATION_PREFIX = "/topic/"; // public static final String APP_PREFIX = "/app"; // public static final String TOPIC_FRIENDS_SIGNIN = "/topic/friends/signin"; // public static final String TOPIC_FRIENDS_SIGNOUT = "/topic/friends/signout"; // } // // Path: rest/src/main/java/io/github/pivopil/rest/handlers/CustomHandshakeInterceptor.java // public class CustomHandshakeInterceptor implements HandshakeInterceptor { // // @Override // public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception { // if (request.getURI().getQuery().split("access_token=").length == 2) { // String token = "Bearer " + request.getURI().getQuery().split("access_token=")[0]; // attributes.put("SPRING.SESSION.ID", token); // attributes.put(HTTP_SESSION_ID_ATTR_NAME, token); // } // return true; // } // // @Override // public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) { // // } // }
import io.github.pivopil.rest.constants.WS_API; import io.github.pivopil.rest.handlers.CustomHandshakeInterceptor; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.session.ExpiringSession; import org.springframework.session.web.socket.config.annotation.AbstractSessionWebSocketMessageBrokerConfigurer; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
package io.github.pivopil.rest.config; /** * Created on 02.11.16. */ @Configuration @EnableScheduling @EnableWebSocketMessageBroker public class WebSocketMessageBrokerConfig extends AbstractSessionWebSocketMessageBrokerConfigurer<ExpiringSession> { protected void configureStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint(WS_API.HANDSHAKE)
// Path: rest/src/main/java/io/github/pivopil/rest/constants/WS_API.java // public class WS_API { // private WS_API() { // // } // // public static final String HANDSHAKE = "/messages"; // public static final String INSTANT_MESSAGE = "/im"; // public static final String ACTIVE_USERS = "/users"; // public static final String QUEUE_MESSAGES = "/queue/messages"; // // public static final String QUEUE_DESTINATION_PREFIX = "/queue/"; // public static final String TOPIC_DESTINATION_PREFIX = "/topic/"; // public static final String APP_PREFIX = "/app"; // public static final String TOPIC_FRIENDS_SIGNIN = "/topic/friends/signin"; // public static final String TOPIC_FRIENDS_SIGNOUT = "/topic/friends/signout"; // } // // Path: rest/src/main/java/io/github/pivopil/rest/handlers/CustomHandshakeInterceptor.java // public class CustomHandshakeInterceptor implements HandshakeInterceptor { // // @Override // public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception { // if (request.getURI().getQuery().split("access_token=").length == 2) { // String token = "Bearer " + request.getURI().getQuery().split("access_token=")[0]; // attributes.put("SPRING.SESSION.ID", token); // attributes.put(HTTP_SESSION_ID_ATTR_NAME, token); // } // return true; // } // // @Override // public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) { // // } // } // Path: rest/src/main/java/io/github/pivopil/rest/config/WebSocketMessageBrokerConfig.java import io.github.pivopil.rest.constants.WS_API; import io.github.pivopil.rest.handlers.CustomHandshakeInterceptor; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.session.ExpiringSession; import org.springframework.session.web.socket.config.annotation.AbstractSessionWebSocketMessageBrokerConfigurer; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; package io.github.pivopil.rest.config; /** * Created on 02.11.16. */ @Configuration @EnableScheduling @EnableWebSocketMessageBroker public class WebSocketMessageBrokerConfig extends AbstractSessionWebSocketMessageBrokerConfigurer<ExpiringSession> { protected void configureStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint(WS_API.HANDSHAKE)
.addInterceptors(new CustomHandshakeInterceptor())
Pivopil/spring-boot-oauth2-rest-service-password-encoding
rest/src/main/java/io/github/pivopil/rest/handlers/WebSocketDisconnectHandler.java
// Path: rest/src/main/java/io/github/pivopil/rest/constants/WS_API.java // public class WS_API { // private WS_API() { // // } // // public static final String HANDSHAKE = "/messages"; // public static final String INSTANT_MESSAGE = "/im"; // public static final String ACTIVE_USERS = "/users"; // public static final String QUEUE_MESSAGES = "/queue/messages"; // // public static final String QUEUE_DESTINATION_PREFIX = "/queue/"; // public static final String TOPIC_DESTINATION_PREFIX = "/topic/"; // public static final String APP_PREFIX = "/app"; // public static final String TOPIC_FRIENDS_SIGNIN = "/topic/friends/signin"; // public static final String TOPIC_FRIENDS_SIGNOUT = "/topic/friends/signout"; // } // // Path: share/src/main/java/io/github/pivopil/share/entities/ActiveWebSocketUser.java // @Entity // public class ActiveWebSocketUser { // @Id // private String id; // // private String username; // // private Calendar connectionTime; // // public ActiveWebSocketUser() { // } // // public ActiveWebSocketUser(String id, String username, Calendar connectionTime) { // super(); // this.id = id; // this.username = username; // this.connectionTime = connectionTime; // } // // public String getUsername() { // return this.username; // } // // public void setUsername(String username) { // this.username = username; // } // // public Calendar getConnectionTime() { // return this.connectionTime; // } // // public void setConnectionTime(Calendar connectionTime) { // this.connectionTime = connectionTime; // } // // } // // Path: share/src/main/java/io/github/pivopil/share/persistence/ActiveWebSocketUserRepository.java // @Repository // public interface ActiveWebSocketUserRepository // extends CrudRepository<ActiveWebSocketUser, String> { // // @Query("select DISTINCT(u.username) from ActiveWebSocketUser u where u.username != :username") // List<String> findAllActiveUsers(@Param("username") String username); // }
import io.github.pivopil.rest.constants.WS_API; import io.github.pivopil.share.entities.ActiveWebSocketUser; import io.github.pivopil.share.persistence.ActiveWebSocketUserRepository; import org.springframework.context.ApplicationListener; import org.springframework.messaging.simp.SimpMessageSendingOperations; import org.springframework.web.socket.messaging.SessionDisconnectEvent; import java.util.Arrays; import java.util.Collections;
package io.github.pivopil.rest.handlers; public class WebSocketDisconnectHandler<S> implements ApplicationListener<SessionDisconnectEvent> {
// Path: rest/src/main/java/io/github/pivopil/rest/constants/WS_API.java // public class WS_API { // private WS_API() { // // } // // public static final String HANDSHAKE = "/messages"; // public static final String INSTANT_MESSAGE = "/im"; // public static final String ACTIVE_USERS = "/users"; // public static final String QUEUE_MESSAGES = "/queue/messages"; // // public static final String QUEUE_DESTINATION_PREFIX = "/queue/"; // public static final String TOPIC_DESTINATION_PREFIX = "/topic/"; // public static final String APP_PREFIX = "/app"; // public static final String TOPIC_FRIENDS_SIGNIN = "/topic/friends/signin"; // public static final String TOPIC_FRIENDS_SIGNOUT = "/topic/friends/signout"; // } // // Path: share/src/main/java/io/github/pivopil/share/entities/ActiveWebSocketUser.java // @Entity // public class ActiveWebSocketUser { // @Id // private String id; // // private String username; // // private Calendar connectionTime; // // public ActiveWebSocketUser() { // } // // public ActiveWebSocketUser(String id, String username, Calendar connectionTime) { // super(); // this.id = id; // this.username = username; // this.connectionTime = connectionTime; // } // // public String getUsername() { // return this.username; // } // // public void setUsername(String username) { // this.username = username; // } // // public Calendar getConnectionTime() { // return this.connectionTime; // } // // public void setConnectionTime(Calendar connectionTime) { // this.connectionTime = connectionTime; // } // // } // // Path: share/src/main/java/io/github/pivopil/share/persistence/ActiveWebSocketUserRepository.java // @Repository // public interface ActiveWebSocketUserRepository // extends CrudRepository<ActiveWebSocketUser, String> { // // @Query("select DISTINCT(u.username) from ActiveWebSocketUser u where u.username != :username") // List<String> findAllActiveUsers(@Param("username") String username); // } // Path: rest/src/main/java/io/github/pivopil/rest/handlers/WebSocketDisconnectHandler.java import io.github.pivopil.rest.constants.WS_API; import io.github.pivopil.share.entities.ActiveWebSocketUser; import io.github.pivopil.share.persistence.ActiveWebSocketUserRepository; import org.springframework.context.ApplicationListener; import org.springframework.messaging.simp.SimpMessageSendingOperations; import org.springframework.web.socket.messaging.SessionDisconnectEvent; import java.util.Arrays; import java.util.Collections; package io.github.pivopil.rest.handlers; public class WebSocketDisconnectHandler<S> implements ApplicationListener<SessionDisconnectEvent> {
private ActiveWebSocketUserRepository repository;
Pivopil/spring-boot-oauth2-rest-service-password-encoding
rest/src/main/java/io/github/pivopil/rest/handlers/WebSocketDisconnectHandler.java
// Path: rest/src/main/java/io/github/pivopil/rest/constants/WS_API.java // public class WS_API { // private WS_API() { // // } // // public static final String HANDSHAKE = "/messages"; // public static final String INSTANT_MESSAGE = "/im"; // public static final String ACTIVE_USERS = "/users"; // public static final String QUEUE_MESSAGES = "/queue/messages"; // // public static final String QUEUE_DESTINATION_PREFIX = "/queue/"; // public static final String TOPIC_DESTINATION_PREFIX = "/topic/"; // public static final String APP_PREFIX = "/app"; // public static final String TOPIC_FRIENDS_SIGNIN = "/topic/friends/signin"; // public static final String TOPIC_FRIENDS_SIGNOUT = "/topic/friends/signout"; // } // // Path: share/src/main/java/io/github/pivopil/share/entities/ActiveWebSocketUser.java // @Entity // public class ActiveWebSocketUser { // @Id // private String id; // // private String username; // // private Calendar connectionTime; // // public ActiveWebSocketUser() { // } // // public ActiveWebSocketUser(String id, String username, Calendar connectionTime) { // super(); // this.id = id; // this.username = username; // this.connectionTime = connectionTime; // } // // public String getUsername() { // return this.username; // } // // public void setUsername(String username) { // this.username = username; // } // // public Calendar getConnectionTime() { // return this.connectionTime; // } // // public void setConnectionTime(Calendar connectionTime) { // this.connectionTime = connectionTime; // } // // } // // Path: share/src/main/java/io/github/pivopil/share/persistence/ActiveWebSocketUserRepository.java // @Repository // public interface ActiveWebSocketUserRepository // extends CrudRepository<ActiveWebSocketUser, String> { // // @Query("select DISTINCT(u.username) from ActiveWebSocketUser u where u.username != :username") // List<String> findAllActiveUsers(@Param("username") String username); // }
import io.github.pivopil.rest.constants.WS_API; import io.github.pivopil.share.entities.ActiveWebSocketUser; import io.github.pivopil.share.persistence.ActiveWebSocketUserRepository; import org.springframework.context.ApplicationListener; import org.springframework.messaging.simp.SimpMessageSendingOperations; import org.springframework.web.socket.messaging.SessionDisconnectEvent; import java.util.Arrays; import java.util.Collections;
package io.github.pivopil.rest.handlers; public class WebSocketDisconnectHandler<S> implements ApplicationListener<SessionDisconnectEvent> { private ActiveWebSocketUserRepository repository; private SimpMessageSendingOperations messagingTemplate; public WebSocketDisconnectHandler(SimpMessageSendingOperations messagingTemplate, ActiveWebSocketUserRepository repository) { super(); this.messagingTemplate = messagingTemplate; this.repository = repository; } public void onApplicationEvent(SessionDisconnectEvent event) { String id = event.getSessionId(); if (id == null) { return; }
// Path: rest/src/main/java/io/github/pivopil/rest/constants/WS_API.java // public class WS_API { // private WS_API() { // // } // // public static final String HANDSHAKE = "/messages"; // public static final String INSTANT_MESSAGE = "/im"; // public static final String ACTIVE_USERS = "/users"; // public static final String QUEUE_MESSAGES = "/queue/messages"; // // public static final String QUEUE_DESTINATION_PREFIX = "/queue/"; // public static final String TOPIC_DESTINATION_PREFIX = "/topic/"; // public static final String APP_PREFIX = "/app"; // public static final String TOPIC_FRIENDS_SIGNIN = "/topic/friends/signin"; // public static final String TOPIC_FRIENDS_SIGNOUT = "/topic/friends/signout"; // } // // Path: share/src/main/java/io/github/pivopil/share/entities/ActiveWebSocketUser.java // @Entity // public class ActiveWebSocketUser { // @Id // private String id; // // private String username; // // private Calendar connectionTime; // // public ActiveWebSocketUser() { // } // // public ActiveWebSocketUser(String id, String username, Calendar connectionTime) { // super(); // this.id = id; // this.username = username; // this.connectionTime = connectionTime; // } // // public String getUsername() { // return this.username; // } // // public void setUsername(String username) { // this.username = username; // } // // public Calendar getConnectionTime() { // return this.connectionTime; // } // // public void setConnectionTime(Calendar connectionTime) { // this.connectionTime = connectionTime; // } // // } // // Path: share/src/main/java/io/github/pivopil/share/persistence/ActiveWebSocketUserRepository.java // @Repository // public interface ActiveWebSocketUserRepository // extends CrudRepository<ActiveWebSocketUser, String> { // // @Query("select DISTINCT(u.username) from ActiveWebSocketUser u where u.username != :username") // List<String> findAllActiveUsers(@Param("username") String username); // } // Path: rest/src/main/java/io/github/pivopil/rest/handlers/WebSocketDisconnectHandler.java import io.github.pivopil.rest.constants.WS_API; import io.github.pivopil.share.entities.ActiveWebSocketUser; import io.github.pivopil.share.persistence.ActiveWebSocketUserRepository; import org.springframework.context.ApplicationListener; import org.springframework.messaging.simp.SimpMessageSendingOperations; import org.springframework.web.socket.messaging.SessionDisconnectEvent; import java.util.Arrays; import java.util.Collections; package io.github.pivopil.rest.handlers; public class WebSocketDisconnectHandler<S> implements ApplicationListener<SessionDisconnectEvent> { private ActiveWebSocketUserRepository repository; private SimpMessageSendingOperations messagingTemplate; public WebSocketDisconnectHandler(SimpMessageSendingOperations messagingTemplate, ActiveWebSocketUserRepository repository) { super(); this.messagingTemplate = messagingTemplate; this.repository = repository; } public void onApplicationEvent(SessionDisconnectEvent event) { String id = event.getSessionId(); if (id == null) { return; }
ActiveWebSocketUser user = this.repository.findOne(id);
Pivopil/spring-boot-oauth2-rest-service-password-encoding
rest/src/main/java/io/github/pivopil/rest/handlers/WebSocketDisconnectHandler.java
// Path: rest/src/main/java/io/github/pivopil/rest/constants/WS_API.java // public class WS_API { // private WS_API() { // // } // // public static final String HANDSHAKE = "/messages"; // public static final String INSTANT_MESSAGE = "/im"; // public static final String ACTIVE_USERS = "/users"; // public static final String QUEUE_MESSAGES = "/queue/messages"; // // public static final String QUEUE_DESTINATION_PREFIX = "/queue/"; // public static final String TOPIC_DESTINATION_PREFIX = "/topic/"; // public static final String APP_PREFIX = "/app"; // public static final String TOPIC_FRIENDS_SIGNIN = "/topic/friends/signin"; // public static final String TOPIC_FRIENDS_SIGNOUT = "/topic/friends/signout"; // } // // Path: share/src/main/java/io/github/pivopil/share/entities/ActiveWebSocketUser.java // @Entity // public class ActiveWebSocketUser { // @Id // private String id; // // private String username; // // private Calendar connectionTime; // // public ActiveWebSocketUser() { // } // // public ActiveWebSocketUser(String id, String username, Calendar connectionTime) { // super(); // this.id = id; // this.username = username; // this.connectionTime = connectionTime; // } // // public String getUsername() { // return this.username; // } // // public void setUsername(String username) { // this.username = username; // } // // public Calendar getConnectionTime() { // return this.connectionTime; // } // // public void setConnectionTime(Calendar connectionTime) { // this.connectionTime = connectionTime; // } // // } // // Path: share/src/main/java/io/github/pivopil/share/persistence/ActiveWebSocketUserRepository.java // @Repository // public interface ActiveWebSocketUserRepository // extends CrudRepository<ActiveWebSocketUser, String> { // // @Query("select DISTINCT(u.username) from ActiveWebSocketUser u where u.username != :username") // List<String> findAllActiveUsers(@Param("username") String username); // }
import io.github.pivopil.rest.constants.WS_API; import io.github.pivopil.share.entities.ActiveWebSocketUser; import io.github.pivopil.share.persistence.ActiveWebSocketUserRepository; import org.springframework.context.ApplicationListener; import org.springframework.messaging.simp.SimpMessageSendingOperations; import org.springframework.web.socket.messaging.SessionDisconnectEvent; import java.util.Arrays; import java.util.Collections;
package io.github.pivopil.rest.handlers; public class WebSocketDisconnectHandler<S> implements ApplicationListener<SessionDisconnectEvent> { private ActiveWebSocketUserRepository repository; private SimpMessageSendingOperations messagingTemplate; public WebSocketDisconnectHandler(SimpMessageSendingOperations messagingTemplate, ActiveWebSocketUserRepository repository) { super(); this.messagingTemplate = messagingTemplate; this.repository = repository; } public void onApplicationEvent(SessionDisconnectEvent event) { String id = event.getSessionId(); if (id == null) { return; } ActiveWebSocketUser user = this.repository.findOne(id); if (user == null) { return; } this.repository.delete(id);
// Path: rest/src/main/java/io/github/pivopil/rest/constants/WS_API.java // public class WS_API { // private WS_API() { // // } // // public static final String HANDSHAKE = "/messages"; // public static final String INSTANT_MESSAGE = "/im"; // public static final String ACTIVE_USERS = "/users"; // public static final String QUEUE_MESSAGES = "/queue/messages"; // // public static final String QUEUE_DESTINATION_PREFIX = "/queue/"; // public static final String TOPIC_DESTINATION_PREFIX = "/topic/"; // public static final String APP_PREFIX = "/app"; // public static final String TOPIC_FRIENDS_SIGNIN = "/topic/friends/signin"; // public static final String TOPIC_FRIENDS_SIGNOUT = "/topic/friends/signout"; // } // // Path: share/src/main/java/io/github/pivopil/share/entities/ActiveWebSocketUser.java // @Entity // public class ActiveWebSocketUser { // @Id // private String id; // // private String username; // // private Calendar connectionTime; // // public ActiveWebSocketUser() { // } // // public ActiveWebSocketUser(String id, String username, Calendar connectionTime) { // super(); // this.id = id; // this.username = username; // this.connectionTime = connectionTime; // } // // public String getUsername() { // return this.username; // } // // public void setUsername(String username) { // this.username = username; // } // // public Calendar getConnectionTime() { // return this.connectionTime; // } // // public void setConnectionTime(Calendar connectionTime) { // this.connectionTime = connectionTime; // } // // } // // Path: share/src/main/java/io/github/pivopil/share/persistence/ActiveWebSocketUserRepository.java // @Repository // public interface ActiveWebSocketUserRepository // extends CrudRepository<ActiveWebSocketUser, String> { // // @Query("select DISTINCT(u.username) from ActiveWebSocketUser u where u.username != :username") // List<String> findAllActiveUsers(@Param("username") String username); // } // Path: rest/src/main/java/io/github/pivopil/rest/handlers/WebSocketDisconnectHandler.java import io.github.pivopil.rest.constants.WS_API; import io.github.pivopil.share.entities.ActiveWebSocketUser; import io.github.pivopil.share.persistence.ActiveWebSocketUserRepository; import org.springframework.context.ApplicationListener; import org.springframework.messaging.simp.SimpMessageSendingOperations; import org.springframework.web.socket.messaging.SessionDisconnectEvent; import java.util.Arrays; import java.util.Collections; package io.github.pivopil.rest.handlers; public class WebSocketDisconnectHandler<S> implements ApplicationListener<SessionDisconnectEvent> { private ActiveWebSocketUserRepository repository; private SimpMessageSendingOperations messagingTemplate; public WebSocketDisconnectHandler(SimpMessageSendingOperations messagingTemplate, ActiveWebSocketUserRepository repository) { super(); this.messagingTemplate = messagingTemplate; this.repository = repository; } public void onApplicationEvent(SessionDisconnectEvent event) { String id = event.getSessionId(); if (id == null) { return; } ActiveWebSocketUser user = this.repository.findOne(id); if (user == null) { return; } this.repository.delete(id);
this.messagingTemplate.convertAndSend(WS_API.TOPIC_FRIENDS_SIGNOUT,
Pivopil/spring-boot-oauth2-rest-service-password-encoding
rest/src/main/java/io/github/pivopil/rest/services/security/CustomSecurityService.java
// Path: rest/src/main/java/io/github/pivopil/rest/constants/ROLES.java // public class ROLES { // private ROLES() { // } // // public static final String ROLE_ADMIN = "ROLE_ADMIN"; // // public static final String ADMIN = "ADMIN"; // // public static final String ROLE_PREFIX = "ROLE_"; // // public static final String LOCAL_ADMIN = "LOCAL_ADMIN"; // public static final String LOCAL_USER = "LOCAL_USER"; // } // // Path: share/src/main/java/io/github/pivopil/share/entities/impl/Role.java // @Entity // public class Role extends BasicEntity implements GrantedAuthority { // // private static final long serialVersionUID = 1L; // // @NotEmpty // @Column(unique = true, nullable = false) // private String name; // // @JsonIgnore // @ManyToMany(fetch = FetchType.LAZY, mappedBy = "roles") // private Set<User> users = new HashSet<User>(); // // @Override // public String getAuthority() { // return name; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Set<User> getUsers() { // return users; // } // // public void setUsers(Set<User> users) { // this.users = users; // } // // }
import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import io.github.pivopil.rest.constants.ROLES; import io.github.pivopil.share.entities.impl.Role; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.acls.domain.BasePermission; import org.springframework.security.acls.domain.ObjectIdentityRetrievalStrategyImpl; import org.springframework.security.acls.domain.PrincipalSid; import org.springframework.security.acls.model.*; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import java.util.*; import java.util.stream.Collectors;
public CustomSecurityService(MutableAclService mutableAclService, CustomACLService customACLService, ObjectIdentityRetrievalStrategyImpl identityRetrievalStrategy) { this.mutableAclService = mutableAclService; this.customACLService = customACLService; this.identityRetrievalStrategy = identityRetrievalStrategy; } private Authentication getAuthentication() { final SecurityContext context = SecurityContextHolder.getContext(); if (context == null) { return null; } return context.getAuthentication(); } private <T> Collection<T> getAuthorities(Class<T> clazz) { final Authentication authentication = getAuthentication(); if (authentication == null) { return new ArrayList<>(); } @SuppressWarnings("uncheked") Collection<T> authorities = (Collection<T>) getAuthentication().getAuthorities(); return authorities; } @Transactional(propagation= Propagation.REQUIRED) public <T> void addAclPermissions(T objectWithId) { ObjectIdentity objectIdentity = identityRetrievalStrategy.getObjectIdentity(objectWithId); mutableAclService.createAcl(objectIdentity);
// Path: rest/src/main/java/io/github/pivopil/rest/constants/ROLES.java // public class ROLES { // private ROLES() { // } // // public static final String ROLE_ADMIN = "ROLE_ADMIN"; // // public static final String ADMIN = "ADMIN"; // // public static final String ROLE_PREFIX = "ROLE_"; // // public static final String LOCAL_ADMIN = "LOCAL_ADMIN"; // public static final String LOCAL_USER = "LOCAL_USER"; // } // // Path: share/src/main/java/io/github/pivopil/share/entities/impl/Role.java // @Entity // public class Role extends BasicEntity implements GrantedAuthority { // // private static final long serialVersionUID = 1L; // // @NotEmpty // @Column(unique = true, nullable = false) // private String name; // // @JsonIgnore // @ManyToMany(fetch = FetchType.LAZY, mappedBy = "roles") // private Set<User> users = new HashSet<User>(); // // @Override // public String getAuthority() { // return name; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Set<User> getUsers() { // return users; // } // // public void setUsers(Set<User> users) { // this.users = users; // } // // } // Path: rest/src/main/java/io/github/pivopil/rest/services/security/CustomSecurityService.java import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import io.github.pivopil.rest.constants.ROLES; import io.github.pivopil.share.entities.impl.Role; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.acls.domain.BasePermission; import org.springframework.security.acls.domain.ObjectIdentityRetrievalStrategyImpl; import org.springframework.security.acls.domain.PrincipalSid; import org.springframework.security.acls.model.*; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import java.util.*; import java.util.stream.Collectors; public CustomSecurityService(MutableAclService mutableAclService, CustomACLService customACLService, ObjectIdentityRetrievalStrategyImpl identityRetrievalStrategy) { this.mutableAclService = mutableAclService; this.customACLService = customACLService; this.identityRetrievalStrategy = identityRetrievalStrategy; } private Authentication getAuthentication() { final SecurityContext context = SecurityContextHolder.getContext(); if (context == null) { return null; } return context.getAuthentication(); } private <T> Collection<T> getAuthorities(Class<T> clazz) { final Authentication authentication = getAuthentication(); if (authentication == null) { return new ArrayList<>(); } @SuppressWarnings("uncheked") Collection<T> authorities = (Collection<T>) getAuthentication().getAuthorities(); return authorities; } @Transactional(propagation= Propagation.REQUIRED) public <T> void addAclPermissions(T objectWithId) { ObjectIdentity objectIdentity = identityRetrievalStrategy.getObjectIdentity(objectWithId); mutableAclService.createAcl(objectIdentity);
Boolean isRoleAdmin = isUserHasRole(ROLES.ROLE_ADMIN);