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
|
---|---|---|---|---|---|---|
alexgamas/treinamento-spring-boot
|
treinamento_5/src/main/java/br/com/gamas/treinamento/repository/UsuarioRepository.java
|
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/model/Usuario.java
// @Entity
// @Table(name = "usuario")
// public class Usuario implements UserDetails{
//
// private static final long serialVersionUID = 3317339439073208844L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// @Column(name = "id", nullable = false, updatable = false)
// private Long id;
//
// @Column(name = "username", nullable = false, unique = true)
// private String username;
//
// @Column(name = "password", nullable = false)
// private String password;
//
// @Column(name = "role", nullable = false)
// @Enumerated(EnumType.STRING)
// private Role role;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// @Override
// public Collection<? extends GrantedAuthority> getAuthorities() {
// List<GrantedAuthority> authorities = new ArrayList<>();
//
// if (role != null) {
// GrantedAuthority authority = new SimpleGrantedAuthority(role.name());
// authorities.add(authority);
// }
//
// return authorities;
// }
//
// @Override
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// @Override
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// @Override
// public boolean isAccountNonExpired() {
// return true;
// }
//
// @Override
// public boolean isAccountNonLocked() {
// return true;
// }
//
// @Override
// public boolean isCredentialsNonExpired() {
// return true;
// }
//
// @Override
// public boolean isEnabled() {
// return true;
// }
//
//
// }
|
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;
import br.com.gamas.treinamento.model.Usuario;
|
package br.com.gamas.treinamento.repository;
@Repository
public class UsuarioRepository {
@PersistenceContext
private EntityManager em;
|
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/model/Usuario.java
// @Entity
// @Table(name = "usuario")
// public class Usuario implements UserDetails{
//
// private static final long serialVersionUID = 3317339439073208844L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// @Column(name = "id", nullable = false, updatable = false)
// private Long id;
//
// @Column(name = "username", nullable = false, unique = true)
// private String username;
//
// @Column(name = "password", nullable = false)
// private String password;
//
// @Column(name = "role", nullable = false)
// @Enumerated(EnumType.STRING)
// private Role role;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// @Override
// public Collection<? extends GrantedAuthority> getAuthorities() {
// List<GrantedAuthority> authorities = new ArrayList<>();
//
// if (role != null) {
// GrantedAuthority authority = new SimpleGrantedAuthority(role.name());
// authorities.add(authority);
// }
//
// return authorities;
// }
//
// @Override
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// @Override
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// @Override
// public boolean isAccountNonExpired() {
// return true;
// }
//
// @Override
// public boolean isAccountNonLocked() {
// return true;
// }
//
// @Override
// public boolean isCredentialsNonExpired() {
// return true;
// }
//
// @Override
// public boolean isEnabled() {
// return true;
// }
//
//
// }
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/repository/UsuarioRepository.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;
import br.com.gamas.treinamento.model.Usuario;
package br.com.gamas.treinamento.repository;
@Repository
public class UsuarioRepository {
@PersistenceContext
private EntityManager em;
|
public Usuario loadUserByUsername(String username) {
|
jboz/plantuml-builder
|
src/main/java/ch/ifocusit/plantuml/classdiagram/model/attribute/Attribute.java
|
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/Link.java
// public class Link {
// private String url;
// private String label;
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getLabel() {
// return label;
// }
//
// public void setLabel(String label) {
// this.label = label;
// }
//
// @Override
// public String toString() {
// return String.format("[[%s{%s}]]", url, label);
// }
//
//
// }
|
import ch.ifocusit.plantuml.classdiagram.model.Link;
import java.util.Optional;
|
/*-
* Plantuml builder
*
* Copyright (C) 2017 Focus IT
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package ch.ifocusit.plantuml.classdiagram.model.attribute;
/**
* @author Julien Boz
*/
public interface Attribute {
public Optional<String> getTypeName();
public String getName();
|
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/Link.java
// public class Link {
// private String url;
// private String label;
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getLabel() {
// return label;
// }
//
// public void setLabel(String label) {
// this.label = label;
// }
//
// @Override
// public String toString() {
// return String.format("[[%s{%s}]]", url, label);
// }
//
//
// }
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/attribute/Attribute.java
import ch.ifocusit.plantuml.classdiagram.model.Link;
import java.util.Optional;
/*-
* Plantuml builder
*
* Copyright (C) 2017 Focus IT
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package ch.ifocusit.plantuml.classdiagram.model.attribute;
/**
* @author Julien Boz
*/
public interface Attribute {
public Optional<String> getTypeName();
public String getName();
|
default public Optional<Link> getLink() {
|
jboz/plantuml-builder
|
src/main/java/ch/ifocusit/plantuml/classdiagram/model/method/Method.java
|
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/Link.java
// public class Link {
// private String url;
// private String label;
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getLabel() {
// return label;
// }
//
// public void setLabel(String label) {
// this.label = label;
// }
//
// @Override
// public String toString() {
// return String.format("[[%s{%s}]]", url, label);
// }
//
//
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/attribute/MethodAttribute.java
// public class MethodAttribute implements Attribute, ClassMember {
//
// private final Parameter methodParameter;
//
// public MethodAttribute(final Parameter methodParameter) {
// this.methodParameter = methodParameter;
// }
//
// @Override
// public Set<Class> getConcernedTypes() {
// return ClassUtils.getConcernedTypes(methodParameter);
// }
//
// public Class getParameterType() {
// return methodParameter.getType();
// }
//
// @Override
// public Class getType() {
// return getParameterType();
// }
//
// @Override
// public Class getDeclaringClass() {
// return methodParameter.getDeclaringExecutable().getDeclaringClass();
// }
//
// @Override
// public Optional<String> getTypeName() {
// return Optional.of(ClassUtils.getSimpleName(methodParameter.getParameterizedType()));
// }
//
// @Override
// public String getName() {
// return methodParameter.getName();
// }
// }
|
import ch.ifocusit.plantuml.classdiagram.model.Link;
import ch.ifocusit.plantuml.classdiagram.model.attribute.MethodAttribute;
import java.util.Optional;
|
/*-
* Plantuml builder
*
* Copyright (C) 2017 Focus IT
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package ch.ifocusit.plantuml.classdiagram.model.method;
/**
* @author Julien Boz
*/
public interface Method {
public Optional<String> getReturnTypeName();
public String getName();
|
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/Link.java
// public class Link {
// private String url;
// private String label;
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getLabel() {
// return label;
// }
//
// public void setLabel(String label) {
// this.label = label;
// }
//
// @Override
// public String toString() {
// return String.format("[[%s{%s}]]", url, label);
// }
//
//
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/attribute/MethodAttribute.java
// public class MethodAttribute implements Attribute, ClassMember {
//
// private final Parameter methodParameter;
//
// public MethodAttribute(final Parameter methodParameter) {
// this.methodParameter = methodParameter;
// }
//
// @Override
// public Set<Class> getConcernedTypes() {
// return ClassUtils.getConcernedTypes(methodParameter);
// }
//
// public Class getParameterType() {
// return methodParameter.getType();
// }
//
// @Override
// public Class getType() {
// return getParameterType();
// }
//
// @Override
// public Class getDeclaringClass() {
// return methodParameter.getDeclaringExecutable().getDeclaringClass();
// }
//
// @Override
// public Optional<String> getTypeName() {
// return Optional.of(ClassUtils.getSimpleName(methodParameter.getParameterizedType()));
// }
//
// @Override
// public String getName() {
// return methodParameter.getName();
// }
// }
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/method/Method.java
import ch.ifocusit.plantuml.classdiagram.model.Link;
import ch.ifocusit.plantuml.classdiagram.model.attribute.MethodAttribute;
import java.util.Optional;
/*-
* Plantuml builder
*
* Copyright (C) 2017 Focus IT
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package ch.ifocusit.plantuml.classdiagram.model.method;
/**
* @author Julien Boz
*/
public interface Method {
public Optional<String> getReturnTypeName();
public String getName();
|
public Optional<MethodAttribute[]> getParameters();
|
jboz/plantuml-builder
|
src/main/java/ch/ifocusit/plantuml/classdiagram/model/method/Method.java
|
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/Link.java
// public class Link {
// private String url;
// private String label;
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getLabel() {
// return label;
// }
//
// public void setLabel(String label) {
// this.label = label;
// }
//
// @Override
// public String toString() {
// return String.format("[[%s{%s}]]", url, label);
// }
//
//
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/attribute/MethodAttribute.java
// public class MethodAttribute implements Attribute, ClassMember {
//
// private final Parameter methodParameter;
//
// public MethodAttribute(final Parameter methodParameter) {
// this.methodParameter = methodParameter;
// }
//
// @Override
// public Set<Class> getConcernedTypes() {
// return ClassUtils.getConcernedTypes(methodParameter);
// }
//
// public Class getParameterType() {
// return methodParameter.getType();
// }
//
// @Override
// public Class getType() {
// return getParameterType();
// }
//
// @Override
// public Class getDeclaringClass() {
// return methodParameter.getDeclaringExecutable().getDeclaringClass();
// }
//
// @Override
// public Optional<String> getTypeName() {
// return Optional.of(ClassUtils.getSimpleName(methodParameter.getParameterizedType()));
// }
//
// @Override
// public String getName() {
// return methodParameter.getName();
// }
// }
|
import ch.ifocusit.plantuml.classdiagram.model.Link;
import ch.ifocusit.plantuml.classdiagram.model.attribute.MethodAttribute;
import java.util.Optional;
|
/*-
* Plantuml builder
*
* Copyright (C) 2017 Focus IT
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package ch.ifocusit.plantuml.classdiagram.model.method;
/**
* @author Julien Boz
*/
public interface Method {
public Optional<String> getReturnTypeName();
public String getName();
public Optional<MethodAttribute[]> getParameters();
|
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/Link.java
// public class Link {
// private String url;
// private String label;
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getLabel() {
// return label;
// }
//
// public void setLabel(String label) {
// this.label = label;
// }
//
// @Override
// public String toString() {
// return String.format("[[%s{%s}]]", url, label);
// }
//
//
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/attribute/MethodAttribute.java
// public class MethodAttribute implements Attribute, ClassMember {
//
// private final Parameter methodParameter;
//
// public MethodAttribute(final Parameter methodParameter) {
// this.methodParameter = methodParameter;
// }
//
// @Override
// public Set<Class> getConcernedTypes() {
// return ClassUtils.getConcernedTypes(methodParameter);
// }
//
// public Class getParameterType() {
// return methodParameter.getType();
// }
//
// @Override
// public Class getType() {
// return getParameterType();
// }
//
// @Override
// public Class getDeclaringClass() {
// return methodParameter.getDeclaringExecutable().getDeclaringClass();
// }
//
// @Override
// public Optional<String> getTypeName() {
// return Optional.of(ClassUtils.getSimpleName(methodParameter.getParameterizedType()));
// }
//
// @Override
// public String getName() {
// return methodParameter.getName();
// }
// }
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/method/Method.java
import ch.ifocusit.plantuml.classdiagram.model.Link;
import ch.ifocusit.plantuml.classdiagram.model.attribute.MethodAttribute;
import java.util.Optional;
/*-
* Plantuml builder
*
* Copyright (C) 2017 Focus IT
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package ch.ifocusit.plantuml.classdiagram.model.method;
/**
* @author Julien Boz
*/
public interface Method {
public Optional<String> getReturnTypeName();
public String getName();
public Optional<MethodAttribute[]> getParameters();
|
default public Optional<Link> getLink() {
|
jboz/plantuml-builder
|
src/main/java/ch/ifocusit/plantuml/classdiagram/model/clazz/Clazz.java
|
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/Link.java
// public class Link {
// private String url;
// private String label;
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getLabel() {
// return label;
// }
//
// public void setLabel(String label) {
// this.label = label;
// }
//
// @Override
// public String toString() {
// return String.format("[[%s{%s}]]", url, label);
// }
//
//
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/method/Method.java
// public interface Method {
//
// public Optional<String> getReturnTypeName();
//
// public String getName();
//
// public Optional<MethodAttribute[]> getParameters();
//
// default public Optional<Link> getLink() {
// return Optional.empty();
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/attribute/Attribute.java
// public interface Attribute {
//
// public Optional<String> getTypeName();
//
// public String getName();
//
// default public Optional<Link> getLink() {
// return Optional.empty();
// }
// }
|
import ch.ifocusit.plantuml.classdiagram.model.Link;
import ch.ifocusit.plantuml.classdiagram.model.method.Method;
import ch.ifocusit.plantuml.classdiagram.model.attribute.Attribute;
import org.apache.commons.lang3.Validate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
|
/*-
* Plantuml builder
*
* Copyright (C) 2017 Focus IT
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package ch.ifocusit.plantuml.classdiagram.model.clazz;
/**
* @author Julien Boz
*/
public interface Clazz extends Comparable<Clazz> {
public String getName();
public Type getType();
|
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/Link.java
// public class Link {
// private String url;
// private String label;
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getLabel() {
// return label;
// }
//
// public void setLabel(String label) {
// this.label = label;
// }
//
// @Override
// public String toString() {
// return String.format("[[%s{%s}]]", url, label);
// }
//
//
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/method/Method.java
// public interface Method {
//
// public Optional<String> getReturnTypeName();
//
// public String getName();
//
// public Optional<MethodAttribute[]> getParameters();
//
// default public Optional<Link> getLink() {
// return Optional.empty();
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/attribute/Attribute.java
// public interface Attribute {
//
// public Optional<String> getTypeName();
//
// public String getName();
//
// default public Optional<Link> getLink() {
// return Optional.empty();
// }
// }
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/clazz/Clazz.java
import ch.ifocusit.plantuml.classdiagram.model.Link;
import ch.ifocusit.plantuml.classdiagram.model.method.Method;
import ch.ifocusit.plantuml.classdiagram.model.attribute.Attribute;
import org.apache.commons.lang3.Validate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/*-
* Plantuml builder
*
* Copyright (C) 2017 Focus IT
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package ch.ifocusit.plantuml.classdiagram.model.clazz;
/**
* @author Julien Boz
*/
public interface Clazz extends Comparable<Clazz> {
public String getName();
public Type getType();
|
default public Optional<Link> getLink() {
|
jboz/plantuml-builder
|
src/main/java/ch/ifocusit/plantuml/classdiagram/model/clazz/Clazz.java
|
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/Link.java
// public class Link {
// private String url;
// private String label;
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getLabel() {
// return label;
// }
//
// public void setLabel(String label) {
// this.label = label;
// }
//
// @Override
// public String toString() {
// return String.format("[[%s{%s}]]", url, label);
// }
//
//
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/method/Method.java
// public interface Method {
//
// public Optional<String> getReturnTypeName();
//
// public String getName();
//
// public Optional<MethodAttribute[]> getParameters();
//
// default public Optional<Link> getLink() {
// return Optional.empty();
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/attribute/Attribute.java
// public interface Attribute {
//
// public Optional<String> getTypeName();
//
// public String getName();
//
// default public Optional<Link> getLink() {
// return Optional.empty();
// }
// }
|
import ch.ifocusit.plantuml.classdiagram.model.Link;
import ch.ifocusit.plantuml.classdiagram.model.method.Method;
import ch.ifocusit.plantuml.classdiagram.model.attribute.Attribute;
import org.apache.commons.lang3.Validate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
|
/*-
* Plantuml builder
*
* Copyright (C) 2017 Focus IT
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package ch.ifocusit.plantuml.classdiagram.model.clazz;
/**
* @author Julien Boz
*/
public interface Clazz extends Comparable<Clazz> {
public String getName();
public Type getType();
default public Optional<Link> getLink() {
return Optional.empty();
}
|
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/Link.java
// public class Link {
// private String url;
// private String label;
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getLabel() {
// return label;
// }
//
// public void setLabel(String label) {
// this.label = label;
// }
//
// @Override
// public String toString() {
// return String.format("[[%s{%s}]]", url, label);
// }
//
//
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/method/Method.java
// public interface Method {
//
// public Optional<String> getReturnTypeName();
//
// public String getName();
//
// public Optional<MethodAttribute[]> getParameters();
//
// default public Optional<Link> getLink() {
// return Optional.empty();
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/attribute/Attribute.java
// public interface Attribute {
//
// public Optional<String> getTypeName();
//
// public String getName();
//
// default public Optional<Link> getLink() {
// return Optional.empty();
// }
// }
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/clazz/Clazz.java
import ch.ifocusit.plantuml.classdiagram.model.Link;
import ch.ifocusit.plantuml.classdiagram.model.method.Method;
import ch.ifocusit.plantuml.classdiagram.model.attribute.Attribute;
import org.apache.commons.lang3.Validate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/*-
* Plantuml builder
*
* Copyright (C) 2017 Focus IT
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package ch.ifocusit.plantuml.classdiagram.model.clazz;
/**
* @author Julien Boz
*/
public interface Clazz extends Comparable<Clazz> {
public String getName();
public Type getType();
default public Optional<Link> getLink() {
return Optional.empty();
}
|
public List<? extends Attribute> getAttributes();
|
jboz/plantuml-builder
|
src/main/java/ch/ifocusit/plantuml/classdiagram/model/clazz/Clazz.java
|
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/Link.java
// public class Link {
// private String url;
// private String label;
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getLabel() {
// return label;
// }
//
// public void setLabel(String label) {
// this.label = label;
// }
//
// @Override
// public String toString() {
// return String.format("[[%s{%s}]]", url, label);
// }
//
//
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/method/Method.java
// public interface Method {
//
// public Optional<String> getReturnTypeName();
//
// public String getName();
//
// public Optional<MethodAttribute[]> getParameters();
//
// default public Optional<Link> getLink() {
// return Optional.empty();
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/attribute/Attribute.java
// public interface Attribute {
//
// public Optional<String> getTypeName();
//
// public String getName();
//
// default public Optional<Link> getLink() {
// return Optional.empty();
// }
// }
|
import ch.ifocusit.plantuml.classdiagram.model.Link;
import ch.ifocusit.plantuml.classdiagram.model.method.Method;
import ch.ifocusit.plantuml.classdiagram.model.attribute.Attribute;
import org.apache.commons.lang3.Validate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
|
/*-
* Plantuml builder
*
* Copyright (C) 2017 Focus IT
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package ch.ifocusit.plantuml.classdiagram.model.clazz;
/**
* @author Julien Boz
*/
public interface Clazz extends Comparable<Clazz> {
public String getName();
public Type getType();
default public Optional<Link> getLink() {
return Optional.empty();
}
public List<? extends Attribute> getAttributes();
|
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/Link.java
// public class Link {
// private String url;
// private String label;
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getLabel() {
// return label;
// }
//
// public void setLabel(String label) {
// this.label = label;
// }
//
// @Override
// public String toString() {
// return String.format("[[%s{%s}]]", url, label);
// }
//
//
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/method/Method.java
// public interface Method {
//
// public Optional<String> getReturnTypeName();
//
// public String getName();
//
// public Optional<MethodAttribute[]> getParameters();
//
// default public Optional<Link> getLink() {
// return Optional.empty();
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/attribute/Attribute.java
// public interface Attribute {
//
// public Optional<String> getTypeName();
//
// public String getName();
//
// default public Optional<Link> getLink() {
// return Optional.empty();
// }
// }
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/clazz/Clazz.java
import ch.ifocusit.plantuml.classdiagram.model.Link;
import ch.ifocusit.plantuml.classdiagram.model.method.Method;
import ch.ifocusit.plantuml.classdiagram.model.attribute.Attribute;
import org.apache.commons.lang3.Validate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/*-
* Plantuml builder
*
* Copyright (C) 2017 Focus IT
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package ch.ifocusit.plantuml.classdiagram.model.clazz;
/**
* @author Julien Boz
*/
public interface Clazz extends Comparable<Clazz> {
public String getName();
public Type getType();
default public Optional<Link> getLink() {
return Optional.empty();
}
public List<? extends Attribute> getAttributes();
|
default public List<? extends Method> getMethods() {
|
jboz/plantuml-builder
|
src/test/java/ch/ifocusit/plantuml/test/helper/domain/Driver.java
|
// Path: src/test/java/ch/ifocusit/plantuml/test/helper/domain/material/Car.java
// @Machine
// public class Car implements Vehicule {
//
// @Machine
// // must be ignored
// private Long ignored;
// @Machine
// private String brand;
// @Machine
// private String model;
//
// private Set<Driver> drivers = new HashSet<>();
//
// private Price price;
//
// @Machine
// private Collection<Wheel> wheels;
//
// public Driver buyBy(Driver driver, BigDecimal amount, Devise devise) {
// this.drivers.add(driver);
// driver.buy(this);
// this.price = Price.of(amount, devise);
// return driver;
// }
//
// public Car addDriver(Driver anotherDriver) {
// drivers.add(anotherDriver);
// anotherDriver.addCar(this);
// return this;
// }
//
// public Collection<Wheel> getWheels() {
// return wheels;
// }
//
// public void addWheel(Wheel wheel) {
// wheels.add(wheel);
// }
//
// @Override
// public String toString() {
// return showMeTheCarInfo();
// }
//
// @Override
// public boolean equals(final Object obj) {
// return EqualsBuilder.reflectionEquals(this, obj);
// }
//
// @Override
// public int hashCode() {
// return HashCodeBuilder.reflectionHashCode(this);
// }
//
// private String showMeTheCarInfo() {
// return brand + "/" + model;
// }
// }
|
import ch.ifocusit.plantuml.test.helper.domain.material.Car;
import java.util.ArrayList;
import java.util.List;
|
/*-
* Plantuml builder
*
* Copyright (C) 2017 Focus IT
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package ch.ifocusit.plantuml.test.helper.domain;
public class Driver {
private String name;
private Long ignored;
|
// Path: src/test/java/ch/ifocusit/plantuml/test/helper/domain/material/Car.java
// @Machine
// public class Car implements Vehicule {
//
// @Machine
// // must be ignored
// private Long ignored;
// @Machine
// private String brand;
// @Machine
// private String model;
//
// private Set<Driver> drivers = new HashSet<>();
//
// private Price price;
//
// @Machine
// private Collection<Wheel> wheels;
//
// public Driver buyBy(Driver driver, BigDecimal amount, Devise devise) {
// this.drivers.add(driver);
// driver.buy(this);
// this.price = Price.of(amount, devise);
// return driver;
// }
//
// public Car addDriver(Driver anotherDriver) {
// drivers.add(anotherDriver);
// anotherDriver.addCar(this);
// return this;
// }
//
// public Collection<Wheel> getWheels() {
// return wheels;
// }
//
// public void addWheel(Wheel wheel) {
// wheels.add(wheel);
// }
//
// @Override
// public String toString() {
// return showMeTheCarInfo();
// }
//
// @Override
// public boolean equals(final Object obj) {
// return EqualsBuilder.reflectionEquals(this, obj);
// }
//
// @Override
// public int hashCode() {
// return HashCodeBuilder.reflectionHashCode(this);
// }
//
// private String showMeTheCarInfo() {
// return brand + "/" + model;
// }
// }
// Path: src/test/java/ch/ifocusit/plantuml/test/helper/domain/Driver.java
import ch.ifocusit.plantuml.test.helper.domain.material.Car;
import java.util.ArrayList;
import java.util.List;
/*-
* Plantuml builder
*
* Copyright (C) 2017 Focus IT
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package ch.ifocusit.plantuml.test.helper.domain;
public class Driver {
private String name;
private Long ignored;
|
private List<Car> cars = new ArrayList<>();
|
jboz/plantuml-builder
|
src/test/java/ch/ifocusit/plantuml/PlantUmlBuilderTest.java
|
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/Association.java
// public enum AssociationType {
//
// LINK("-"),
// DIRECTION("-->"),
// BI_DIRECTION("<->"),
// INHERITANCE("<|--");
//
// private String symbol;
//
// AssociationType(String symbol) {
// this.symbol = symbol;
// }
//
// @Override
// public String toString() {
// return symbol;
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/Cardinality.java
// public enum Cardinality {
//
// NONE(""),
// MANY("*"),
// ONE("1");
//
// private String symbol;
//
// Cardinality(String symbol) {
// this.symbol = symbol;
// }
//
// @Override
// public String toString() {
// return symbol;
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/attribute/SimpleAttribute.java
// public class SimpleAttribute implements Attribute {
//
// private String type;
// private String name;
//
// public SimpleAttribute(String name, String type) {
// this.type = type;
// this.name = name;
// }
//
// @Override
// public Optional<String> getTypeName() {
// return Optional.ofNullable(type);
// }
//
// @Override
// public String getName() {
// return name;
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/clazz/Clazz.java
// public interface Clazz extends Comparable<Clazz> {
//
// public String getName();
//
// public Type getType();
//
// default public Optional<Link> getLink() {
// return Optional.empty();
// }
//
// public List<? extends Attribute> getAttributes();
//
// default public List<? extends Method> getMethods() {
// return new ArrayList<>();
// }
//
// default public Optional<List<String>> getStereotypes() {
// return Optional.empty();
// }
//
// default public Optional<String> getBackgroundColor() {
// return Optional.empty();
// }
//
// default public Optional<String> getBorderColor() {
// return Optional.empty();
// }
//
// default public void validate() {
// Validate.notNull(getName(), "Class name must be defined !");
// Validate.notNull(getType(), String.format("Class '%s' type must be defined !", getName()));
// }
//
// @Override
// default int compareTo(Clazz clazz) {
// return getName().compareTo(clazz.getName());
// }
//
// default boolean hasContent() {
// return !getAttributes().isEmpty() || !getMethods().isEmpty();
// }
//
// enum Type {
// INTERFACE("interface"),
// ENUM("enum"),
// CLASS("class"),
// ABSTRACT("abstract class");
//
// private String name;
//
// Type(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/clazz/SimpleClazz.java
// public class SimpleClazz implements Clazz {
//
// private String name;
// private Type type;
// private List<Attribute> attributes = new ArrayList<>();
//
// @Override
// public String getName() {
// return name;
// }
//
// @Override
// public Type getType() {
// return type;
// }
//
// @Override
// public List<Attribute> getAttributes() {
// return attributes;
// }
//
// public static SimpleClazz create(String name, Type type, Attribute... attributes) {
// SimpleClazz c = new SimpleClazz();
// c.name = name;
// c.type = type;
// Stream.of(attributes).forEach(c.attributes::add);
// return c;
// }
// }
|
import ch.ifocusit.plantuml.classdiagram.model.Association.AssociationType;
import ch.ifocusit.plantuml.classdiagram.model.Cardinality;
import ch.ifocusit.plantuml.classdiagram.model.attribute.SimpleAttribute;
import ch.ifocusit.plantuml.classdiagram.model.clazz.Clazz;
import ch.ifocusit.plantuml.classdiagram.model.clazz.SimpleClazz;
import org.junit.Test;
import static org.fest.assertions.Assertions.*;
|
/*-
* Plantuml builder
*
* Copyright (C) 2017 Focus IT
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package ch.ifocusit.plantuml;
public class PlantUmlBuilderTest {
private static final String CR = PlantUmlBuilder.NEWLINE;
@Test
public void buildInterface() {
|
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/Association.java
// public enum AssociationType {
//
// LINK("-"),
// DIRECTION("-->"),
// BI_DIRECTION("<->"),
// INHERITANCE("<|--");
//
// private String symbol;
//
// AssociationType(String symbol) {
// this.symbol = symbol;
// }
//
// @Override
// public String toString() {
// return symbol;
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/Cardinality.java
// public enum Cardinality {
//
// NONE(""),
// MANY("*"),
// ONE("1");
//
// private String symbol;
//
// Cardinality(String symbol) {
// this.symbol = symbol;
// }
//
// @Override
// public String toString() {
// return symbol;
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/attribute/SimpleAttribute.java
// public class SimpleAttribute implements Attribute {
//
// private String type;
// private String name;
//
// public SimpleAttribute(String name, String type) {
// this.type = type;
// this.name = name;
// }
//
// @Override
// public Optional<String> getTypeName() {
// return Optional.ofNullable(type);
// }
//
// @Override
// public String getName() {
// return name;
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/clazz/Clazz.java
// public interface Clazz extends Comparable<Clazz> {
//
// public String getName();
//
// public Type getType();
//
// default public Optional<Link> getLink() {
// return Optional.empty();
// }
//
// public List<? extends Attribute> getAttributes();
//
// default public List<? extends Method> getMethods() {
// return new ArrayList<>();
// }
//
// default public Optional<List<String>> getStereotypes() {
// return Optional.empty();
// }
//
// default public Optional<String> getBackgroundColor() {
// return Optional.empty();
// }
//
// default public Optional<String> getBorderColor() {
// return Optional.empty();
// }
//
// default public void validate() {
// Validate.notNull(getName(), "Class name must be defined !");
// Validate.notNull(getType(), String.format("Class '%s' type must be defined !", getName()));
// }
//
// @Override
// default int compareTo(Clazz clazz) {
// return getName().compareTo(clazz.getName());
// }
//
// default boolean hasContent() {
// return !getAttributes().isEmpty() || !getMethods().isEmpty();
// }
//
// enum Type {
// INTERFACE("interface"),
// ENUM("enum"),
// CLASS("class"),
// ABSTRACT("abstract class");
//
// private String name;
//
// Type(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/clazz/SimpleClazz.java
// public class SimpleClazz implements Clazz {
//
// private String name;
// private Type type;
// private List<Attribute> attributes = new ArrayList<>();
//
// @Override
// public String getName() {
// return name;
// }
//
// @Override
// public Type getType() {
// return type;
// }
//
// @Override
// public List<Attribute> getAttributes() {
// return attributes;
// }
//
// public static SimpleClazz create(String name, Type type, Attribute... attributes) {
// SimpleClazz c = new SimpleClazz();
// c.name = name;
// c.type = type;
// Stream.of(attributes).forEach(c.attributes::add);
// return c;
// }
// }
// Path: src/test/java/ch/ifocusit/plantuml/PlantUmlBuilderTest.java
import ch.ifocusit.plantuml.classdiagram.model.Association.AssociationType;
import ch.ifocusit.plantuml.classdiagram.model.Cardinality;
import ch.ifocusit.plantuml.classdiagram.model.attribute.SimpleAttribute;
import ch.ifocusit.plantuml.classdiagram.model.clazz.Clazz;
import ch.ifocusit.plantuml.classdiagram.model.clazz.SimpleClazz;
import org.junit.Test;
import static org.fest.assertions.Assertions.*;
/*-
* Plantuml builder
*
* Copyright (C) 2017 Focus IT
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package ch.ifocusit.plantuml;
public class PlantUmlBuilderTest {
private static final String CR = PlantUmlBuilder.NEWLINE;
@Test
public void buildInterface() {
|
final String diagram = new PlantUmlBuilder().addType(SimpleClazz.create("Vehicule", Clazz.Type.INTERFACE)).build();
|
jboz/plantuml-builder
|
src/test/java/ch/ifocusit/plantuml/PlantUmlBuilderTest.java
|
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/Association.java
// public enum AssociationType {
//
// LINK("-"),
// DIRECTION("-->"),
// BI_DIRECTION("<->"),
// INHERITANCE("<|--");
//
// private String symbol;
//
// AssociationType(String symbol) {
// this.symbol = symbol;
// }
//
// @Override
// public String toString() {
// return symbol;
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/Cardinality.java
// public enum Cardinality {
//
// NONE(""),
// MANY("*"),
// ONE("1");
//
// private String symbol;
//
// Cardinality(String symbol) {
// this.symbol = symbol;
// }
//
// @Override
// public String toString() {
// return symbol;
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/attribute/SimpleAttribute.java
// public class SimpleAttribute implements Attribute {
//
// private String type;
// private String name;
//
// public SimpleAttribute(String name, String type) {
// this.type = type;
// this.name = name;
// }
//
// @Override
// public Optional<String> getTypeName() {
// return Optional.ofNullable(type);
// }
//
// @Override
// public String getName() {
// return name;
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/clazz/Clazz.java
// public interface Clazz extends Comparable<Clazz> {
//
// public String getName();
//
// public Type getType();
//
// default public Optional<Link> getLink() {
// return Optional.empty();
// }
//
// public List<? extends Attribute> getAttributes();
//
// default public List<? extends Method> getMethods() {
// return new ArrayList<>();
// }
//
// default public Optional<List<String>> getStereotypes() {
// return Optional.empty();
// }
//
// default public Optional<String> getBackgroundColor() {
// return Optional.empty();
// }
//
// default public Optional<String> getBorderColor() {
// return Optional.empty();
// }
//
// default public void validate() {
// Validate.notNull(getName(), "Class name must be defined !");
// Validate.notNull(getType(), String.format("Class '%s' type must be defined !", getName()));
// }
//
// @Override
// default int compareTo(Clazz clazz) {
// return getName().compareTo(clazz.getName());
// }
//
// default boolean hasContent() {
// return !getAttributes().isEmpty() || !getMethods().isEmpty();
// }
//
// enum Type {
// INTERFACE("interface"),
// ENUM("enum"),
// CLASS("class"),
// ABSTRACT("abstract class");
//
// private String name;
//
// Type(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/clazz/SimpleClazz.java
// public class SimpleClazz implements Clazz {
//
// private String name;
// private Type type;
// private List<Attribute> attributes = new ArrayList<>();
//
// @Override
// public String getName() {
// return name;
// }
//
// @Override
// public Type getType() {
// return type;
// }
//
// @Override
// public List<Attribute> getAttributes() {
// return attributes;
// }
//
// public static SimpleClazz create(String name, Type type, Attribute... attributes) {
// SimpleClazz c = new SimpleClazz();
// c.name = name;
// c.type = type;
// Stream.of(attributes).forEach(c.attributes::add);
// return c;
// }
// }
|
import ch.ifocusit.plantuml.classdiagram.model.Association.AssociationType;
import ch.ifocusit.plantuml.classdiagram.model.Cardinality;
import ch.ifocusit.plantuml.classdiagram.model.attribute.SimpleAttribute;
import ch.ifocusit.plantuml.classdiagram.model.clazz.Clazz;
import ch.ifocusit.plantuml.classdiagram.model.clazz.SimpleClazz;
import org.junit.Test;
import static org.fest.assertions.Assertions.*;
|
/*-
* Plantuml builder
*
* Copyright (C) 2017 Focus IT
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package ch.ifocusit.plantuml;
public class PlantUmlBuilderTest {
private static final String CR = PlantUmlBuilder.NEWLINE;
@Test
public void buildInterface() {
|
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/Association.java
// public enum AssociationType {
//
// LINK("-"),
// DIRECTION("-->"),
// BI_DIRECTION("<->"),
// INHERITANCE("<|--");
//
// private String symbol;
//
// AssociationType(String symbol) {
// this.symbol = symbol;
// }
//
// @Override
// public String toString() {
// return symbol;
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/Cardinality.java
// public enum Cardinality {
//
// NONE(""),
// MANY("*"),
// ONE("1");
//
// private String symbol;
//
// Cardinality(String symbol) {
// this.symbol = symbol;
// }
//
// @Override
// public String toString() {
// return symbol;
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/attribute/SimpleAttribute.java
// public class SimpleAttribute implements Attribute {
//
// private String type;
// private String name;
//
// public SimpleAttribute(String name, String type) {
// this.type = type;
// this.name = name;
// }
//
// @Override
// public Optional<String> getTypeName() {
// return Optional.ofNullable(type);
// }
//
// @Override
// public String getName() {
// return name;
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/clazz/Clazz.java
// public interface Clazz extends Comparable<Clazz> {
//
// public String getName();
//
// public Type getType();
//
// default public Optional<Link> getLink() {
// return Optional.empty();
// }
//
// public List<? extends Attribute> getAttributes();
//
// default public List<? extends Method> getMethods() {
// return new ArrayList<>();
// }
//
// default public Optional<List<String>> getStereotypes() {
// return Optional.empty();
// }
//
// default public Optional<String> getBackgroundColor() {
// return Optional.empty();
// }
//
// default public Optional<String> getBorderColor() {
// return Optional.empty();
// }
//
// default public void validate() {
// Validate.notNull(getName(), "Class name must be defined !");
// Validate.notNull(getType(), String.format("Class '%s' type must be defined !", getName()));
// }
//
// @Override
// default int compareTo(Clazz clazz) {
// return getName().compareTo(clazz.getName());
// }
//
// default boolean hasContent() {
// return !getAttributes().isEmpty() || !getMethods().isEmpty();
// }
//
// enum Type {
// INTERFACE("interface"),
// ENUM("enum"),
// CLASS("class"),
// ABSTRACT("abstract class");
//
// private String name;
//
// Type(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/clazz/SimpleClazz.java
// public class SimpleClazz implements Clazz {
//
// private String name;
// private Type type;
// private List<Attribute> attributes = new ArrayList<>();
//
// @Override
// public String getName() {
// return name;
// }
//
// @Override
// public Type getType() {
// return type;
// }
//
// @Override
// public List<Attribute> getAttributes() {
// return attributes;
// }
//
// public static SimpleClazz create(String name, Type type, Attribute... attributes) {
// SimpleClazz c = new SimpleClazz();
// c.name = name;
// c.type = type;
// Stream.of(attributes).forEach(c.attributes::add);
// return c;
// }
// }
// Path: src/test/java/ch/ifocusit/plantuml/PlantUmlBuilderTest.java
import ch.ifocusit.plantuml.classdiagram.model.Association.AssociationType;
import ch.ifocusit.plantuml.classdiagram.model.Cardinality;
import ch.ifocusit.plantuml.classdiagram.model.attribute.SimpleAttribute;
import ch.ifocusit.plantuml.classdiagram.model.clazz.Clazz;
import ch.ifocusit.plantuml.classdiagram.model.clazz.SimpleClazz;
import org.junit.Test;
import static org.fest.assertions.Assertions.*;
/*-
* Plantuml builder
*
* Copyright (C) 2017 Focus IT
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package ch.ifocusit.plantuml;
public class PlantUmlBuilderTest {
private static final String CR = PlantUmlBuilder.NEWLINE;
@Test
public void buildInterface() {
|
final String diagram = new PlantUmlBuilder().addType(SimpleClazz.create("Vehicule", Clazz.Type.INTERFACE)).build();
|
jboz/plantuml-builder
|
src/test/java/ch/ifocusit/plantuml/PlantUmlBuilderTest.java
|
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/Association.java
// public enum AssociationType {
//
// LINK("-"),
// DIRECTION("-->"),
// BI_DIRECTION("<->"),
// INHERITANCE("<|--");
//
// private String symbol;
//
// AssociationType(String symbol) {
// this.symbol = symbol;
// }
//
// @Override
// public String toString() {
// return symbol;
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/Cardinality.java
// public enum Cardinality {
//
// NONE(""),
// MANY("*"),
// ONE("1");
//
// private String symbol;
//
// Cardinality(String symbol) {
// this.symbol = symbol;
// }
//
// @Override
// public String toString() {
// return symbol;
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/attribute/SimpleAttribute.java
// public class SimpleAttribute implements Attribute {
//
// private String type;
// private String name;
//
// public SimpleAttribute(String name, String type) {
// this.type = type;
// this.name = name;
// }
//
// @Override
// public Optional<String> getTypeName() {
// return Optional.ofNullable(type);
// }
//
// @Override
// public String getName() {
// return name;
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/clazz/Clazz.java
// public interface Clazz extends Comparable<Clazz> {
//
// public String getName();
//
// public Type getType();
//
// default public Optional<Link> getLink() {
// return Optional.empty();
// }
//
// public List<? extends Attribute> getAttributes();
//
// default public List<? extends Method> getMethods() {
// return new ArrayList<>();
// }
//
// default public Optional<List<String>> getStereotypes() {
// return Optional.empty();
// }
//
// default public Optional<String> getBackgroundColor() {
// return Optional.empty();
// }
//
// default public Optional<String> getBorderColor() {
// return Optional.empty();
// }
//
// default public void validate() {
// Validate.notNull(getName(), "Class name must be defined !");
// Validate.notNull(getType(), String.format("Class '%s' type must be defined !", getName()));
// }
//
// @Override
// default int compareTo(Clazz clazz) {
// return getName().compareTo(clazz.getName());
// }
//
// default boolean hasContent() {
// return !getAttributes().isEmpty() || !getMethods().isEmpty();
// }
//
// enum Type {
// INTERFACE("interface"),
// ENUM("enum"),
// CLASS("class"),
// ABSTRACT("abstract class");
//
// private String name;
//
// Type(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/clazz/SimpleClazz.java
// public class SimpleClazz implements Clazz {
//
// private String name;
// private Type type;
// private List<Attribute> attributes = new ArrayList<>();
//
// @Override
// public String getName() {
// return name;
// }
//
// @Override
// public Type getType() {
// return type;
// }
//
// @Override
// public List<Attribute> getAttributes() {
// return attributes;
// }
//
// public static SimpleClazz create(String name, Type type, Attribute... attributes) {
// SimpleClazz c = new SimpleClazz();
// c.name = name;
// c.type = type;
// Stream.of(attributes).forEach(c.attributes::add);
// return c;
// }
// }
|
import ch.ifocusit.plantuml.classdiagram.model.Association.AssociationType;
import ch.ifocusit.plantuml.classdiagram.model.Cardinality;
import ch.ifocusit.plantuml.classdiagram.model.attribute.SimpleAttribute;
import ch.ifocusit.plantuml.classdiagram.model.clazz.Clazz;
import ch.ifocusit.plantuml.classdiagram.model.clazz.SimpleClazz;
import org.junit.Test;
import static org.fest.assertions.Assertions.*;
|
/*-
* Plantuml builder
*
* Copyright (C) 2017 Focus IT
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package ch.ifocusit.plantuml;
public class PlantUmlBuilderTest {
private static final String CR = PlantUmlBuilder.NEWLINE;
@Test
public void buildInterface() {
final String diagram = new PlantUmlBuilder().addType(SimpleClazz.create("Vehicule", Clazz.Type.INTERFACE)).build();
assertThat(diagram).isEqualTo("interface \"Vehicule\"" + CR + CR);
}
@Test
public void buildClassNoField() {
final String diagram = new PlantUmlBuilder().addType(SimpleClazz.create("Wheel", Clazz.Type.CLASS)).build();
assertThat(diagram).isEqualTo("class \"Wheel\"" + CR + CR);
}
@Test
public void buildClassWithManyFields() {
final String diagram = new PlantUmlBuilder()
.addType(SimpleClazz.create("Car", Clazz.Type.CLASS,
|
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/Association.java
// public enum AssociationType {
//
// LINK("-"),
// DIRECTION("-->"),
// BI_DIRECTION("<->"),
// INHERITANCE("<|--");
//
// private String symbol;
//
// AssociationType(String symbol) {
// this.symbol = symbol;
// }
//
// @Override
// public String toString() {
// return symbol;
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/Cardinality.java
// public enum Cardinality {
//
// NONE(""),
// MANY("*"),
// ONE("1");
//
// private String symbol;
//
// Cardinality(String symbol) {
// this.symbol = symbol;
// }
//
// @Override
// public String toString() {
// return symbol;
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/attribute/SimpleAttribute.java
// public class SimpleAttribute implements Attribute {
//
// private String type;
// private String name;
//
// public SimpleAttribute(String name, String type) {
// this.type = type;
// this.name = name;
// }
//
// @Override
// public Optional<String> getTypeName() {
// return Optional.ofNullable(type);
// }
//
// @Override
// public String getName() {
// return name;
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/clazz/Clazz.java
// public interface Clazz extends Comparable<Clazz> {
//
// public String getName();
//
// public Type getType();
//
// default public Optional<Link> getLink() {
// return Optional.empty();
// }
//
// public List<? extends Attribute> getAttributes();
//
// default public List<? extends Method> getMethods() {
// return new ArrayList<>();
// }
//
// default public Optional<List<String>> getStereotypes() {
// return Optional.empty();
// }
//
// default public Optional<String> getBackgroundColor() {
// return Optional.empty();
// }
//
// default public Optional<String> getBorderColor() {
// return Optional.empty();
// }
//
// default public void validate() {
// Validate.notNull(getName(), "Class name must be defined !");
// Validate.notNull(getType(), String.format("Class '%s' type must be defined !", getName()));
// }
//
// @Override
// default int compareTo(Clazz clazz) {
// return getName().compareTo(clazz.getName());
// }
//
// default boolean hasContent() {
// return !getAttributes().isEmpty() || !getMethods().isEmpty();
// }
//
// enum Type {
// INTERFACE("interface"),
// ENUM("enum"),
// CLASS("class"),
// ABSTRACT("abstract class");
//
// private String name;
//
// Type(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/clazz/SimpleClazz.java
// public class SimpleClazz implements Clazz {
//
// private String name;
// private Type type;
// private List<Attribute> attributes = new ArrayList<>();
//
// @Override
// public String getName() {
// return name;
// }
//
// @Override
// public Type getType() {
// return type;
// }
//
// @Override
// public List<Attribute> getAttributes() {
// return attributes;
// }
//
// public static SimpleClazz create(String name, Type type, Attribute... attributes) {
// SimpleClazz c = new SimpleClazz();
// c.name = name;
// c.type = type;
// Stream.of(attributes).forEach(c.attributes::add);
// return c;
// }
// }
// Path: src/test/java/ch/ifocusit/plantuml/PlantUmlBuilderTest.java
import ch.ifocusit.plantuml.classdiagram.model.Association.AssociationType;
import ch.ifocusit.plantuml.classdiagram.model.Cardinality;
import ch.ifocusit.plantuml.classdiagram.model.attribute.SimpleAttribute;
import ch.ifocusit.plantuml.classdiagram.model.clazz.Clazz;
import ch.ifocusit.plantuml.classdiagram.model.clazz.SimpleClazz;
import org.junit.Test;
import static org.fest.assertions.Assertions.*;
/*-
* Plantuml builder
*
* Copyright (C) 2017 Focus IT
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package ch.ifocusit.plantuml;
public class PlantUmlBuilderTest {
private static final String CR = PlantUmlBuilder.NEWLINE;
@Test
public void buildInterface() {
final String diagram = new PlantUmlBuilder().addType(SimpleClazz.create("Vehicule", Clazz.Type.INTERFACE)).build();
assertThat(diagram).isEqualTo("interface \"Vehicule\"" + CR + CR);
}
@Test
public void buildClassNoField() {
final String diagram = new PlantUmlBuilder().addType(SimpleClazz.create("Wheel", Clazz.Type.CLASS)).build();
assertThat(diagram).isEqualTo("class \"Wheel\"" + CR + CR);
}
@Test
public void buildClassWithManyFields() {
final String diagram = new PlantUmlBuilder()
.addType(SimpleClazz.create("Car", Clazz.Type.CLASS,
|
new SimpleAttribute("brand", "String"),
|
jboz/plantuml-builder
|
src/test/java/ch/ifocusit/plantuml/PlantUmlBuilderTest.java
|
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/Association.java
// public enum AssociationType {
//
// LINK("-"),
// DIRECTION("-->"),
// BI_DIRECTION("<->"),
// INHERITANCE("<|--");
//
// private String symbol;
//
// AssociationType(String symbol) {
// this.symbol = symbol;
// }
//
// @Override
// public String toString() {
// return symbol;
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/Cardinality.java
// public enum Cardinality {
//
// NONE(""),
// MANY("*"),
// ONE("1");
//
// private String symbol;
//
// Cardinality(String symbol) {
// this.symbol = symbol;
// }
//
// @Override
// public String toString() {
// return symbol;
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/attribute/SimpleAttribute.java
// public class SimpleAttribute implements Attribute {
//
// private String type;
// private String name;
//
// public SimpleAttribute(String name, String type) {
// this.type = type;
// this.name = name;
// }
//
// @Override
// public Optional<String> getTypeName() {
// return Optional.ofNullable(type);
// }
//
// @Override
// public String getName() {
// return name;
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/clazz/Clazz.java
// public interface Clazz extends Comparable<Clazz> {
//
// public String getName();
//
// public Type getType();
//
// default public Optional<Link> getLink() {
// return Optional.empty();
// }
//
// public List<? extends Attribute> getAttributes();
//
// default public List<? extends Method> getMethods() {
// return new ArrayList<>();
// }
//
// default public Optional<List<String>> getStereotypes() {
// return Optional.empty();
// }
//
// default public Optional<String> getBackgroundColor() {
// return Optional.empty();
// }
//
// default public Optional<String> getBorderColor() {
// return Optional.empty();
// }
//
// default public void validate() {
// Validate.notNull(getName(), "Class name must be defined !");
// Validate.notNull(getType(), String.format("Class '%s' type must be defined !", getName()));
// }
//
// @Override
// default int compareTo(Clazz clazz) {
// return getName().compareTo(clazz.getName());
// }
//
// default boolean hasContent() {
// return !getAttributes().isEmpty() || !getMethods().isEmpty();
// }
//
// enum Type {
// INTERFACE("interface"),
// ENUM("enum"),
// CLASS("class"),
// ABSTRACT("abstract class");
//
// private String name;
//
// Type(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/clazz/SimpleClazz.java
// public class SimpleClazz implements Clazz {
//
// private String name;
// private Type type;
// private List<Attribute> attributes = new ArrayList<>();
//
// @Override
// public String getName() {
// return name;
// }
//
// @Override
// public Type getType() {
// return type;
// }
//
// @Override
// public List<Attribute> getAttributes() {
// return attributes;
// }
//
// public static SimpleClazz create(String name, Type type, Attribute... attributes) {
// SimpleClazz c = new SimpleClazz();
// c.name = name;
// c.type = type;
// Stream.of(attributes).forEach(c.attributes::add);
// return c;
// }
// }
|
import ch.ifocusit.plantuml.classdiagram.model.Association.AssociationType;
import ch.ifocusit.plantuml.classdiagram.model.Cardinality;
import ch.ifocusit.plantuml.classdiagram.model.attribute.SimpleAttribute;
import ch.ifocusit.plantuml.classdiagram.model.clazz.Clazz;
import ch.ifocusit.plantuml.classdiagram.model.clazz.SimpleClazz;
import org.junit.Test;
import static org.fest.assertions.Assertions.*;
|
.addType(SimpleClazz.create("Car", Clazz.Type.CLASS,
new SimpleAttribute("brand", "String"),
new SimpleAttribute("wheels", "Collection<Wheel>")))
.build();
assertThat(diagram).isEqualTo("class \"Car\" {" + CR +
" brand : String" + CR +
" wheels : Collection<Wheel>" + CR +
"}" + CR + CR);
}
@Test
public void buildEnum() {
final String diagram = new PlantUmlBuilder()
.addType(SimpleClazz.create("Devise", Clazz.Type.ENUM,
new SimpleAttribute("CHF", null),
new SimpleAttribute("EUR", null),
new SimpleAttribute("USD", null)))
.build();
assertThat(diagram).isEqualTo("enum \"Devise\" {" + CR +
" CHF" + CR +
" EUR" + CR +
" USD" + CR +
"}" + CR + CR);
}
@Test
public void buildAssociations() throws Exception {
String diagram = new PlantUmlBuilder()
|
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/Association.java
// public enum AssociationType {
//
// LINK("-"),
// DIRECTION("-->"),
// BI_DIRECTION("<->"),
// INHERITANCE("<|--");
//
// private String symbol;
//
// AssociationType(String symbol) {
// this.symbol = symbol;
// }
//
// @Override
// public String toString() {
// return symbol;
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/Cardinality.java
// public enum Cardinality {
//
// NONE(""),
// MANY("*"),
// ONE("1");
//
// private String symbol;
//
// Cardinality(String symbol) {
// this.symbol = symbol;
// }
//
// @Override
// public String toString() {
// return symbol;
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/attribute/SimpleAttribute.java
// public class SimpleAttribute implements Attribute {
//
// private String type;
// private String name;
//
// public SimpleAttribute(String name, String type) {
// this.type = type;
// this.name = name;
// }
//
// @Override
// public Optional<String> getTypeName() {
// return Optional.ofNullable(type);
// }
//
// @Override
// public String getName() {
// return name;
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/clazz/Clazz.java
// public interface Clazz extends Comparable<Clazz> {
//
// public String getName();
//
// public Type getType();
//
// default public Optional<Link> getLink() {
// return Optional.empty();
// }
//
// public List<? extends Attribute> getAttributes();
//
// default public List<? extends Method> getMethods() {
// return new ArrayList<>();
// }
//
// default public Optional<List<String>> getStereotypes() {
// return Optional.empty();
// }
//
// default public Optional<String> getBackgroundColor() {
// return Optional.empty();
// }
//
// default public Optional<String> getBorderColor() {
// return Optional.empty();
// }
//
// default public void validate() {
// Validate.notNull(getName(), "Class name must be defined !");
// Validate.notNull(getType(), String.format("Class '%s' type must be defined !", getName()));
// }
//
// @Override
// default int compareTo(Clazz clazz) {
// return getName().compareTo(clazz.getName());
// }
//
// default boolean hasContent() {
// return !getAttributes().isEmpty() || !getMethods().isEmpty();
// }
//
// enum Type {
// INTERFACE("interface"),
// ENUM("enum"),
// CLASS("class"),
// ABSTRACT("abstract class");
//
// private String name;
//
// Type(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/clazz/SimpleClazz.java
// public class SimpleClazz implements Clazz {
//
// private String name;
// private Type type;
// private List<Attribute> attributes = new ArrayList<>();
//
// @Override
// public String getName() {
// return name;
// }
//
// @Override
// public Type getType() {
// return type;
// }
//
// @Override
// public List<Attribute> getAttributes() {
// return attributes;
// }
//
// public static SimpleClazz create(String name, Type type, Attribute... attributes) {
// SimpleClazz c = new SimpleClazz();
// c.name = name;
// c.type = type;
// Stream.of(attributes).forEach(c.attributes::add);
// return c;
// }
// }
// Path: src/test/java/ch/ifocusit/plantuml/PlantUmlBuilderTest.java
import ch.ifocusit.plantuml.classdiagram.model.Association.AssociationType;
import ch.ifocusit.plantuml.classdiagram.model.Cardinality;
import ch.ifocusit.plantuml.classdiagram.model.attribute.SimpleAttribute;
import ch.ifocusit.plantuml.classdiagram.model.clazz.Clazz;
import ch.ifocusit.plantuml.classdiagram.model.clazz.SimpleClazz;
import org.junit.Test;
import static org.fest.assertions.Assertions.*;
.addType(SimpleClazz.create("Car", Clazz.Type.CLASS,
new SimpleAttribute("brand", "String"),
new SimpleAttribute("wheels", "Collection<Wheel>")))
.build();
assertThat(diagram).isEqualTo("class \"Car\" {" + CR +
" brand : String" + CR +
" wheels : Collection<Wheel>" + CR +
"}" + CR + CR);
}
@Test
public void buildEnum() {
final String diagram = new PlantUmlBuilder()
.addType(SimpleClazz.create("Devise", Clazz.Type.ENUM,
new SimpleAttribute("CHF", null),
new SimpleAttribute("EUR", null),
new SimpleAttribute("USD", null)))
.build();
assertThat(diagram).isEqualTo("enum \"Devise\" {" + CR +
" CHF" + CR +
" EUR" + CR +
" USD" + CR +
"}" + CR + CR);
}
@Test
public void buildAssociations() throws Exception {
String diagram = new PlantUmlBuilder()
|
.addAssociation("Vehicule", "Car", AssociationType.INHERITANCE)
|
jboz/plantuml-builder
|
src/test/java/ch/ifocusit/plantuml/PlantUmlBuilderTest.java
|
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/Association.java
// public enum AssociationType {
//
// LINK("-"),
// DIRECTION("-->"),
// BI_DIRECTION("<->"),
// INHERITANCE("<|--");
//
// private String symbol;
//
// AssociationType(String symbol) {
// this.symbol = symbol;
// }
//
// @Override
// public String toString() {
// return symbol;
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/Cardinality.java
// public enum Cardinality {
//
// NONE(""),
// MANY("*"),
// ONE("1");
//
// private String symbol;
//
// Cardinality(String symbol) {
// this.symbol = symbol;
// }
//
// @Override
// public String toString() {
// return symbol;
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/attribute/SimpleAttribute.java
// public class SimpleAttribute implements Attribute {
//
// private String type;
// private String name;
//
// public SimpleAttribute(String name, String type) {
// this.type = type;
// this.name = name;
// }
//
// @Override
// public Optional<String> getTypeName() {
// return Optional.ofNullable(type);
// }
//
// @Override
// public String getName() {
// return name;
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/clazz/Clazz.java
// public interface Clazz extends Comparable<Clazz> {
//
// public String getName();
//
// public Type getType();
//
// default public Optional<Link> getLink() {
// return Optional.empty();
// }
//
// public List<? extends Attribute> getAttributes();
//
// default public List<? extends Method> getMethods() {
// return new ArrayList<>();
// }
//
// default public Optional<List<String>> getStereotypes() {
// return Optional.empty();
// }
//
// default public Optional<String> getBackgroundColor() {
// return Optional.empty();
// }
//
// default public Optional<String> getBorderColor() {
// return Optional.empty();
// }
//
// default public void validate() {
// Validate.notNull(getName(), "Class name must be defined !");
// Validate.notNull(getType(), String.format("Class '%s' type must be defined !", getName()));
// }
//
// @Override
// default int compareTo(Clazz clazz) {
// return getName().compareTo(clazz.getName());
// }
//
// default boolean hasContent() {
// return !getAttributes().isEmpty() || !getMethods().isEmpty();
// }
//
// enum Type {
// INTERFACE("interface"),
// ENUM("enum"),
// CLASS("class"),
// ABSTRACT("abstract class");
//
// private String name;
//
// Type(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/clazz/SimpleClazz.java
// public class SimpleClazz implements Clazz {
//
// private String name;
// private Type type;
// private List<Attribute> attributes = new ArrayList<>();
//
// @Override
// public String getName() {
// return name;
// }
//
// @Override
// public Type getType() {
// return type;
// }
//
// @Override
// public List<Attribute> getAttributes() {
// return attributes;
// }
//
// public static SimpleClazz create(String name, Type type, Attribute... attributes) {
// SimpleClazz c = new SimpleClazz();
// c.name = name;
// c.type = type;
// Stream.of(attributes).forEach(c.attributes::add);
// return c;
// }
// }
|
import ch.ifocusit.plantuml.classdiagram.model.Association.AssociationType;
import ch.ifocusit.plantuml.classdiagram.model.Cardinality;
import ch.ifocusit.plantuml.classdiagram.model.attribute.SimpleAttribute;
import ch.ifocusit.plantuml.classdiagram.model.clazz.Clazz;
import ch.ifocusit.plantuml.classdiagram.model.clazz.SimpleClazz;
import org.junit.Test;
import static org.fest.assertions.Assertions.*;
|
new SimpleAttribute("wheels", "Collection<Wheel>")))
.build();
assertThat(diagram).isEqualTo("class \"Car\" {" + CR +
" brand : String" + CR +
" wheels : Collection<Wheel>" + CR +
"}" + CR + CR);
}
@Test
public void buildEnum() {
final String diagram = new PlantUmlBuilder()
.addType(SimpleClazz.create("Devise", Clazz.Type.ENUM,
new SimpleAttribute("CHF", null),
new SimpleAttribute("EUR", null),
new SimpleAttribute("USD", null)))
.build();
assertThat(diagram).isEqualTo("enum \"Devise\" {" + CR +
" CHF" + CR +
" EUR" + CR +
" USD" + CR +
"}" + CR + CR);
}
@Test
public void buildAssociations() throws Exception {
String diagram = new PlantUmlBuilder()
.addAssociation("Vehicule", "Car", AssociationType.INHERITANCE)
.addAssociation("Car", "Price", AssociationType.DIRECTION, "price")
|
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/Association.java
// public enum AssociationType {
//
// LINK("-"),
// DIRECTION("-->"),
// BI_DIRECTION("<->"),
// INHERITANCE("<|--");
//
// private String symbol;
//
// AssociationType(String symbol) {
// this.symbol = symbol;
// }
//
// @Override
// public String toString() {
// return symbol;
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/Cardinality.java
// public enum Cardinality {
//
// NONE(""),
// MANY("*"),
// ONE("1");
//
// private String symbol;
//
// Cardinality(String symbol) {
// this.symbol = symbol;
// }
//
// @Override
// public String toString() {
// return symbol;
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/attribute/SimpleAttribute.java
// public class SimpleAttribute implements Attribute {
//
// private String type;
// private String name;
//
// public SimpleAttribute(String name, String type) {
// this.type = type;
// this.name = name;
// }
//
// @Override
// public Optional<String> getTypeName() {
// return Optional.ofNullable(type);
// }
//
// @Override
// public String getName() {
// return name;
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/clazz/Clazz.java
// public interface Clazz extends Comparable<Clazz> {
//
// public String getName();
//
// public Type getType();
//
// default public Optional<Link> getLink() {
// return Optional.empty();
// }
//
// public List<? extends Attribute> getAttributes();
//
// default public List<? extends Method> getMethods() {
// return new ArrayList<>();
// }
//
// default public Optional<List<String>> getStereotypes() {
// return Optional.empty();
// }
//
// default public Optional<String> getBackgroundColor() {
// return Optional.empty();
// }
//
// default public Optional<String> getBorderColor() {
// return Optional.empty();
// }
//
// default public void validate() {
// Validate.notNull(getName(), "Class name must be defined !");
// Validate.notNull(getType(), String.format("Class '%s' type must be defined !", getName()));
// }
//
// @Override
// default int compareTo(Clazz clazz) {
// return getName().compareTo(clazz.getName());
// }
//
// default boolean hasContent() {
// return !getAttributes().isEmpty() || !getMethods().isEmpty();
// }
//
// enum Type {
// INTERFACE("interface"),
// ENUM("enum"),
// CLASS("class"),
// ABSTRACT("abstract class");
//
// private String name;
//
// Type(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
// }
//
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/clazz/SimpleClazz.java
// public class SimpleClazz implements Clazz {
//
// private String name;
// private Type type;
// private List<Attribute> attributes = new ArrayList<>();
//
// @Override
// public String getName() {
// return name;
// }
//
// @Override
// public Type getType() {
// return type;
// }
//
// @Override
// public List<Attribute> getAttributes() {
// return attributes;
// }
//
// public static SimpleClazz create(String name, Type type, Attribute... attributes) {
// SimpleClazz c = new SimpleClazz();
// c.name = name;
// c.type = type;
// Stream.of(attributes).forEach(c.attributes::add);
// return c;
// }
// }
// Path: src/test/java/ch/ifocusit/plantuml/PlantUmlBuilderTest.java
import ch.ifocusit.plantuml.classdiagram.model.Association.AssociationType;
import ch.ifocusit.plantuml.classdiagram.model.Cardinality;
import ch.ifocusit.plantuml.classdiagram.model.attribute.SimpleAttribute;
import ch.ifocusit.plantuml.classdiagram.model.clazz.Clazz;
import ch.ifocusit.plantuml.classdiagram.model.clazz.SimpleClazz;
import org.junit.Test;
import static org.fest.assertions.Assertions.*;
new SimpleAttribute("wheels", "Collection<Wheel>")))
.build();
assertThat(diagram).isEqualTo("class \"Car\" {" + CR +
" brand : String" + CR +
" wheels : Collection<Wheel>" + CR +
"}" + CR + CR);
}
@Test
public void buildEnum() {
final String diagram = new PlantUmlBuilder()
.addType(SimpleClazz.create("Devise", Clazz.Type.ENUM,
new SimpleAttribute("CHF", null),
new SimpleAttribute("EUR", null),
new SimpleAttribute("USD", null)))
.build();
assertThat(diagram).isEqualTo("enum \"Devise\" {" + CR +
" CHF" + CR +
" EUR" + CR +
" USD" + CR +
"}" + CR + CR);
}
@Test
public void buildAssociations() throws Exception {
String diagram = new PlantUmlBuilder()
.addAssociation("Vehicule", "Car", AssociationType.INHERITANCE)
.addAssociation("Car", "Price", AssociationType.DIRECTION, "price")
|
.addAssociation("Car", "Wheel", AssociationType.DIRECTION, "wheels", Cardinality.NONE, Cardinality.MANY)
|
jboz/plantuml-builder
|
src/main/java/ch/ifocusit/plantuml/classdiagram/model/clazz/SimpleClazz.java
|
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/attribute/Attribute.java
// public interface Attribute {
//
// public Optional<String> getTypeName();
//
// public String getName();
//
// default public Optional<Link> getLink() {
// return Optional.empty();
// }
// }
|
import ch.ifocusit.plantuml.classdiagram.model.attribute.Attribute;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
|
/*-
* Plantuml builder
*
* Copyright (C) 2017 Focus IT
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package ch.ifocusit.plantuml.classdiagram.model.clazz;
/**
* @author Julien Boz
*/
public class SimpleClazz implements Clazz {
private String name;
private Type type;
|
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/attribute/Attribute.java
// public interface Attribute {
//
// public Optional<String> getTypeName();
//
// public String getName();
//
// default public Optional<Link> getLink() {
// return Optional.empty();
// }
// }
// Path: src/main/java/ch/ifocusit/plantuml/classdiagram/model/clazz/SimpleClazz.java
import ch.ifocusit.plantuml.classdiagram.model.attribute.Attribute;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
/*-
* Plantuml builder
*
* Copyright (C) 2017 Focus IT
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package ch.ifocusit.plantuml.classdiagram.model.clazz;
/**
* @author Julien Boz
*/
public class SimpleClazz implements Clazz {
private String name;
private Type type;
|
private List<Attribute> attributes = new ArrayList<>();
|
jboz/plantuml-builder
|
src/test/java/ch/ifocusit/plantuml/test/helper/domain/material/Car.java
|
// Path: src/test/java/ch/ifocusit/plantuml/test/helper/domain/Devise.java
// public enum Devise {
// CHF, EUR, USD
// }
//
// Path: src/test/java/ch/ifocusit/plantuml/test/helper/domain/Driver.java
// public class Driver {
// private String name;
// private Long ignored;
// private List<Car> cars = new ArrayList<>();
//
// public void buy(Car car) {
// cars.add(car);
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(final String name) {
// this.name = name;
// }
//
// public List<Car> getCars() {
// return cars;
// }
//
// public void setCars(final List<Car> cars) {
// this.cars = cars;
// }
//
// public void addCar(Car car) {
// cars.add(car);
// }
// }
//
// Path: src/test/java/ch/ifocusit/plantuml/test/helper/domain/Price.java
// public class Price implements Serializable {
// public static final long serialVersionUID = 42L;
// static final String CONST = "aConstant";
//
// private BigDecimal amount;
// private Devise devise;
//
// public static Price of(final BigDecimal amount, final Devise devise) {
// final Price price = new Price();
// price.amount = amount;
// price.devise = devise;
// return price;
// }
// }
|
import java.util.HashSet;
import java.util.Set;
import ch.ifocusit.plantuml.test.helper.domain.Devise;
import ch.ifocusit.plantuml.test.helper.domain.Driver;
import ch.ifocusit.plantuml.test.helper.domain.Price;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import java.math.BigDecimal;
import java.util.Collection;
|
/*-
* Plantuml builder
*
* Copyright (C) 2017 Focus IT
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package ch.ifocusit.plantuml.test.helper.domain.material;
@Machine
public class Car implements Vehicule {
@Machine
// must be ignored
private Long ignored;
@Machine
private String brand;
@Machine
private String model;
|
// Path: src/test/java/ch/ifocusit/plantuml/test/helper/domain/Devise.java
// public enum Devise {
// CHF, EUR, USD
// }
//
// Path: src/test/java/ch/ifocusit/plantuml/test/helper/domain/Driver.java
// public class Driver {
// private String name;
// private Long ignored;
// private List<Car> cars = new ArrayList<>();
//
// public void buy(Car car) {
// cars.add(car);
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(final String name) {
// this.name = name;
// }
//
// public List<Car> getCars() {
// return cars;
// }
//
// public void setCars(final List<Car> cars) {
// this.cars = cars;
// }
//
// public void addCar(Car car) {
// cars.add(car);
// }
// }
//
// Path: src/test/java/ch/ifocusit/plantuml/test/helper/domain/Price.java
// public class Price implements Serializable {
// public static final long serialVersionUID = 42L;
// static final String CONST = "aConstant";
//
// private BigDecimal amount;
// private Devise devise;
//
// public static Price of(final BigDecimal amount, final Devise devise) {
// final Price price = new Price();
// price.amount = amount;
// price.devise = devise;
// return price;
// }
// }
// Path: src/test/java/ch/ifocusit/plantuml/test/helper/domain/material/Car.java
import java.util.HashSet;
import java.util.Set;
import ch.ifocusit.plantuml.test.helper.domain.Devise;
import ch.ifocusit.plantuml.test.helper.domain.Driver;
import ch.ifocusit.plantuml.test.helper.domain.Price;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import java.math.BigDecimal;
import java.util.Collection;
/*-
* Plantuml builder
*
* Copyright (C) 2017 Focus IT
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package ch.ifocusit.plantuml.test.helper.domain.material;
@Machine
public class Car implements Vehicule {
@Machine
// must be ignored
private Long ignored;
@Machine
private String brand;
@Machine
private String model;
|
private Set<Driver> drivers = new HashSet<>();
|
jboz/plantuml-builder
|
src/test/java/ch/ifocusit/plantuml/test/helper/domain/material/Car.java
|
// Path: src/test/java/ch/ifocusit/plantuml/test/helper/domain/Devise.java
// public enum Devise {
// CHF, EUR, USD
// }
//
// Path: src/test/java/ch/ifocusit/plantuml/test/helper/domain/Driver.java
// public class Driver {
// private String name;
// private Long ignored;
// private List<Car> cars = new ArrayList<>();
//
// public void buy(Car car) {
// cars.add(car);
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(final String name) {
// this.name = name;
// }
//
// public List<Car> getCars() {
// return cars;
// }
//
// public void setCars(final List<Car> cars) {
// this.cars = cars;
// }
//
// public void addCar(Car car) {
// cars.add(car);
// }
// }
//
// Path: src/test/java/ch/ifocusit/plantuml/test/helper/domain/Price.java
// public class Price implements Serializable {
// public static final long serialVersionUID = 42L;
// static final String CONST = "aConstant";
//
// private BigDecimal amount;
// private Devise devise;
//
// public static Price of(final BigDecimal amount, final Devise devise) {
// final Price price = new Price();
// price.amount = amount;
// price.devise = devise;
// return price;
// }
// }
|
import java.util.HashSet;
import java.util.Set;
import ch.ifocusit.plantuml.test.helper.domain.Devise;
import ch.ifocusit.plantuml.test.helper.domain.Driver;
import ch.ifocusit.plantuml.test.helper.domain.Price;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import java.math.BigDecimal;
import java.util.Collection;
|
/*-
* Plantuml builder
*
* Copyright (C) 2017 Focus IT
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package ch.ifocusit.plantuml.test.helper.domain.material;
@Machine
public class Car implements Vehicule {
@Machine
// must be ignored
private Long ignored;
@Machine
private String brand;
@Machine
private String model;
private Set<Driver> drivers = new HashSet<>();
|
// Path: src/test/java/ch/ifocusit/plantuml/test/helper/domain/Devise.java
// public enum Devise {
// CHF, EUR, USD
// }
//
// Path: src/test/java/ch/ifocusit/plantuml/test/helper/domain/Driver.java
// public class Driver {
// private String name;
// private Long ignored;
// private List<Car> cars = new ArrayList<>();
//
// public void buy(Car car) {
// cars.add(car);
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(final String name) {
// this.name = name;
// }
//
// public List<Car> getCars() {
// return cars;
// }
//
// public void setCars(final List<Car> cars) {
// this.cars = cars;
// }
//
// public void addCar(Car car) {
// cars.add(car);
// }
// }
//
// Path: src/test/java/ch/ifocusit/plantuml/test/helper/domain/Price.java
// public class Price implements Serializable {
// public static final long serialVersionUID = 42L;
// static final String CONST = "aConstant";
//
// private BigDecimal amount;
// private Devise devise;
//
// public static Price of(final BigDecimal amount, final Devise devise) {
// final Price price = new Price();
// price.amount = amount;
// price.devise = devise;
// return price;
// }
// }
// Path: src/test/java/ch/ifocusit/plantuml/test/helper/domain/material/Car.java
import java.util.HashSet;
import java.util.Set;
import ch.ifocusit.plantuml.test.helper.domain.Devise;
import ch.ifocusit.plantuml.test.helper.domain.Driver;
import ch.ifocusit.plantuml.test.helper.domain.Price;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import java.math.BigDecimal;
import java.util.Collection;
/*-
* Plantuml builder
*
* Copyright (C) 2017 Focus IT
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package ch.ifocusit.plantuml.test.helper.domain.material;
@Machine
public class Car implements Vehicule {
@Machine
// must be ignored
private Long ignored;
@Machine
private String brand;
@Machine
private String model;
private Set<Driver> drivers = new HashSet<>();
|
private Price price;
|
jboz/plantuml-builder
|
src/test/java/ch/ifocusit/plantuml/test/helper/domain/material/Car.java
|
// Path: src/test/java/ch/ifocusit/plantuml/test/helper/domain/Devise.java
// public enum Devise {
// CHF, EUR, USD
// }
//
// Path: src/test/java/ch/ifocusit/plantuml/test/helper/domain/Driver.java
// public class Driver {
// private String name;
// private Long ignored;
// private List<Car> cars = new ArrayList<>();
//
// public void buy(Car car) {
// cars.add(car);
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(final String name) {
// this.name = name;
// }
//
// public List<Car> getCars() {
// return cars;
// }
//
// public void setCars(final List<Car> cars) {
// this.cars = cars;
// }
//
// public void addCar(Car car) {
// cars.add(car);
// }
// }
//
// Path: src/test/java/ch/ifocusit/plantuml/test/helper/domain/Price.java
// public class Price implements Serializable {
// public static final long serialVersionUID = 42L;
// static final String CONST = "aConstant";
//
// private BigDecimal amount;
// private Devise devise;
//
// public static Price of(final BigDecimal amount, final Devise devise) {
// final Price price = new Price();
// price.amount = amount;
// price.devise = devise;
// return price;
// }
// }
|
import java.util.HashSet;
import java.util.Set;
import ch.ifocusit.plantuml.test.helper.domain.Devise;
import ch.ifocusit.plantuml.test.helper.domain.Driver;
import ch.ifocusit.plantuml.test.helper.domain.Price;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import java.math.BigDecimal;
import java.util.Collection;
|
/*-
* Plantuml builder
*
* Copyright (C) 2017 Focus IT
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package ch.ifocusit.plantuml.test.helper.domain.material;
@Machine
public class Car implements Vehicule {
@Machine
// must be ignored
private Long ignored;
@Machine
private String brand;
@Machine
private String model;
private Set<Driver> drivers = new HashSet<>();
private Price price;
@Machine
private Collection<Wheel> wheels;
|
// Path: src/test/java/ch/ifocusit/plantuml/test/helper/domain/Devise.java
// public enum Devise {
// CHF, EUR, USD
// }
//
// Path: src/test/java/ch/ifocusit/plantuml/test/helper/domain/Driver.java
// public class Driver {
// private String name;
// private Long ignored;
// private List<Car> cars = new ArrayList<>();
//
// public void buy(Car car) {
// cars.add(car);
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(final String name) {
// this.name = name;
// }
//
// public List<Car> getCars() {
// return cars;
// }
//
// public void setCars(final List<Car> cars) {
// this.cars = cars;
// }
//
// public void addCar(Car car) {
// cars.add(car);
// }
// }
//
// Path: src/test/java/ch/ifocusit/plantuml/test/helper/domain/Price.java
// public class Price implements Serializable {
// public static final long serialVersionUID = 42L;
// static final String CONST = "aConstant";
//
// private BigDecimal amount;
// private Devise devise;
//
// public static Price of(final BigDecimal amount, final Devise devise) {
// final Price price = new Price();
// price.amount = amount;
// price.devise = devise;
// return price;
// }
// }
// Path: src/test/java/ch/ifocusit/plantuml/test/helper/domain/material/Car.java
import java.util.HashSet;
import java.util.Set;
import ch.ifocusit.plantuml.test.helper.domain.Devise;
import ch.ifocusit.plantuml.test.helper.domain.Driver;
import ch.ifocusit.plantuml.test.helper.domain.Price;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import java.math.BigDecimal;
import java.util.Collection;
/*-
* Plantuml builder
*
* Copyright (C) 2017 Focus IT
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package ch.ifocusit.plantuml.test.helper.domain.material;
@Machine
public class Car implements Vehicule {
@Machine
// must be ignored
private Long ignored;
@Machine
private String brand;
@Machine
private String model;
private Set<Driver> drivers = new HashSet<>();
private Price price;
@Machine
private Collection<Wheel> wheels;
|
public Driver buyBy(Driver driver, BigDecimal amount, Devise devise) {
|
ivanpribela/svetovid-lib
|
src/org/svetovid/util/JsonHelper.java
|
// Path: src/org/svetovid/SvetovidFormatException.java
// public class SvetovidFormatException extends SvetovidException {
//
// private static final long serialVersionUID = 1829394491209593218L;
//
// /**
// * Constructs a {@code SvetovidFormatException} with the specified message.
// *
// * @param type
// * The type to which the string could not be parsed
// * @param string
// * The string that could not be parsed
// */
// public SvetovidFormatException(Class<?> type, String string) {
// super(type.getSimpleName(),
// string == null ? null : "\"" + string + "\"");
// }
//
// /**
// * Constructs a {@code SvetovidFormatException} with the specified detail
// * message and cause.
// *
// * @param type
// * The type to which the string could not be parsed
// * @param string
// * The string that could not be parsed
// * @param cause
// * The cause, if any
// */
// public SvetovidFormatException(Class<?> type, String string,
// Throwable cause) {
// super(type.getSimpleName(), cause,
// string == null ? null : "\"" + string + "\"");
// }
//
// /**
// * Constructs a {@code SvetovidFormatException} with multiple suppressed
// * causes.
// *
// * @param causes
// * The suppressed causes of this exception
// */
// public SvetovidFormatException(Throwable... causes) {
// super("Array");
// for (Throwable cause : causes) {
// addSuppressed(cause);
// }
// }
//
// /**
// * Constructs a {@code SvetovidFormatException} with multiple suppressed
// * causes.
// *
// * @param causes
// * The suppressed causes of this exception
// */
// public SvetovidFormatException(List<? extends Throwable> causes) {
// super("Array");
// for (Throwable cause : causes) {
// addSuppressed(cause);
// }
// }
//
// /**
// * Constructs a {@code SvetovidFormatException} with the specified detail
// * message and cause.
// *
// * @param messageKey
// * The resource bundle key of the detail message, which is saved
// * for later retrieval by the {@link #getMessage()} method
// * @param string
// * The string that could not be parsed
// * @param cause
// * The cause, if any
// */
// public SvetovidFormatException(String messageKey, String string,
// Throwable cause) {
// super(messageKey, cause, string);
// }
//
// /**
// * Constructs a {@code SvetovidFormatException} with the specified detail
// * message and cause.
// *
// * @param string
// * The string that could not be parsed
// * @param cause
// * The cause of the format exception
// */
// public SvetovidFormatException(IllegalFormatException cause, String string) {
// super("PrintFormat." + cause.getClass().getSimpleName(), cause, string);
// }
// }
|
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.svetovid.SvetovidFormatException;
|
Map<String, Object> map = (Map<String, Object>) object;
return map;
} catch (ClassCastException e) {
throw new SvetovidJsonException(JsonType.OBJECT,
object.getClass(), path);
}
}
/**
* Returns the raw object at the specified JSON path resolved on the given
* object.
*
* @param object
* the object to apply the path to
* @param path
* the path to follow
*
* @return the raw object extracted from the given object using the given
* path.
*
* @throws SvetovidFormatException
* if there was an error parsing the path.
* @throws SvetovidJsonException
* if the array or object along the path cannot be converted.
*/
public static Object get(Object object, String path) {
return get(object, path, "");
}
private static Object get(Object object, String path, String resolved)
|
// Path: src/org/svetovid/SvetovidFormatException.java
// public class SvetovidFormatException extends SvetovidException {
//
// private static final long serialVersionUID = 1829394491209593218L;
//
// /**
// * Constructs a {@code SvetovidFormatException} with the specified message.
// *
// * @param type
// * The type to which the string could not be parsed
// * @param string
// * The string that could not be parsed
// */
// public SvetovidFormatException(Class<?> type, String string) {
// super(type.getSimpleName(),
// string == null ? null : "\"" + string + "\"");
// }
//
// /**
// * Constructs a {@code SvetovidFormatException} with the specified detail
// * message and cause.
// *
// * @param type
// * The type to which the string could not be parsed
// * @param string
// * The string that could not be parsed
// * @param cause
// * The cause, if any
// */
// public SvetovidFormatException(Class<?> type, String string,
// Throwable cause) {
// super(type.getSimpleName(), cause,
// string == null ? null : "\"" + string + "\"");
// }
//
// /**
// * Constructs a {@code SvetovidFormatException} with multiple suppressed
// * causes.
// *
// * @param causes
// * The suppressed causes of this exception
// */
// public SvetovidFormatException(Throwable... causes) {
// super("Array");
// for (Throwable cause : causes) {
// addSuppressed(cause);
// }
// }
//
// /**
// * Constructs a {@code SvetovidFormatException} with multiple suppressed
// * causes.
// *
// * @param causes
// * The suppressed causes of this exception
// */
// public SvetovidFormatException(List<? extends Throwable> causes) {
// super("Array");
// for (Throwable cause : causes) {
// addSuppressed(cause);
// }
// }
//
// /**
// * Constructs a {@code SvetovidFormatException} with the specified detail
// * message and cause.
// *
// * @param messageKey
// * The resource bundle key of the detail message, which is saved
// * for later retrieval by the {@link #getMessage()} method
// * @param string
// * The string that could not be parsed
// * @param cause
// * The cause, if any
// */
// public SvetovidFormatException(String messageKey, String string,
// Throwable cause) {
// super(messageKey, cause, string);
// }
//
// /**
// * Constructs a {@code SvetovidFormatException} with the specified detail
// * message and cause.
// *
// * @param string
// * The string that could not be parsed
// * @param cause
// * The cause of the format exception
// */
// public SvetovidFormatException(IllegalFormatException cause, String string) {
// super("PrintFormat." + cause.getClass().getSimpleName(), cause, string);
// }
// }
// Path: src/org/svetovid/util/JsonHelper.java
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.svetovid.SvetovidFormatException;
Map<String, Object> map = (Map<String, Object>) object;
return map;
} catch (ClassCastException e) {
throw new SvetovidJsonException(JsonType.OBJECT,
object.getClass(), path);
}
}
/**
* Returns the raw object at the specified JSON path resolved on the given
* object.
*
* @param object
* the object to apply the path to
* @param path
* the path to follow
*
* @return the raw object extracted from the given object using the given
* path.
*
* @throws SvetovidFormatException
* if there was an error parsing the path.
* @throws SvetovidJsonException
* if the array or object along the path cannot be converted.
*/
public static Object get(Object object, String path) {
return get(object, path, "");
}
private static Object get(Object object, String path, String resolved)
|
throws SvetovidFormatException, SvetovidJsonException {
|
ivanpribela/svetovid-lib
|
src/org/svetovid/run/SvetovidJvmProcessBuilder.java
|
// Path: src/org/svetovid/io/SvetovidProcess.java
// public class SvetovidProcess {
//
// public final Process process;
// public final SvetovidWriter in;
// public final SvetovidReader out;
// public final SvetovidReader err;
//
// public SvetovidProcess(Process process) {
// this.process = process;
// in = new DefaultSvetovidWriter(process.getOutputStream());
// out = new DefaultSvetovidReader(process.getInputStream());
// err = new DefaultSvetovidReader(process.getErrorStream());
// }
//
// public String toString() {
// return process.toString();
// }
//
// public int waitFor() throws InterruptedException {
// return process.waitFor();
// }
//
// public boolean isAlive() {
// try {
// process.exitValue();
// return false;
// } catch(IllegalThreadStateException e) {
// return true;
// }
// }
//
// public int exitValue() {
// return process.exitValue();
// }
//
// public void destroy() {
// process.destroy();
// }
// }
//
// Path: src/org/svetovid/util/CompoundList.java
// public class CompoundList<E> extends AbstractList<E> {
//
// private List<List<E>> lists = new ArrayList<>();
//
// public CompoundList() {
// }
//
// @SafeVarargs
// public CompoundList(List<E>... lists) {
// for (List<E> list : lists) {
// this.lists.add(list);
// }
// }
//
// public List<E> getSublist(int index) {
// return lists.get(index);
// }
//
// public void setSublist(int index, List<E> list) {
// lists.set(index, list);
// }
//
// public int addSublist(List<E> list) {
// lists.add(list);
// return lists.size() - 1;
// }
//
// public int insertSublist(int index, List<E> list) {
// lists.add(index, list);
// return index;
// }
//
// public List<E> removeSublist(int index) {
// return lists.remove(index);
// }
//
// @Override
// public int size() {
// int size = 0;
// for (List<E> list : lists) {
// if (list == null) {
// continue;
// }
// size = size + list.size();
// }
// return size;
// }
//
// @Override
// public E get(int index) {
// if (index < 0) {
// throw new IndexOutOfBoundsException("Index: " + index);
// }
// int totalSize = 0;
// for (List<E> list : lists) {
// if (list == null) {
// continue;
// }
// int size = list.size();
// if (index < size) {
// return list.get(index);
// }
// index = index - size;
// totalSize = totalSize + size;
// }
// throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + totalSize);
// }
//
// @Override
// public Object[] toArray() {
// Object[][] arrays = new Object[lists.size()][];
// int size = 0;
// for (int i = 0; i < lists.size(); i++) {
// List<E> list = lists.get(i);
// if (list == null) {
// continue;
// }
// arrays[i] = list.toArray();
// size = size + arrays[i].length;
// }
// Object[] array = new Object[size];
// int index = 0;
// for (Object[] arr : arrays) {
// System.arraycopy(arr, 0, array, index, arr.length);
// index = index + arr.length;
// }
// return array;
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public <T> T[] toArray(T[] a) {
// Object[] array = toArray();
// if (a.length < array.length) {
// return (T[]) array;
// }
// System.arraycopy(array, 0, a, 0, array.length);
// return a;
// }
// }
|
import java.io.File;
import java.io.IOException;
import java.lang.ProcessBuilder.Redirect;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.svetovid.io.SvetovidProcess;
import org.svetovid.util.CompoundList;
|
/*
* Copyright 2015 Ivan Pribela
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.svetovid.run;
public class SvetovidJvmProcessBuilder extends SvetovidProcessBuilder {
private List<String> executable = new ArrayList<>(1);
{
executable.add("java");
}
private List<String> classpath;
private List<String> commandClasspath = new ArrayList<>();
private List<String> extDirs;
private List<String> commandExtDirs = new ArrayList<>();
private List<String> endorsedDirs;
private List<String> commandEndorsedDirs = new ArrayList<>();
private List<String> libraryDirs;
private List<String> commandLibraryDirs = new ArrayList<>();
private Map<String, String> systemProperties = new HashMap<>();
private List<String> commandSystemProperties = new ArrayList<>();
|
// Path: src/org/svetovid/io/SvetovidProcess.java
// public class SvetovidProcess {
//
// public final Process process;
// public final SvetovidWriter in;
// public final SvetovidReader out;
// public final SvetovidReader err;
//
// public SvetovidProcess(Process process) {
// this.process = process;
// in = new DefaultSvetovidWriter(process.getOutputStream());
// out = new DefaultSvetovidReader(process.getInputStream());
// err = new DefaultSvetovidReader(process.getErrorStream());
// }
//
// public String toString() {
// return process.toString();
// }
//
// public int waitFor() throws InterruptedException {
// return process.waitFor();
// }
//
// public boolean isAlive() {
// try {
// process.exitValue();
// return false;
// } catch(IllegalThreadStateException e) {
// return true;
// }
// }
//
// public int exitValue() {
// return process.exitValue();
// }
//
// public void destroy() {
// process.destroy();
// }
// }
//
// Path: src/org/svetovid/util/CompoundList.java
// public class CompoundList<E> extends AbstractList<E> {
//
// private List<List<E>> lists = new ArrayList<>();
//
// public CompoundList() {
// }
//
// @SafeVarargs
// public CompoundList(List<E>... lists) {
// for (List<E> list : lists) {
// this.lists.add(list);
// }
// }
//
// public List<E> getSublist(int index) {
// return lists.get(index);
// }
//
// public void setSublist(int index, List<E> list) {
// lists.set(index, list);
// }
//
// public int addSublist(List<E> list) {
// lists.add(list);
// return lists.size() - 1;
// }
//
// public int insertSublist(int index, List<E> list) {
// lists.add(index, list);
// return index;
// }
//
// public List<E> removeSublist(int index) {
// return lists.remove(index);
// }
//
// @Override
// public int size() {
// int size = 0;
// for (List<E> list : lists) {
// if (list == null) {
// continue;
// }
// size = size + list.size();
// }
// return size;
// }
//
// @Override
// public E get(int index) {
// if (index < 0) {
// throw new IndexOutOfBoundsException("Index: " + index);
// }
// int totalSize = 0;
// for (List<E> list : lists) {
// if (list == null) {
// continue;
// }
// int size = list.size();
// if (index < size) {
// return list.get(index);
// }
// index = index - size;
// totalSize = totalSize + size;
// }
// throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + totalSize);
// }
//
// @Override
// public Object[] toArray() {
// Object[][] arrays = new Object[lists.size()][];
// int size = 0;
// for (int i = 0; i < lists.size(); i++) {
// List<E> list = lists.get(i);
// if (list == null) {
// continue;
// }
// arrays[i] = list.toArray();
// size = size + arrays[i].length;
// }
// Object[] array = new Object[size];
// int index = 0;
// for (Object[] arr : arrays) {
// System.arraycopy(arr, 0, array, index, arr.length);
// index = index + arr.length;
// }
// return array;
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public <T> T[] toArray(T[] a) {
// Object[] array = toArray();
// if (a.length < array.length) {
// return (T[]) array;
// }
// System.arraycopy(array, 0, a, 0, array.length);
// return a;
// }
// }
// Path: src/org/svetovid/run/SvetovidJvmProcessBuilder.java
import java.io.File;
import java.io.IOException;
import java.lang.ProcessBuilder.Redirect;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.svetovid.io.SvetovidProcess;
import org.svetovid.util.CompoundList;
/*
* Copyright 2015 Ivan Pribela
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.svetovid.run;
public class SvetovidJvmProcessBuilder extends SvetovidProcessBuilder {
private List<String> executable = new ArrayList<>(1);
{
executable.add("java");
}
private List<String> classpath;
private List<String> commandClasspath = new ArrayList<>();
private List<String> extDirs;
private List<String> commandExtDirs = new ArrayList<>();
private List<String> endorsedDirs;
private List<String> commandEndorsedDirs = new ArrayList<>();
private List<String> libraryDirs;
private List<String> commandLibraryDirs = new ArrayList<>();
private Map<String, String> systemProperties = new HashMap<>();
private List<String> commandSystemProperties = new ArrayList<>();
|
private CompoundList<String> wholeCommand = new CompoundList<String>(executable, commandClasspath, commandExtDirs, commandEndorsedDirs, commandLibraryDirs, commandSystemProperties, new ArrayList<String>(), null);
|
ivanpribela/svetovid-lib
|
src/org/svetovid/run/SvetovidJvmProcessBuilder.java
|
// Path: src/org/svetovid/io/SvetovidProcess.java
// public class SvetovidProcess {
//
// public final Process process;
// public final SvetovidWriter in;
// public final SvetovidReader out;
// public final SvetovidReader err;
//
// public SvetovidProcess(Process process) {
// this.process = process;
// in = new DefaultSvetovidWriter(process.getOutputStream());
// out = new DefaultSvetovidReader(process.getInputStream());
// err = new DefaultSvetovidReader(process.getErrorStream());
// }
//
// public String toString() {
// return process.toString();
// }
//
// public int waitFor() throws InterruptedException {
// return process.waitFor();
// }
//
// public boolean isAlive() {
// try {
// process.exitValue();
// return false;
// } catch(IllegalThreadStateException e) {
// return true;
// }
// }
//
// public int exitValue() {
// return process.exitValue();
// }
//
// public void destroy() {
// process.destroy();
// }
// }
//
// Path: src/org/svetovid/util/CompoundList.java
// public class CompoundList<E> extends AbstractList<E> {
//
// private List<List<E>> lists = new ArrayList<>();
//
// public CompoundList() {
// }
//
// @SafeVarargs
// public CompoundList(List<E>... lists) {
// for (List<E> list : lists) {
// this.lists.add(list);
// }
// }
//
// public List<E> getSublist(int index) {
// return lists.get(index);
// }
//
// public void setSublist(int index, List<E> list) {
// lists.set(index, list);
// }
//
// public int addSublist(List<E> list) {
// lists.add(list);
// return lists.size() - 1;
// }
//
// public int insertSublist(int index, List<E> list) {
// lists.add(index, list);
// return index;
// }
//
// public List<E> removeSublist(int index) {
// return lists.remove(index);
// }
//
// @Override
// public int size() {
// int size = 0;
// for (List<E> list : lists) {
// if (list == null) {
// continue;
// }
// size = size + list.size();
// }
// return size;
// }
//
// @Override
// public E get(int index) {
// if (index < 0) {
// throw new IndexOutOfBoundsException("Index: " + index);
// }
// int totalSize = 0;
// for (List<E> list : lists) {
// if (list == null) {
// continue;
// }
// int size = list.size();
// if (index < size) {
// return list.get(index);
// }
// index = index - size;
// totalSize = totalSize + size;
// }
// throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + totalSize);
// }
//
// @Override
// public Object[] toArray() {
// Object[][] arrays = new Object[lists.size()][];
// int size = 0;
// for (int i = 0; i < lists.size(); i++) {
// List<E> list = lists.get(i);
// if (list == null) {
// continue;
// }
// arrays[i] = list.toArray();
// size = size + arrays[i].length;
// }
// Object[] array = new Object[size];
// int index = 0;
// for (Object[] arr : arrays) {
// System.arraycopy(arr, 0, array, index, arr.length);
// index = index + arr.length;
// }
// return array;
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public <T> T[] toArray(T[] a) {
// Object[] array = toArray();
// if (a.length < array.length) {
// return (T[]) array;
// }
// System.arraycopy(array, 0, a, 0, array.length);
// return a;
// }
// }
|
import java.io.File;
import java.io.IOException;
import java.lang.ProcessBuilder.Redirect;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.svetovid.io.SvetovidProcess;
import org.svetovid.util.CompoundList;
|
public SvetovidJvmProcessBuilder redirectInput(Path file) {
super.redirectInput(file);
return this;
}
@Override
public SvetovidJvmProcessBuilder redirectOutput(Path file) {
super.redirectOutput(file);
return this;
}
@Override
public SvetovidJvmProcessBuilder redirectError(Path file) {
super.redirectError(file);
return this;
}
@Override
public SvetovidJvmProcessBuilder inheritIO() {
super.inheritIO();
return this;
}
@Override
public SvetovidJvmProcessBuilder redirectErrorStream(boolean redirectErrorStream) {
super.redirectErrorStream(redirectErrorStream);
return this;
}
@Override
|
// Path: src/org/svetovid/io/SvetovidProcess.java
// public class SvetovidProcess {
//
// public final Process process;
// public final SvetovidWriter in;
// public final SvetovidReader out;
// public final SvetovidReader err;
//
// public SvetovidProcess(Process process) {
// this.process = process;
// in = new DefaultSvetovidWriter(process.getOutputStream());
// out = new DefaultSvetovidReader(process.getInputStream());
// err = new DefaultSvetovidReader(process.getErrorStream());
// }
//
// public String toString() {
// return process.toString();
// }
//
// public int waitFor() throws InterruptedException {
// return process.waitFor();
// }
//
// public boolean isAlive() {
// try {
// process.exitValue();
// return false;
// } catch(IllegalThreadStateException e) {
// return true;
// }
// }
//
// public int exitValue() {
// return process.exitValue();
// }
//
// public void destroy() {
// process.destroy();
// }
// }
//
// Path: src/org/svetovid/util/CompoundList.java
// public class CompoundList<E> extends AbstractList<E> {
//
// private List<List<E>> lists = new ArrayList<>();
//
// public CompoundList() {
// }
//
// @SafeVarargs
// public CompoundList(List<E>... lists) {
// for (List<E> list : lists) {
// this.lists.add(list);
// }
// }
//
// public List<E> getSublist(int index) {
// return lists.get(index);
// }
//
// public void setSublist(int index, List<E> list) {
// lists.set(index, list);
// }
//
// public int addSublist(List<E> list) {
// lists.add(list);
// return lists.size() - 1;
// }
//
// public int insertSublist(int index, List<E> list) {
// lists.add(index, list);
// return index;
// }
//
// public List<E> removeSublist(int index) {
// return lists.remove(index);
// }
//
// @Override
// public int size() {
// int size = 0;
// for (List<E> list : lists) {
// if (list == null) {
// continue;
// }
// size = size + list.size();
// }
// return size;
// }
//
// @Override
// public E get(int index) {
// if (index < 0) {
// throw new IndexOutOfBoundsException("Index: " + index);
// }
// int totalSize = 0;
// for (List<E> list : lists) {
// if (list == null) {
// continue;
// }
// int size = list.size();
// if (index < size) {
// return list.get(index);
// }
// index = index - size;
// totalSize = totalSize + size;
// }
// throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + totalSize);
// }
//
// @Override
// public Object[] toArray() {
// Object[][] arrays = new Object[lists.size()][];
// int size = 0;
// for (int i = 0; i < lists.size(); i++) {
// List<E> list = lists.get(i);
// if (list == null) {
// continue;
// }
// arrays[i] = list.toArray();
// size = size + arrays[i].length;
// }
// Object[] array = new Object[size];
// int index = 0;
// for (Object[] arr : arrays) {
// System.arraycopy(arr, 0, array, index, arr.length);
// index = index + arr.length;
// }
// return array;
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public <T> T[] toArray(T[] a) {
// Object[] array = toArray();
// if (a.length < array.length) {
// return (T[]) array;
// }
// System.arraycopy(array, 0, a, 0, array.length);
// return a;
// }
// }
// Path: src/org/svetovid/run/SvetovidJvmProcessBuilder.java
import java.io.File;
import java.io.IOException;
import java.lang.ProcessBuilder.Redirect;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.svetovid.io.SvetovidProcess;
import org.svetovid.util.CompoundList;
public SvetovidJvmProcessBuilder redirectInput(Path file) {
super.redirectInput(file);
return this;
}
@Override
public SvetovidJvmProcessBuilder redirectOutput(Path file) {
super.redirectOutput(file);
return this;
}
@Override
public SvetovidJvmProcessBuilder redirectError(Path file) {
super.redirectError(file);
return this;
}
@Override
public SvetovidJvmProcessBuilder inheritIO() {
super.inheritIO();
return this;
}
@Override
public SvetovidJvmProcessBuilder redirectErrorStream(boolean redirectErrorStream) {
super.redirectErrorStream(redirectErrorStream);
return this;
}
@Override
|
public SvetovidProcess start() throws IOException {
|
ivanpribela/svetovid-lib
|
src/org/svetovid/io/SvetovidWriter.java
|
// Path: src/org/svetovid/SvetovidFormatException.java
// public class SvetovidFormatException extends SvetovidException {
//
// private static final long serialVersionUID = 1829394491209593218L;
//
// /**
// * Constructs a {@code SvetovidFormatException} with the specified message.
// *
// * @param type
// * The type to which the string could not be parsed
// * @param string
// * The string that could not be parsed
// */
// public SvetovidFormatException(Class<?> type, String string) {
// super(type.getSimpleName(),
// string == null ? null : "\"" + string + "\"");
// }
//
// /**
// * Constructs a {@code SvetovidFormatException} with the specified detail
// * message and cause.
// *
// * @param type
// * The type to which the string could not be parsed
// * @param string
// * The string that could not be parsed
// * @param cause
// * The cause, if any
// */
// public SvetovidFormatException(Class<?> type, String string,
// Throwable cause) {
// super(type.getSimpleName(), cause,
// string == null ? null : "\"" + string + "\"");
// }
//
// /**
// * Constructs a {@code SvetovidFormatException} with multiple suppressed
// * causes.
// *
// * @param causes
// * The suppressed causes of this exception
// */
// public SvetovidFormatException(Throwable... causes) {
// super("Array");
// for (Throwable cause : causes) {
// addSuppressed(cause);
// }
// }
//
// /**
// * Constructs a {@code SvetovidFormatException} with multiple suppressed
// * causes.
// *
// * @param causes
// * The suppressed causes of this exception
// */
// public SvetovidFormatException(List<? extends Throwable> causes) {
// super("Array");
// for (Throwable cause : causes) {
// addSuppressed(cause);
// }
// }
//
// /**
// * Constructs a {@code SvetovidFormatException} with the specified detail
// * message and cause.
// *
// * @param messageKey
// * The resource bundle key of the detail message, which is saved
// * for later retrieval by the {@link #getMessage()} method
// * @param string
// * The string that could not be parsed
// * @param cause
// * The cause, if any
// */
// public SvetovidFormatException(String messageKey, String string,
// Throwable cause) {
// super(messageKey, cause, string);
// }
//
// /**
// * Constructs a {@code SvetovidFormatException} with the specified detail
// * message and cause.
// *
// * @param string
// * The string that could not be parsed
// * @param cause
// * The cause of the format exception
// */
// public SvetovidFormatException(IllegalFormatException cause, String string) {
// super("PrintFormat." + cause.getClass().getSimpleName(), cause, string);
// }
// }
|
import java.io.Closeable;
import org.svetovid.SvetovidFormatException;
|
* if an error occurred during the operation.
*/
public void println(Object[][] value) throws SvetovidIOException;
/**
* Prints a formatted string using the specified format string and
* arguments. For details see {@link java.util.Formatter}.
*
* @param format
* A format string as described in {@link java.util.Formatter}
* string syntax.
* @param arguments
* Arguments referenced by the format specifiers in the format
* string. If there are more arguments than format specifiers,
* the extra arguments are ignored. The number of arguments is
* variable and may be zero. The behavior on a null argument
* depends on the conversion.
*
* @throws SvetovidFormatException
* If a format string is {@code null}, contains an illegal
* syntax, a format specifier that is incompatible with the
* given arguments, insufficient arguments given the format
* string, or other illegal conditions. For specification of all
* possible formatting errors, see the Details section of the
* {@link java.util.Formatter} class specification.
*
* @throws SvetovidIOException
* if an error occurred during the operation.
*/
public void printf(String format, Object... arguments)
|
// Path: src/org/svetovid/SvetovidFormatException.java
// public class SvetovidFormatException extends SvetovidException {
//
// private static final long serialVersionUID = 1829394491209593218L;
//
// /**
// * Constructs a {@code SvetovidFormatException} with the specified message.
// *
// * @param type
// * The type to which the string could not be parsed
// * @param string
// * The string that could not be parsed
// */
// public SvetovidFormatException(Class<?> type, String string) {
// super(type.getSimpleName(),
// string == null ? null : "\"" + string + "\"");
// }
//
// /**
// * Constructs a {@code SvetovidFormatException} with the specified detail
// * message and cause.
// *
// * @param type
// * The type to which the string could not be parsed
// * @param string
// * The string that could not be parsed
// * @param cause
// * The cause, if any
// */
// public SvetovidFormatException(Class<?> type, String string,
// Throwable cause) {
// super(type.getSimpleName(), cause,
// string == null ? null : "\"" + string + "\"");
// }
//
// /**
// * Constructs a {@code SvetovidFormatException} with multiple suppressed
// * causes.
// *
// * @param causes
// * The suppressed causes of this exception
// */
// public SvetovidFormatException(Throwable... causes) {
// super("Array");
// for (Throwable cause : causes) {
// addSuppressed(cause);
// }
// }
//
// /**
// * Constructs a {@code SvetovidFormatException} with multiple suppressed
// * causes.
// *
// * @param causes
// * The suppressed causes of this exception
// */
// public SvetovidFormatException(List<? extends Throwable> causes) {
// super("Array");
// for (Throwable cause : causes) {
// addSuppressed(cause);
// }
// }
//
// /**
// * Constructs a {@code SvetovidFormatException} with the specified detail
// * message and cause.
// *
// * @param messageKey
// * The resource bundle key of the detail message, which is saved
// * for later retrieval by the {@link #getMessage()} method
// * @param string
// * The string that could not be parsed
// * @param cause
// * The cause, if any
// */
// public SvetovidFormatException(String messageKey, String string,
// Throwable cause) {
// super(messageKey, cause, string);
// }
//
// /**
// * Constructs a {@code SvetovidFormatException} with the specified detail
// * message and cause.
// *
// * @param string
// * The string that could not be parsed
// * @param cause
// * The cause of the format exception
// */
// public SvetovidFormatException(IllegalFormatException cause, String string) {
// super("PrintFormat." + cause.getClass().getSimpleName(), cause, string);
// }
// }
// Path: src/org/svetovid/io/SvetovidWriter.java
import java.io.Closeable;
import org.svetovid.SvetovidFormatException;
* if an error occurred during the operation.
*/
public void println(Object[][] value) throws SvetovidIOException;
/**
* Prints a formatted string using the specified format string and
* arguments. For details see {@link java.util.Formatter}.
*
* @param format
* A format string as described in {@link java.util.Formatter}
* string syntax.
* @param arguments
* Arguments referenced by the format specifiers in the format
* string. If there are more arguments than format specifiers,
* the extra arguments are ignored. The number of arguments is
* variable and may be zero. The behavior on a null argument
* depends on the conversion.
*
* @throws SvetovidFormatException
* If a format string is {@code null}, contains an illegal
* syntax, a format specifier that is incompatible with the
* given arguments, insufficient arguments given the format
* string, or other illegal conditions. For specification of all
* possible formatting errors, see the Details section of the
* {@link java.util.Formatter} class specification.
*
* @throws SvetovidIOException
* if an error occurred during the operation.
*/
public void printf(String format, Object... arguments)
|
throws SvetovidFormatException, SvetovidIOException;
|
ivanpribela/svetovid-lib
|
src/org/svetovid/run/SvetovidProcessBuilder.java
|
// Path: src/org/svetovid/io/SvetovidProcess.java
// public class SvetovidProcess {
//
// public final Process process;
// public final SvetovidWriter in;
// public final SvetovidReader out;
// public final SvetovidReader err;
//
// public SvetovidProcess(Process process) {
// this.process = process;
// in = new DefaultSvetovidWriter(process.getOutputStream());
// out = new DefaultSvetovidReader(process.getInputStream());
// err = new DefaultSvetovidReader(process.getErrorStream());
// }
//
// public String toString() {
// return process.toString();
// }
//
// public int waitFor() throws InterruptedException {
// return process.waitFor();
// }
//
// public boolean isAlive() {
// try {
// process.exitValue();
// return false;
// } catch(IllegalThreadStateException e) {
// return true;
// }
// }
//
// public int exitValue() {
// return process.exitValue();
// }
//
// public void destroy() {
// process.destroy();
// }
// }
|
import java.io.IOException;
import java.lang.ProcessBuilder.Redirect;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.svetovid.io.SvetovidProcess;
|
public SvetovidProcessBuilder redirectOutput(Path file) {
builder.redirectOutput(file.toFile());
return this;
}
public SvetovidProcessBuilder redirectError(Path file) {
builder.redirectError(file.toFile());
return this;
}
public SvetovidProcessBuilder inheritIO() {
builder.inheritIO();
return this;
}
public boolean redirectErrorStream() {
return builder.redirectErrorStream();
}
public SvetovidProcessBuilder redirectErrorStream(boolean redirectErrorStream) {
builder.redirectErrorStream(redirectErrorStream);
return this;
}
public List<String> effectiveCommand() {
List<String> cmd = builder.command();
cmd = new ArrayList<>(cmd);
return cmd;
}
|
// Path: src/org/svetovid/io/SvetovidProcess.java
// public class SvetovidProcess {
//
// public final Process process;
// public final SvetovidWriter in;
// public final SvetovidReader out;
// public final SvetovidReader err;
//
// public SvetovidProcess(Process process) {
// this.process = process;
// in = new DefaultSvetovidWriter(process.getOutputStream());
// out = new DefaultSvetovidReader(process.getInputStream());
// err = new DefaultSvetovidReader(process.getErrorStream());
// }
//
// public String toString() {
// return process.toString();
// }
//
// public int waitFor() throws InterruptedException {
// return process.waitFor();
// }
//
// public boolean isAlive() {
// try {
// process.exitValue();
// return false;
// } catch(IllegalThreadStateException e) {
// return true;
// }
// }
//
// public int exitValue() {
// return process.exitValue();
// }
//
// public void destroy() {
// process.destroy();
// }
// }
// Path: src/org/svetovid/run/SvetovidProcessBuilder.java
import java.io.IOException;
import java.lang.ProcessBuilder.Redirect;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.svetovid.io.SvetovidProcess;
public SvetovidProcessBuilder redirectOutput(Path file) {
builder.redirectOutput(file.toFile());
return this;
}
public SvetovidProcessBuilder redirectError(Path file) {
builder.redirectError(file.toFile());
return this;
}
public SvetovidProcessBuilder inheritIO() {
builder.inheritIO();
return this;
}
public boolean redirectErrorStream() {
return builder.redirectErrorStream();
}
public SvetovidProcessBuilder redirectErrorStream(boolean redirectErrorStream) {
builder.redirectErrorStream(redirectErrorStream);
return this;
}
public List<String> effectiveCommand() {
List<String> cmd = builder.command();
cmd = new ArrayList<>(cmd);
return cmd;
}
|
public SvetovidProcess start() throws IOException {
|
ivanpribela/svetovid-lib
|
src/org/svetovid/demo/Calculator.java
|
// Path: src/org/svetovid/run/Start.java
// public class Start {
//
// public static void main(String[] arguments) {
//
// // No class to run
// if (arguments.length == 0) {
// return;
// }
//
// // Find the class
// String className = arguments[0];
// Class<?> type;
// try {
// type = Class.forName(className);
// } catch (ClassNotFoundException e) {
// e.printStackTrace();
// return;
// }
//
// // Find a method
// Method[] methods = type.getDeclaredMethods();
// String methodName = null;
// if (arguments.length > 1) {
// methodName = arguments[1];
// }
// methods = filterMethods(methods, methodName);
//
// // Prepare the instance
// Object instance = null;
//
// // Invoke all matching methods
// for (Method method : methods) {
//
// // Prepare the instance
// if ((instance == null) && !Modifier.isStatic(method.getModifiers())) {
// try {
// instance = type.newInstance();
// } catch (InstantiationException e) {
// // Leave at null
// } catch (IllegalAccessException e) {
// // Leave at null
// }
// }
//
// // Prepare parameters
// int argumentCount = arguments.length - 1;
// if (method.getName().equals(methodName)) {
// argumentCount--;
// }
// int actualArgumentCount = method.getParameterTypes().length;
// String[] stringArguments = new String[actualArgumentCount];
// System.arraycopy(arguments, arguments.length - argumentCount, stringArguments, 0, actualArgumentCount < argumentCount ? actualArgumentCount : argumentCount);
// Object[] methodArguments = new Object[actualArgumentCount];
// Class<?>[] argumentTypes = method.getParameterTypes();
// for (int i = 0; i < actualArgumentCount; i++) {
// methodArguments[i] = convertArgument(argumentTypes[i], stringArguments[i]);
// }
//
// // Invoke the method
// Object result = null;
// try {
// method.setAccessible(true);
// result = method.invoke(instance, methodArguments);
// } catch (IllegalAccessException e) {
// // Will not happen
// } catch (IllegalArgumentException e) {
// result = e;
// } catch (InvocationTargetException e) {
// result = e.getCause();
// }
//
// // Output the result
// StringBuilder output = new StringBuilder();
// output.append(method.getName());
// output.append("(");
// boolean placeDelimiter = false;
// for (Object argument : methodArguments) {
// if (placeDelimiter) {
// output.append(", ");
// }
// output.append(argument);
// placeDelimiter = true;
// }
// output.append(") = ");
// output.append(result);
// System.out.println(output.toString());
// if (result instanceof Throwable) {
// ((Throwable) result).printStackTrace();
// }
//
// }
// }
//
// private static Method[] filterMethods(Method[] methods, String name) {
// if (methods.length == 0) {
// return new Method[0];
// }
// if (methods.length == 1) {
// return methods;
// }
// List<Method> result = new ArrayList<>();
// for (Method method : methods) {
// if (method.getName().equals(name)) {
// result.add(method);
// }
// }
// if (result.size() > 0) {
// methods = result.toArray(new Method[result.size()]);
// }
// return methods;
// }
//
// private static Object convertArgument(Class<?> type, String string) {
// if (String.class.equals(type)) {
// return string;
// }
// if (type.isPrimitive()) {
// type = primitiveToWrapperMap.get(type);
// }
// try {
// return type.getMethod("valueOf", String.class).invoke(null, string);
// } catch (NoSuchMethodException|SecurityException|IllegalAccessException|IllegalArgumentException|InvocationTargetException e) {
// // Do nothing
// }
// try {
// return type.getConstructor(String.class).newInstance();
// } catch (InstantiationException|IllegalAccessException|IllegalArgumentException|InvocationTargetException|NoSuchMethodException|SecurityException e) {
// // Do nothing
// }
// return null;
// }
//
// private static Map<Class<?>, Class<?>> primitiveToWrapperMap = new HashMap<>();
// static {
// primitiveToWrapperMap.put(boolean.class, Boolean.class);
// primitiveToWrapperMap.put(byte.class, Byte.class);
// primitiveToWrapperMap.put(char.class, Character.class);
// primitiveToWrapperMap.put(short.class, Short.class);
// primitiveToWrapperMap.put(int.class, Integer.class);
// primitiveToWrapperMap.put(long.class, Long.class);
// primitiveToWrapperMap.put(float.class, Float.class);
// primitiveToWrapperMap.put(double.class, Double.class);
// primitiveToWrapperMap.put(void.class, Void.class);
// }
// }
|
import org.svetovid.run.Start;
|
}
@SuppressWarnings("unused")
private double add(double a, double b) {
return a + b;
}
public double add(double a, double b, double c) {
return a + b + c;
}
public double minus(double a) {
return -a;
}
protected String add(double a, String b) {
return a + b;
}
public static int sub(int a, int b) {
return a - b;
}
public static int mul(int a, int b) {
return a * b;
}
public static void main(String[] arguments) {
// Running this main method has the same result as using the Start class with the following arguments
arguments = new String[] { "org.svetovid.demo.Calculator", "add", "6", "3" };
|
// Path: src/org/svetovid/run/Start.java
// public class Start {
//
// public static void main(String[] arguments) {
//
// // No class to run
// if (arguments.length == 0) {
// return;
// }
//
// // Find the class
// String className = arguments[0];
// Class<?> type;
// try {
// type = Class.forName(className);
// } catch (ClassNotFoundException e) {
// e.printStackTrace();
// return;
// }
//
// // Find a method
// Method[] methods = type.getDeclaredMethods();
// String methodName = null;
// if (arguments.length > 1) {
// methodName = arguments[1];
// }
// methods = filterMethods(methods, methodName);
//
// // Prepare the instance
// Object instance = null;
//
// // Invoke all matching methods
// for (Method method : methods) {
//
// // Prepare the instance
// if ((instance == null) && !Modifier.isStatic(method.getModifiers())) {
// try {
// instance = type.newInstance();
// } catch (InstantiationException e) {
// // Leave at null
// } catch (IllegalAccessException e) {
// // Leave at null
// }
// }
//
// // Prepare parameters
// int argumentCount = arguments.length - 1;
// if (method.getName().equals(methodName)) {
// argumentCount--;
// }
// int actualArgumentCount = method.getParameterTypes().length;
// String[] stringArguments = new String[actualArgumentCount];
// System.arraycopy(arguments, arguments.length - argumentCount, stringArguments, 0, actualArgumentCount < argumentCount ? actualArgumentCount : argumentCount);
// Object[] methodArguments = new Object[actualArgumentCount];
// Class<?>[] argumentTypes = method.getParameterTypes();
// for (int i = 0; i < actualArgumentCount; i++) {
// methodArguments[i] = convertArgument(argumentTypes[i], stringArguments[i]);
// }
//
// // Invoke the method
// Object result = null;
// try {
// method.setAccessible(true);
// result = method.invoke(instance, methodArguments);
// } catch (IllegalAccessException e) {
// // Will not happen
// } catch (IllegalArgumentException e) {
// result = e;
// } catch (InvocationTargetException e) {
// result = e.getCause();
// }
//
// // Output the result
// StringBuilder output = new StringBuilder();
// output.append(method.getName());
// output.append("(");
// boolean placeDelimiter = false;
// for (Object argument : methodArguments) {
// if (placeDelimiter) {
// output.append(", ");
// }
// output.append(argument);
// placeDelimiter = true;
// }
// output.append(") = ");
// output.append(result);
// System.out.println(output.toString());
// if (result instanceof Throwable) {
// ((Throwable) result).printStackTrace();
// }
//
// }
// }
//
// private static Method[] filterMethods(Method[] methods, String name) {
// if (methods.length == 0) {
// return new Method[0];
// }
// if (methods.length == 1) {
// return methods;
// }
// List<Method> result = new ArrayList<>();
// for (Method method : methods) {
// if (method.getName().equals(name)) {
// result.add(method);
// }
// }
// if (result.size() > 0) {
// methods = result.toArray(new Method[result.size()]);
// }
// return methods;
// }
//
// private static Object convertArgument(Class<?> type, String string) {
// if (String.class.equals(type)) {
// return string;
// }
// if (type.isPrimitive()) {
// type = primitiveToWrapperMap.get(type);
// }
// try {
// return type.getMethod("valueOf", String.class).invoke(null, string);
// } catch (NoSuchMethodException|SecurityException|IllegalAccessException|IllegalArgumentException|InvocationTargetException e) {
// // Do nothing
// }
// try {
// return type.getConstructor(String.class).newInstance();
// } catch (InstantiationException|IllegalAccessException|IllegalArgumentException|InvocationTargetException|NoSuchMethodException|SecurityException e) {
// // Do nothing
// }
// return null;
// }
//
// private static Map<Class<?>, Class<?>> primitiveToWrapperMap = new HashMap<>();
// static {
// primitiveToWrapperMap.put(boolean.class, Boolean.class);
// primitiveToWrapperMap.put(byte.class, Byte.class);
// primitiveToWrapperMap.put(char.class, Character.class);
// primitiveToWrapperMap.put(short.class, Short.class);
// primitiveToWrapperMap.put(int.class, Integer.class);
// primitiveToWrapperMap.put(long.class, Long.class);
// primitiveToWrapperMap.put(float.class, Float.class);
// primitiveToWrapperMap.put(double.class, Double.class);
// primitiveToWrapperMap.put(void.class, Void.class);
// }
// }
// Path: src/org/svetovid/demo/Calculator.java
import org.svetovid.run.Start;
}
@SuppressWarnings("unused")
private double add(double a, double b) {
return a + b;
}
public double add(double a, double b, double c) {
return a + b + c;
}
public double minus(double a) {
return -a;
}
protected String add(double a, String b) {
return a + b;
}
public static int sub(int a, int b) {
return a - b;
}
public static int mul(int a, int b) {
return a * b;
}
public static void main(String[] arguments) {
// Running this main method has the same result as using the Start class with the following arguments
arguments = new String[] { "org.svetovid.demo.Calculator", "add", "6", "3" };
|
Start.main(arguments);
|
mozammel/mNet
|
src/main/java/org/jugbd/mnet/web/editor/GenderEditor.java
|
// Path: src/main/java/org/jugbd/mnet/domain/enums/Gender.java
// public enum Gender {
//
// MALE("Male"),
// FEMALE("Female"),
// OTHER("Other");
//
// private String label;
//
// Gender(String label) {
// this.label = label;
// }
//
// public String getLabel() {
// return label;
// }
// }
|
import org.jugbd.mnet.domain.enums.Gender;
import java.beans.PropertyEditorSupport;
|
package org.jugbd.mnet.web.editor;
/**
* @author ronygomes
*/
public class GenderEditor extends PropertyEditorSupport {
@Override
public void setAsText(String text) {
|
// Path: src/main/java/org/jugbd/mnet/domain/enums/Gender.java
// public enum Gender {
//
// MALE("Male"),
// FEMALE("Female"),
// OTHER("Other");
//
// private String label;
//
// Gender(String label) {
// this.label = label;
// }
//
// public String getLabel() {
// return label;
// }
// }
// Path: src/main/java/org/jugbd/mnet/web/editor/GenderEditor.java
import org.jugbd.mnet.domain.enums.Gender;
import java.beans.PropertyEditorSupport;
package org.jugbd.mnet.web.editor;
/**
* @author ronygomes
*/
public class GenderEditor extends PropertyEditorSupport {
@Override
public void setAsText(String text) {
|
for (Gender gender : Gender.values()) {
|
mozammel/mNet
|
src/main/java/org/jugbd/mnet/web/controller/PictureInformationController.java
|
// Path: src/main/java/org/jugbd/mnet/domain/enums/PictureInformationType.java
// public enum PictureInformationType {
//
// DAY_ONE("Day One"),
//
// PREOPERATIVE("Pre-operative"),
//
// PRE_OPERATION("Pre-operation"),
//
// POSTOPERATIVE("Post operative"),
//
// ON_DISCHARGE("On Discharge");
//
// private String label;
//
// PictureInformationType(String label) {
// this.label = label;
// }
//
// public String getLabel() {
// return label;
// }
//
// }
//
// Path: src/main/java/org/jugbd/mnet/service/PictureInformationService.java
// @Component
// public interface PictureInformationService {
// PictureInformation save(PictureInformation pictureInformation);
//
// PictureInformation findOne(Long id);
//
// void upload(Long registerId, MultipartFile file, PictureInformationType pictureInformationType, String fileName, String comment);
//
// ResponseEntity<byte[]> getUploadedFileAsResponseEntity(Long fileId);
//
// PictureInformation findPictureInformationByRegistrationId(Long registerId);
// }
//
// Path: src/main/java/org/jugbd/mnet/utils/FileUtils.java
// public class FileUtils {
// public static final int FILE_NAME_MAX_SIZE = 60;
//
// private static final Map<String, String> extensionContentTypeMap;
//
// static {
// extensionContentTypeMap = new HashMap<>();
// extensionContentTypeMap.put("jpg", "image/jpeg");
// extensionContentTypeMap.put("jpeg", "image/jpeg");
// extensionContentTypeMap.put("png", "image/png");
// extensionContentTypeMap.put("pdf", "application/pdf");
// extensionContentTypeMap.put("doc", "application/msword");
// extensionContentTypeMap.put("docx", "application/msword");
// }
//
// public static boolean isValidFile(MultipartFile file, String[] fileTypeList) {
// String fileName = file.getOriginalFilename();
// String extension = getExtensionInLowerCase(fileName);
// for (String validFileType : fileTypeList) {
// if (extension.equalsIgnoreCase(validFileType)) {
// return true;
// }
// }
// return false;
// }
//
// public static String getContentType(String extension) {
// return extensionContentTypeMap.get(extension.toLowerCase());
// }
//
// public static String getExtensionInLowerCase(String fileName) {
// return FilenameUtils.getExtension(fileName).toLowerCase();
// }
//
// public static String getExtensionFromContentType(String contentType) {
// String key = "";
// for (Map.Entry<String, String> entry : extensionContentTypeMap.entrySet()) {
// if ((entry.getValue().equalsIgnoreCase(contentType))) {
// key = entry.getKey();
// }
// }
// return key;
// }
//
// /**
// * Get file name trimmed to FILE_NAME_MAX_SIZE and also extension to lower case (bcoz, people tend to have file in uppercase extension like JPG, jpg)
// *
// * @param fileName User's file name
// * @return
// */
// public static String getFilteredFileName(String fileName) {
// String extension = getExtensionInLowerCase(fileName);
// String baseName = FilenameUtils.getBaseName(fileName);
// baseName = baseName.replaceAll(" ", "-");
// return StringUtils.getTrimmedString(baseName, FILE_NAME_MAX_SIZE - extension.length()) + "." + extension;
// }
// }
|
import org.jugbd.mnet.dao.AttachmentDao;
import org.jugbd.mnet.domain.Attachment;
import org.jugbd.mnet.domain.PictureInformation;
import org.jugbd.mnet.domain.enums.PictureInformationType;
import org.jugbd.mnet.service.PictureInformationService;
import org.jugbd.mnet.service.RegisterService;
import org.jugbd.mnet.utils.Contestant;
import org.jugbd.mnet.utils.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import java.io.IOException;
|
package org.jugbd.mnet.web.controller;
/**
* @author Bazlur Rahman Rokon
* @date 12/27/14.
*/
@Controller
@Secured({"ROLE_ADMIN", "ROLE_USER"})
public class PictureInformationController {
private Logger log = LoggerFactory.getLogger(PictureInformationController.class);
@Autowired
private RegisterService registerService;
@Autowired
|
// Path: src/main/java/org/jugbd/mnet/domain/enums/PictureInformationType.java
// public enum PictureInformationType {
//
// DAY_ONE("Day One"),
//
// PREOPERATIVE("Pre-operative"),
//
// PRE_OPERATION("Pre-operation"),
//
// POSTOPERATIVE("Post operative"),
//
// ON_DISCHARGE("On Discharge");
//
// private String label;
//
// PictureInformationType(String label) {
// this.label = label;
// }
//
// public String getLabel() {
// return label;
// }
//
// }
//
// Path: src/main/java/org/jugbd/mnet/service/PictureInformationService.java
// @Component
// public interface PictureInformationService {
// PictureInformation save(PictureInformation pictureInformation);
//
// PictureInformation findOne(Long id);
//
// void upload(Long registerId, MultipartFile file, PictureInformationType pictureInformationType, String fileName, String comment);
//
// ResponseEntity<byte[]> getUploadedFileAsResponseEntity(Long fileId);
//
// PictureInformation findPictureInformationByRegistrationId(Long registerId);
// }
//
// Path: src/main/java/org/jugbd/mnet/utils/FileUtils.java
// public class FileUtils {
// public static final int FILE_NAME_MAX_SIZE = 60;
//
// private static final Map<String, String> extensionContentTypeMap;
//
// static {
// extensionContentTypeMap = new HashMap<>();
// extensionContentTypeMap.put("jpg", "image/jpeg");
// extensionContentTypeMap.put("jpeg", "image/jpeg");
// extensionContentTypeMap.put("png", "image/png");
// extensionContentTypeMap.put("pdf", "application/pdf");
// extensionContentTypeMap.put("doc", "application/msword");
// extensionContentTypeMap.put("docx", "application/msword");
// }
//
// public static boolean isValidFile(MultipartFile file, String[] fileTypeList) {
// String fileName = file.getOriginalFilename();
// String extension = getExtensionInLowerCase(fileName);
// for (String validFileType : fileTypeList) {
// if (extension.equalsIgnoreCase(validFileType)) {
// return true;
// }
// }
// return false;
// }
//
// public static String getContentType(String extension) {
// return extensionContentTypeMap.get(extension.toLowerCase());
// }
//
// public static String getExtensionInLowerCase(String fileName) {
// return FilenameUtils.getExtension(fileName).toLowerCase();
// }
//
// public static String getExtensionFromContentType(String contentType) {
// String key = "";
// for (Map.Entry<String, String> entry : extensionContentTypeMap.entrySet()) {
// if ((entry.getValue().equalsIgnoreCase(contentType))) {
// key = entry.getKey();
// }
// }
// return key;
// }
//
// /**
// * Get file name trimmed to FILE_NAME_MAX_SIZE and also extension to lower case (bcoz, people tend to have file in uppercase extension like JPG, jpg)
// *
// * @param fileName User's file name
// * @return
// */
// public static String getFilteredFileName(String fileName) {
// String extension = getExtensionInLowerCase(fileName);
// String baseName = FilenameUtils.getBaseName(fileName);
// baseName = baseName.replaceAll(" ", "-");
// return StringUtils.getTrimmedString(baseName, FILE_NAME_MAX_SIZE - extension.length()) + "." + extension;
// }
// }
// Path: src/main/java/org/jugbd/mnet/web/controller/PictureInformationController.java
import org.jugbd.mnet.dao.AttachmentDao;
import org.jugbd.mnet.domain.Attachment;
import org.jugbd.mnet.domain.PictureInformation;
import org.jugbd.mnet.domain.enums.PictureInformationType;
import org.jugbd.mnet.service.PictureInformationService;
import org.jugbd.mnet.service.RegisterService;
import org.jugbd.mnet.utils.Contestant;
import org.jugbd.mnet.utils.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import java.io.IOException;
package org.jugbd.mnet.web.controller;
/**
* @author Bazlur Rahman Rokon
* @date 12/27/14.
*/
@Controller
@Secured({"ROLE_ADMIN", "ROLE_USER"})
public class PictureInformationController {
private Logger log = LoggerFactory.getLogger(PictureInformationController.class);
@Autowired
private RegisterService registerService;
@Autowired
|
private PictureInformationService pictureInformationService;
|
mozammel/mNet
|
src/main/java/org/jugbd/mnet/web/controller/PictureInformationController.java
|
// Path: src/main/java/org/jugbd/mnet/domain/enums/PictureInformationType.java
// public enum PictureInformationType {
//
// DAY_ONE("Day One"),
//
// PREOPERATIVE("Pre-operative"),
//
// PRE_OPERATION("Pre-operation"),
//
// POSTOPERATIVE("Post operative"),
//
// ON_DISCHARGE("On Discharge");
//
// private String label;
//
// PictureInformationType(String label) {
// this.label = label;
// }
//
// public String getLabel() {
// return label;
// }
//
// }
//
// Path: src/main/java/org/jugbd/mnet/service/PictureInformationService.java
// @Component
// public interface PictureInformationService {
// PictureInformation save(PictureInformation pictureInformation);
//
// PictureInformation findOne(Long id);
//
// void upload(Long registerId, MultipartFile file, PictureInformationType pictureInformationType, String fileName, String comment);
//
// ResponseEntity<byte[]> getUploadedFileAsResponseEntity(Long fileId);
//
// PictureInformation findPictureInformationByRegistrationId(Long registerId);
// }
//
// Path: src/main/java/org/jugbd/mnet/utils/FileUtils.java
// public class FileUtils {
// public static final int FILE_NAME_MAX_SIZE = 60;
//
// private static final Map<String, String> extensionContentTypeMap;
//
// static {
// extensionContentTypeMap = new HashMap<>();
// extensionContentTypeMap.put("jpg", "image/jpeg");
// extensionContentTypeMap.put("jpeg", "image/jpeg");
// extensionContentTypeMap.put("png", "image/png");
// extensionContentTypeMap.put("pdf", "application/pdf");
// extensionContentTypeMap.put("doc", "application/msword");
// extensionContentTypeMap.put("docx", "application/msword");
// }
//
// public static boolean isValidFile(MultipartFile file, String[] fileTypeList) {
// String fileName = file.getOriginalFilename();
// String extension = getExtensionInLowerCase(fileName);
// for (String validFileType : fileTypeList) {
// if (extension.equalsIgnoreCase(validFileType)) {
// return true;
// }
// }
// return false;
// }
//
// public static String getContentType(String extension) {
// return extensionContentTypeMap.get(extension.toLowerCase());
// }
//
// public static String getExtensionInLowerCase(String fileName) {
// return FilenameUtils.getExtension(fileName).toLowerCase();
// }
//
// public static String getExtensionFromContentType(String contentType) {
// String key = "";
// for (Map.Entry<String, String> entry : extensionContentTypeMap.entrySet()) {
// if ((entry.getValue().equalsIgnoreCase(contentType))) {
// key = entry.getKey();
// }
// }
// return key;
// }
//
// /**
// * Get file name trimmed to FILE_NAME_MAX_SIZE and also extension to lower case (bcoz, people tend to have file in uppercase extension like JPG, jpg)
// *
// * @param fileName User's file name
// * @return
// */
// public static String getFilteredFileName(String fileName) {
// String extension = getExtensionInLowerCase(fileName);
// String baseName = FilenameUtils.getBaseName(fileName);
// baseName = baseName.replaceAll(" ", "-");
// return StringUtils.getTrimmedString(baseName, FILE_NAME_MAX_SIZE - extension.length()) + "." + extension;
// }
// }
|
import org.jugbd.mnet.dao.AttachmentDao;
import org.jugbd.mnet.domain.Attachment;
import org.jugbd.mnet.domain.PictureInformation;
import org.jugbd.mnet.domain.enums.PictureInformationType;
import org.jugbd.mnet.service.PictureInformationService;
import org.jugbd.mnet.service.RegisterService;
import org.jugbd.mnet.utils.Contestant;
import org.jugbd.mnet.utils.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import java.io.IOException;
|
package org.jugbd.mnet.web.controller;
/**
* @author Bazlur Rahman Rokon
* @date 12/27/14.
*/
@Controller
@Secured({"ROLE_ADMIN", "ROLE_USER"})
public class PictureInformationController {
private Logger log = LoggerFactory.getLogger(PictureInformationController.class);
@Autowired
private RegisterService registerService;
@Autowired
private PictureInformationService pictureInformationService;
@Autowired
private AttachmentDao attachmentDao;
@RequestMapping(value = "picture/{registerId}", method = RequestMethod.GET)
public String show(@PathVariable Long registerId, Model uiModel) {
PictureInformation pictureInformation = pictureInformationService.findPictureInformationByRegistrationId(registerId);
uiModel.addAttribute("pictureInformation", pictureInformation);
uiModel.addAttribute("register", pictureInformation.getRegister());
return "picture/show";
}
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public String uploadPhoto(@RequestParam("file") MultipartFile file,
|
// Path: src/main/java/org/jugbd/mnet/domain/enums/PictureInformationType.java
// public enum PictureInformationType {
//
// DAY_ONE("Day One"),
//
// PREOPERATIVE("Pre-operative"),
//
// PRE_OPERATION("Pre-operation"),
//
// POSTOPERATIVE("Post operative"),
//
// ON_DISCHARGE("On Discharge");
//
// private String label;
//
// PictureInformationType(String label) {
// this.label = label;
// }
//
// public String getLabel() {
// return label;
// }
//
// }
//
// Path: src/main/java/org/jugbd/mnet/service/PictureInformationService.java
// @Component
// public interface PictureInformationService {
// PictureInformation save(PictureInformation pictureInformation);
//
// PictureInformation findOne(Long id);
//
// void upload(Long registerId, MultipartFile file, PictureInformationType pictureInformationType, String fileName, String comment);
//
// ResponseEntity<byte[]> getUploadedFileAsResponseEntity(Long fileId);
//
// PictureInformation findPictureInformationByRegistrationId(Long registerId);
// }
//
// Path: src/main/java/org/jugbd/mnet/utils/FileUtils.java
// public class FileUtils {
// public static final int FILE_NAME_MAX_SIZE = 60;
//
// private static final Map<String, String> extensionContentTypeMap;
//
// static {
// extensionContentTypeMap = new HashMap<>();
// extensionContentTypeMap.put("jpg", "image/jpeg");
// extensionContentTypeMap.put("jpeg", "image/jpeg");
// extensionContentTypeMap.put("png", "image/png");
// extensionContentTypeMap.put("pdf", "application/pdf");
// extensionContentTypeMap.put("doc", "application/msword");
// extensionContentTypeMap.put("docx", "application/msword");
// }
//
// public static boolean isValidFile(MultipartFile file, String[] fileTypeList) {
// String fileName = file.getOriginalFilename();
// String extension = getExtensionInLowerCase(fileName);
// for (String validFileType : fileTypeList) {
// if (extension.equalsIgnoreCase(validFileType)) {
// return true;
// }
// }
// return false;
// }
//
// public static String getContentType(String extension) {
// return extensionContentTypeMap.get(extension.toLowerCase());
// }
//
// public static String getExtensionInLowerCase(String fileName) {
// return FilenameUtils.getExtension(fileName).toLowerCase();
// }
//
// public static String getExtensionFromContentType(String contentType) {
// String key = "";
// for (Map.Entry<String, String> entry : extensionContentTypeMap.entrySet()) {
// if ((entry.getValue().equalsIgnoreCase(contentType))) {
// key = entry.getKey();
// }
// }
// return key;
// }
//
// /**
// * Get file name trimmed to FILE_NAME_MAX_SIZE and also extension to lower case (bcoz, people tend to have file in uppercase extension like JPG, jpg)
// *
// * @param fileName User's file name
// * @return
// */
// public static String getFilteredFileName(String fileName) {
// String extension = getExtensionInLowerCase(fileName);
// String baseName = FilenameUtils.getBaseName(fileName);
// baseName = baseName.replaceAll(" ", "-");
// return StringUtils.getTrimmedString(baseName, FILE_NAME_MAX_SIZE - extension.length()) + "." + extension;
// }
// }
// Path: src/main/java/org/jugbd/mnet/web/controller/PictureInformationController.java
import org.jugbd.mnet.dao.AttachmentDao;
import org.jugbd.mnet.domain.Attachment;
import org.jugbd.mnet.domain.PictureInformation;
import org.jugbd.mnet.domain.enums.PictureInformationType;
import org.jugbd.mnet.service.PictureInformationService;
import org.jugbd.mnet.service.RegisterService;
import org.jugbd.mnet.utils.Contestant;
import org.jugbd.mnet.utils.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import java.io.IOException;
package org.jugbd.mnet.web.controller;
/**
* @author Bazlur Rahman Rokon
* @date 12/27/14.
*/
@Controller
@Secured({"ROLE_ADMIN", "ROLE_USER"})
public class PictureInformationController {
private Logger log = LoggerFactory.getLogger(PictureInformationController.class);
@Autowired
private RegisterService registerService;
@Autowired
private PictureInformationService pictureInformationService;
@Autowired
private AttachmentDao attachmentDao;
@RequestMapping(value = "picture/{registerId}", method = RequestMethod.GET)
public String show(@PathVariable Long registerId, Model uiModel) {
PictureInformation pictureInformation = pictureInformationService.findPictureInformationByRegistrationId(registerId);
uiModel.addAttribute("pictureInformation", pictureInformation);
uiModel.addAttribute("register", pictureInformation.getRegister());
return "picture/show";
}
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public String uploadPhoto(@RequestParam("file") MultipartFile file,
|
@RequestParam("pictureInformationType") PictureInformationType pictureInformationType,
|
mozammel/mNet
|
src/main/java/org/jugbd/mnet/web/controller/PictureInformationController.java
|
// Path: src/main/java/org/jugbd/mnet/domain/enums/PictureInformationType.java
// public enum PictureInformationType {
//
// DAY_ONE("Day One"),
//
// PREOPERATIVE("Pre-operative"),
//
// PRE_OPERATION("Pre-operation"),
//
// POSTOPERATIVE("Post operative"),
//
// ON_DISCHARGE("On Discharge");
//
// private String label;
//
// PictureInformationType(String label) {
// this.label = label;
// }
//
// public String getLabel() {
// return label;
// }
//
// }
//
// Path: src/main/java/org/jugbd/mnet/service/PictureInformationService.java
// @Component
// public interface PictureInformationService {
// PictureInformation save(PictureInformation pictureInformation);
//
// PictureInformation findOne(Long id);
//
// void upload(Long registerId, MultipartFile file, PictureInformationType pictureInformationType, String fileName, String comment);
//
// ResponseEntity<byte[]> getUploadedFileAsResponseEntity(Long fileId);
//
// PictureInformation findPictureInformationByRegistrationId(Long registerId);
// }
//
// Path: src/main/java/org/jugbd/mnet/utils/FileUtils.java
// public class FileUtils {
// public static final int FILE_NAME_MAX_SIZE = 60;
//
// private static final Map<String, String> extensionContentTypeMap;
//
// static {
// extensionContentTypeMap = new HashMap<>();
// extensionContentTypeMap.put("jpg", "image/jpeg");
// extensionContentTypeMap.put("jpeg", "image/jpeg");
// extensionContentTypeMap.put("png", "image/png");
// extensionContentTypeMap.put("pdf", "application/pdf");
// extensionContentTypeMap.put("doc", "application/msword");
// extensionContentTypeMap.put("docx", "application/msword");
// }
//
// public static boolean isValidFile(MultipartFile file, String[] fileTypeList) {
// String fileName = file.getOriginalFilename();
// String extension = getExtensionInLowerCase(fileName);
// for (String validFileType : fileTypeList) {
// if (extension.equalsIgnoreCase(validFileType)) {
// return true;
// }
// }
// return false;
// }
//
// public static String getContentType(String extension) {
// return extensionContentTypeMap.get(extension.toLowerCase());
// }
//
// public static String getExtensionInLowerCase(String fileName) {
// return FilenameUtils.getExtension(fileName).toLowerCase();
// }
//
// public static String getExtensionFromContentType(String contentType) {
// String key = "";
// for (Map.Entry<String, String> entry : extensionContentTypeMap.entrySet()) {
// if ((entry.getValue().equalsIgnoreCase(contentType))) {
// key = entry.getKey();
// }
// }
// return key;
// }
//
// /**
// * Get file name trimmed to FILE_NAME_MAX_SIZE and also extension to lower case (bcoz, people tend to have file in uppercase extension like JPG, jpg)
// *
// * @param fileName User's file name
// * @return
// */
// public static String getFilteredFileName(String fileName) {
// String extension = getExtensionInLowerCase(fileName);
// String baseName = FilenameUtils.getBaseName(fileName);
// baseName = baseName.replaceAll(" ", "-");
// return StringUtils.getTrimmedString(baseName, FILE_NAME_MAX_SIZE - extension.length()) + "." + extension;
// }
// }
|
import org.jugbd.mnet.dao.AttachmentDao;
import org.jugbd.mnet.domain.Attachment;
import org.jugbd.mnet.domain.PictureInformation;
import org.jugbd.mnet.domain.enums.PictureInformationType;
import org.jugbd.mnet.service.PictureInformationService;
import org.jugbd.mnet.service.RegisterService;
import org.jugbd.mnet.utils.Contestant;
import org.jugbd.mnet.utils.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import java.io.IOException;
|
RedirectAttributes redirectAttributes
) throws IOException {
log.debug("uploadPhoto() pictureInformationType ={}", pictureInformationType);
String errorMsg = validate(file, Contestant.VALID_FILE_TYPE_LIST, Contestant.FILE_MAX_SIZE_BYTES, "Photo");
if (!errorMsg.isEmpty()) {
redirectAttributes.addFlashAttribute("error", errorMsg);
return "picture/show";
}
pictureInformationService.upload(registerId, file, pictureInformationType, fileName, comment);
redirectAttributes.addFlashAttribute("message", "File successfully uploaded");
return "redirect:/picture/" + registerId;
}
@RequestMapping(value = "picture/delete/{registerId}/{attachmentId}", method = RequestMethod.POST)
public String remove(@PathVariable Long registerId, @PathVariable Long attachmentId) {
Attachment attachment = attachmentDao.findOne(attachmentId);
attachment.setDeleted(true);
attachmentDao.save(attachment);
return "redirect:/picture/" + registerId;
}
private String validate(MultipartFile file, String[] validFileTypes, int maxFileSize, String field) {
|
// Path: src/main/java/org/jugbd/mnet/domain/enums/PictureInformationType.java
// public enum PictureInformationType {
//
// DAY_ONE("Day One"),
//
// PREOPERATIVE("Pre-operative"),
//
// PRE_OPERATION("Pre-operation"),
//
// POSTOPERATIVE("Post operative"),
//
// ON_DISCHARGE("On Discharge");
//
// private String label;
//
// PictureInformationType(String label) {
// this.label = label;
// }
//
// public String getLabel() {
// return label;
// }
//
// }
//
// Path: src/main/java/org/jugbd/mnet/service/PictureInformationService.java
// @Component
// public interface PictureInformationService {
// PictureInformation save(PictureInformation pictureInformation);
//
// PictureInformation findOne(Long id);
//
// void upload(Long registerId, MultipartFile file, PictureInformationType pictureInformationType, String fileName, String comment);
//
// ResponseEntity<byte[]> getUploadedFileAsResponseEntity(Long fileId);
//
// PictureInformation findPictureInformationByRegistrationId(Long registerId);
// }
//
// Path: src/main/java/org/jugbd/mnet/utils/FileUtils.java
// public class FileUtils {
// public static final int FILE_NAME_MAX_SIZE = 60;
//
// private static final Map<String, String> extensionContentTypeMap;
//
// static {
// extensionContentTypeMap = new HashMap<>();
// extensionContentTypeMap.put("jpg", "image/jpeg");
// extensionContentTypeMap.put("jpeg", "image/jpeg");
// extensionContentTypeMap.put("png", "image/png");
// extensionContentTypeMap.put("pdf", "application/pdf");
// extensionContentTypeMap.put("doc", "application/msword");
// extensionContentTypeMap.put("docx", "application/msword");
// }
//
// public static boolean isValidFile(MultipartFile file, String[] fileTypeList) {
// String fileName = file.getOriginalFilename();
// String extension = getExtensionInLowerCase(fileName);
// for (String validFileType : fileTypeList) {
// if (extension.equalsIgnoreCase(validFileType)) {
// return true;
// }
// }
// return false;
// }
//
// public static String getContentType(String extension) {
// return extensionContentTypeMap.get(extension.toLowerCase());
// }
//
// public static String getExtensionInLowerCase(String fileName) {
// return FilenameUtils.getExtension(fileName).toLowerCase();
// }
//
// public static String getExtensionFromContentType(String contentType) {
// String key = "";
// for (Map.Entry<String, String> entry : extensionContentTypeMap.entrySet()) {
// if ((entry.getValue().equalsIgnoreCase(contentType))) {
// key = entry.getKey();
// }
// }
// return key;
// }
//
// /**
// * Get file name trimmed to FILE_NAME_MAX_SIZE and also extension to lower case (bcoz, people tend to have file in uppercase extension like JPG, jpg)
// *
// * @param fileName User's file name
// * @return
// */
// public static String getFilteredFileName(String fileName) {
// String extension = getExtensionInLowerCase(fileName);
// String baseName = FilenameUtils.getBaseName(fileName);
// baseName = baseName.replaceAll(" ", "-");
// return StringUtils.getTrimmedString(baseName, FILE_NAME_MAX_SIZE - extension.length()) + "." + extension;
// }
// }
// Path: src/main/java/org/jugbd/mnet/web/controller/PictureInformationController.java
import org.jugbd.mnet.dao.AttachmentDao;
import org.jugbd.mnet.domain.Attachment;
import org.jugbd.mnet.domain.PictureInformation;
import org.jugbd.mnet.domain.enums.PictureInformationType;
import org.jugbd.mnet.service.PictureInformationService;
import org.jugbd.mnet.service.RegisterService;
import org.jugbd.mnet.utils.Contestant;
import org.jugbd.mnet.utils.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import java.io.IOException;
RedirectAttributes redirectAttributes
) throws IOException {
log.debug("uploadPhoto() pictureInformationType ={}", pictureInformationType);
String errorMsg = validate(file, Contestant.VALID_FILE_TYPE_LIST, Contestant.FILE_MAX_SIZE_BYTES, "Photo");
if (!errorMsg.isEmpty()) {
redirectAttributes.addFlashAttribute("error", errorMsg);
return "picture/show";
}
pictureInformationService.upload(registerId, file, pictureInformationType, fileName, comment);
redirectAttributes.addFlashAttribute("message", "File successfully uploaded");
return "redirect:/picture/" + registerId;
}
@RequestMapping(value = "picture/delete/{registerId}/{attachmentId}", method = RequestMethod.POST)
public String remove(@PathVariable Long registerId, @PathVariable Long attachmentId) {
Attachment attachment = attachmentDao.findOne(attachmentId);
attachment.setDeleted(true);
attachmentDao.save(attachment);
return "redirect:/picture/" + registerId;
}
private String validate(MultipartFile file, String[] validFileTypes, int maxFileSize, String field) {
|
if (!FileUtils.isValidFile(file, validFileTypes)) {
|
mozammel/mNet
|
src/main/java/org/jugbd/mnet/service/ComplicationManagementService.java
|
// Path: src/main/java/org/jugbd/mnet/domain/ComplicationManagement.java
// @Entity
// public class ComplicationManagement extends PersistentObject implements Auditable {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Version
// private Long version;
//
// @NotEmpty
// @Size(max = 2000)
// private String postOperativeComplication;
//
// @Size(max = 2000)
// private String managementOfComplication;
//
// @NotNull
// @Column(length = 12)
// @Enumerated(EnumType.STRING)
// private Outcome outcome;
//
// @Size(max = 100)
// private String comment; // if others
//
// @NotNull
// private Integer hospitalStays;
//
// @Size(max = 2000)
// private String caseSummery;
//
// @JsonIgnore
// @OneToOne(mappedBy = "complicationManagement")
// private Register register;
//
// //backLink, in case this is removed
// @Column(name = "register_id_bklink")
// private Long registerId;
//
// @Override
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public Long getVersion() {
// return version;
// }
//
// public void setVersion(Long version) {
// this.version = version;
// }
//
// public String getPostOperativeComplication() {
// return postOperativeComplication;
// }
//
// public void setPostOperativeComplication(String postOperativeComplication) {
// this.postOperativeComplication = postOperativeComplication;
// }
//
// public String getManagementOfComplication() {
// return managementOfComplication;
// }
//
// public void setManagementOfComplication(String managementOfComplication) {
// this.managementOfComplication = managementOfComplication;
// }
//
// public Outcome getOutcome() {
// return outcome;
// }
//
// public void setOutcome(Outcome outcome) {
// this.outcome = outcome;
// }
//
// public String getComment() {
// return comment;
// }
//
// public void setComment(String comment) {
// this.comment = comment;
// }
//
// public Integer getHospitalStays() {
// return hospitalStays;
// }
//
// public void setHospitalStays(Integer hospitalStays) {
// this.hospitalStays = hospitalStays;
// }
//
// public String getCaseSummery() {
// return caseSummery;
// }
//
// public void setCaseSummery(String caseSummery) {
// this.caseSummery = caseSummery;
// }
//
// public Register getRegister() {
// return register;
// }
//
// public void setRegister(Register register) {
// this.register = register;
// }
//
// public Long getRegisterId() {
// return registerId;
// }
//
// public ComplicationManagement setRegisterId(Long registerId) {
// this.registerId = registerId;
// return this;
// }
// }
|
import org.jugbd.mnet.domain.ComplicationManagement;
import org.springframework.stereotype.Component;
|
package org.jugbd.mnet.service;
/**
* @author Bazlur Rahman Rokon
* @date 12/26/14.
*/
@Component
public interface ComplicationManagementService {
|
// Path: src/main/java/org/jugbd/mnet/domain/ComplicationManagement.java
// @Entity
// public class ComplicationManagement extends PersistentObject implements Auditable {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Version
// private Long version;
//
// @NotEmpty
// @Size(max = 2000)
// private String postOperativeComplication;
//
// @Size(max = 2000)
// private String managementOfComplication;
//
// @NotNull
// @Column(length = 12)
// @Enumerated(EnumType.STRING)
// private Outcome outcome;
//
// @Size(max = 100)
// private String comment; // if others
//
// @NotNull
// private Integer hospitalStays;
//
// @Size(max = 2000)
// private String caseSummery;
//
// @JsonIgnore
// @OneToOne(mappedBy = "complicationManagement")
// private Register register;
//
// //backLink, in case this is removed
// @Column(name = "register_id_bklink")
// private Long registerId;
//
// @Override
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public Long getVersion() {
// return version;
// }
//
// public void setVersion(Long version) {
// this.version = version;
// }
//
// public String getPostOperativeComplication() {
// return postOperativeComplication;
// }
//
// public void setPostOperativeComplication(String postOperativeComplication) {
// this.postOperativeComplication = postOperativeComplication;
// }
//
// public String getManagementOfComplication() {
// return managementOfComplication;
// }
//
// public void setManagementOfComplication(String managementOfComplication) {
// this.managementOfComplication = managementOfComplication;
// }
//
// public Outcome getOutcome() {
// return outcome;
// }
//
// public void setOutcome(Outcome outcome) {
// this.outcome = outcome;
// }
//
// public String getComment() {
// return comment;
// }
//
// public void setComment(String comment) {
// this.comment = comment;
// }
//
// public Integer getHospitalStays() {
// return hospitalStays;
// }
//
// public void setHospitalStays(Integer hospitalStays) {
// this.hospitalStays = hospitalStays;
// }
//
// public String getCaseSummery() {
// return caseSummery;
// }
//
// public void setCaseSummery(String caseSummery) {
// this.caseSummery = caseSummery;
// }
//
// public Register getRegister() {
// return register;
// }
//
// public void setRegister(Register register) {
// this.register = register;
// }
//
// public Long getRegisterId() {
// return registerId;
// }
//
// public ComplicationManagement setRegisterId(Long registerId) {
// this.registerId = registerId;
// return this;
// }
// }
// Path: src/main/java/org/jugbd/mnet/service/ComplicationManagementService.java
import org.jugbd.mnet.domain.ComplicationManagement;
import org.springframework.stereotype.Component;
package org.jugbd.mnet.service;
/**
* @author Bazlur Rahman Rokon
* @date 12/26/14.
*/
@Component
public interface ComplicationManagementService {
|
ComplicationManagement save(ComplicationManagement complicationManagement);
|
mozammel/mNet
|
src/main/java/org/jugbd/mnet/web/controller/DiagnosisController.java
|
// Path: src/main/java/org/jugbd/mnet/service/DiagnosisService.java
// @Component
// public interface DiagnosisService {
// Diagnosis save(Diagnosis diagnosis);
//
// Diagnosis findOne(Long id);
//
// Diagnosis save(Diagnosis diagnosis, RegistrationType registrationType);
// }
|
import org.jugbd.mnet.domain.Diagnosis;
import org.jugbd.mnet.domain.enums.RegistrationType;
import org.jugbd.mnet.service.DiagnosisService;
import org.jugbd.mnet.service.RegisterService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.validation.Valid;
|
package org.jugbd.mnet.web.controller;
/**
* @author Mushfekur Rahman (mushfek0001)
*/
@Controller
@Secured({"ROLE_ADMIN", "ROLE_USER"})
@RequestMapping("/diagnosis")
public class DiagnosisController {
private static final Logger log = LoggerFactory.getLogger(DiagnosisController.class);
public static final String REDIRECT_REGISTER_DIAGNOSIS = "redirect:/register/diagnosis/";
@Autowired
|
// Path: src/main/java/org/jugbd/mnet/service/DiagnosisService.java
// @Component
// public interface DiagnosisService {
// Diagnosis save(Diagnosis diagnosis);
//
// Diagnosis findOne(Long id);
//
// Diagnosis save(Diagnosis diagnosis, RegistrationType registrationType);
// }
// Path: src/main/java/org/jugbd/mnet/web/controller/DiagnosisController.java
import org.jugbd.mnet.domain.Diagnosis;
import org.jugbd.mnet.domain.enums.RegistrationType;
import org.jugbd.mnet.service.DiagnosisService;
import org.jugbd.mnet.service.RegisterService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.validation.Valid;
package org.jugbd.mnet.web.controller;
/**
* @author Mushfekur Rahman (mushfek0001)
*/
@Controller
@Secured({"ROLE_ADMIN", "ROLE_USER"})
@RequestMapping("/diagnosis")
public class DiagnosisController {
private static final Logger log = LoggerFactory.getLogger(DiagnosisController.class);
public static final String REDIRECT_REGISTER_DIAGNOSIS = "redirect:/register/diagnosis/";
@Autowired
|
private DiagnosisService diagnosisService;
|
mozammel/mNet
|
src/main/java/org/jugbd/mnet/service/PictureInformationService.java
|
// Path: src/main/java/org/jugbd/mnet/domain/enums/PictureInformationType.java
// public enum PictureInformationType {
//
// DAY_ONE("Day One"),
//
// PREOPERATIVE("Pre-operative"),
//
// PRE_OPERATION("Pre-operation"),
//
// POSTOPERATIVE("Post operative"),
//
// ON_DISCHARGE("On Discharge");
//
// private String label;
//
// PictureInformationType(String label) {
// this.label = label;
// }
//
// public String getLabel() {
// return label;
// }
//
// }
|
import org.jugbd.mnet.domain.PictureInformation;
import org.jugbd.mnet.domain.enums.PictureInformationType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
|
package org.jugbd.mnet.service;
/**
* @author Bazlur Rahman Rokon
* @date 12/27/14.
*/
@Component
public interface PictureInformationService {
PictureInformation save(PictureInformation pictureInformation);
PictureInformation findOne(Long id);
|
// Path: src/main/java/org/jugbd/mnet/domain/enums/PictureInformationType.java
// public enum PictureInformationType {
//
// DAY_ONE("Day One"),
//
// PREOPERATIVE("Pre-operative"),
//
// PRE_OPERATION("Pre-operation"),
//
// POSTOPERATIVE("Post operative"),
//
// ON_DISCHARGE("On Discharge");
//
// private String label;
//
// PictureInformationType(String label) {
// this.label = label;
// }
//
// public String getLabel() {
// return label;
// }
//
// }
// Path: src/main/java/org/jugbd/mnet/service/PictureInformationService.java
import org.jugbd.mnet.domain.PictureInformation;
import org.jugbd.mnet.domain.enums.PictureInformationType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
package org.jugbd.mnet.service;
/**
* @author Bazlur Rahman Rokon
* @date 12/27/14.
*/
@Component
public interface PictureInformationService {
PictureInformation save(PictureInformation pictureInformation);
PictureInformation findOne(Long id);
|
void upload(Long registerId, MultipartFile file, PictureInformationType pictureInformationType, String fileName, String comment);
|
kevinbayes/vest
|
src/test/java/me/bayes/vertx/vest/TestJaxrsToVertxPathConverter.java
|
// Path: src/main/java/me/bayes/vertx/vest/util/UriPathUtil.java
// public final class UriPathUtil {
//
// private UriPathUtil() { }
//
//
// /**
// * Retrieve the context from the provided {@link Application}'s {@link ApplicationPath}.
// *
// * @param application with a {@link ApplicationPath} annotation.
// * @return String of the path.
// */
// public static String getApplicationContext(Application application) {
//
// final Class<?> clazz = application.getClass();
// final ApplicationPath applicationPath = clazz.getAnnotation(ApplicationPath.class);
//
// String path = (applicationPath == null) ? "/" :
// applicationPath.value();
//
// if(path.length() < 1) {
// return "/";
// } else {
// return path.charAt(0) == '/' ? path : "/" + path;
// }
// }
//
//
// /**
// * Concat paths to a single one in the form of parent/child.
// *
// * @param parent
// * @param child
// * @return a url in {@link String} form.
// */
// public static String concatPaths(String parent, String child) {
//
// if(parent.endsWith("/") ^ child.startsWith("/")) {
// return parent + child;
// } else if(!parent.endsWith("/") && !child.startsWith("/")) {
// return parent + "/" + child;
// } else if(parent.endsWith("/") && child.startsWith("/")) {
// return parent + child.substring(1);
// } else {
// return (parent + child).replaceAll("//", "/");
// }
//
// }
//
//
// /**
// * Taken path declared in a {@link javax.ws.rs.Path} annotation and replaces it with
// * a vertx compliant path.
// *
// * http://vertx.io/core_manual_java.html#extracting-parameters-from-the-path
// *
// * WARNING: This current approach removes the regular expression validations of
// * the path parameters.
// *
// * @param path - URI of the service
// * @return vertx path as string
// */
// public static String convertPath(String path) {
//
// final StringBuilder newPath = new StringBuilder();
//
// boolean foundPathVariable = false;
// boolean foundRegularExpression = false;
//
// for(int i = 0; i < path.length(); i++) {
// char currentCharacter = path.charAt(i);
//
// if(currentCharacter == '{') {
// foundPathVariable = true;
// newPath.append(":");
// } else if(currentCharacter == '}') {
// foundPathVariable = false;
// foundRegularExpression = false;
// } else if(foundPathVariable && currentCharacter == ':') {
// foundRegularExpression = true;
// } else if(foundPathVariable && (foundRegularExpression ||
// currentCharacter == ' ')) {
// continue;
// } else if(i == path.length() - 1 && currentCharacter == '/') {
// continue;
// } else {
// newPath.append(currentCharacter);
// }
// }
//
// return newPath.toString();
//
// }
//
// }
|
import static org.junit.Assert.*;
import me.bayes.vertx.vest.util.UriPathUtil;
import org.junit.Test;
|
/**
* Copyright 2013 Bayes Technologies
*
* 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 me.bayes.vertx.vest;
public class TestJaxrsToVertxPathConverter {
@Test
public void testConvertPathWithVariable() {
//given
String path = "/username/{username : [a-zA-Z][a-zA-Z_0-9]}";
String expected = "/username/:username";
//when
|
// Path: src/main/java/me/bayes/vertx/vest/util/UriPathUtil.java
// public final class UriPathUtil {
//
// private UriPathUtil() { }
//
//
// /**
// * Retrieve the context from the provided {@link Application}'s {@link ApplicationPath}.
// *
// * @param application with a {@link ApplicationPath} annotation.
// * @return String of the path.
// */
// public static String getApplicationContext(Application application) {
//
// final Class<?> clazz = application.getClass();
// final ApplicationPath applicationPath = clazz.getAnnotation(ApplicationPath.class);
//
// String path = (applicationPath == null) ? "/" :
// applicationPath.value();
//
// if(path.length() < 1) {
// return "/";
// } else {
// return path.charAt(0) == '/' ? path : "/" + path;
// }
// }
//
//
// /**
// * Concat paths to a single one in the form of parent/child.
// *
// * @param parent
// * @param child
// * @return a url in {@link String} form.
// */
// public static String concatPaths(String parent, String child) {
//
// if(parent.endsWith("/") ^ child.startsWith("/")) {
// return parent + child;
// } else if(!parent.endsWith("/") && !child.startsWith("/")) {
// return parent + "/" + child;
// } else if(parent.endsWith("/") && child.startsWith("/")) {
// return parent + child.substring(1);
// } else {
// return (parent + child).replaceAll("//", "/");
// }
//
// }
//
//
// /**
// * Taken path declared in a {@link javax.ws.rs.Path} annotation and replaces it with
// * a vertx compliant path.
// *
// * http://vertx.io/core_manual_java.html#extracting-parameters-from-the-path
// *
// * WARNING: This current approach removes the regular expression validations of
// * the path parameters.
// *
// * @param path - URI of the service
// * @return vertx path as string
// */
// public static String convertPath(String path) {
//
// final StringBuilder newPath = new StringBuilder();
//
// boolean foundPathVariable = false;
// boolean foundRegularExpression = false;
//
// for(int i = 0; i < path.length(); i++) {
// char currentCharacter = path.charAt(i);
//
// if(currentCharacter == '{') {
// foundPathVariable = true;
// newPath.append(":");
// } else if(currentCharacter == '}') {
// foundPathVariable = false;
// foundRegularExpression = false;
// } else if(foundPathVariable && currentCharacter == ':') {
// foundRegularExpression = true;
// } else if(foundPathVariable && (foundRegularExpression ||
// currentCharacter == ' ')) {
// continue;
// } else if(i == path.length() - 1 && currentCharacter == '/') {
// continue;
// } else {
// newPath.append(currentCharacter);
// }
// }
//
// return newPath.toString();
//
// }
//
// }
// Path: src/test/java/me/bayes/vertx/vest/TestJaxrsToVertxPathConverter.java
import static org.junit.Assert.*;
import me.bayes.vertx.vest.util.UriPathUtil;
import org.junit.Test;
/**
* Copyright 2013 Bayes Technologies
*
* 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 me.bayes.vertx.vest;
public class TestJaxrsToVertxPathConverter {
@Test
public void testConvertPathWithVariable() {
//given
String path = "/username/{username : [a-zA-Z][a-zA-Z_0-9]}";
String expected = "/username/:username";
//when
|
String result = UriPathUtil.convertPath(path);
|
kevinbayes/vest
|
src/test/java/me/bayes/vertx/vest/deploy/VestVerticleTest.java
|
// Path: src/main/java/me/bayes/vertx/vest/deploy/VestVerticle.java
// public class VestVerticle extends AbstractVestVerticle {
//
// public VestApplication createApplication(final JsonObject config) throws Exception {
//
// final JsonArray vestPackagesToScan = config.getJsonArray("vestPackagesToScan");
// final JsonArray vestClasses = config.getJsonArray("vestClasses");
// final String applicationClass = config.getString("applicationClass", "me.bayes.vertx.vest.deploy.RootContextVestApplication");
// final VestApplication application = (VestApplication) Class.forName(applicationClass).newInstance();
//
// //Add packages to scan
// if(vestPackagesToScan != null) {
// for(Object obj : vestPackagesToScan) {
// application.addPackagesToScan(String.valueOf(obj));
// }
// }
//
// //Add classes
// if(vestClasses != null) {
// for(Object obj : vestClasses) {
// Class<?> clazz = Class.forName((String)obj);
// application.addEndpointClasses(clazz);
// }
// }
//
// application.addSingleton(vertx);
// if(vertx != null) {
// application.addSingleton(vertx.getOrCreateContext());
// application.addSingleton(vertx.getOrCreateContext().config());
// }
//
// return application;
// }
//
//
// public RouterBuilder createBuilder(VestApplication application)
// throws Exception {
// return new DefaultRouterBuilder(application);
// }
//
// }
//
// Path: src/test/java/me/bayes/vertx/vest/sample/PingEndpoint.java
// @Path("/ping")
// public class PingEndpoint {
//
// @GET
// public void get() {
// System.out.println("Hello");
// }
//
// }
|
import static org.junit.Assert.*;
import javax.ws.rs.core.Application;
import io.vertx.core.json.JsonObject;
import me.bayes.vertx.vest.deploy.VestVerticle;
import me.bayes.vertx.vest.sample.PingEndpoint;
import org.junit.Before;
import org.junit.Test;
|
/**
* Copyright 2013 Bayes Technologies
*
* 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 me.bayes.vertx.vest.deploy;
/**
* @author kevinbayes
*
*/
public class VestVerticleTest {
private static final String JSON_CONFIG_PACKAGES_TO_SCAN = "{\"vestPackagesToScan\":[\"me.bayes.vertx.vest.sample\"]}";
private static final String JSON_CONFIG_CLASSES_TO_ADD = "{\"vestClasses\":[\"me.bayes.vertx.vest.sample.PingEndpoint\"]}";
|
// Path: src/main/java/me/bayes/vertx/vest/deploy/VestVerticle.java
// public class VestVerticle extends AbstractVestVerticle {
//
// public VestApplication createApplication(final JsonObject config) throws Exception {
//
// final JsonArray vestPackagesToScan = config.getJsonArray("vestPackagesToScan");
// final JsonArray vestClasses = config.getJsonArray("vestClasses");
// final String applicationClass = config.getString("applicationClass", "me.bayes.vertx.vest.deploy.RootContextVestApplication");
// final VestApplication application = (VestApplication) Class.forName(applicationClass).newInstance();
//
// //Add packages to scan
// if(vestPackagesToScan != null) {
// for(Object obj : vestPackagesToScan) {
// application.addPackagesToScan(String.valueOf(obj));
// }
// }
//
// //Add classes
// if(vestClasses != null) {
// for(Object obj : vestClasses) {
// Class<?> clazz = Class.forName((String)obj);
// application.addEndpointClasses(clazz);
// }
// }
//
// application.addSingleton(vertx);
// if(vertx != null) {
// application.addSingleton(vertx.getOrCreateContext());
// application.addSingleton(vertx.getOrCreateContext().config());
// }
//
// return application;
// }
//
//
// public RouterBuilder createBuilder(VestApplication application)
// throws Exception {
// return new DefaultRouterBuilder(application);
// }
//
// }
//
// Path: src/test/java/me/bayes/vertx/vest/sample/PingEndpoint.java
// @Path("/ping")
// public class PingEndpoint {
//
// @GET
// public void get() {
// System.out.println("Hello");
// }
//
// }
// Path: src/test/java/me/bayes/vertx/vest/deploy/VestVerticleTest.java
import static org.junit.Assert.*;
import javax.ws.rs.core.Application;
import io.vertx.core.json.JsonObject;
import me.bayes.vertx.vest.deploy.VestVerticle;
import me.bayes.vertx.vest.sample.PingEndpoint;
import org.junit.Before;
import org.junit.Test;
/**
* Copyright 2013 Bayes Technologies
*
* 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 me.bayes.vertx.vest.deploy;
/**
* @author kevinbayes
*
*/
public class VestVerticleTest {
private static final String JSON_CONFIG_PACKAGES_TO_SCAN = "{\"vestPackagesToScan\":[\"me.bayes.vertx.vest.sample\"]}";
private static final String JSON_CONFIG_CLASSES_TO_ADD = "{\"vestClasses\":[\"me.bayes.vertx.vest.sample.PingEndpoint\"]}";
|
private VestVerticle vestVerticle;
|
kevinbayes/vest
|
src/test/java/me/bayes/vertx/vest/deploy/VestVerticleTest.java
|
// Path: src/main/java/me/bayes/vertx/vest/deploy/VestVerticle.java
// public class VestVerticle extends AbstractVestVerticle {
//
// public VestApplication createApplication(final JsonObject config) throws Exception {
//
// final JsonArray vestPackagesToScan = config.getJsonArray("vestPackagesToScan");
// final JsonArray vestClasses = config.getJsonArray("vestClasses");
// final String applicationClass = config.getString("applicationClass", "me.bayes.vertx.vest.deploy.RootContextVestApplication");
// final VestApplication application = (VestApplication) Class.forName(applicationClass).newInstance();
//
// //Add packages to scan
// if(vestPackagesToScan != null) {
// for(Object obj : vestPackagesToScan) {
// application.addPackagesToScan(String.valueOf(obj));
// }
// }
//
// //Add classes
// if(vestClasses != null) {
// for(Object obj : vestClasses) {
// Class<?> clazz = Class.forName((String)obj);
// application.addEndpointClasses(clazz);
// }
// }
//
// application.addSingleton(vertx);
// if(vertx != null) {
// application.addSingleton(vertx.getOrCreateContext());
// application.addSingleton(vertx.getOrCreateContext().config());
// }
//
// return application;
// }
//
//
// public RouterBuilder createBuilder(VestApplication application)
// throws Exception {
// return new DefaultRouterBuilder(application);
// }
//
// }
//
// Path: src/test/java/me/bayes/vertx/vest/sample/PingEndpoint.java
// @Path("/ping")
// public class PingEndpoint {
//
// @GET
// public void get() {
// System.out.println("Hello");
// }
//
// }
|
import static org.junit.Assert.*;
import javax.ws.rs.core.Application;
import io.vertx.core.json.JsonObject;
import me.bayes.vertx.vest.deploy.VestVerticle;
import me.bayes.vertx.vest.sample.PingEndpoint;
import org.junit.Before;
import org.junit.Test;
|
/**
* Copyright 2013 Bayes Technologies
*
* 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 me.bayes.vertx.vest.deploy;
/**
* @author kevinbayes
*
*/
public class VestVerticleTest {
private static final String JSON_CONFIG_PACKAGES_TO_SCAN = "{\"vestPackagesToScan\":[\"me.bayes.vertx.vest.sample\"]}";
private static final String JSON_CONFIG_CLASSES_TO_ADD = "{\"vestClasses\":[\"me.bayes.vertx.vest.sample.PingEndpoint\"]}";
private VestVerticle vestVerticle;
@Before
public void setUp() {
vestVerticle = new VestVerticle();
}
/**
* Test method for {@link me.bayes.vertx.vest.deploy.VestVerticle#createApplication(org.vertx.java.core.json.JsonObject)}.
*/
@Test
public void testCreateApplicationWithPackageScan() {
//Given
JsonObject config = new JsonObject(JSON_CONFIG_PACKAGES_TO_SCAN);
Application application = null;
try {
//When
application = vestVerticle.createApplication(config);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
if(application == null) {
fail("Application not initialized.");
}
//Then
assertTrue(application.getClasses().size() == 1);
|
// Path: src/main/java/me/bayes/vertx/vest/deploy/VestVerticle.java
// public class VestVerticle extends AbstractVestVerticle {
//
// public VestApplication createApplication(final JsonObject config) throws Exception {
//
// final JsonArray vestPackagesToScan = config.getJsonArray("vestPackagesToScan");
// final JsonArray vestClasses = config.getJsonArray("vestClasses");
// final String applicationClass = config.getString("applicationClass", "me.bayes.vertx.vest.deploy.RootContextVestApplication");
// final VestApplication application = (VestApplication) Class.forName(applicationClass).newInstance();
//
// //Add packages to scan
// if(vestPackagesToScan != null) {
// for(Object obj : vestPackagesToScan) {
// application.addPackagesToScan(String.valueOf(obj));
// }
// }
//
// //Add classes
// if(vestClasses != null) {
// for(Object obj : vestClasses) {
// Class<?> clazz = Class.forName((String)obj);
// application.addEndpointClasses(clazz);
// }
// }
//
// application.addSingleton(vertx);
// if(vertx != null) {
// application.addSingleton(vertx.getOrCreateContext());
// application.addSingleton(vertx.getOrCreateContext().config());
// }
//
// return application;
// }
//
//
// public RouterBuilder createBuilder(VestApplication application)
// throws Exception {
// return new DefaultRouterBuilder(application);
// }
//
// }
//
// Path: src/test/java/me/bayes/vertx/vest/sample/PingEndpoint.java
// @Path("/ping")
// public class PingEndpoint {
//
// @GET
// public void get() {
// System.out.println("Hello");
// }
//
// }
// Path: src/test/java/me/bayes/vertx/vest/deploy/VestVerticleTest.java
import static org.junit.Assert.*;
import javax.ws.rs.core.Application;
import io.vertx.core.json.JsonObject;
import me.bayes.vertx.vest.deploy.VestVerticle;
import me.bayes.vertx.vest.sample.PingEndpoint;
import org.junit.Before;
import org.junit.Test;
/**
* Copyright 2013 Bayes Technologies
*
* 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 me.bayes.vertx.vest.deploy;
/**
* @author kevinbayes
*
*/
public class VestVerticleTest {
private static final String JSON_CONFIG_PACKAGES_TO_SCAN = "{\"vestPackagesToScan\":[\"me.bayes.vertx.vest.sample\"]}";
private static final String JSON_CONFIG_CLASSES_TO_ADD = "{\"vestClasses\":[\"me.bayes.vertx.vest.sample.PingEndpoint\"]}";
private VestVerticle vestVerticle;
@Before
public void setUp() {
vestVerticle = new VestVerticle();
}
/**
* Test method for {@link me.bayes.vertx.vest.deploy.VestVerticle#createApplication(org.vertx.java.core.json.JsonObject)}.
*/
@Test
public void testCreateApplicationWithPackageScan() {
//Given
JsonObject config = new JsonObject(JSON_CONFIG_PACKAGES_TO_SCAN);
Application application = null;
try {
//When
application = vestVerticle.createApplication(config);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
if(application == null) {
fail("Application not initialized.");
}
//Then
assertTrue(application.getClasses().size() == 1);
|
assertTrue(application.getClasses().contains(PingEndpoint.class));
|
jefalbino/jsmart-web
|
src/main/java/com/jsmartframework/web/tag/ValidateTagHandler.java
|
// Path: src/main/java/com/jsmartframework/web/tag/type/Look.java
// public enum Look {
//
// DEFAULT,
// PRIMARY,
// SUCCESS,
// INFO,
// WARNING,
// DANGER,
// MUTED,
// LINK,
// ERROR;
//
// public static boolean validate(String look) {
// try {
// Look.valueOf(look.toUpperCase());
// return true;
// } catch (Exception e) {
// return false;
// }
// }
//
// public static boolean validateValidate(String look) {
// return SUCCESS.equalsIgnoreCase(look) || WARNING.equalsIgnoreCase(look)
// || ERROR.equalsIgnoreCase(look);
// }
//
// public static boolean validateBasic(String look) {
// return SUCCESS.equalsIgnoreCase(look) || INFO.equalsIgnoreCase(look)
// || WARNING.equalsIgnoreCase(look) || DANGER.equalsIgnoreCase(look);
// }
//
// public static boolean validateLook(String look) {
// return DEFAULT.equalsIgnoreCase(look) || PRIMARY.equalsIgnoreCase(look)
// || SUCCESS.equalsIgnoreCase(look) || INFO.equalsIgnoreCase(look)
// || WARNING.equalsIgnoreCase(look) || DANGER.equalsIgnoreCase(look);
// }
//
// public static boolean validateButton(String look) {
// return validateLook(look) || LINK.equalsIgnoreCase(look);
// }
//
// public static boolean validateText(String look) {
// return validateLook(look) || MUTED.equalsIgnoreCase(look);
// }
//
// public static String[] getValues() {
// int index = 0;
// Look[] looks = values();
// String[] values = new String[looks.length];
//
// for (Look look : looks) {
// values[index++] = look.name().toLowerCase();
// }
// return values;
// }
//
// public static String[] getButtonValues() {
// String[] values = new String[7];
// values[0] = DEFAULT.name().toLowerCase();
// values[1] = PRIMARY.name().toLowerCase();
// values[2] = SUCCESS.name().toLowerCase();
// values[3] = INFO.name().toLowerCase();
// values[4] = WARNING.name().toLowerCase();
// values[5] = DANGER.name().toLowerCase();
// values[6] = LINK.name().toLowerCase();
// return values;
// }
//
// public static String[] getBasicValues() {
// String[] values = new String[4];
// values[0] = SUCCESS.name().toLowerCase();
// values[1] = INFO.name().toLowerCase();
// values[2] = WARNING.name().toLowerCase();
// values[3] = DANGER.name().toLowerCase();
// return values;
// }
//
// public static String[] getValidateValues() {
// String[] values = new String[3];
// values[0] = SUCCESS.name().toLowerCase();
// values[1] = WARNING.name().toLowerCase();
// values[2] = ERROR.name().toLowerCase();
// return values;
// }
//
// public static String[] getLookValues() {
// String[] values = new String[6];
// values[0] = DEFAULT.name().toLowerCase();
// values[1] = PRIMARY.name().toLowerCase();
// values[2] = SUCCESS.name().toLowerCase();
// values[3] = INFO.name().toLowerCase();
// values[4] = WARNING.name().toLowerCase();
// values[5] = DANGER.name().toLowerCase();
// return values;
// }
//
// public static String[] getTextValues() {
// String[] values = new String[7];
// values[0] = DEFAULT.name().toLowerCase();
// values[1] = PRIMARY.name().toLowerCase();
// values[2] = SUCCESS.name().toLowerCase();
// values[3] = INFO.name().toLowerCase();
// values[4] = WARNING.name().toLowerCase();
// values[5] = DANGER.name().toLowerCase();
// values[5] = MUTED.name().toLowerCase();
// return values;
// }
//
// public boolean equalsIgnoreCase(String string) {
// return this.name().equalsIgnoreCase(string);
// }
// }
|
import com.jsmartframework.web.exception.InvalidAttributeException;
import com.jsmartframework.web.manager.TagHandler;
import com.jsmartframework.web.tag.html.Tag;
import com.jsmartframework.web.tag.type.Look;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.JspTag;
|
/*
* JSmart Framework - Java Web Development Framework
* Copyright (c) 2015, Jeferson Albino da Silva, All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3.0 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jsmartframework.web.tag;
public final class ValidateTagHandler extends TagHandler {
private String text;
private String maxLength;
private Integer minLength;
private String regex;
|
// Path: src/main/java/com/jsmartframework/web/tag/type/Look.java
// public enum Look {
//
// DEFAULT,
// PRIMARY,
// SUCCESS,
// INFO,
// WARNING,
// DANGER,
// MUTED,
// LINK,
// ERROR;
//
// public static boolean validate(String look) {
// try {
// Look.valueOf(look.toUpperCase());
// return true;
// } catch (Exception e) {
// return false;
// }
// }
//
// public static boolean validateValidate(String look) {
// return SUCCESS.equalsIgnoreCase(look) || WARNING.equalsIgnoreCase(look)
// || ERROR.equalsIgnoreCase(look);
// }
//
// public static boolean validateBasic(String look) {
// return SUCCESS.equalsIgnoreCase(look) || INFO.equalsIgnoreCase(look)
// || WARNING.equalsIgnoreCase(look) || DANGER.equalsIgnoreCase(look);
// }
//
// public static boolean validateLook(String look) {
// return DEFAULT.equalsIgnoreCase(look) || PRIMARY.equalsIgnoreCase(look)
// || SUCCESS.equalsIgnoreCase(look) || INFO.equalsIgnoreCase(look)
// || WARNING.equalsIgnoreCase(look) || DANGER.equalsIgnoreCase(look);
// }
//
// public static boolean validateButton(String look) {
// return validateLook(look) || LINK.equalsIgnoreCase(look);
// }
//
// public static boolean validateText(String look) {
// return validateLook(look) || MUTED.equalsIgnoreCase(look);
// }
//
// public static String[] getValues() {
// int index = 0;
// Look[] looks = values();
// String[] values = new String[looks.length];
//
// for (Look look : looks) {
// values[index++] = look.name().toLowerCase();
// }
// return values;
// }
//
// public static String[] getButtonValues() {
// String[] values = new String[7];
// values[0] = DEFAULT.name().toLowerCase();
// values[1] = PRIMARY.name().toLowerCase();
// values[2] = SUCCESS.name().toLowerCase();
// values[3] = INFO.name().toLowerCase();
// values[4] = WARNING.name().toLowerCase();
// values[5] = DANGER.name().toLowerCase();
// values[6] = LINK.name().toLowerCase();
// return values;
// }
//
// public static String[] getBasicValues() {
// String[] values = new String[4];
// values[0] = SUCCESS.name().toLowerCase();
// values[1] = INFO.name().toLowerCase();
// values[2] = WARNING.name().toLowerCase();
// values[3] = DANGER.name().toLowerCase();
// return values;
// }
//
// public static String[] getValidateValues() {
// String[] values = new String[3];
// values[0] = SUCCESS.name().toLowerCase();
// values[1] = WARNING.name().toLowerCase();
// values[2] = ERROR.name().toLowerCase();
// return values;
// }
//
// public static String[] getLookValues() {
// String[] values = new String[6];
// values[0] = DEFAULT.name().toLowerCase();
// values[1] = PRIMARY.name().toLowerCase();
// values[2] = SUCCESS.name().toLowerCase();
// values[3] = INFO.name().toLowerCase();
// values[4] = WARNING.name().toLowerCase();
// values[5] = DANGER.name().toLowerCase();
// return values;
// }
//
// public static String[] getTextValues() {
// String[] values = new String[7];
// values[0] = DEFAULT.name().toLowerCase();
// values[1] = PRIMARY.name().toLowerCase();
// values[2] = SUCCESS.name().toLowerCase();
// values[3] = INFO.name().toLowerCase();
// values[4] = WARNING.name().toLowerCase();
// values[5] = DANGER.name().toLowerCase();
// values[5] = MUTED.name().toLowerCase();
// return values;
// }
//
// public boolean equalsIgnoreCase(String string) {
// return this.name().equalsIgnoreCase(string);
// }
// }
// Path: src/main/java/com/jsmartframework/web/tag/ValidateTagHandler.java
import com.jsmartframework.web.exception.InvalidAttributeException;
import com.jsmartframework.web.manager.TagHandler;
import com.jsmartframework.web.tag.html.Tag;
import com.jsmartframework.web.tag.type.Look;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.JspTag;
/*
* JSmart Framework - Java Web Development Framework
* Copyright (c) 2015, Jeferson Albino da Silva, All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3.0 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jsmartframework.web.tag;
public final class ValidateTagHandler extends TagHandler {
private String text;
private String maxLength;
private Integer minLength;
private String regex;
|
private String look = Look.ERROR.name().toLowerCase();
|
http-builder-ng/http-builder-ng
|
http-builder-ng-core/src/main/java/groovyx/net/http/optional/Jackson.java
|
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/NativeHandlers.java
// public static boolean handleRawUpload(final ChainedHttpConfig config, final ToServer ts) {
// final ChainedHttpConfig.ChainedRequest request = config.getChainedRequest();
// final Object body = request.actualBody();
// final Charset charset = request.actualCharset();
//
// try {
// if (body instanceof File) {
// ts.toServer(new FileInputStream((File) body));
// return true;
// } else if (body instanceof Path) {
// ts.toServer(Files.newInputStream((Path) body));
// return true;
// } else if (body instanceof byte[]) {
// ts.toServer(new ByteArrayInputStream((byte[]) body));
// return true;
// } else if (body instanceof InputStream) {
// ts.toServer((InputStream) body);
// return true;
// } else if (body instanceof Reader) {
// ts.toServer(new ReaderInputStream((Reader) body, charset));
// return true;
// } else {
// return false;
// }
// } catch (IOException e) {
// throw new TransportingException(e);
// }
// }
|
import com.fasterxml.jackson.databind.ObjectMapper;
import groovyx.net.http.*;
import java.io.IOException;
import java.io.StringWriter;
import static groovyx.net.http.NativeHandlers.Encoders.handleRawUpload;
|
/**
* Copyright (C) 2017 HttpBuilder-NG Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package groovyx.net.http.optional;
/**
* Parser and Encoder methods for handling JSON content using the https://github.com/FasterXML/jackson[Jackson] JSON library.
*/
public class Jackson {
static final String OBJECT_MAPPER_ID = "0w4XJJnlTNK8dvISuCDTlsusPQE=";
/**
* Used to parse the server response content using the Jackson JSON parser.
*
* @param config the configuration
* @param fromServer the server content accessor
* @return the parsed object
*/
@SuppressWarnings("WeakerAccess")
public static Object parse(final ChainedHttpConfig config, final FromServer fromServer) {
try {
final ObjectMapper mapper = (ObjectMapper) config.actualContext(fromServer.getContentType(), OBJECT_MAPPER_ID);
return mapper.readValue(fromServer.getReader(), config.getChainedResponse().getType());
} catch (IOException e) {
throw new TransportingException(e);
}
}
/**
* Used to encode the request content using the Jackson JSON encoder.
*
* @param config the configuration
* @param ts the server request content accessor
*/
@SuppressWarnings("WeakerAccess")
public static void encode(final ChainedHttpConfig config, final ToServer ts) {
try {
|
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/NativeHandlers.java
// public static boolean handleRawUpload(final ChainedHttpConfig config, final ToServer ts) {
// final ChainedHttpConfig.ChainedRequest request = config.getChainedRequest();
// final Object body = request.actualBody();
// final Charset charset = request.actualCharset();
//
// try {
// if (body instanceof File) {
// ts.toServer(new FileInputStream((File) body));
// return true;
// } else if (body instanceof Path) {
// ts.toServer(Files.newInputStream((Path) body));
// return true;
// } else if (body instanceof byte[]) {
// ts.toServer(new ByteArrayInputStream((byte[]) body));
// return true;
// } else if (body instanceof InputStream) {
// ts.toServer((InputStream) body);
// return true;
// } else if (body instanceof Reader) {
// ts.toServer(new ReaderInputStream((Reader) body, charset));
// return true;
// } else {
// return false;
// }
// } catch (IOException e) {
// throw new TransportingException(e);
// }
// }
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/optional/Jackson.java
import com.fasterxml.jackson.databind.ObjectMapper;
import groovyx.net.http.*;
import java.io.IOException;
import java.io.StringWriter;
import static groovyx.net.http.NativeHandlers.Encoders.handleRawUpload;
/**
* Copyright (C) 2017 HttpBuilder-NG Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package groovyx.net.http.optional;
/**
* Parser and Encoder methods for handling JSON content using the https://github.com/FasterXML/jackson[Jackson] JSON library.
*/
public class Jackson {
static final String OBJECT_MAPPER_ID = "0w4XJJnlTNK8dvISuCDTlsusPQE=";
/**
* Used to parse the server response content using the Jackson JSON parser.
*
* @param config the configuration
* @param fromServer the server content accessor
* @return the parsed object
*/
@SuppressWarnings("WeakerAccess")
public static Object parse(final ChainedHttpConfig config, final FromServer fromServer) {
try {
final ObjectMapper mapper = (ObjectMapper) config.actualContext(fromServer.getContentType(), OBJECT_MAPPER_ID);
return mapper.readValue(fromServer.getReader(), config.getChainedResponse().getType());
} catch (IOException e) {
throw new TransportingException(e);
}
}
/**
* Used to encode the request content using the Jackson JSON encoder.
*
* @param config the configuration
* @param ts the server request content accessor
*/
@SuppressWarnings("WeakerAccess")
public static void encode(final ChainedHttpConfig config, final ToServer ts) {
try {
|
if (handleRawUpload(config, ts)) {
|
http-builder-ng/http-builder-ng
|
http-builder-ng-core/src/main/java/groovyx/net/http/UriBuilder.java
|
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/Traverser.java
// public static <V> Predicate<V> notValue(final V v) { return (toTest) -> !v.equals(toTest); }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/Traverser.java
// public static <T,V> V traverse(final T target, final Function<T,T> next,
// final Function<T,V> getValue, final Predicate<V> testValue) {
// final V v = getValue.apply(target);
// if(testValue.test(v)) {
// return v;
// }
//
// final T nextTarget = next.apply(target);
// if(nextTarget != null) {
// return traverse(nextTarget, next, getValue, testValue);
// }
//
// return null;
// }
|
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Collections.singletonList;
import groovy.lang.GString;
import org.codehaus.groovy.runtime.GStringImpl;
import java.io.IOException;
import java.net.HttpCookie;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static groovyx.net.http.Traverser.notValue;
import static groovyx.net.http.Traverser.traverse;
import static java.lang.String.format;
|
/**
* Copyright (C) 2017 HttpBuilder-NG Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package groovyx.net.http;
/**
* Provides a simple means of creating a request URI and optionally overriding its parts.
*
* [source,groovy]
* ----
* def uri = UriBuilder.basic(UriBuilder.root())
* .setFull('http://localhost:10101')
* .setPath('/foo')
* .toURI()
* ----
*
* Generally, this class is not instantiated directly, but created by the {@link HttpConfig} instance and modified.
*/
public abstract class UriBuilder {
public static final int DEFAULT_PORT = -1;
/**
* Sets the scheme part of the URI.
*
* @param val the value to use as the scheme part of the URI
* @return a reference to this builder
*/
public abstract UriBuilder setScheme(String val);
/**
* Retrieves the scheme part of the URI.
*
* @return the URI scheme
*/
public abstract String getScheme();
/**
* Sets the port part of the URI.
*
* @param val the value to use as the port part of the URI
* @return a reference to this builder
*/
public abstract UriBuilder setPort(int val);
/**
* Retrieves the port part of the URI.
*
* @return the port part of the URI
*/
public abstract int getPort();
/**
* Sets the host part of the URI.
*
* @param val the value to use as the host part of the URI
* @return a reference to this builder
*/
public abstract UriBuilder setHost(String val);
/**
* Retrieves the host part of the URI.
*
* @return the host part of the URI
*/
public abstract String getHost();
/**
* Sets the path part of the URI.
*
* @param val the path part of the URI
* @return a reference to the builder
*/
public abstract UriBuilder setPath(GString val);
/**
* Retrieves the path part of the URI.
*
* @return the path part of the URI
*/
public abstract GString getPath();
/**
* Sets the query string part of the `URI` from the provided map. The query string key-value pairs will be generated from the key-value pairs
* of the map and are NOT URL-encoded. Nested maps or other data structures are not supported.
*
* @param val the map of query string parameters
* @return a reference to the builder
*/
public abstract UriBuilder setQuery(Map<String, ?> val);
/**
* Retrieves the `Map` of query string parameters for the `URI`.
*
* @return the `Map` of query string parameters for the `URI`.
*/
public abstract Map<String, ?> getQuery();
/**
* Sets the fragment part of the `URI`.
*
* @param val the fragment part of the `URI`
* @return a reference to the builder
*/
public abstract UriBuilder setFragment(String val);
/**
* Retrieves the fragment part of the `URI`.
*
* @return the fragment part of the `URI`
*/
public abstract String getFragment();
/**
* Sets the user info part of the `URI`.
*
* @param val the user info part of the `URI`
* @return a reference to the builder
*/
public abstract UriBuilder setUserInfo(String val);
/**
* Retrieves the user info part of the `URI`.
*
* @return the user info part of the `URI`
*/
public abstract String getUserInfo();
public abstract UriBuilder getParent();
/**
* Sets the path part of the URI.
*
* @param str the path part of the URI
* @return a reference to the builder
*/
public UriBuilder setPath(final String str) {
final String[] parts;
if (str.startsWith("/")) {
parts = new String[]{str};
} else {
final String base = getPath().toString();
parts = new String[]{base, base.endsWith("/") ? "" : "/", str};
}
return setPath(new GStringImpl(EMPTY, parts));
}
public URI forCookie(final HttpCookie cookie) throws URISyntaxException {
|
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/Traverser.java
// public static <V> Predicate<V> notValue(final V v) { return (toTest) -> !v.equals(toTest); }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/Traverser.java
// public static <T,V> V traverse(final T target, final Function<T,T> next,
// final Function<T,V> getValue, final Predicate<V> testValue) {
// final V v = getValue.apply(target);
// if(testValue.test(v)) {
// return v;
// }
//
// final T nextTarget = next.apply(target);
// if(nextTarget != null) {
// return traverse(nextTarget, next, getValue, testValue);
// }
//
// return null;
// }
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/UriBuilder.java
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Collections.singletonList;
import groovy.lang.GString;
import org.codehaus.groovy.runtime.GStringImpl;
import java.io.IOException;
import java.net.HttpCookie;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static groovyx.net.http.Traverser.notValue;
import static groovyx.net.http.Traverser.traverse;
import static java.lang.String.format;
/**
* Copyright (C) 2017 HttpBuilder-NG Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package groovyx.net.http;
/**
* Provides a simple means of creating a request URI and optionally overriding its parts.
*
* [source,groovy]
* ----
* def uri = UriBuilder.basic(UriBuilder.root())
* .setFull('http://localhost:10101')
* .setPath('/foo')
* .toURI()
* ----
*
* Generally, this class is not instantiated directly, but created by the {@link HttpConfig} instance and modified.
*/
public abstract class UriBuilder {
public static final int DEFAULT_PORT = -1;
/**
* Sets the scheme part of the URI.
*
* @param val the value to use as the scheme part of the URI
* @return a reference to this builder
*/
public abstract UriBuilder setScheme(String val);
/**
* Retrieves the scheme part of the URI.
*
* @return the URI scheme
*/
public abstract String getScheme();
/**
* Sets the port part of the URI.
*
* @param val the value to use as the port part of the URI
* @return a reference to this builder
*/
public abstract UriBuilder setPort(int val);
/**
* Retrieves the port part of the URI.
*
* @return the port part of the URI
*/
public abstract int getPort();
/**
* Sets the host part of the URI.
*
* @param val the value to use as the host part of the URI
* @return a reference to this builder
*/
public abstract UriBuilder setHost(String val);
/**
* Retrieves the host part of the URI.
*
* @return the host part of the URI
*/
public abstract String getHost();
/**
* Sets the path part of the URI.
*
* @param val the path part of the URI
* @return a reference to the builder
*/
public abstract UriBuilder setPath(GString val);
/**
* Retrieves the path part of the URI.
*
* @return the path part of the URI
*/
public abstract GString getPath();
/**
* Sets the query string part of the `URI` from the provided map. The query string key-value pairs will be generated from the key-value pairs
* of the map and are NOT URL-encoded. Nested maps or other data structures are not supported.
*
* @param val the map of query string parameters
* @return a reference to the builder
*/
public abstract UriBuilder setQuery(Map<String, ?> val);
/**
* Retrieves the `Map` of query string parameters for the `URI`.
*
* @return the `Map` of query string parameters for the `URI`.
*/
public abstract Map<String, ?> getQuery();
/**
* Sets the fragment part of the `URI`.
*
* @param val the fragment part of the `URI`
* @return a reference to the builder
*/
public abstract UriBuilder setFragment(String val);
/**
* Retrieves the fragment part of the `URI`.
*
* @return the fragment part of the `URI`
*/
public abstract String getFragment();
/**
* Sets the user info part of the `URI`.
*
* @param val the user info part of the `URI`
* @return a reference to the builder
*/
public abstract UriBuilder setUserInfo(String val);
/**
* Retrieves the user info part of the `URI`.
*
* @return the user info part of the `URI`
*/
public abstract String getUserInfo();
public abstract UriBuilder getParent();
/**
* Sets the path part of the URI.
*
* @param str the path part of the URI
* @return a reference to the builder
*/
public UriBuilder setPath(final String str) {
final String[] parts;
if (str.startsWith("/")) {
parts = new String[]{str};
} else {
final String base = getPath().toString();
parts = new String[]{base, base.endsWith("/") ? "" : "/", str};
}
return setPath(new GStringImpl(EMPTY, parts));
}
public URI forCookie(final HttpCookie cookie) throws URISyntaxException {
|
final String scheme = traverse(this, UriBuilder::getParent, UriBuilder::getScheme, Traverser::notNull);
|
http-builder-ng/http-builder-ng
|
http-builder-ng-core/src/main/java/groovyx/net/http/UriBuilder.java
|
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/Traverser.java
// public static <V> Predicate<V> notValue(final V v) { return (toTest) -> !v.equals(toTest); }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/Traverser.java
// public static <T,V> V traverse(final T target, final Function<T,T> next,
// final Function<T,V> getValue, final Predicate<V> testValue) {
// final V v = getValue.apply(target);
// if(testValue.test(v)) {
// return v;
// }
//
// final T nextTarget = next.apply(target);
// if(nextTarget != null) {
// return traverse(nextTarget, next, getValue, testValue);
// }
//
// return null;
// }
|
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Collections.singletonList;
import groovy.lang.GString;
import org.codehaus.groovy.runtime.GStringImpl;
import java.io.IOException;
import java.net.HttpCookie;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static groovyx.net.http.Traverser.notValue;
import static groovyx.net.http.Traverser.traverse;
import static java.lang.String.format;
|
/**
* Copyright (C) 2017 HttpBuilder-NG Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package groovyx.net.http;
/**
* Provides a simple means of creating a request URI and optionally overriding its parts.
*
* [source,groovy]
* ----
* def uri = UriBuilder.basic(UriBuilder.root())
* .setFull('http://localhost:10101')
* .setPath('/foo')
* .toURI()
* ----
*
* Generally, this class is not instantiated directly, but created by the {@link HttpConfig} instance and modified.
*/
public abstract class UriBuilder {
public static final int DEFAULT_PORT = -1;
/**
* Sets the scheme part of the URI.
*
* @param val the value to use as the scheme part of the URI
* @return a reference to this builder
*/
public abstract UriBuilder setScheme(String val);
/**
* Retrieves the scheme part of the URI.
*
* @return the URI scheme
*/
public abstract String getScheme();
/**
* Sets the port part of the URI.
*
* @param val the value to use as the port part of the URI
* @return a reference to this builder
*/
public abstract UriBuilder setPort(int val);
/**
* Retrieves the port part of the URI.
*
* @return the port part of the URI
*/
public abstract int getPort();
/**
* Sets the host part of the URI.
*
* @param val the value to use as the host part of the URI
* @return a reference to this builder
*/
public abstract UriBuilder setHost(String val);
/**
* Retrieves the host part of the URI.
*
* @return the host part of the URI
*/
public abstract String getHost();
/**
* Sets the path part of the URI.
*
* @param val the path part of the URI
* @return a reference to the builder
*/
public abstract UriBuilder setPath(GString val);
/**
* Retrieves the path part of the URI.
*
* @return the path part of the URI
*/
public abstract GString getPath();
/**
* Sets the query string part of the `URI` from the provided map. The query string key-value pairs will be generated from the key-value pairs
* of the map and are NOT URL-encoded. Nested maps or other data structures are not supported.
*
* @param val the map of query string parameters
* @return a reference to the builder
*/
public abstract UriBuilder setQuery(Map<String, ?> val);
/**
* Retrieves the `Map` of query string parameters for the `URI`.
*
* @return the `Map` of query string parameters for the `URI`.
*/
public abstract Map<String, ?> getQuery();
/**
* Sets the fragment part of the `URI`.
*
* @param val the fragment part of the `URI`
* @return a reference to the builder
*/
public abstract UriBuilder setFragment(String val);
/**
* Retrieves the fragment part of the `URI`.
*
* @return the fragment part of the `URI`
*/
public abstract String getFragment();
/**
* Sets the user info part of the `URI`.
*
* @param val the user info part of the `URI`
* @return a reference to the builder
*/
public abstract UriBuilder setUserInfo(String val);
/**
* Retrieves the user info part of the `URI`.
*
* @return the user info part of the `URI`
*/
public abstract String getUserInfo();
public abstract UriBuilder getParent();
/**
* Sets the path part of the URI.
*
* @param str the path part of the URI
* @return a reference to the builder
*/
public UriBuilder setPath(final String str) {
final String[] parts;
if (str.startsWith("/")) {
parts = new String[]{str};
} else {
final String base = getPath().toString();
parts = new String[]{base, base.endsWith("/") ? "" : "/", str};
}
return setPath(new GStringImpl(EMPTY, parts));
}
public URI forCookie(final HttpCookie cookie) throws URISyntaxException {
final String scheme = traverse(this, UriBuilder::getParent, UriBuilder::getScheme, Traverser::notNull);
|
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/Traverser.java
// public static <V> Predicate<V> notValue(final V v) { return (toTest) -> !v.equals(toTest); }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/Traverser.java
// public static <T,V> V traverse(final T target, final Function<T,T> next,
// final Function<T,V> getValue, final Predicate<V> testValue) {
// final V v = getValue.apply(target);
// if(testValue.test(v)) {
// return v;
// }
//
// final T nextTarget = next.apply(target);
// if(nextTarget != null) {
// return traverse(nextTarget, next, getValue, testValue);
// }
//
// return null;
// }
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/UriBuilder.java
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Collections.singletonList;
import groovy.lang.GString;
import org.codehaus.groovy.runtime.GStringImpl;
import java.io.IOException;
import java.net.HttpCookie;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static groovyx.net.http.Traverser.notValue;
import static groovyx.net.http.Traverser.traverse;
import static java.lang.String.format;
/**
* Copyright (C) 2017 HttpBuilder-NG Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package groovyx.net.http;
/**
* Provides a simple means of creating a request URI and optionally overriding its parts.
*
* [source,groovy]
* ----
* def uri = UriBuilder.basic(UriBuilder.root())
* .setFull('http://localhost:10101')
* .setPath('/foo')
* .toURI()
* ----
*
* Generally, this class is not instantiated directly, but created by the {@link HttpConfig} instance and modified.
*/
public abstract class UriBuilder {
public static final int DEFAULT_PORT = -1;
/**
* Sets the scheme part of the URI.
*
* @param val the value to use as the scheme part of the URI
* @return a reference to this builder
*/
public abstract UriBuilder setScheme(String val);
/**
* Retrieves the scheme part of the URI.
*
* @return the URI scheme
*/
public abstract String getScheme();
/**
* Sets the port part of the URI.
*
* @param val the value to use as the port part of the URI
* @return a reference to this builder
*/
public abstract UriBuilder setPort(int val);
/**
* Retrieves the port part of the URI.
*
* @return the port part of the URI
*/
public abstract int getPort();
/**
* Sets the host part of the URI.
*
* @param val the value to use as the host part of the URI
* @return a reference to this builder
*/
public abstract UriBuilder setHost(String val);
/**
* Retrieves the host part of the URI.
*
* @return the host part of the URI
*/
public abstract String getHost();
/**
* Sets the path part of the URI.
*
* @param val the path part of the URI
* @return a reference to the builder
*/
public abstract UriBuilder setPath(GString val);
/**
* Retrieves the path part of the URI.
*
* @return the path part of the URI
*/
public abstract GString getPath();
/**
* Sets the query string part of the `URI` from the provided map. The query string key-value pairs will be generated from the key-value pairs
* of the map and are NOT URL-encoded. Nested maps or other data structures are not supported.
*
* @param val the map of query string parameters
* @return a reference to the builder
*/
public abstract UriBuilder setQuery(Map<String, ?> val);
/**
* Retrieves the `Map` of query string parameters for the `URI`.
*
* @return the `Map` of query string parameters for the `URI`.
*/
public abstract Map<String, ?> getQuery();
/**
* Sets the fragment part of the `URI`.
*
* @param val the fragment part of the `URI`
* @return a reference to the builder
*/
public abstract UriBuilder setFragment(String val);
/**
* Retrieves the fragment part of the `URI`.
*
* @return the fragment part of the `URI`
*/
public abstract String getFragment();
/**
* Sets the user info part of the `URI`.
*
* @param val the user info part of the `URI`
* @return a reference to the builder
*/
public abstract UriBuilder setUserInfo(String val);
/**
* Retrieves the user info part of the `URI`.
*
* @return the user info part of the `URI`
*/
public abstract String getUserInfo();
public abstract UriBuilder getParent();
/**
* Sets the path part of the URI.
*
* @param str the path part of the URI
* @return a reference to the builder
*/
public UriBuilder setPath(final String str) {
final String[] parts;
if (str.startsWith("/")) {
parts = new String[]{str};
} else {
final String base = getPath().toString();
parts = new String[]{base, base.endsWith("/") ? "" : "/", str};
}
return setPath(new GStringImpl(EMPTY, parts));
}
public URI forCookie(final HttpCookie cookie) throws URISyntaxException {
final String scheme = traverse(this, UriBuilder::getParent, UriBuilder::getScheme, Traverser::notNull);
|
final Integer port = traverse(this, UriBuilder::getParent, UriBuilder::getPort, notValue(DEFAULT_PORT));
|
http-builder-ng/http-builder-ng
|
http-builder-ng-core/src/main/java/groovyx/net/http/util/IoUtils.java
|
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/TransportingException.java
// public class TransportingException extends RuntimeException {
//
// public TransportingException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// public TransportingException(final Throwable cause) {
// super(cause);
// }
// }
|
import groovyx.net.http.TransportingException;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
|
public static String copyAsString(final BufferedInputStream inputStream) throws IOException, IllegalStateException {
if (inputStream == null) return null;
try {
inputStream.mark(Integer.MAX_VALUE);
return new String(streamToBytes(inputStream, false));
} finally {
try {
inputStream.reset();
} catch (IOException ioe) {
throw new IllegalStateException("Unable to reset stream - original stream content may be corrupted");
}
}
}
/**
* Transfers the contents of the {@link InputStream} into the {@link OutputStream}, optionally closing the stream.
*
* @param istream the input stream
* @param ostream the output stream
* @param close whether or not to close the output stream
*/
public static void transfer(final InputStream istream, final OutputStream ostream, final boolean close) {
try {
final byte[] bytes = new byte[2_048];
int read;
while ((read = istream.read(bytes)) != -1) {
ostream.write(bytes, 0, read);
}
} catch (IOException e) {
|
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/TransportingException.java
// public class TransportingException extends RuntimeException {
//
// public TransportingException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// public TransportingException(final Throwable cause) {
// super(cause);
// }
// }
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/util/IoUtils.java
import groovyx.net.http.TransportingException;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public static String copyAsString(final BufferedInputStream inputStream) throws IOException, IllegalStateException {
if (inputStream == null) return null;
try {
inputStream.mark(Integer.MAX_VALUE);
return new String(streamToBytes(inputStream, false));
} finally {
try {
inputStream.reset();
} catch (IOException ioe) {
throw new IllegalStateException("Unable to reset stream - original stream content may be corrupted");
}
}
}
/**
* Transfers the contents of the {@link InputStream} into the {@link OutputStream}, optionally closing the stream.
*
* @param istream the input stream
* @param ostream the output stream
* @param close whether or not to close the output stream
*/
public static void transfer(final InputStream istream, final OutputStream ostream, final boolean close) {
try {
final byte[] bytes = new byte[2_048];
int read;
while ((read = istream.read(bytes)) != -1) {
ostream.write(bytes, 0, read);
}
} catch (IOException e) {
|
throw new TransportingException(e);
|
http-builder-ng/http-builder-ng
|
http-builder-ng-core/src/main/java/groovyx/net/http/HttpConfig.java
|
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/fn/ClosureBiFunction.java
// public class ClosureBiFunction<IN_0, IN_1, OUT> implements BiFunction<IN_0, IN_1, OUT> {
//
// private final Closure<OUT> closure;
//
// public ClosureBiFunction(final Closure<OUT> closure) {
// this.closure = closure;
// }
//
// public Closure<OUT> getClosure() {
// return closure;
// }
//
// @Override
// public OUT apply(IN_0 in_0, IN_1 in_1) {
// return closure.call(closureArgs(in_0, in_1));
// }
//
// private Object[] closureArgs(final IN_0 in_0, final IN_1 in_1) {
// final int size = closure.getMaximumNumberOfParameters();
// final Object[] args = new Object[size];
//
// if (size >= 1) {
// args[0] = in_0;
// }
//
// if (size >= 2) {
// args[1] = in_1;
// }
//
// return args;
// }
// }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/fn/ClosureFunction.java
// public class ClosureFunction<IN_0, OUT> implements Function<IN_0, OUT> {
//
// private final Closure<OUT> closure;
// private final int size;
//
// public ClosureFunction(final Closure<OUT> closure) {
// this.closure = closure;
// this.size = closure.getMaximumNumberOfParameters();
// if(size != 1) {
// throw new IllegalArgumentException("Closure needs to accept a single argument");
// }
// }
//
// public Closure<OUT> getClosure() {
// return closure;
// }
//
// @Override
// public OUT apply(final IN_0 in_0) {
// return closure.call(in_0);
// }
// }
|
import groovy.lang.Closure;
import groovyx.net.http.fn.ClosureBiFunction;
import groovyx.net.http.fn.ClosureFunction;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.Charset;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;
|
* Defines the configurable HTTP response properties.
*/
interface Response {
/**
* Configures the execution of the provided closure "when" the given status occurs in the response. The `closure` will be called with an instance
* of the response as a `FromServer` instance and the response body as an `Object` (if there is one). The value returned from the closure will be
* used as the result value of the request; this allows the closure to modify the captured response.
*
* [source,groovy]
* ----
* def http = HttpBuilder.configure {
* request.uri = 'http://localhost:10101'
* }
*
* http.get {
* request.uri.path = '/foo'
* response.when(Status.SUCCESS){
* // executed when a successful response is received
* }
* }
* ----
*
* This method is the same as calling either the `success(Closure)` or `failure(Closure)` methods. Only one closure may be mapped to each
* status.
*
* @param status the response {@link Status} enum
* @param closure the closure to be executed
*/
default void when(Status status, Closure<?> closure) {
|
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/fn/ClosureBiFunction.java
// public class ClosureBiFunction<IN_0, IN_1, OUT> implements BiFunction<IN_0, IN_1, OUT> {
//
// private final Closure<OUT> closure;
//
// public ClosureBiFunction(final Closure<OUT> closure) {
// this.closure = closure;
// }
//
// public Closure<OUT> getClosure() {
// return closure;
// }
//
// @Override
// public OUT apply(IN_0 in_0, IN_1 in_1) {
// return closure.call(closureArgs(in_0, in_1));
// }
//
// private Object[] closureArgs(final IN_0 in_0, final IN_1 in_1) {
// final int size = closure.getMaximumNumberOfParameters();
// final Object[] args = new Object[size];
//
// if (size >= 1) {
// args[0] = in_0;
// }
//
// if (size >= 2) {
// args[1] = in_1;
// }
//
// return args;
// }
// }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/fn/ClosureFunction.java
// public class ClosureFunction<IN_0, OUT> implements Function<IN_0, OUT> {
//
// private final Closure<OUT> closure;
// private final int size;
//
// public ClosureFunction(final Closure<OUT> closure) {
// this.closure = closure;
// this.size = closure.getMaximumNumberOfParameters();
// if(size != 1) {
// throw new IllegalArgumentException("Closure needs to accept a single argument");
// }
// }
//
// public Closure<OUT> getClosure() {
// return closure;
// }
//
// @Override
// public OUT apply(final IN_0 in_0) {
// return closure.call(in_0);
// }
// }
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/HttpConfig.java
import groovy.lang.Closure;
import groovyx.net.http.fn.ClosureBiFunction;
import groovyx.net.http.fn.ClosureFunction;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.Charset;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;
* Defines the configurable HTTP response properties.
*/
interface Response {
/**
* Configures the execution of the provided closure "when" the given status occurs in the response. The `closure` will be called with an instance
* of the response as a `FromServer` instance and the response body as an `Object` (if there is one). The value returned from the closure will be
* used as the result value of the request; this allows the closure to modify the captured response.
*
* [source,groovy]
* ----
* def http = HttpBuilder.configure {
* request.uri = 'http://localhost:10101'
* }
*
* http.get {
* request.uri.path = '/foo'
* response.when(Status.SUCCESS){
* // executed when a successful response is received
* }
* }
* ----
*
* This method is the same as calling either the `success(Closure)` or `failure(Closure)` methods. Only one closure may be mapped to each
* status.
*
* @param status the response {@link Status} enum
* @param closure the closure to be executed
*/
default void when(Status status, Closure<?> closure) {
|
when(status, new ClosureBiFunction<>(closure));
|
http-builder-ng/http-builder-ng
|
http-builder-ng-core/src/main/java/groovyx/net/http/HttpConfig.java
|
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/fn/ClosureBiFunction.java
// public class ClosureBiFunction<IN_0, IN_1, OUT> implements BiFunction<IN_0, IN_1, OUT> {
//
// private final Closure<OUT> closure;
//
// public ClosureBiFunction(final Closure<OUT> closure) {
// this.closure = closure;
// }
//
// public Closure<OUT> getClosure() {
// return closure;
// }
//
// @Override
// public OUT apply(IN_0 in_0, IN_1 in_1) {
// return closure.call(closureArgs(in_0, in_1));
// }
//
// private Object[] closureArgs(final IN_0 in_0, final IN_1 in_1) {
// final int size = closure.getMaximumNumberOfParameters();
// final Object[] args = new Object[size];
//
// if (size >= 1) {
// args[0] = in_0;
// }
//
// if (size >= 2) {
// args[1] = in_1;
// }
//
// return args;
// }
// }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/fn/ClosureFunction.java
// public class ClosureFunction<IN_0, OUT> implements Function<IN_0, OUT> {
//
// private final Closure<OUT> closure;
// private final int size;
//
// public ClosureFunction(final Closure<OUT> closure) {
// this.closure = closure;
// this.size = closure.getMaximumNumberOfParameters();
// if(size != 1) {
// throw new IllegalArgumentException("Closure needs to accept a single argument");
// }
// }
//
// public Closure<OUT> getClosure() {
// return closure;
// }
//
// @Override
// public OUT apply(final IN_0 in_0) {
// return closure.call(in_0);
// }
// }
|
import groovy.lang.Closure;
import groovyx.net.http.fn.ClosureBiFunction;
import groovyx.net.http.fn.ClosureFunction;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.Charset;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;
|
* different from a failure condition because there is no response, no status code, no headers, etc. The `closure` will be called with
* the best guess as to what was the original exception. Some attempts will be made to unwrap exceptions that are of type
* {@link groovyx.net.http.TransportingException} or {@link java.lang.reflect.UndeclaredThrowableException}. The `closure`
* should have a single {@link java.lang.Throwable} argument.
*
* The value returned from the closure will be used as the result value of the request. Since there is no response
* body for the closure to process, this usually means that the closure should do one of three things: re-throw the exception or
* throw a wrapped version of the exception, return null, or return a predefined empty value.
*
* [source,groovy]
* ----
* def http = HttpBuilder.configure {
* request.uri = 'http://localhost:10101'
* }
*
* http.get {
* request.uri.path = '/foo'
* response.exception { Throwable t ->
* t.printStackTrace();
* throw new RuntimeException(t);
* }
* }
* ----
*
* The default exception method wraps the exception in a {@link java.lang.RuntimeException} (if it is
* not already of that type) and rethrows.
*
* @param closure the closure to be executed
*/
default void exception(Closure<?> closure) {
|
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/fn/ClosureBiFunction.java
// public class ClosureBiFunction<IN_0, IN_1, OUT> implements BiFunction<IN_0, IN_1, OUT> {
//
// private final Closure<OUT> closure;
//
// public ClosureBiFunction(final Closure<OUT> closure) {
// this.closure = closure;
// }
//
// public Closure<OUT> getClosure() {
// return closure;
// }
//
// @Override
// public OUT apply(IN_0 in_0, IN_1 in_1) {
// return closure.call(closureArgs(in_0, in_1));
// }
//
// private Object[] closureArgs(final IN_0 in_0, final IN_1 in_1) {
// final int size = closure.getMaximumNumberOfParameters();
// final Object[] args = new Object[size];
//
// if (size >= 1) {
// args[0] = in_0;
// }
//
// if (size >= 2) {
// args[1] = in_1;
// }
//
// return args;
// }
// }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/fn/ClosureFunction.java
// public class ClosureFunction<IN_0, OUT> implements Function<IN_0, OUT> {
//
// private final Closure<OUT> closure;
// private final int size;
//
// public ClosureFunction(final Closure<OUT> closure) {
// this.closure = closure;
// this.size = closure.getMaximumNumberOfParameters();
// if(size != 1) {
// throw new IllegalArgumentException("Closure needs to accept a single argument");
// }
// }
//
// public Closure<OUT> getClosure() {
// return closure;
// }
//
// @Override
// public OUT apply(final IN_0 in_0) {
// return closure.call(in_0);
// }
// }
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/HttpConfig.java
import groovy.lang.Closure;
import groovyx.net.http.fn.ClosureBiFunction;
import groovyx.net.http.fn.ClosureFunction;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.Charset;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;
* different from a failure condition because there is no response, no status code, no headers, etc. The `closure` will be called with
* the best guess as to what was the original exception. Some attempts will be made to unwrap exceptions that are of type
* {@link groovyx.net.http.TransportingException} or {@link java.lang.reflect.UndeclaredThrowableException}. The `closure`
* should have a single {@link java.lang.Throwable} argument.
*
* The value returned from the closure will be used as the result value of the request. Since there is no response
* body for the closure to process, this usually means that the closure should do one of three things: re-throw the exception or
* throw a wrapped version of the exception, return null, or return a predefined empty value.
*
* [source,groovy]
* ----
* def http = HttpBuilder.configure {
* request.uri = 'http://localhost:10101'
* }
*
* http.get {
* request.uri.path = '/foo'
* response.exception { Throwable t ->
* t.printStackTrace();
* throw new RuntimeException(t);
* }
* }
* ----
*
* The default exception method wraps the exception in a {@link java.lang.RuntimeException} (if it is
* not already of that type) and rethrows.
*
* @param closure the closure to be executed
*/
default void exception(Closure<?> closure) {
|
exception(new ClosureFunction<>(closure));
|
http-builder-ng/http-builder-ng
|
http-builder-ng-okhttp/src/main/java/groovyx/net/http/OkHttpEncoders.java
|
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/EmbeddedEncoder.java
// public static byte[] encode(final ChainedHttpConfig config, final String contentType, final Object content) {
// final InMemoryToServer toServer = new InMemoryToServer();
// BiConsumer<ChainedHttpConfig, ToServer> encoder = config.findEncoder(contentType);
// encoder.accept(new ConfigFragment(config, contentType, content), toServer);
// return toServer.getBytes();
// }
|
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okio.Buffer;
import java.io.IOException;
import static groovyx.net.http.ContentTypes.MULTIPART_FORMDATA;
import static groovyx.net.http.ContentTypes.MULTIPART_MIXED;
import static groovyx.net.http.EmbeddedEncoder.encode;
import static okhttp3.MediaType.parse;
import static okhttp3.RequestBody.create;
|
/**
* Copyright (C) 2017 HttpBuilder-NG Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package groovyx.net.http;
/**
* Request content encoders specific to the OkHttp client implementation.
*
* See the {@link MultipartContent} class documentation for more configuration details.
*/
public class OkHttpEncoders {
/**
* Encodes multipart/form-data where the body content must be an instance of the {@link MultipartContent} class. Individual parts will be
* encoded using the encoders available to the {@link ChainedHttpConfig} object.
*
* @param config the chained configuration object
* @param ts the server adapter
*/
public static void multipart(final ChainedHttpConfig config, final ToServer ts) {
try {
final ChainedHttpConfig.ChainedRequest request = config.getChainedRequest();
final Object body = request.actualBody();
if (!(body instanceof MultipartContent)) {
throw new IllegalArgumentException("Multipart body content must be MultipartContent.");
}
final String contentType = request.actualContentType();
if (!(contentType.equals(MULTIPART_FORMDATA.getAt(0)) || contentType.equals(MULTIPART_MIXED.getAt(0)))) {
throw new IllegalArgumentException("Multipart body content must be multipart/form-data.");
}
final MultipartBody.Builder builder = new MultipartBody.Builder();
for (final MultipartContent.MultipartPart mpe : ((MultipartContent) body).parts()) {
if (mpe.getFileName() == null) {
builder.addFormDataPart(mpe.getFieldName(), (String) mpe.getContent());
} else {
builder.addFormDataPart(
mpe.getFieldName(),
mpe.getFileName(),
|
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/EmbeddedEncoder.java
// public static byte[] encode(final ChainedHttpConfig config, final String contentType, final Object content) {
// final InMemoryToServer toServer = new InMemoryToServer();
// BiConsumer<ChainedHttpConfig, ToServer> encoder = config.findEncoder(contentType);
// encoder.accept(new ConfigFragment(config, contentType, content), toServer);
// return toServer.getBytes();
// }
// Path: http-builder-ng-okhttp/src/main/java/groovyx/net/http/OkHttpEncoders.java
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okio.Buffer;
import java.io.IOException;
import static groovyx.net.http.ContentTypes.MULTIPART_FORMDATA;
import static groovyx.net.http.ContentTypes.MULTIPART_MIXED;
import static groovyx.net.http.EmbeddedEncoder.encode;
import static okhttp3.MediaType.parse;
import static okhttp3.RequestBody.create;
/**
* Copyright (C) 2017 HttpBuilder-NG Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package groovyx.net.http;
/**
* Request content encoders specific to the OkHttp client implementation.
*
* See the {@link MultipartContent} class documentation for more configuration details.
*/
public class OkHttpEncoders {
/**
* Encodes multipart/form-data where the body content must be an instance of the {@link MultipartContent} class. Individual parts will be
* encoded using the encoders available to the {@link ChainedHttpConfig} object.
*
* @param config the chained configuration object
* @param ts the server adapter
*/
public static void multipart(final ChainedHttpConfig config, final ToServer ts) {
try {
final ChainedHttpConfig.ChainedRequest request = config.getChainedRequest();
final Object body = request.actualBody();
if (!(body instanceof MultipartContent)) {
throw new IllegalArgumentException("Multipart body content must be MultipartContent.");
}
final String contentType = request.actualContentType();
if (!(contentType.equals(MULTIPART_FORMDATA.getAt(0)) || contentType.equals(MULTIPART_MIXED.getAt(0)))) {
throw new IllegalArgumentException("Multipart body content must be multipart/form-data.");
}
final MultipartBody.Builder builder = new MultipartBody.Builder();
for (final MultipartContent.MultipartPart mpe : ((MultipartContent) body).parts()) {
if (mpe.getFileName() == null) {
builder.addFormDataPart(mpe.getFieldName(), (String) mpe.getContent());
} else {
builder.addFormDataPart(
mpe.getFieldName(),
mpe.getFileName(),
|
create(parse(mpe.getContentType()), encode(config, mpe.getContentType(), mpe.getContent()))
|
http-builder-ng/http-builder-ng
|
http-builder-ng-core/src/main/java/groovyx/net/http/MultipartContent.java
|
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/util/Misc.java
// public static String randomString(final int size) {
// final StringBuilder buffer = new StringBuilder(size);
// for(int i = 0; i < size; ++i) {
// buffer.append(theChars[current().nextInt(theChars.length)]);
// }
//
// return buffer.toString();
// }
|
import groovy.lang.Closure;
import groovy.lang.DelegatesTo;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Consumer;
import static java.util.Collections.unmodifiableList;
import static groovyx.net.http.util.Misc.randomString;
|
/**
* Copyright (C) 2017 HttpBuilder-NG Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package groovyx.net.http;
/**
* Multipart request content object used to define the multipart data. An example would be:
*
* [source,groovy]
* ----
* request.contentType = 'multipart/form-data'
* request.body = multipart {
* field 'userid','someuser'
* part 'icon', 'user-icon.jpg', 'image/jpeg', imageFile
* }
* ----
*
* which would define a `multipart/form-data` request with a field part and a file part with the specified properties.
*/
public class MultipartContent {
private final List<MultipartPart> entries = new LinkedList<>();
|
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/util/Misc.java
// public static String randomString(final int size) {
// final StringBuilder buffer = new StringBuilder(size);
// for(int i = 0; i < size; ++i) {
// buffer.append(theChars[current().nextInt(theChars.length)]);
// }
//
// return buffer.toString();
// }
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/MultipartContent.java
import groovy.lang.Closure;
import groovy.lang.DelegatesTo;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Consumer;
import static java.util.Collections.unmodifiableList;
import static groovyx.net.http.util.Misc.randomString;
/**
* Copyright (C) 2017 HttpBuilder-NG Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package groovyx.net.http;
/**
* Multipart request content object used to define the multipart data. An example would be:
*
* [source,groovy]
* ----
* request.contentType = 'multipart/form-data'
* request.body = multipart {
* field 'userid','someuser'
* part 'icon', 'user-icon.jpg', 'image/jpeg', imageFile
* }
* ----
*
* which would define a `multipart/form-data` request with a field part and a file part with the specified properties.
*/
public class MultipartContent {
private final List<MultipartPart> entries = new LinkedList<>();
|
private final String boundary = randomString(16);
|
http-builder-ng/http-builder-ng
|
http-builder-ng-okhttp/src/main/java/groovyx/net/http/OkHttpBuilder.java
|
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/util/IoUtils.java
// public class IoUtils {
//
// /**
// * Reads all bytes from the stream into a byte array.
// *
// * @param inputStream the {@link InputStream}
// * @return the array of bytes from the stream
// * @throws IOException if there is a problem reading the stream
// */
// public static byte[] streamToBytes(final InputStream inputStream) throws IOException {
// return streamToBytes(inputStream, true);
// }
//
// public static byte[] streamToBytes(final InputStream inputStream, boolean close) throws IOException {
// try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
// final byte[] bytes = new byte[2_048];
//
// int read;
// while ((read = inputStream.read(bytes)) != -1) {
// outputStream.write(bytes, 0, read);
// }
//
// return outputStream.toByteArray();
//
// } finally {
// if (close) inputStream.close();
// }
// }
//
// /**
// * Safely copies the contents of the {@link BufferedInputStream} to a {@link String} and resets the stream.
// * This method is generally only useful for testing and logging purposes.
// *
// * @param inputStream the BufferedInputStream
// * @return a String copy of the stream contents
// * @throws IOException if something goes wrong with the stream
// * @throws IllegalStateException if the stream cannot be reset
// */
// public static String copyAsString(final BufferedInputStream inputStream) throws IOException, IllegalStateException {
// if (inputStream == null) return null;
//
// try {
// inputStream.mark(Integer.MAX_VALUE);
// return new String(streamToBytes(inputStream, false));
// } finally {
// try {
// inputStream.reset();
// } catch (IOException ioe) {
// throw new IllegalStateException("Unable to reset stream - original stream content may be corrupted");
// }
// }
// }
//
// /**
// * Transfers the contents of the {@link InputStream} into the {@link OutputStream}, optionally closing the stream.
// *
// * @param istream the input stream
// * @param ostream the output stream
// * @param close whether or not to close the output stream
// */
// public static void transfer(final InputStream istream, final OutputStream ostream, final boolean close) {
// try {
// final byte[] bytes = new byte[2_048];
// int read;
// while ((read = istream.read(bytes)) != -1) {
// ostream.write(bytes, 0, read);
// }
// } catch (IOException e) {
// throw new TransportingException(e);
// } finally {
// if (close) {
// try {
// ostream.close();
// } catch (IOException ioe) {
// throw new TransportingException(ioe);
// }
// }
// }
// }
// }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/FromServer.java
// public static Header<?> keyValue(String key, String value) {
// final BiFunction<String, String, ? extends Header> func = constructors.get(key);
// return func == null ? new ValueOnly(key, value) : func.apply(key, value);
// }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/HttpBuilder.java
// static final ResponseHandlerFunction HANDLER_FUNCTION = new ResponseHandlerFunction();
|
import com.burgstaller.okhttp.AuthenticationCacheInterceptor;
import com.burgstaller.okhttp.CachingAuthenticatorDecorator;
import com.burgstaller.okhttp.digest.CachingAuthenticator;
import com.burgstaller.okhttp.digest.DigestAuthenticator;
import groovy.lang.Closure;
import groovy.lang.DelegatesTo;
import groovyx.net.http.util.IoUtils;
import okhttp3.*;
import okio.BufferedSink;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.InputStream;
import java.net.Proxy;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
import java.util.function.Function;
import static groovyx.net.http.FromServer.Header.keyValue;
import static groovyx.net.http.HttpBuilder.ResponseHandlerFunction.HANDLER_FUNCTION;
import static groovyx.net.http.HttpConfig.AuthType.DIGEST;
import static okhttp3.MediaType.parse;
|
for (Map.Entry<String, String> e : cookiesToAdd(clientConfig, cr).entrySet()) {
requestBuilder.addHeader(e.getKey(), e.getValue());
}
}
private static void applyAuth(final Request.Builder requestBuilder, final ChainedHttpConfig chainedConfig) {
final HttpConfig.Auth auth = chainedConfig.getChainedRequest().actualAuth();
if (auth != null) {
switch (auth.getAuthType()) {
case BASIC:
requestBuilder.addHeader("Authorization", Credentials.basic(auth.getUser(), auth.getPassword()));
break;
case DIGEST:
// supported in constructor with an interceptor
}
}
}
private Object execute(final Function<HttpUrl, Request.Builder> makeBuilder, final ChainedHttpConfig chainedConfig) {
try {
final ChainedHttpConfig.ChainedRequest cr = chainedConfig.getChainedRequest();
final URI uri = cr.getUri().toURI();
final HttpUrl httpUrl = HttpUrl.get(uri);
final Request.Builder requestBuilder = makeBuilder.apply(httpUrl);
applyHeaders(requestBuilder, cr);
applyAuth(requestBuilder, chainedConfig);
try (Response response = client.newCall(requestBuilder.build()).execute()) {
|
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/util/IoUtils.java
// public class IoUtils {
//
// /**
// * Reads all bytes from the stream into a byte array.
// *
// * @param inputStream the {@link InputStream}
// * @return the array of bytes from the stream
// * @throws IOException if there is a problem reading the stream
// */
// public static byte[] streamToBytes(final InputStream inputStream) throws IOException {
// return streamToBytes(inputStream, true);
// }
//
// public static byte[] streamToBytes(final InputStream inputStream, boolean close) throws IOException {
// try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
// final byte[] bytes = new byte[2_048];
//
// int read;
// while ((read = inputStream.read(bytes)) != -1) {
// outputStream.write(bytes, 0, read);
// }
//
// return outputStream.toByteArray();
//
// } finally {
// if (close) inputStream.close();
// }
// }
//
// /**
// * Safely copies the contents of the {@link BufferedInputStream} to a {@link String} and resets the stream.
// * This method is generally only useful for testing and logging purposes.
// *
// * @param inputStream the BufferedInputStream
// * @return a String copy of the stream contents
// * @throws IOException if something goes wrong with the stream
// * @throws IllegalStateException if the stream cannot be reset
// */
// public static String copyAsString(final BufferedInputStream inputStream) throws IOException, IllegalStateException {
// if (inputStream == null) return null;
//
// try {
// inputStream.mark(Integer.MAX_VALUE);
// return new String(streamToBytes(inputStream, false));
// } finally {
// try {
// inputStream.reset();
// } catch (IOException ioe) {
// throw new IllegalStateException("Unable to reset stream - original stream content may be corrupted");
// }
// }
// }
//
// /**
// * Transfers the contents of the {@link InputStream} into the {@link OutputStream}, optionally closing the stream.
// *
// * @param istream the input stream
// * @param ostream the output stream
// * @param close whether or not to close the output stream
// */
// public static void transfer(final InputStream istream, final OutputStream ostream, final boolean close) {
// try {
// final byte[] bytes = new byte[2_048];
// int read;
// while ((read = istream.read(bytes)) != -1) {
// ostream.write(bytes, 0, read);
// }
// } catch (IOException e) {
// throw new TransportingException(e);
// } finally {
// if (close) {
// try {
// ostream.close();
// } catch (IOException ioe) {
// throw new TransportingException(ioe);
// }
// }
// }
// }
// }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/FromServer.java
// public static Header<?> keyValue(String key, String value) {
// final BiFunction<String, String, ? extends Header> func = constructors.get(key);
// return func == null ? new ValueOnly(key, value) : func.apply(key, value);
// }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/HttpBuilder.java
// static final ResponseHandlerFunction HANDLER_FUNCTION = new ResponseHandlerFunction();
// Path: http-builder-ng-okhttp/src/main/java/groovyx/net/http/OkHttpBuilder.java
import com.burgstaller.okhttp.AuthenticationCacheInterceptor;
import com.burgstaller.okhttp.CachingAuthenticatorDecorator;
import com.burgstaller.okhttp.digest.CachingAuthenticator;
import com.burgstaller.okhttp.digest.DigestAuthenticator;
import groovy.lang.Closure;
import groovy.lang.DelegatesTo;
import groovyx.net.http.util.IoUtils;
import okhttp3.*;
import okio.BufferedSink;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.InputStream;
import java.net.Proxy;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
import java.util.function.Function;
import static groovyx.net.http.FromServer.Header.keyValue;
import static groovyx.net.http.HttpBuilder.ResponseHandlerFunction.HANDLER_FUNCTION;
import static groovyx.net.http.HttpConfig.AuthType.DIGEST;
import static okhttp3.MediaType.parse;
for (Map.Entry<String, String> e : cookiesToAdd(clientConfig, cr).entrySet()) {
requestBuilder.addHeader(e.getKey(), e.getValue());
}
}
private static void applyAuth(final Request.Builder requestBuilder, final ChainedHttpConfig chainedConfig) {
final HttpConfig.Auth auth = chainedConfig.getChainedRequest().actualAuth();
if (auth != null) {
switch (auth.getAuthType()) {
case BASIC:
requestBuilder.addHeader("Authorization", Credentials.basic(auth.getUser(), auth.getPassword()));
break;
case DIGEST:
// supported in constructor with an interceptor
}
}
}
private Object execute(final Function<HttpUrl, Request.Builder> makeBuilder, final ChainedHttpConfig chainedConfig) {
try {
final ChainedHttpConfig.ChainedRequest cr = chainedConfig.getChainedRequest();
final URI uri = cr.getUri().toURI();
final HttpUrl httpUrl = HttpUrl.get(uri);
final Request.Builder requestBuilder = makeBuilder.apply(httpUrl);
applyHeaders(requestBuilder, cr);
applyAuth(requestBuilder, chainedConfig);
try (Response response = client.newCall(requestBuilder.build()).execute()) {
|
return HANDLER_FUNCTION.apply(chainedConfig, new OkHttpFromServer(chainedConfig.getChainedRequest().getUri().toURI(), response));
|
http-builder-ng/http-builder-ng
|
http-builder-ng-okhttp/src/main/java/groovyx/net/http/OkHttpBuilder.java
|
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/util/IoUtils.java
// public class IoUtils {
//
// /**
// * Reads all bytes from the stream into a byte array.
// *
// * @param inputStream the {@link InputStream}
// * @return the array of bytes from the stream
// * @throws IOException if there is a problem reading the stream
// */
// public static byte[] streamToBytes(final InputStream inputStream) throws IOException {
// return streamToBytes(inputStream, true);
// }
//
// public static byte[] streamToBytes(final InputStream inputStream, boolean close) throws IOException {
// try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
// final byte[] bytes = new byte[2_048];
//
// int read;
// while ((read = inputStream.read(bytes)) != -1) {
// outputStream.write(bytes, 0, read);
// }
//
// return outputStream.toByteArray();
//
// } finally {
// if (close) inputStream.close();
// }
// }
//
// /**
// * Safely copies the contents of the {@link BufferedInputStream} to a {@link String} and resets the stream.
// * This method is generally only useful for testing and logging purposes.
// *
// * @param inputStream the BufferedInputStream
// * @return a String copy of the stream contents
// * @throws IOException if something goes wrong with the stream
// * @throws IllegalStateException if the stream cannot be reset
// */
// public static String copyAsString(final BufferedInputStream inputStream) throws IOException, IllegalStateException {
// if (inputStream == null) return null;
//
// try {
// inputStream.mark(Integer.MAX_VALUE);
// return new String(streamToBytes(inputStream, false));
// } finally {
// try {
// inputStream.reset();
// } catch (IOException ioe) {
// throw new IllegalStateException("Unable to reset stream - original stream content may be corrupted");
// }
// }
// }
//
// /**
// * Transfers the contents of the {@link InputStream} into the {@link OutputStream}, optionally closing the stream.
// *
// * @param istream the input stream
// * @param ostream the output stream
// * @param close whether or not to close the output stream
// */
// public static void transfer(final InputStream istream, final OutputStream ostream, final boolean close) {
// try {
// final byte[] bytes = new byte[2_048];
// int read;
// while ((read = istream.read(bytes)) != -1) {
// ostream.write(bytes, 0, read);
// }
// } catch (IOException e) {
// throw new TransportingException(e);
// } finally {
// if (close) {
// try {
// ostream.close();
// } catch (IOException ioe) {
// throw new TransportingException(ioe);
// }
// }
// }
// }
// }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/FromServer.java
// public static Header<?> keyValue(String key, String value) {
// final BiFunction<String, String, ? extends Header> func = constructors.get(key);
// return func == null ? new ValueOnly(key, value) : func.apply(key, value);
// }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/HttpBuilder.java
// static final ResponseHandlerFunction HANDLER_FUNCTION = new ResponseHandlerFunction();
|
import com.burgstaller.okhttp.AuthenticationCacheInterceptor;
import com.burgstaller.okhttp.CachingAuthenticatorDecorator;
import com.burgstaller.okhttp.digest.CachingAuthenticator;
import com.burgstaller.okhttp.digest.DigestAuthenticator;
import groovy.lang.Closure;
import groovy.lang.DelegatesTo;
import groovyx.net.http.util.IoUtils;
import okhttp3.*;
import okio.BufferedSink;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.InputStream;
import java.net.Proxy;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
import java.util.function.Function;
import static groovyx.net.http.FromServer.Header.keyValue;
import static groovyx.net.http.HttpBuilder.ResponseHandlerFunction.HANDLER_FUNCTION;
import static groovyx.net.http.HttpConfig.AuthType.DIGEST;
import static okhttp3.MediaType.parse;
|
}
}
private class OkHttpFromServer implements FromServer {
private final URI uri;
private final Response response;
private List<Header<?>> headers;
private boolean body;
private OkHttpFromServer(final URI uri, final Response response) {
this.uri = uri;
this.response = response;
this.headers = populateHeaders();
addCookieStore(uri, headers);
try {
body = !response.body().source().exhausted() && response.peekBody(1).bytes().length > 0;
} catch (IOException e) {
body = false;
}
}
private List<Header<?>> populateHeaders() {
final Headers headers = response.headers();
List<Header<?>> ret = new ArrayList<>();
for (String name : headers.names()) {
List<String> values = headers.values(name);
for (String value : values) {
|
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/util/IoUtils.java
// public class IoUtils {
//
// /**
// * Reads all bytes from the stream into a byte array.
// *
// * @param inputStream the {@link InputStream}
// * @return the array of bytes from the stream
// * @throws IOException if there is a problem reading the stream
// */
// public static byte[] streamToBytes(final InputStream inputStream) throws IOException {
// return streamToBytes(inputStream, true);
// }
//
// public static byte[] streamToBytes(final InputStream inputStream, boolean close) throws IOException {
// try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
// final byte[] bytes = new byte[2_048];
//
// int read;
// while ((read = inputStream.read(bytes)) != -1) {
// outputStream.write(bytes, 0, read);
// }
//
// return outputStream.toByteArray();
//
// } finally {
// if (close) inputStream.close();
// }
// }
//
// /**
// * Safely copies the contents of the {@link BufferedInputStream} to a {@link String} and resets the stream.
// * This method is generally only useful for testing and logging purposes.
// *
// * @param inputStream the BufferedInputStream
// * @return a String copy of the stream contents
// * @throws IOException if something goes wrong with the stream
// * @throws IllegalStateException if the stream cannot be reset
// */
// public static String copyAsString(final BufferedInputStream inputStream) throws IOException, IllegalStateException {
// if (inputStream == null) return null;
//
// try {
// inputStream.mark(Integer.MAX_VALUE);
// return new String(streamToBytes(inputStream, false));
// } finally {
// try {
// inputStream.reset();
// } catch (IOException ioe) {
// throw new IllegalStateException("Unable to reset stream - original stream content may be corrupted");
// }
// }
// }
//
// /**
// * Transfers the contents of the {@link InputStream} into the {@link OutputStream}, optionally closing the stream.
// *
// * @param istream the input stream
// * @param ostream the output stream
// * @param close whether or not to close the output stream
// */
// public static void transfer(final InputStream istream, final OutputStream ostream, final boolean close) {
// try {
// final byte[] bytes = new byte[2_048];
// int read;
// while ((read = istream.read(bytes)) != -1) {
// ostream.write(bytes, 0, read);
// }
// } catch (IOException e) {
// throw new TransportingException(e);
// } finally {
// if (close) {
// try {
// ostream.close();
// } catch (IOException ioe) {
// throw new TransportingException(ioe);
// }
// }
// }
// }
// }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/FromServer.java
// public static Header<?> keyValue(String key, String value) {
// final BiFunction<String, String, ? extends Header> func = constructors.get(key);
// return func == null ? new ValueOnly(key, value) : func.apply(key, value);
// }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/HttpBuilder.java
// static final ResponseHandlerFunction HANDLER_FUNCTION = new ResponseHandlerFunction();
// Path: http-builder-ng-okhttp/src/main/java/groovyx/net/http/OkHttpBuilder.java
import com.burgstaller.okhttp.AuthenticationCacheInterceptor;
import com.burgstaller.okhttp.CachingAuthenticatorDecorator;
import com.burgstaller.okhttp.digest.CachingAuthenticator;
import com.burgstaller.okhttp.digest.DigestAuthenticator;
import groovy.lang.Closure;
import groovy.lang.DelegatesTo;
import groovyx.net.http.util.IoUtils;
import okhttp3.*;
import okio.BufferedSink;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.InputStream;
import java.net.Proxy;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
import java.util.function.Function;
import static groovyx.net.http.FromServer.Header.keyValue;
import static groovyx.net.http.HttpBuilder.ResponseHandlerFunction.HANDLER_FUNCTION;
import static groovyx.net.http.HttpConfig.AuthType.DIGEST;
import static okhttp3.MediaType.parse;
}
}
private class OkHttpFromServer implements FromServer {
private final URI uri;
private final Response response;
private List<Header<?>> headers;
private boolean body;
private OkHttpFromServer(final URI uri, final Response response) {
this.uri = uri;
this.response = response;
this.headers = populateHeaders();
addCookieStore(uri, headers);
try {
body = !response.body().source().exhausted() && response.peekBody(1).bytes().length > 0;
} catch (IOException e) {
body = false;
}
}
private List<Header<?>> populateHeaders() {
final Headers headers = response.headers();
List<Header<?>> ret = new ArrayList<>();
for (String name : headers.names()) {
List<String> values = headers.values(name);
for (String value : values) {
|
ret.add(keyValue(name, value));
|
http-builder-ng/http-builder-ng
|
http-builder-ng-okhttp/src/main/java/groovyx/net/http/OkHttpBuilder.java
|
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/util/IoUtils.java
// public class IoUtils {
//
// /**
// * Reads all bytes from the stream into a byte array.
// *
// * @param inputStream the {@link InputStream}
// * @return the array of bytes from the stream
// * @throws IOException if there is a problem reading the stream
// */
// public static byte[] streamToBytes(final InputStream inputStream) throws IOException {
// return streamToBytes(inputStream, true);
// }
//
// public static byte[] streamToBytes(final InputStream inputStream, boolean close) throws IOException {
// try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
// final byte[] bytes = new byte[2_048];
//
// int read;
// while ((read = inputStream.read(bytes)) != -1) {
// outputStream.write(bytes, 0, read);
// }
//
// return outputStream.toByteArray();
//
// } finally {
// if (close) inputStream.close();
// }
// }
//
// /**
// * Safely copies the contents of the {@link BufferedInputStream} to a {@link String} and resets the stream.
// * This method is generally only useful for testing and logging purposes.
// *
// * @param inputStream the BufferedInputStream
// * @return a String copy of the stream contents
// * @throws IOException if something goes wrong with the stream
// * @throws IllegalStateException if the stream cannot be reset
// */
// public static String copyAsString(final BufferedInputStream inputStream) throws IOException, IllegalStateException {
// if (inputStream == null) return null;
//
// try {
// inputStream.mark(Integer.MAX_VALUE);
// return new String(streamToBytes(inputStream, false));
// } finally {
// try {
// inputStream.reset();
// } catch (IOException ioe) {
// throw new IllegalStateException("Unable to reset stream - original stream content may be corrupted");
// }
// }
// }
//
// /**
// * Transfers the contents of the {@link InputStream} into the {@link OutputStream}, optionally closing the stream.
// *
// * @param istream the input stream
// * @param ostream the output stream
// * @param close whether or not to close the output stream
// */
// public static void transfer(final InputStream istream, final OutputStream ostream, final boolean close) {
// try {
// final byte[] bytes = new byte[2_048];
// int read;
// while ((read = istream.read(bytes)) != -1) {
// ostream.write(bytes, 0, read);
// }
// } catch (IOException e) {
// throw new TransportingException(e);
// } finally {
// if (close) {
// try {
// ostream.close();
// } catch (IOException ioe) {
// throw new TransportingException(ioe);
// }
// }
// }
// }
// }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/FromServer.java
// public static Header<?> keyValue(String key, String value) {
// final BiFunction<String, String, ? extends Header> func = constructors.get(key);
// return func == null ? new ValueOnly(key, value) : func.apply(key, value);
// }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/HttpBuilder.java
// static final ResponseHandlerFunction HANDLER_FUNCTION = new ResponseHandlerFunction();
|
import com.burgstaller.okhttp.AuthenticationCacheInterceptor;
import com.burgstaller.okhttp.CachingAuthenticatorDecorator;
import com.burgstaller.okhttp.digest.CachingAuthenticator;
import com.burgstaller.okhttp.digest.DigestAuthenticator;
import groovy.lang.Closure;
import groovy.lang.DelegatesTo;
import groovyx.net.http.util.IoUtils;
import okhttp3.*;
import okio.BufferedSink;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.InputStream;
import java.net.Proxy;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
import java.util.function.Function;
import static groovyx.net.http.FromServer.Header.keyValue;
import static groovyx.net.http.HttpBuilder.ResponseHandlerFunction.HANDLER_FUNCTION;
import static groovyx.net.http.HttpConfig.AuthType.DIGEST;
import static okhttp3.MediaType.parse;
|
}
@Override
public boolean getHasBody() {
return body;
}
@Override
public URI getUri() {
return uri;
}
@Override
public void finish() {
response.close();
}
}
private static class OkHttpToServer extends RequestBody implements ToServer {
private ChainedHttpConfig config;
private byte[] bytes;
private OkHttpToServer(final ChainedHttpConfig config) {
this.config = config;
}
@Override
public void toServer(final InputStream inputStream) {
try {
|
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/util/IoUtils.java
// public class IoUtils {
//
// /**
// * Reads all bytes from the stream into a byte array.
// *
// * @param inputStream the {@link InputStream}
// * @return the array of bytes from the stream
// * @throws IOException if there is a problem reading the stream
// */
// public static byte[] streamToBytes(final InputStream inputStream) throws IOException {
// return streamToBytes(inputStream, true);
// }
//
// public static byte[] streamToBytes(final InputStream inputStream, boolean close) throws IOException {
// try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
// final byte[] bytes = new byte[2_048];
//
// int read;
// while ((read = inputStream.read(bytes)) != -1) {
// outputStream.write(bytes, 0, read);
// }
//
// return outputStream.toByteArray();
//
// } finally {
// if (close) inputStream.close();
// }
// }
//
// /**
// * Safely copies the contents of the {@link BufferedInputStream} to a {@link String} and resets the stream.
// * This method is generally only useful for testing and logging purposes.
// *
// * @param inputStream the BufferedInputStream
// * @return a String copy of the stream contents
// * @throws IOException if something goes wrong with the stream
// * @throws IllegalStateException if the stream cannot be reset
// */
// public static String copyAsString(final BufferedInputStream inputStream) throws IOException, IllegalStateException {
// if (inputStream == null) return null;
//
// try {
// inputStream.mark(Integer.MAX_VALUE);
// return new String(streamToBytes(inputStream, false));
// } finally {
// try {
// inputStream.reset();
// } catch (IOException ioe) {
// throw new IllegalStateException("Unable to reset stream - original stream content may be corrupted");
// }
// }
// }
//
// /**
// * Transfers the contents of the {@link InputStream} into the {@link OutputStream}, optionally closing the stream.
// *
// * @param istream the input stream
// * @param ostream the output stream
// * @param close whether or not to close the output stream
// */
// public static void transfer(final InputStream istream, final OutputStream ostream, final boolean close) {
// try {
// final byte[] bytes = new byte[2_048];
// int read;
// while ((read = istream.read(bytes)) != -1) {
// ostream.write(bytes, 0, read);
// }
// } catch (IOException e) {
// throw new TransportingException(e);
// } finally {
// if (close) {
// try {
// ostream.close();
// } catch (IOException ioe) {
// throw new TransportingException(ioe);
// }
// }
// }
// }
// }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/FromServer.java
// public static Header<?> keyValue(String key, String value) {
// final BiFunction<String, String, ? extends Header> func = constructors.get(key);
// return func == null ? new ValueOnly(key, value) : func.apply(key, value);
// }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/HttpBuilder.java
// static final ResponseHandlerFunction HANDLER_FUNCTION = new ResponseHandlerFunction();
// Path: http-builder-ng-okhttp/src/main/java/groovyx/net/http/OkHttpBuilder.java
import com.burgstaller.okhttp.AuthenticationCacheInterceptor;
import com.burgstaller.okhttp.CachingAuthenticatorDecorator;
import com.burgstaller.okhttp.digest.CachingAuthenticator;
import com.burgstaller.okhttp.digest.DigestAuthenticator;
import groovy.lang.Closure;
import groovy.lang.DelegatesTo;
import groovyx.net.http.util.IoUtils;
import okhttp3.*;
import okio.BufferedSink;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.InputStream;
import java.net.Proxy;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
import java.util.function.Function;
import static groovyx.net.http.FromServer.Header.keyValue;
import static groovyx.net.http.HttpBuilder.ResponseHandlerFunction.HANDLER_FUNCTION;
import static groovyx.net.http.HttpConfig.AuthType.DIGEST;
import static okhttp3.MediaType.parse;
}
@Override
public boolean getHasBody() {
return body;
}
@Override
public URI getUri() {
return uri;
}
@Override
public void finish() {
response.close();
}
}
private static class OkHttpToServer extends RequestBody implements ToServer {
private ChainedHttpConfig config;
private byte[] bytes;
private OkHttpToServer(final ChainedHttpConfig config) {
this.config = config;
}
@Override
public void toServer(final InputStream inputStream) {
try {
|
this.bytes = IoUtils.streamToBytes(inputStream);
|
http-builder-ng/http-builder-ng
|
http-builder-ng-core/src/main/java/groovyx/net/http/ChainedHttpConfig.java
|
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/Traverser.java
// public static <T,V> V traverse(final T target, final Function<T,T> next,
// final Function<T,V> getValue, final Predicate<V> testValue) {
// final V v = getValue.apply(target);
// if(testValue.test(v)) {
// return v;
// }
//
// final T nextTarget = next.apply(target);
// if(nextTarget != null) {
// return traverse(nextTarget, next, getValue, testValue);
// }
//
// return null;
// }
|
import java.net.HttpCookie;
import java.nio.charset.Charset;
import java.util.AbstractMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
import static groovyx.net.http.Traverser.traverse;
|
/**
* Copyright (C) 2017 HttpBuilder-NG Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package groovyx.net.http;
public interface ChainedHttpConfig extends HttpConfig {
interface ChainedRequest extends Request {
ChainedRequest getParent();
List<HttpCookie> getCookies();
Object getBody();
String getContentType();
Map<String, BiConsumer<ChainedHttpConfig, ToServer>> getEncoderMap();
Charset getCharset();
default Charset actualCharset() {
|
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/Traverser.java
// public static <T,V> V traverse(final T target, final Function<T,T> next,
// final Function<T,V> getValue, final Predicate<V> testValue) {
// final V v = getValue.apply(target);
// if(testValue.test(v)) {
// return v;
// }
//
// final T nextTarget = next.apply(target);
// if(nextTarget != null) {
// return traverse(nextTarget, next, getValue, testValue);
// }
//
// return null;
// }
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/ChainedHttpConfig.java
import java.net.HttpCookie;
import java.nio.charset.Charset;
import java.util.AbstractMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
import static groovyx.net.http.Traverser.traverse;
/**
* Copyright (C) 2017 HttpBuilder-NG Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package groovyx.net.http;
public interface ChainedHttpConfig extends HttpConfig {
interface ChainedRequest extends Request {
ChainedRequest getParent();
List<HttpCookie> getCookies();
Object getBody();
String getContentType();
Map<String, BiConsumer<ChainedHttpConfig, ToServer>> getEncoderMap();
Charset getCharset();
default Charset actualCharset() {
|
return traverse(this, ChainedRequest::getParent, ChainedRequest::getCharset, Traverser::notNull);
|
http-builder-ng/http-builder-ng
|
http-builder-ng-apache/src/main/java/groovyx/net/http/ApacheEncoders.java
|
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/util/Misc.java
// public static String randomString(final int size) {
// final StringBuilder buffer = new StringBuilder(size);
// for(int i = 0; i < size; ++i) {
// buffer.append(theChars[current().nextInt(theChars.length)]);
// }
//
// return buffer.toString();
// }
|
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import java.io.IOException;
import static groovyx.net.http.ContentTypes.MULTIPART_FORMDATA;
import static groovyx.net.http.ContentTypes.MULTIPART_MIXED;
import static org.apache.http.entity.ContentType.parse;
import static groovyx.net.http.util.Misc.randomString;
|
/**
* Copyright (C) 2017 HttpBuilder-NG Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package groovyx.net.http;
/**
* Request content encoders specific to the Apache client implementation.
*
* See the {@link MultipartContent} class documentation for more configuration details.
*/
public class ApacheEncoders {
/**
* Encodes multipart/form-data where the body content must be an instance of the {@link MultipartContent} class. Individual parts will be
* encoded using the encoders available to the {@link ChainedHttpConfig} object.
*
* @param config the chained configuration object
* @param ts the server adapter
*/
public static void multipart(final ChainedHttpConfig config, final ToServer ts) {
try {
final ChainedHttpConfig.ChainedRequest request = config.getChainedRequest();
final Object body = request.actualBody();
if (!(body instanceof MultipartContent)) {
throw new IllegalArgumentException("Multipart body content must be MultipartContent.");
}
final String contentType = request.actualContentType();
if (!(contentType.equals(MULTIPART_FORMDATA.getAt(0)) || contentType.equals(MULTIPART_MIXED.getAt(0)))) {
throw new IllegalArgumentException("Multipart body content must be multipart/form-data.");
}
|
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/util/Misc.java
// public static String randomString(final int size) {
// final StringBuilder buffer = new StringBuilder(size);
// for(int i = 0; i < size; ++i) {
// buffer.append(theChars[current().nextInt(theChars.length)]);
// }
//
// return buffer.toString();
// }
// Path: http-builder-ng-apache/src/main/java/groovyx/net/http/ApacheEncoders.java
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import java.io.IOException;
import static groovyx.net.http.ContentTypes.MULTIPART_FORMDATA;
import static groovyx.net.http.ContentTypes.MULTIPART_MIXED;
import static org.apache.http.entity.ContentType.parse;
import static groovyx.net.http.util.Misc.randomString;
/**
* Copyright (C) 2017 HttpBuilder-NG Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package groovyx.net.http;
/**
* Request content encoders specific to the Apache client implementation.
*
* See the {@link MultipartContent} class documentation for more configuration details.
*/
public class ApacheEncoders {
/**
* Encodes multipart/form-data where the body content must be an instance of the {@link MultipartContent} class. Individual parts will be
* encoded using the encoders available to the {@link ChainedHttpConfig} object.
*
* @param config the chained configuration object
* @param ts the server adapter
*/
public static void multipart(final ChainedHttpConfig config, final ToServer ts) {
try {
final ChainedHttpConfig.ChainedRequest request = config.getChainedRequest();
final Object body = request.actualBody();
if (!(body instanceof MultipartContent)) {
throw new IllegalArgumentException("Multipart body content must be MultipartContent.");
}
final String contentType = request.actualContentType();
if (!(contentType.equals(MULTIPART_FORMDATA.getAt(0)) || contentType.equals(MULTIPART_MIXED.getAt(0)))) {
throw new IllegalArgumentException("Multipart body content must be multipart/form-data.");
}
|
final String boundary = randomString(10);
|
http-builder-ng/http-builder-ng
|
http-builder-ng-core/src/main/java/groovyx/net/http/JavaHttpBuilder.java
|
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/util/IoUtils.java
// public class IoUtils {
//
// /**
// * Reads all bytes from the stream into a byte array.
// *
// * @param inputStream the {@link InputStream}
// * @return the array of bytes from the stream
// * @throws IOException if there is a problem reading the stream
// */
// public static byte[] streamToBytes(final InputStream inputStream) throws IOException {
// return streamToBytes(inputStream, true);
// }
//
// public static byte[] streamToBytes(final InputStream inputStream, boolean close) throws IOException {
// try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
// final byte[] bytes = new byte[2_048];
//
// int read;
// while ((read = inputStream.read(bytes)) != -1) {
// outputStream.write(bytes, 0, read);
// }
//
// return outputStream.toByteArray();
//
// } finally {
// if (close) inputStream.close();
// }
// }
//
// /**
// * Safely copies the contents of the {@link BufferedInputStream} to a {@link String} and resets the stream.
// * This method is generally only useful for testing and logging purposes.
// *
// * @param inputStream the BufferedInputStream
// * @return a String copy of the stream contents
// * @throws IOException if something goes wrong with the stream
// * @throws IllegalStateException if the stream cannot be reset
// */
// public static String copyAsString(final BufferedInputStream inputStream) throws IOException, IllegalStateException {
// if (inputStream == null) return null;
//
// try {
// inputStream.mark(Integer.MAX_VALUE);
// return new String(streamToBytes(inputStream, false));
// } finally {
// try {
// inputStream.reset();
// } catch (IOException ioe) {
// throw new IllegalStateException("Unable to reset stream - original stream content may be corrupted");
// }
// }
// }
//
// /**
// * Transfers the contents of the {@link InputStream} into the {@link OutputStream}, optionally closing the stream.
// *
// * @param istream the input stream
// * @param ostream the output stream
// * @param close whether or not to close the output stream
// */
// public static void transfer(final InputStream istream, final OutputStream ostream, final boolean close) {
// try {
// final byte[] bytes = new byte[2_048];
// int read;
// while ((read = istream.read(bytes)) != -1) {
// ostream.write(bytes, 0, read);
// }
// } catch (IOException e) {
// throw new TransportingException(e);
// } finally {
// if (close) {
// try {
// ostream.close();
// } catch (IOException ioe) {
// throw new TransportingException(ioe);
// }
// }
// }
// }
// }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/HttpBuilder.java
// static final ResponseHandlerFunction HANDLER_FUNCTION = new ResponseHandlerFunction();
|
import java.util.function.Consumer;
import java.util.zip.GZIPInputStream;
import java.util.zip.InflaterInputStream;
import static groovyx.net.http.HttpBuilder.ResponseHandlerFunction.HANDLER_FUNCTION;
import groovyx.net.http.util.IoUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.*;
import java.nio.charset.Charset;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
|
requestConfig.findEncoder().accept(requestConfig, j2s);
}
if (log.isDebugEnabled()) {
log.debug("Request-URI({}): {}", connection.getRequestMethod(), theUri);
}
addHeaders();
connection.connect();
if (j2s != null) {
if (contentLog.isDebugEnabled()) {
contentLog.debug("Request-Body({}): {}", requestConfig.getChainedRequest().actualContentType(), j2s.content());
}
j2s.transfer();
}
final JavaFromServer fromServer = new JavaFromServer(theUri);
if (contentLog.isDebugEnabled()) {
contentLog.debug("Response-Body: {}", fromServer.content());
}
if (headerLog.isDebugEnabled()) {
fromServer.getHeaders().forEach(header -> headerLog.debug("Response-Header: {} -> {}", header.getKey(), header.getValue()));
}
|
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/util/IoUtils.java
// public class IoUtils {
//
// /**
// * Reads all bytes from the stream into a byte array.
// *
// * @param inputStream the {@link InputStream}
// * @return the array of bytes from the stream
// * @throws IOException if there is a problem reading the stream
// */
// public static byte[] streamToBytes(final InputStream inputStream) throws IOException {
// return streamToBytes(inputStream, true);
// }
//
// public static byte[] streamToBytes(final InputStream inputStream, boolean close) throws IOException {
// try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
// final byte[] bytes = new byte[2_048];
//
// int read;
// while ((read = inputStream.read(bytes)) != -1) {
// outputStream.write(bytes, 0, read);
// }
//
// return outputStream.toByteArray();
//
// } finally {
// if (close) inputStream.close();
// }
// }
//
// /**
// * Safely copies the contents of the {@link BufferedInputStream} to a {@link String} and resets the stream.
// * This method is generally only useful for testing and logging purposes.
// *
// * @param inputStream the BufferedInputStream
// * @return a String copy of the stream contents
// * @throws IOException if something goes wrong with the stream
// * @throws IllegalStateException if the stream cannot be reset
// */
// public static String copyAsString(final BufferedInputStream inputStream) throws IOException, IllegalStateException {
// if (inputStream == null) return null;
//
// try {
// inputStream.mark(Integer.MAX_VALUE);
// return new String(streamToBytes(inputStream, false));
// } finally {
// try {
// inputStream.reset();
// } catch (IOException ioe) {
// throw new IllegalStateException("Unable to reset stream - original stream content may be corrupted");
// }
// }
// }
//
// /**
// * Transfers the contents of the {@link InputStream} into the {@link OutputStream}, optionally closing the stream.
// *
// * @param istream the input stream
// * @param ostream the output stream
// * @param close whether or not to close the output stream
// */
// public static void transfer(final InputStream istream, final OutputStream ostream, final boolean close) {
// try {
// final byte[] bytes = new byte[2_048];
// int read;
// while ((read = istream.read(bytes)) != -1) {
// ostream.write(bytes, 0, read);
// }
// } catch (IOException e) {
// throw new TransportingException(e);
// } finally {
// if (close) {
// try {
// ostream.close();
// } catch (IOException ioe) {
// throw new TransportingException(ioe);
// }
// }
// }
// }
// }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/HttpBuilder.java
// static final ResponseHandlerFunction HANDLER_FUNCTION = new ResponseHandlerFunction();
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/JavaHttpBuilder.java
import java.util.function.Consumer;
import java.util.zip.GZIPInputStream;
import java.util.zip.InflaterInputStream;
import static groovyx.net.http.HttpBuilder.ResponseHandlerFunction.HANDLER_FUNCTION;
import groovyx.net.http.util.IoUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.*;
import java.nio.charset.Charset;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
requestConfig.findEncoder().accept(requestConfig, j2s);
}
if (log.isDebugEnabled()) {
log.debug("Request-URI({}): {}", connection.getRequestMethod(), theUri);
}
addHeaders();
connection.connect();
if (j2s != null) {
if (contentLog.isDebugEnabled()) {
contentLog.debug("Request-Body({}): {}", requestConfig.getChainedRequest().actualContentType(), j2s.content());
}
j2s.transfer();
}
final JavaFromServer fromServer = new JavaFromServer(theUri);
if (contentLog.isDebugEnabled()) {
contentLog.debug("Response-Body: {}", fromServer.content());
}
if (headerLog.isDebugEnabled()) {
fromServer.getHeaders().forEach(header -> headerLog.debug("Response-Header: {} -> {}", header.getKey(), header.getValue()));
}
|
return HANDLER_FUNCTION.apply(requestConfig, fromServer);
|
http-builder-ng/http-builder-ng
|
http-builder-ng-core/src/main/java/groovyx/net/http/JavaHttpBuilder.java
|
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/util/IoUtils.java
// public class IoUtils {
//
// /**
// * Reads all bytes from the stream into a byte array.
// *
// * @param inputStream the {@link InputStream}
// * @return the array of bytes from the stream
// * @throws IOException if there is a problem reading the stream
// */
// public static byte[] streamToBytes(final InputStream inputStream) throws IOException {
// return streamToBytes(inputStream, true);
// }
//
// public static byte[] streamToBytes(final InputStream inputStream, boolean close) throws IOException {
// try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
// final byte[] bytes = new byte[2_048];
//
// int read;
// while ((read = inputStream.read(bytes)) != -1) {
// outputStream.write(bytes, 0, read);
// }
//
// return outputStream.toByteArray();
//
// } finally {
// if (close) inputStream.close();
// }
// }
//
// /**
// * Safely copies the contents of the {@link BufferedInputStream} to a {@link String} and resets the stream.
// * This method is generally only useful for testing and logging purposes.
// *
// * @param inputStream the BufferedInputStream
// * @return a String copy of the stream contents
// * @throws IOException if something goes wrong with the stream
// * @throws IllegalStateException if the stream cannot be reset
// */
// public static String copyAsString(final BufferedInputStream inputStream) throws IOException, IllegalStateException {
// if (inputStream == null) return null;
//
// try {
// inputStream.mark(Integer.MAX_VALUE);
// return new String(streamToBytes(inputStream, false));
// } finally {
// try {
// inputStream.reset();
// } catch (IOException ioe) {
// throw new IllegalStateException("Unable to reset stream - original stream content may be corrupted");
// }
// }
// }
//
// /**
// * Transfers the contents of the {@link InputStream} into the {@link OutputStream}, optionally closing the stream.
// *
// * @param istream the input stream
// * @param ostream the output stream
// * @param close whether or not to close the output stream
// */
// public static void transfer(final InputStream istream, final OutputStream ostream, final boolean close) {
// try {
// final byte[] bytes = new byte[2_048];
// int read;
// while ((read = istream.read(bytes)) != -1) {
// ostream.write(bytes, 0, read);
// }
// } catch (IOException e) {
// throw new TransportingException(e);
// } finally {
// if (close) {
// try {
// ostream.close();
// } catch (IOException ioe) {
// throw new TransportingException(ioe);
// }
// }
// }
// }
// }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/HttpBuilder.java
// static final ResponseHandlerFunction HANDLER_FUNCTION = new ResponseHandlerFunction();
|
import java.util.function.Consumer;
import java.util.zip.GZIPInputStream;
import java.util.zip.InflaterInputStream;
import static groovyx.net.http.HttpBuilder.ResponseHandlerFunction.HANDLER_FUNCTION;
import groovyx.net.http.util.IoUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.*;
import java.nio.charset.Charset;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
|
contentLog.debug("Request-Body({}): {}", requestConfig.getChainedRequest().actualContentType(), j2s.content());
}
j2s.transfer();
}
final JavaFromServer fromServer = new JavaFromServer(theUri);
if (contentLog.isDebugEnabled()) {
contentLog.debug("Response-Body: {}", fromServer.content());
}
if (headerLog.isDebugEnabled()) {
fromServer.getHeaders().forEach(header -> headerLog.debug("Response-Header: {} -> {}", header.getKey(), header.getValue()));
}
return HANDLER_FUNCTION.apply(requestConfig, fromServer);
});
}
protected class JavaToServer implements ToServer {
private BufferedInputStream inputStream;
public void toServer(final InputStream inputStream) {
this.inputStream = inputStream instanceof BufferedInputStream ? (BufferedInputStream) inputStream : new BufferedInputStream(inputStream);
}
void transfer() throws IOException {
|
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/util/IoUtils.java
// public class IoUtils {
//
// /**
// * Reads all bytes from the stream into a byte array.
// *
// * @param inputStream the {@link InputStream}
// * @return the array of bytes from the stream
// * @throws IOException if there is a problem reading the stream
// */
// public static byte[] streamToBytes(final InputStream inputStream) throws IOException {
// return streamToBytes(inputStream, true);
// }
//
// public static byte[] streamToBytes(final InputStream inputStream, boolean close) throws IOException {
// try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
// final byte[] bytes = new byte[2_048];
//
// int read;
// while ((read = inputStream.read(bytes)) != -1) {
// outputStream.write(bytes, 0, read);
// }
//
// return outputStream.toByteArray();
//
// } finally {
// if (close) inputStream.close();
// }
// }
//
// /**
// * Safely copies the contents of the {@link BufferedInputStream} to a {@link String} and resets the stream.
// * This method is generally only useful for testing and logging purposes.
// *
// * @param inputStream the BufferedInputStream
// * @return a String copy of the stream contents
// * @throws IOException if something goes wrong with the stream
// * @throws IllegalStateException if the stream cannot be reset
// */
// public static String copyAsString(final BufferedInputStream inputStream) throws IOException, IllegalStateException {
// if (inputStream == null) return null;
//
// try {
// inputStream.mark(Integer.MAX_VALUE);
// return new String(streamToBytes(inputStream, false));
// } finally {
// try {
// inputStream.reset();
// } catch (IOException ioe) {
// throw new IllegalStateException("Unable to reset stream - original stream content may be corrupted");
// }
// }
// }
//
// /**
// * Transfers the contents of the {@link InputStream} into the {@link OutputStream}, optionally closing the stream.
// *
// * @param istream the input stream
// * @param ostream the output stream
// * @param close whether or not to close the output stream
// */
// public static void transfer(final InputStream istream, final OutputStream ostream, final boolean close) {
// try {
// final byte[] bytes = new byte[2_048];
// int read;
// while ((read = istream.read(bytes)) != -1) {
// ostream.write(bytes, 0, read);
// }
// } catch (IOException e) {
// throw new TransportingException(e);
// } finally {
// if (close) {
// try {
// ostream.close();
// } catch (IOException ioe) {
// throw new TransportingException(ioe);
// }
// }
// }
// }
// }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/HttpBuilder.java
// static final ResponseHandlerFunction HANDLER_FUNCTION = new ResponseHandlerFunction();
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/JavaHttpBuilder.java
import java.util.function.Consumer;
import java.util.zip.GZIPInputStream;
import java.util.zip.InflaterInputStream;
import static groovyx.net.http.HttpBuilder.ResponseHandlerFunction.HANDLER_FUNCTION;
import groovyx.net.http.util.IoUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.*;
import java.nio.charset.Charset;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
contentLog.debug("Request-Body({}): {}", requestConfig.getChainedRequest().actualContentType(), j2s.content());
}
j2s.transfer();
}
final JavaFromServer fromServer = new JavaFromServer(theUri);
if (contentLog.isDebugEnabled()) {
contentLog.debug("Response-Body: {}", fromServer.content());
}
if (headerLog.isDebugEnabled()) {
fromServer.getHeaders().forEach(header -> headerLog.debug("Response-Header: {} -> {}", header.getKey(), header.getValue()));
}
return HANDLER_FUNCTION.apply(requestConfig, fromServer);
});
}
protected class JavaToServer implements ToServer {
private BufferedInputStream inputStream;
public void toServer(final InputStream inputStream) {
this.inputStream = inputStream instanceof BufferedInputStream ? (BufferedInputStream) inputStream : new BufferedInputStream(inputStream);
}
void transfer() throws IOException {
|
IoUtils.transfer(inputStream, connection.getOutputStream(), true);
|
http-builder-ng/http-builder-ng
|
http-builder-ng-core/src/main/java/groovyx/net/http/NativeHandlers.java
|
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/util/IoUtils.java
// public class IoUtils {
//
// /**
// * Reads all bytes from the stream into a byte array.
// *
// * @param inputStream the {@link InputStream}
// * @return the array of bytes from the stream
// * @throws IOException if there is a problem reading the stream
// */
// public static byte[] streamToBytes(final InputStream inputStream) throws IOException {
// return streamToBytes(inputStream, true);
// }
//
// public static byte[] streamToBytes(final InputStream inputStream, boolean close) throws IOException {
// try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
// final byte[] bytes = new byte[2_048];
//
// int read;
// while ((read = inputStream.read(bytes)) != -1) {
// outputStream.write(bytes, 0, read);
// }
//
// return outputStream.toByteArray();
//
// } finally {
// if (close) inputStream.close();
// }
// }
//
// /**
// * Safely copies the contents of the {@link BufferedInputStream} to a {@link String} and resets the stream.
// * This method is generally only useful for testing and logging purposes.
// *
// * @param inputStream the BufferedInputStream
// * @return a String copy of the stream contents
// * @throws IOException if something goes wrong with the stream
// * @throws IllegalStateException if the stream cannot be reset
// */
// public static String copyAsString(final BufferedInputStream inputStream) throws IOException, IllegalStateException {
// if (inputStream == null) return null;
//
// try {
// inputStream.mark(Integer.MAX_VALUE);
// return new String(streamToBytes(inputStream, false));
// } finally {
// try {
// inputStream.reset();
// } catch (IOException ioe) {
// throw new IllegalStateException("Unable to reset stream - original stream content may be corrupted");
// }
// }
// }
//
// /**
// * Transfers the contents of the {@link InputStream} into the {@link OutputStream}, optionally closing the stream.
// *
// * @param istream the input stream
// * @param ostream the output stream
// * @param close whether or not to close the output stream
// */
// public static void transfer(final InputStream istream, final OutputStream ostream, final boolean close) {
// try {
// final byte[] bytes = new byte[2_048];
// int read;
// while ((read = istream.read(bytes)) != -1) {
// ostream.write(bytes, 0, read);
// }
// } catch (IOException e) {
// throw new TransportingException(e);
// } finally {
// if (close) {
// try {
// ostream.close();
// } catch (IOException ioe) {
// throw new TransportingException(ioe);
// }
// }
// }
// }
// }
|
import groovy.json.JsonBuilder;
import groovy.json.JsonSlurper;
import groovy.lang.Closure;
import groovy.lang.GString;
import groovy.lang.Writable;
import groovy.util.XmlSlurper;
import groovy.util.slurpersupport.GPathResult;
import groovy.xml.StreamingMarkupBuilder;
import groovyx.net.http.util.IoUtils;
import org.apache.xml.resolver.Catalog;
import org.apache.xml.resolver.CatalogManager;
import org.apache.xml.resolver.tools.CatalogResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
|
* This CatalogResolver is static to avoid the overhead of re-parsing the catalog definition file every time. Unfortunately, there's no
* way to share a single Catalog instance between resolvers. The {@link Catalog} class is technically not thread-safe, but as long as you
* do not parse catalog files while using the resolver, it should be fine.
*/
public static CatalogResolver catalogResolver;
static {
CatalogManager catalogManager = new CatalogManager();
catalogManager.setIgnoreMissingProperties(true);
catalogManager.setUseStaticCatalog(false);
catalogManager.setRelativeCatalogs(true);
try {
catalogResolver = new CatalogResolver(catalogManager);
catalogResolver.getCatalog().parseCatalog(NativeHandlers.class.getResource("/catalog/html.xml"));
} catch (IOException ex) {
if (log.isWarnEnabled()) {
log.warn("Could not resolve default XML catalog", ex);
}
}
}
/**
* Standard parser for raw bytes.
*
* @param fromServer Backend indenpendent representation of data returned from http server
* @return Raw bytes of body returned from http server
*/
public static byte[] streamToBytes(final ChainedHttpConfig config, final FromServer fromServer) {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/util/IoUtils.java
// public class IoUtils {
//
// /**
// * Reads all bytes from the stream into a byte array.
// *
// * @param inputStream the {@link InputStream}
// * @return the array of bytes from the stream
// * @throws IOException if there is a problem reading the stream
// */
// public static byte[] streamToBytes(final InputStream inputStream) throws IOException {
// return streamToBytes(inputStream, true);
// }
//
// public static byte[] streamToBytes(final InputStream inputStream, boolean close) throws IOException {
// try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
// final byte[] bytes = new byte[2_048];
//
// int read;
// while ((read = inputStream.read(bytes)) != -1) {
// outputStream.write(bytes, 0, read);
// }
//
// return outputStream.toByteArray();
//
// } finally {
// if (close) inputStream.close();
// }
// }
//
// /**
// * Safely copies the contents of the {@link BufferedInputStream} to a {@link String} and resets the stream.
// * This method is generally only useful for testing and logging purposes.
// *
// * @param inputStream the BufferedInputStream
// * @return a String copy of the stream contents
// * @throws IOException if something goes wrong with the stream
// * @throws IllegalStateException if the stream cannot be reset
// */
// public static String copyAsString(final BufferedInputStream inputStream) throws IOException, IllegalStateException {
// if (inputStream == null) return null;
//
// try {
// inputStream.mark(Integer.MAX_VALUE);
// return new String(streamToBytes(inputStream, false));
// } finally {
// try {
// inputStream.reset();
// } catch (IOException ioe) {
// throw new IllegalStateException("Unable to reset stream - original stream content may be corrupted");
// }
// }
// }
//
// /**
// * Transfers the contents of the {@link InputStream} into the {@link OutputStream}, optionally closing the stream.
// *
// * @param istream the input stream
// * @param ostream the output stream
// * @param close whether or not to close the output stream
// */
// public static void transfer(final InputStream istream, final OutputStream ostream, final boolean close) {
// try {
// final byte[] bytes = new byte[2_048];
// int read;
// while ((read = istream.read(bytes)) != -1) {
// ostream.write(bytes, 0, read);
// }
// } catch (IOException e) {
// throw new TransportingException(e);
// } finally {
// if (close) {
// try {
// ostream.close();
// } catch (IOException ioe) {
// throw new TransportingException(ioe);
// }
// }
// }
// }
// }
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/NativeHandlers.java
import groovy.json.JsonBuilder;
import groovy.json.JsonSlurper;
import groovy.lang.Closure;
import groovy.lang.GString;
import groovy.lang.Writable;
import groovy.util.XmlSlurper;
import groovy.util.slurpersupport.GPathResult;
import groovy.xml.StreamingMarkupBuilder;
import groovyx.net.http.util.IoUtils;
import org.apache.xml.resolver.Catalog;
import org.apache.xml.resolver.CatalogManager;
import org.apache.xml.resolver.tools.CatalogResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
* This CatalogResolver is static to avoid the overhead of re-parsing the catalog definition file every time. Unfortunately, there's no
* way to share a single Catalog instance between resolvers. The {@link Catalog} class is technically not thread-safe, but as long as you
* do not parse catalog files while using the resolver, it should be fine.
*/
public static CatalogResolver catalogResolver;
static {
CatalogManager catalogManager = new CatalogManager();
catalogManager.setIgnoreMissingProperties(true);
catalogManager.setUseStaticCatalog(false);
catalogManager.setRelativeCatalogs(true);
try {
catalogResolver = new CatalogResolver(catalogManager);
catalogResolver.getCatalog().parseCatalog(NativeHandlers.class.getResource("/catalog/html.xml"));
} catch (IOException ex) {
if (log.isWarnEnabled()) {
log.warn("Could not resolve default XML catalog", ex);
}
}
}
/**
* Standard parser for raw bytes.
*
* @param fromServer Backend indenpendent representation of data returned from http server
* @return Raw bytes of body returned from http server
*/
public static byte[] streamToBytes(final ChainedHttpConfig config, final FromServer fromServer) {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
IoUtils.transfer(fromServer.getInputStream(), baos, true);
|
http-builder-ng/http-builder-ng
|
http-builder-ng-core/src/main/java/groovyx/net/http/HttpObjectConfigImpl.java
|
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/HttpConfigs.java
// public static ChainedHttpConfig threadSafe(final ChainedHttpConfig parent) {
// return new ThreadSafeHttpConfig(parent);
// }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/HttpConfigs.java
// public static ChainedHttpConfig root() {
// return root;
// }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/util/SslUtils.java
// @SuppressWarnings("WeakerAccess")
// public static final HostnameVerifier ANY_HOSTNAME = (s, sslSession) -> true;
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/util/SslUtils.java
// public static SSLContext acceptingSslContext() {
// try {
// SSLContext sslContext = SSLContext.getInstance("SSL");
// sslContext.init(null, TRUST_MANAGERS, new SecureRandom());
// return sslContext;
//
// } catch (NoSuchAlgorithmException | KeyManagementException ex) {
// throw new RuntimeException("Unable to create issue-ignoring SSLContext: " + ex.getMessage(), ex);
// }
// }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/util/Misc.java
// public static boolean isPropertySet(final String prop) {
// final String value = getProperty(prop, "false").toLowerCase();
// return (value.equals("true") ||
// value.equals("yes") ||
// value.equals("t") ||
// value.equals("on") ||
// value.equals("1"));
// }
|
import static groovyx.net.http.util.Misc.isPropertySet;
import java.net.Proxy;
import java.net.UnknownHostException;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.io.File;
import java.util.EnumMap;
import java.util.concurrent.Executor;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import static groovyx.net.http.HttpConfigs.threadSafe;
import static groovyx.net.http.HttpConfigs.root;
import static groovyx.net.http.util.SslUtils.ANY_HOSTNAME;
import static groovyx.net.http.util.SslUtils.acceptingSslContext;
|
/**
* Copyright (C) 2017 HttpBuilder-NG Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package groovyx.net.http;
public class HttpObjectConfigImpl implements HttpObjectConfig {
private final ChainedHttpConfig config = threadSafe(root());
public ChainedHttpConfig getChainedConfig() {
return config;
}
final Exec exec = new Exec();
final ClientConfig clientConfig = new ClientConfig();
public static Object nullInterceptor(final ChainedHttpConfig config, final Function<ChainedHttpConfig, Object> func) {
return func.apply(config);
}
private static class Exec implements Execution {
private int maxThreads = 1;
private Executor executor = SingleThreaded.instance;
private SSLContext sslContext;
private HostnameVerifier hostnameVerifier;
private final EnumMap<HttpVerb, BiFunction<ChainedHttpConfig, Function<ChainedHttpConfig, Object>, Object>> interceptors;
private ProxyInfo proxyInfo;
public Exec() {
interceptors = new EnumMap<>(HttpVerb.class);
for (HttpVerb verb : HttpVerb.values()) {
interceptors.put(verb, HttpObjectConfigImpl::nullInterceptor);
}
|
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/HttpConfigs.java
// public static ChainedHttpConfig threadSafe(final ChainedHttpConfig parent) {
// return new ThreadSafeHttpConfig(parent);
// }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/HttpConfigs.java
// public static ChainedHttpConfig root() {
// return root;
// }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/util/SslUtils.java
// @SuppressWarnings("WeakerAccess")
// public static final HostnameVerifier ANY_HOSTNAME = (s, sslSession) -> true;
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/util/SslUtils.java
// public static SSLContext acceptingSslContext() {
// try {
// SSLContext sslContext = SSLContext.getInstance("SSL");
// sslContext.init(null, TRUST_MANAGERS, new SecureRandom());
// return sslContext;
//
// } catch (NoSuchAlgorithmException | KeyManagementException ex) {
// throw new RuntimeException("Unable to create issue-ignoring SSLContext: " + ex.getMessage(), ex);
// }
// }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/util/Misc.java
// public static boolean isPropertySet(final String prop) {
// final String value = getProperty(prop, "false").toLowerCase();
// return (value.equals("true") ||
// value.equals("yes") ||
// value.equals("t") ||
// value.equals("on") ||
// value.equals("1"));
// }
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/HttpObjectConfigImpl.java
import static groovyx.net.http.util.Misc.isPropertySet;
import java.net.Proxy;
import java.net.UnknownHostException;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.io.File;
import java.util.EnumMap;
import java.util.concurrent.Executor;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import static groovyx.net.http.HttpConfigs.threadSafe;
import static groovyx.net.http.HttpConfigs.root;
import static groovyx.net.http.util.SslUtils.ANY_HOSTNAME;
import static groovyx.net.http.util.SslUtils.acceptingSslContext;
/**
* Copyright (C) 2017 HttpBuilder-NG Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package groovyx.net.http;
public class HttpObjectConfigImpl implements HttpObjectConfig {
private final ChainedHttpConfig config = threadSafe(root());
public ChainedHttpConfig getChainedConfig() {
return config;
}
final Exec exec = new Exec();
final ClientConfig clientConfig = new ClientConfig();
public static Object nullInterceptor(final ChainedHttpConfig config, final Function<ChainedHttpConfig, Object> func) {
return func.apply(config);
}
private static class Exec implements Execution {
private int maxThreads = 1;
private Executor executor = SingleThreaded.instance;
private SSLContext sslContext;
private HostnameVerifier hostnameVerifier;
private final EnumMap<HttpVerb, BiFunction<ChainedHttpConfig, Function<ChainedHttpConfig, Object>, Object>> interceptors;
private ProxyInfo proxyInfo;
public Exec() {
interceptors = new EnumMap<>(HttpVerb.class);
for (HttpVerb verb : HttpVerb.values()) {
interceptors.put(verb, HttpObjectConfigImpl::nullInterceptor);
}
|
if(isPropertySet("groovyx.net.http.ignore-ssl-issues")) {
|
http-builder-ng/http-builder-ng
|
http-builder-ng-core/src/main/java/groovyx/net/http/HttpObjectConfigImpl.java
|
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/HttpConfigs.java
// public static ChainedHttpConfig threadSafe(final ChainedHttpConfig parent) {
// return new ThreadSafeHttpConfig(parent);
// }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/HttpConfigs.java
// public static ChainedHttpConfig root() {
// return root;
// }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/util/SslUtils.java
// @SuppressWarnings("WeakerAccess")
// public static final HostnameVerifier ANY_HOSTNAME = (s, sslSession) -> true;
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/util/SslUtils.java
// public static SSLContext acceptingSslContext() {
// try {
// SSLContext sslContext = SSLContext.getInstance("SSL");
// sslContext.init(null, TRUST_MANAGERS, new SecureRandom());
// return sslContext;
//
// } catch (NoSuchAlgorithmException | KeyManagementException ex) {
// throw new RuntimeException("Unable to create issue-ignoring SSLContext: " + ex.getMessage(), ex);
// }
// }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/util/Misc.java
// public static boolean isPropertySet(final String prop) {
// final String value = getProperty(prop, "false").toLowerCase();
// return (value.equals("true") ||
// value.equals("yes") ||
// value.equals("t") ||
// value.equals("on") ||
// value.equals("1"));
// }
|
import static groovyx.net.http.util.Misc.isPropertySet;
import java.net.Proxy;
import java.net.UnknownHostException;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.io.File;
import java.util.EnumMap;
import java.util.concurrent.Executor;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import static groovyx.net.http.HttpConfigs.threadSafe;
import static groovyx.net.http.HttpConfigs.root;
import static groovyx.net.http.util.SslUtils.ANY_HOSTNAME;
import static groovyx.net.http.util.SslUtils.acceptingSslContext;
|
/**
* Copyright (C) 2017 HttpBuilder-NG Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package groovyx.net.http;
public class HttpObjectConfigImpl implements HttpObjectConfig {
private final ChainedHttpConfig config = threadSafe(root());
public ChainedHttpConfig getChainedConfig() {
return config;
}
final Exec exec = new Exec();
final ClientConfig clientConfig = new ClientConfig();
public static Object nullInterceptor(final ChainedHttpConfig config, final Function<ChainedHttpConfig, Object> func) {
return func.apply(config);
}
private static class Exec implements Execution {
private int maxThreads = 1;
private Executor executor = SingleThreaded.instance;
private SSLContext sslContext;
private HostnameVerifier hostnameVerifier;
private final EnumMap<HttpVerb, BiFunction<ChainedHttpConfig, Function<ChainedHttpConfig, Object>, Object>> interceptors;
private ProxyInfo proxyInfo;
public Exec() {
interceptors = new EnumMap<>(HttpVerb.class);
for (HttpVerb verb : HttpVerb.values()) {
interceptors.put(verb, HttpObjectConfigImpl::nullInterceptor);
}
if(isPropertySet("groovyx.net.http.ignore-ssl-issues")) {
|
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/HttpConfigs.java
// public static ChainedHttpConfig threadSafe(final ChainedHttpConfig parent) {
// return new ThreadSafeHttpConfig(parent);
// }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/HttpConfigs.java
// public static ChainedHttpConfig root() {
// return root;
// }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/util/SslUtils.java
// @SuppressWarnings("WeakerAccess")
// public static final HostnameVerifier ANY_HOSTNAME = (s, sslSession) -> true;
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/util/SslUtils.java
// public static SSLContext acceptingSslContext() {
// try {
// SSLContext sslContext = SSLContext.getInstance("SSL");
// sslContext.init(null, TRUST_MANAGERS, new SecureRandom());
// return sslContext;
//
// } catch (NoSuchAlgorithmException | KeyManagementException ex) {
// throw new RuntimeException("Unable to create issue-ignoring SSLContext: " + ex.getMessage(), ex);
// }
// }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/util/Misc.java
// public static boolean isPropertySet(final String prop) {
// final String value = getProperty(prop, "false").toLowerCase();
// return (value.equals("true") ||
// value.equals("yes") ||
// value.equals("t") ||
// value.equals("on") ||
// value.equals("1"));
// }
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/HttpObjectConfigImpl.java
import static groovyx.net.http.util.Misc.isPropertySet;
import java.net.Proxy;
import java.net.UnknownHostException;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.io.File;
import java.util.EnumMap;
import java.util.concurrent.Executor;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import static groovyx.net.http.HttpConfigs.threadSafe;
import static groovyx.net.http.HttpConfigs.root;
import static groovyx.net.http.util.SslUtils.ANY_HOSTNAME;
import static groovyx.net.http.util.SslUtils.acceptingSslContext;
/**
* Copyright (C) 2017 HttpBuilder-NG Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package groovyx.net.http;
public class HttpObjectConfigImpl implements HttpObjectConfig {
private final ChainedHttpConfig config = threadSafe(root());
public ChainedHttpConfig getChainedConfig() {
return config;
}
final Exec exec = new Exec();
final ClientConfig clientConfig = new ClientConfig();
public static Object nullInterceptor(final ChainedHttpConfig config, final Function<ChainedHttpConfig, Object> func) {
return func.apply(config);
}
private static class Exec implements Execution {
private int maxThreads = 1;
private Executor executor = SingleThreaded.instance;
private SSLContext sslContext;
private HostnameVerifier hostnameVerifier;
private final EnumMap<HttpVerb, BiFunction<ChainedHttpConfig, Function<ChainedHttpConfig, Object>, Object>> interceptors;
private ProxyInfo proxyInfo;
public Exec() {
interceptors = new EnumMap<>(HttpVerb.class);
for (HttpVerb verb : HttpVerb.values()) {
interceptors.put(verb, HttpObjectConfigImpl::nullInterceptor);
}
if(isPropertySet("groovyx.net.http.ignore-ssl-issues")) {
|
setSslContext(acceptingSslContext());
|
http-builder-ng/http-builder-ng
|
http-builder-ng-core/src/main/java/groovyx/net/http/HttpObjectConfigImpl.java
|
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/HttpConfigs.java
// public static ChainedHttpConfig threadSafe(final ChainedHttpConfig parent) {
// return new ThreadSafeHttpConfig(parent);
// }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/HttpConfigs.java
// public static ChainedHttpConfig root() {
// return root;
// }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/util/SslUtils.java
// @SuppressWarnings("WeakerAccess")
// public static final HostnameVerifier ANY_HOSTNAME = (s, sslSession) -> true;
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/util/SslUtils.java
// public static SSLContext acceptingSslContext() {
// try {
// SSLContext sslContext = SSLContext.getInstance("SSL");
// sslContext.init(null, TRUST_MANAGERS, new SecureRandom());
// return sslContext;
//
// } catch (NoSuchAlgorithmException | KeyManagementException ex) {
// throw new RuntimeException("Unable to create issue-ignoring SSLContext: " + ex.getMessage(), ex);
// }
// }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/util/Misc.java
// public static boolean isPropertySet(final String prop) {
// final String value = getProperty(prop, "false").toLowerCase();
// return (value.equals("true") ||
// value.equals("yes") ||
// value.equals("t") ||
// value.equals("on") ||
// value.equals("1"));
// }
|
import static groovyx.net.http.util.Misc.isPropertySet;
import java.net.Proxy;
import java.net.UnknownHostException;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.io.File;
import java.util.EnumMap;
import java.util.concurrent.Executor;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import static groovyx.net.http.HttpConfigs.threadSafe;
import static groovyx.net.http.HttpConfigs.root;
import static groovyx.net.http.util.SslUtils.ANY_HOSTNAME;
import static groovyx.net.http.util.SslUtils.acceptingSslContext;
|
/**
* Copyright (C) 2017 HttpBuilder-NG Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package groovyx.net.http;
public class HttpObjectConfigImpl implements HttpObjectConfig {
private final ChainedHttpConfig config = threadSafe(root());
public ChainedHttpConfig getChainedConfig() {
return config;
}
final Exec exec = new Exec();
final ClientConfig clientConfig = new ClientConfig();
public static Object nullInterceptor(final ChainedHttpConfig config, final Function<ChainedHttpConfig, Object> func) {
return func.apply(config);
}
private static class Exec implements Execution {
private int maxThreads = 1;
private Executor executor = SingleThreaded.instance;
private SSLContext sslContext;
private HostnameVerifier hostnameVerifier;
private final EnumMap<HttpVerb, BiFunction<ChainedHttpConfig, Function<ChainedHttpConfig, Object>, Object>> interceptors;
private ProxyInfo proxyInfo;
public Exec() {
interceptors = new EnumMap<>(HttpVerb.class);
for (HttpVerb verb : HttpVerb.values()) {
interceptors.put(verb, HttpObjectConfigImpl::nullInterceptor);
}
if(isPropertySet("groovyx.net.http.ignore-ssl-issues")) {
setSslContext(acceptingSslContext());
|
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/HttpConfigs.java
// public static ChainedHttpConfig threadSafe(final ChainedHttpConfig parent) {
// return new ThreadSafeHttpConfig(parent);
// }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/HttpConfigs.java
// public static ChainedHttpConfig root() {
// return root;
// }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/util/SslUtils.java
// @SuppressWarnings("WeakerAccess")
// public static final HostnameVerifier ANY_HOSTNAME = (s, sslSession) -> true;
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/util/SslUtils.java
// public static SSLContext acceptingSslContext() {
// try {
// SSLContext sslContext = SSLContext.getInstance("SSL");
// sslContext.init(null, TRUST_MANAGERS, new SecureRandom());
// return sslContext;
//
// } catch (NoSuchAlgorithmException | KeyManagementException ex) {
// throw new RuntimeException("Unable to create issue-ignoring SSLContext: " + ex.getMessage(), ex);
// }
// }
//
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/util/Misc.java
// public static boolean isPropertySet(final String prop) {
// final String value = getProperty(prop, "false").toLowerCase();
// return (value.equals("true") ||
// value.equals("yes") ||
// value.equals("t") ||
// value.equals("on") ||
// value.equals("1"));
// }
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/HttpObjectConfigImpl.java
import static groovyx.net.http.util.Misc.isPropertySet;
import java.net.Proxy;
import java.net.UnknownHostException;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.io.File;
import java.util.EnumMap;
import java.util.concurrent.Executor;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import static groovyx.net.http.HttpConfigs.threadSafe;
import static groovyx.net.http.HttpConfigs.root;
import static groovyx.net.http.util.SslUtils.ANY_HOSTNAME;
import static groovyx.net.http.util.SslUtils.acceptingSslContext;
/**
* Copyright (C) 2017 HttpBuilder-NG Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package groovyx.net.http;
public class HttpObjectConfigImpl implements HttpObjectConfig {
private final ChainedHttpConfig config = threadSafe(root());
public ChainedHttpConfig getChainedConfig() {
return config;
}
final Exec exec = new Exec();
final ClientConfig clientConfig = new ClientConfig();
public static Object nullInterceptor(final ChainedHttpConfig config, final Function<ChainedHttpConfig, Object> func) {
return func.apply(config);
}
private static class Exec implements Execution {
private int maxThreads = 1;
private Executor executor = SingleThreaded.instance;
private SSLContext sslContext;
private HostnameVerifier hostnameVerifier;
private final EnumMap<HttpVerb, BiFunction<ChainedHttpConfig, Function<ChainedHttpConfig, Object>, Object>> interceptors;
private ProxyInfo proxyInfo;
public Exec() {
interceptors = new EnumMap<>(HttpVerb.class);
for (HttpVerb verb : HttpVerb.values()) {
interceptors.put(verb, HttpObjectConfigImpl::nullInterceptor);
}
if(isPropertySet("groovyx.net.http.ignore-ssl-issues")) {
setSslContext(acceptingSslContext());
|
setHostnameVerifier(ANY_HOSTNAME);
|
http-builder-ng/http-builder-ng
|
http-builder-ng-core/src/main/java/groovyx/net/http/EmbeddedEncoder.java
|
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/util/IoUtils.java
// public class IoUtils {
//
// /**
// * Reads all bytes from the stream into a byte array.
// *
// * @param inputStream the {@link InputStream}
// * @return the array of bytes from the stream
// * @throws IOException if there is a problem reading the stream
// */
// public static byte[] streamToBytes(final InputStream inputStream) throws IOException {
// return streamToBytes(inputStream, true);
// }
//
// public static byte[] streamToBytes(final InputStream inputStream, boolean close) throws IOException {
// try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
// final byte[] bytes = new byte[2_048];
//
// int read;
// while ((read = inputStream.read(bytes)) != -1) {
// outputStream.write(bytes, 0, read);
// }
//
// return outputStream.toByteArray();
//
// } finally {
// if (close) inputStream.close();
// }
// }
//
// /**
// * Safely copies the contents of the {@link BufferedInputStream} to a {@link String} and resets the stream.
// * This method is generally only useful for testing and logging purposes.
// *
// * @param inputStream the BufferedInputStream
// * @return a String copy of the stream contents
// * @throws IOException if something goes wrong with the stream
// * @throws IllegalStateException if the stream cannot be reset
// */
// public static String copyAsString(final BufferedInputStream inputStream) throws IOException, IllegalStateException {
// if (inputStream == null) return null;
//
// try {
// inputStream.mark(Integer.MAX_VALUE);
// return new String(streamToBytes(inputStream, false));
// } finally {
// try {
// inputStream.reset();
// } catch (IOException ioe) {
// throw new IllegalStateException("Unable to reset stream - original stream content may be corrupted");
// }
// }
// }
//
// /**
// * Transfers the contents of the {@link InputStream} into the {@link OutputStream}, optionally closing the stream.
// *
// * @param istream the input stream
// * @param ostream the output stream
// * @param close whether or not to close the output stream
// */
// public static void transfer(final InputStream istream, final OutputStream ostream, final boolean close) {
// try {
// final byte[] bytes = new byte[2_048];
// int read;
// while ((read = istream.read(bytes)) != -1) {
// ostream.write(bytes, 0, read);
// }
// } catch (IOException e) {
// throw new TransportingException(e);
// } finally {
// if (close) {
// try {
// ostream.close();
// } catch (IOException ioe) {
// throw new TransportingException(ioe);
// }
// }
// }
// }
// }
|
import groovyx.net.http.util.IoUtils;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.function.BiConsumer;
|
/**
* Copyright (C) 2017 HttpBuilder-NG Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package groovyx.net.http;
/**
* Used to apply standard encoders in an embedded request context, primarily for multipart request content encoding.
*
* This is not really a public interface class.
*/
class EmbeddedEncoder {
public static byte[] encode(final ChainedHttpConfig config, final String contentType, final Object content) {
final InMemoryToServer toServer = new InMemoryToServer();
BiConsumer<ChainedHttpConfig, ToServer> encoder = config.findEncoder(contentType);
encoder.accept(new ConfigFragment(config, contentType, content), toServer);
return toServer.getBytes();
}
private static class InMemoryToServer implements ToServer {
private byte[] bytes;
@Override
public void toServer(final InputStream inputStream) {
try {
|
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/util/IoUtils.java
// public class IoUtils {
//
// /**
// * Reads all bytes from the stream into a byte array.
// *
// * @param inputStream the {@link InputStream}
// * @return the array of bytes from the stream
// * @throws IOException if there is a problem reading the stream
// */
// public static byte[] streamToBytes(final InputStream inputStream) throws IOException {
// return streamToBytes(inputStream, true);
// }
//
// public static byte[] streamToBytes(final InputStream inputStream, boolean close) throws IOException {
// try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
// final byte[] bytes = new byte[2_048];
//
// int read;
// while ((read = inputStream.read(bytes)) != -1) {
// outputStream.write(bytes, 0, read);
// }
//
// return outputStream.toByteArray();
//
// } finally {
// if (close) inputStream.close();
// }
// }
//
// /**
// * Safely copies the contents of the {@link BufferedInputStream} to a {@link String} and resets the stream.
// * This method is generally only useful for testing and logging purposes.
// *
// * @param inputStream the BufferedInputStream
// * @return a String copy of the stream contents
// * @throws IOException if something goes wrong with the stream
// * @throws IllegalStateException if the stream cannot be reset
// */
// public static String copyAsString(final BufferedInputStream inputStream) throws IOException, IllegalStateException {
// if (inputStream == null) return null;
//
// try {
// inputStream.mark(Integer.MAX_VALUE);
// return new String(streamToBytes(inputStream, false));
// } finally {
// try {
// inputStream.reset();
// } catch (IOException ioe) {
// throw new IllegalStateException("Unable to reset stream - original stream content may be corrupted");
// }
// }
// }
//
// /**
// * Transfers the contents of the {@link InputStream} into the {@link OutputStream}, optionally closing the stream.
// *
// * @param istream the input stream
// * @param ostream the output stream
// * @param close whether or not to close the output stream
// */
// public static void transfer(final InputStream istream, final OutputStream ostream, final boolean close) {
// try {
// final byte[] bytes = new byte[2_048];
// int read;
// while ((read = istream.read(bytes)) != -1) {
// ostream.write(bytes, 0, read);
// }
// } catch (IOException e) {
// throw new TransportingException(e);
// } finally {
// if (close) {
// try {
// ostream.close();
// } catch (IOException ioe) {
// throw new TransportingException(ioe);
// }
// }
// }
// }
// }
// Path: http-builder-ng-core/src/main/java/groovyx/net/http/EmbeddedEncoder.java
import groovyx.net.http.util.IoUtils;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.function.BiConsumer;
/**
* Copyright (C) 2017 HttpBuilder-NG Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package groovyx.net.http;
/**
* Used to apply standard encoders in an embedded request context, primarily for multipart request content encoding.
*
* This is not really a public interface class.
*/
class EmbeddedEncoder {
public static byte[] encode(final ChainedHttpConfig config, final String contentType, final Object content) {
final InMemoryToServer toServer = new InMemoryToServer();
BiConsumer<ChainedHttpConfig, ToServer> encoder = config.findEncoder(contentType);
encoder.accept(new ConfigFragment(config, contentType, content), toServer);
return toServer.getBytes();
}
private static class InMemoryToServer implements ToServer {
private byte[] bytes;
@Override
public void toServer(final InputStream inputStream) {
try {
|
bytes = IoUtils.streamToBytes(inputStream);
|
junjunguo/PocketMaps
|
PocketMaps/app/src/main/java/com/villoren/android/kalmanlocationmanager/lib/LooperThread.java
|
// Path: PocketMaps/app/src/main/java/com/junjunguo/pocketmaps/activities/Permission.java
// public class Permission extends AppCompatActivity
// implements ActivityCompat.OnRequestPermissionsResultCallback, OnClickListener
// {
// static String[] sPermission;
// static boolean isFirstForcedPermission;
// static int idCounter = 0;
// static boolean isAsking = false;
//
// /** Start a Permission-Request, and calls activity.finish().
// * @param sPermission The Permission of android.Manifest.permission.xyz
// * @param isFirstForcedPermission True, if the first one of sPermission is forced. **/
// public static void startRequest(String[] sPermission, boolean isFirstForcedPermission, Activity activity)
// {
// Permission.sPermission = sPermission;
// Permission.isFirstForcedPermission = isFirstForcedPermission;
//
// Intent intent = new Intent(activity, Permission.class);
// activity.startActivity(intent);
// // activity.finish();
// }
//
// @Override protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// if (sPermission == null) { finish(); return; }
// setContentView(R.layout.activity_text);
// Button okButton = (Button) findViewById(R.id.okTextButton);
// EditText listText = (EditText) findViewById(R.id.areaText);
// listText.setFocusable(false);
// listText.setText(getPermissionText());
// okButton.setOnClickListener(this);
// }
//
// private CharSequence getPermissionText()
// {
// StringBuilder sb = new StringBuilder();
// sb.append("Asking for permissions:\n\n");
// String necessary = "Necessary:\n";
// if (!isFirstForcedPermission) { necessary = "Recommended:\n"; }
// for (String curPermission : sPermission)
// {
// sb.append(necessary);
// necessary = "Recommended:\n";
// sb.append(curPermission.replace('.', '\n'));
// sb.append("\n\n");
// }
// return sb;
// }
//
// @Override protected void onResume()
// {
// super.onResume();
// if (!isAsking) {}
// else if (checkPermission(sPermission[0], this))
// {
// finish();
// }
// else if (!isFirstForcedPermission)
// {
// finish();
// }
// else
// {
// logUser("App needs access!!!");
// }
// isAsking = false;
// }
//
// @Override
// public void onClick(View v)
// {
// if (v.getId()==R.id.okTextButton)
// {
// log("Selected: Permission-Ok");
// requestPermissionLater(sPermission);
// isAsking = true;
// }
// }
//
// @Override
// public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
// if (grantResults.length >= 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// finish();
// } else {
// if (!isFirstForcedPermission)
// {
// finish();
// }
// else
// {
// logUser("App needs access for this feature!");
// }
// }
// }
//
// /** Check if permission is already permitted.
// * @param sPermission The Permission of android.Manifest.permission.xyz **/
// public static boolean checkPermission(String sPermission, Context context) {
// // Check if the Camera permission has been granted
// if (ActivityCompat.checkSelfPermission(context, sPermission)
// == PackageManager.PERMISSION_GRANTED) {
// return true;
// } else {
// return false;
// }
// }
//
// /** Check for permission to permit.
// * @param sPermission The Permission of android.Manifest.permission.xyz **/
// private void requestPermissionLater(String[] sPermission) {
// // if (ActivityCompat.shouldShowRequestPermissionRationale(this,
// // sPermission)) {
// ActivityCompat.requestPermissions(this,
// sPermission,
// getId());
// // } else {
// // logUser("Permission is not available: " + sPermission);
// // return false;
// // }
// }
//
// private int getId()
// {
// idCounter ++;
// return idCounter;
// }
//
// private void log(String str)
// {
// Log.i(Permission.class.getName(), str);
// }
//
// private void logUser(String str)
// {
// Log.i(Permission.class.getName(), str);
// try
// {
// Toast.makeText(this.getBaseContext(), str, Toast.LENGTH_SHORT).show();
// }
// catch (Exception e) { e.printStackTrace(); }
// }
// }
//
// Path: PocketMaps/app/src/main/java/com/villoren/android/kalmanlocationmanager/lib/KalmanLocationManager.java
// public static final String KALMAN_PROVIDER = "kalman";
//
// Path: PocketMaps/app/src/main/java/com/villoren/android/kalmanlocationmanager/lib/KalmanLocationManager.java
// public enum UseProvider { GPS, NET, GPS_AND_NET }
|
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import com.junjunguo.pocketmaps.activities.Permission;
import static com.villoren.android.kalmanlocationmanager.lib.KalmanLocationManager.KALMAN_PROVIDER;
import static com.villoren.android.kalmanlocationmanager.lib.KalmanLocationManager.UseProvider;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
|
@Override
public void onProviderDisabled(String provider) {
final String finalProvider = provider;
mClientHandler.post(new Runnable() {
@Override
public void run() {
mClientLocationListener.onProviderDisabled(finalProvider);
}
});
}
};
private Handler.Callback mOwnHandlerCallback = new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
if (mMaxPredictTimeReached)
{
// Enqueue next prediction
mOwnHandler.removeMessages(0);
mOwnHandler.sendEmptyMessageDelayed(0, mMinTimeFilter);
return true;
}
// Prepare location
|
// Path: PocketMaps/app/src/main/java/com/junjunguo/pocketmaps/activities/Permission.java
// public class Permission extends AppCompatActivity
// implements ActivityCompat.OnRequestPermissionsResultCallback, OnClickListener
// {
// static String[] sPermission;
// static boolean isFirstForcedPermission;
// static int idCounter = 0;
// static boolean isAsking = false;
//
// /** Start a Permission-Request, and calls activity.finish().
// * @param sPermission The Permission of android.Manifest.permission.xyz
// * @param isFirstForcedPermission True, if the first one of sPermission is forced. **/
// public static void startRequest(String[] sPermission, boolean isFirstForcedPermission, Activity activity)
// {
// Permission.sPermission = sPermission;
// Permission.isFirstForcedPermission = isFirstForcedPermission;
//
// Intent intent = new Intent(activity, Permission.class);
// activity.startActivity(intent);
// // activity.finish();
// }
//
// @Override protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// if (sPermission == null) { finish(); return; }
// setContentView(R.layout.activity_text);
// Button okButton = (Button) findViewById(R.id.okTextButton);
// EditText listText = (EditText) findViewById(R.id.areaText);
// listText.setFocusable(false);
// listText.setText(getPermissionText());
// okButton.setOnClickListener(this);
// }
//
// private CharSequence getPermissionText()
// {
// StringBuilder sb = new StringBuilder();
// sb.append("Asking for permissions:\n\n");
// String necessary = "Necessary:\n";
// if (!isFirstForcedPermission) { necessary = "Recommended:\n"; }
// for (String curPermission : sPermission)
// {
// sb.append(necessary);
// necessary = "Recommended:\n";
// sb.append(curPermission.replace('.', '\n'));
// sb.append("\n\n");
// }
// return sb;
// }
//
// @Override protected void onResume()
// {
// super.onResume();
// if (!isAsking) {}
// else if (checkPermission(sPermission[0], this))
// {
// finish();
// }
// else if (!isFirstForcedPermission)
// {
// finish();
// }
// else
// {
// logUser("App needs access!!!");
// }
// isAsking = false;
// }
//
// @Override
// public void onClick(View v)
// {
// if (v.getId()==R.id.okTextButton)
// {
// log("Selected: Permission-Ok");
// requestPermissionLater(sPermission);
// isAsking = true;
// }
// }
//
// @Override
// public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
// if (grantResults.length >= 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// finish();
// } else {
// if (!isFirstForcedPermission)
// {
// finish();
// }
// else
// {
// logUser("App needs access for this feature!");
// }
// }
// }
//
// /** Check if permission is already permitted.
// * @param sPermission The Permission of android.Manifest.permission.xyz **/
// public static boolean checkPermission(String sPermission, Context context) {
// // Check if the Camera permission has been granted
// if (ActivityCompat.checkSelfPermission(context, sPermission)
// == PackageManager.PERMISSION_GRANTED) {
// return true;
// } else {
// return false;
// }
// }
//
// /** Check for permission to permit.
// * @param sPermission The Permission of android.Manifest.permission.xyz **/
// private void requestPermissionLater(String[] sPermission) {
// // if (ActivityCompat.shouldShowRequestPermissionRationale(this,
// // sPermission)) {
// ActivityCompat.requestPermissions(this,
// sPermission,
// getId());
// // } else {
// // logUser("Permission is not available: " + sPermission);
// // return false;
// // }
// }
//
// private int getId()
// {
// idCounter ++;
// return idCounter;
// }
//
// private void log(String str)
// {
// Log.i(Permission.class.getName(), str);
// }
//
// private void logUser(String str)
// {
// Log.i(Permission.class.getName(), str);
// try
// {
// Toast.makeText(this.getBaseContext(), str, Toast.LENGTH_SHORT).show();
// }
// catch (Exception e) { e.printStackTrace(); }
// }
// }
//
// Path: PocketMaps/app/src/main/java/com/villoren/android/kalmanlocationmanager/lib/KalmanLocationManager.java
// public static final String KALMAN_PROVIDER = "kalman";
//
// Path: PocketMaps/app/src/main/java/com/villoren/android/kalmanlocationmanager/lib/KalmanLocationManager.java
// public enum UseProvider { GPS, NET, GPS_AND_NET }
// Path: PocketMaps/app/src/main/java/com/villoren/android/kalmanlocationmanager/lib/LooperThread.java
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import com.junjunguo.pocketmaps.activities.Permission;
import static com.villoren.android.kalmanlocationmanager.lib.KalmanLocationManager.KALMAN_PROVIDER;
import static com.villoren.android.kalmanlocationmanager.lib.KalmanLocationManager.UseProvider;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
@Override
public void onProviderDisabled(String provider) {
final String finalProvider = provider;
mClientHandler.post(new Runnable() {
@Override
public void run() {
mClientLocationListener.onProviderDisabled(finalProvider);
}
});
}
};
private Handler.Callback mOwnHandlerCallback = new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
if (mMaxPredictTimeReached)
{
// Enqueue next prediction
mOwnHandler.removeMessages(0);
mOwnHandler.sendEmptyMessageDelayed(0, mMinTimeFilter);
return true;
}
// Prepare location
|
final Location location = new Location(KALMAN_PROVIDER);
|
junjunguo/PocketMaps
|
PocketMaps/app/src/main/java/com/junjunguo/pocketmaps/fragments/MyAddressAdapter.java
|
// Path: PocketMaps/app/src/main/java/com/junjunguo/pocketmaps/geocoding/AddressLoc.java
// public class AddressLoc
// {
// private static final char STRING_SEP = '|';
// private static final char STRING_SEP_ESC = '/';
//
// /** Adds the address to prop.
// * @param updateLocName The old name of address (=firstLine) to update **/
// public static void addToProp(Properties prop, Address address, String updateLocName)
// {
// if (updateLocName!=null) { prop.remove(updateLocName); }
// ArrayList<String> addr = getLines(address);
// StringBuilder sb = new StringBuilder();
// for (int i=1; i<addr.size(); i++)
// {
// sb.append(addr.get(i).replace(STRING_SEP, STRING_SEP_ESC));
// sb.append('|');
// }
// sb.append(address.getLatitude());
// sb.append('|');
// sb.append(address.getLongitude());
// String addrName = addr.get(0);
// if (prop.containsKey(addrName))
// {
// if (updateLocName!=null)
// { // Use old name instead of overriding!
// addrName = updateLocName;
// }
// else
// {
// int index = 0;
// while(prop.containsKey(addrName + "_" + index)) { index++; }
// addrName = addrName + "_" + index;
// }
// }
// prop.put(addrName, sb.toString());
// }
//
// /** Gets all lines from address.
// * @return Array with a length of min 1. **/
// public static ArrayList<String> getLines(Address address)
// {
// ArrayList<String> list = new ArrayList<String>();
// putLine(list, address.getFeatureName());
// putLine(list, address.getThoroughfare());
// putLine(list, address.getUrl());
// putLine(list, address.getPostalCode());
// putLine(list, address.getSubThoroughfare());
// putLine(list, address.getPremises());
// putLine(list, address.getSubAdminArea());
// putLine(list, address.getAdminArea());
// putLine(list, address.getCountryCode());
// putLine(list, address.getCountryName());
// putLine(list, address.getSubLocality());
// putLine(list, address.getLocality());
// putLine(list, address.getPhone());
// for (int i=0; i<=address.getMaxAddressLineIndex(); i++)
// {
// putLine(list, address.getAddressLine(i));
// }
// if (list.size() == 0) { list.add(Variable.getVariable().getCountry()); }
// return list;
// }
//
// private static void putLine(ArrayList<String> list, String line)
// {
// if (line == null) { return; }
// if (line.isEmpty()) { return; }
// if (list.contains(line)) { return; }
// list.add(line);
// }
//
// public static Address readFromPropEntry(Entry<Object, Object> entry)
// {
// Address addr = new Address(Locale.getDefault());
// addr.setAddressLine(0, entry.getKey().toString());
// String[] lines = entry.getValue().toString().split("\\" + STRING_SEP, -1);
// for (int i=0; i<(lines.length-2); i++)
// {
// addr.setAddressLine(i+1, lines[i]);
// }
// try
// { // Last two values are lat and lon!
// addr.setLatitude(Double.parseDouble(lines[lines.length-2]));
// addr.setLongitude(Double.parseDouble(lines[lines.length-1]));
// }
// catch (NumberFormatException e)
// {
// log("Can not read lat lon from stored Favourite!");
// return null;
// }
// return addr;
// }
//
// private static void log(String str)
// {
// Log.i(AddressLoc.class.getName(), str);
// }
// }
//
// Path: PocketMaps/app/src/main/java/com/junjunguo/pocketmaps/model/listeners/OnClickAddressListener.java
// public interface OnClickAddressListener {
// /**
// * tell Activity what to do when address is clicked
// *
// * @param view
// */
// void onClick(Address addr);
// }
|
import android.location.Address;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.junjunguo.pocketmaps.R;
import com.junjunguo.pocketmaps.geocoding.AddressLoc;
import com.junjunguo.pocketmaps.model.listeners.OnClickAddressListener;
import java.util.ArrayList;
import java.util.List;
|
package com.junjunguo.pocketmaps.fragments;
/**
* This file is part of PocketMaps
* <p/>
* Created by GuoJunjun <junjunguo.com> on July 03, 2015.
*/
public class MyAddressAdapter extends RecyclerView.Adapter<MyAddressAdapter.ViewHolder> {
private List<Address> addressList;
|
// Path: PocketMaps/app/src/main/java/com/junjunguo/pocketmaps/geocoding/AddressLoc.java
// public class AddressLoc
// {
// private static final char STRING_SEP = '|';
// private static final char STRING_SEP_ESC = '/';
//
// /** Adds the address to prop.
// * @param updateLocName The old name of address (=firstLine) to update **/
// public static void addToProp(Properties prop, Address address, String updateLocName)
// {
// if (updateLocName!=null) { prop.remove(updateLocName); }
// ArrayList<String> addr = getLines(address);
// StringBuilder sb = new StringBuilder();
// for (int i=1; i<addr.size(); i++)
// {
// sb.append(addr.get(i).replace(STRING_SEP, STRING_SEP_ESC));
// sb.append('|');
// }
// sb.append(address.getLatitude());
// sb.append('|');
// sb.append(address.getLongitude());
// String addrName = addr.get(0);
// if (prop.containsKey(addrName))
// {
// if (updateLocName!=null)
// { // Use old name instead of overriding!
// addrName = updateLocName;
// }
// else
// {
// int index = 0;
// while(prop.containsKey(addrName + "_" + index)) { index++; }
// addrName = addrName + "_" + index;
// }
// }
// prop.put(addrName, sb.toString());
// }
//
// /** Gets all lines from address.
// * @return Array with a length of min 1. **/
// public static ArrayList<String> getLines(Address address)
// {
// ArrayList<String> list = new ArrayList<String>();
// putLine(list, address.getFeatureName());
// putLine(list, address.getThoroughfare());
// putLine(list, address.getUrl());
// putLine(list, address.getPostalCode());
// putLine(list, address.getSubThoroughfare());
// putLine(list, address.getPremises());
// putLine(list, address.getSubAdminArea());
// putLine(list, address.getAdminArea());
// putLine(list, address.getCountryCode());
// putLine(list, address.getCountryName());
// putLine(list, address.getSubLocality());
// putLine(list, address.getLocality());
// putLine(list, address.getPhone());
// for (int i=0; i<=address.getMaxAddressLineIndex(); i++)
// {
// putLine(list, address.getAddressLine(i));
// }
// if (list.size() == 0) { list.add(Variable.getVariable().getCountry()); }
// return list;
// }
//
// private static void putLine(ArrayList<String> list, String line)
// {
// if (line == null) { return; }
// if (line.isEmpty()) { return; }
// if (list.contains(line)) { return; }
// list.add(line);
// }
//
// public static Address readFromPropEntry(Entry<Object, Object> entry)
// {
// Address addr = new Address(Locale.getDefault());
// addr.setAddressLine(0, entry.getKey().toString());
// String[] lines = entry.getValue().toString().split("\\" + STRING_SEP, -1);
// for (int i=0; i<(lines.length-2); i++)
// {
// addr.setAddressLine(i+1, lines[i]);
// }
// try
// { // Last two values are lat and lon!
// addr.setLatitude(Double.parseDouble(lines[lines.length-2]));
// addr.setLongitude(Double.parseDouble(lines[lines.length-1]));
// }
// catch (NumberFormatException e)
// {
// log("Can not read lat lon from stored Favourite!");
// return null;
// }
// return addr;
// }
//
// private static void log(String str)
// {
// Log.i(AddressLoc.class.getName(), str);
// }
// }
//
// Path: PocketMaps/app/src/main/java/com/junjunguo/pocketmaps/model/listeners/OnClickAddressListener.java
// public interface OnClickAddressListener {
// /**
// * tell Activity what to do when address is clicked
// *
// * @param view
// */
// void onClick(Address addr);
// }
// Path: PocketMaps/app/src/main/java/com/junjunguo/pocketmaps/fragments/MyAddressAdapter.java
import android.location.Address;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.junjunguo.pocketmaps.R;
import com.junjunguo.pocketmaps.geocoding.AddressLoc;
import com.junjunguo.pocketmaps.model.listeners.OnClickAddressListener;
import java.util.ArrayList;
import java.util.List;
package com.junjunguo.pocketmaps.fragments;
/**
* This file is part of PocketMaps
* <p/>
* Created by GuoJunjun <junjunguo.com> on July 03, 2015.
*/
public class MyAddressAdapter extends RecyclerView.Adapter<MyAddressAdapter.ViewHolder> {
private List<Address> addressList;
|
private OnClickAddressListener onClickAddressListener;
|
junjunguo/PocketMaps
|
PocketMaps/app/src/main/java/com/junjunguo/pocketmaps/fragments/MyAddressAdapter.java
|
// Path: PocketMaps/app/src/main/java/com/junjunguo/pocketmaps/geocoding/AddressLoc.java
// public class AddressLoc
// {
// private static final char STRING_SEP = '|';
// private static final char STRING_SEP_ESC = '/';
//
// /** Adds the address to prop.
// * @param updateLocName The old name of address (=firstLine) to update **/
// public static void addToProp(Properties prop, Address address, String updateLocName)
// {
// if (updateLocName!=null) { prop.remove(updateLocName); }
// ArrayList<String> addr = getLines(address);
// StringBuilder sb = new StringBuilder();
// for (int i=1; i<addr.size(); i++)
// {
// sb.append(addr.get(i).replace(STRING_SEP, STRING_SEP_ESC));
// sb.append('|');
// }
// sb.append(address.getLatitude());
// sb.append('|');
// sb.append(address.getLongitude());
// String addrName = addr.get(0);
// if (prop.containsKey(addrName))
// {
// if (updateLocName!=null)
// { // Use old name instead of overriding!
// addrName = updateLocName;
// }
// else
// {
// int index = 0;
// while(prop.containsKey(addrName + "_" + index)) { index++; }
// addrName = addrName + "_" + index;
// }
// }
// prop.put(addrName, sb.toString());
// }
//
// /** Gets all lines from address.
// * @return Array with a length of min 1. **/
// public static ArrayList<String> getLines(Address address)
// {
// ArrayList<String> list = new ArrayList<String>();
// putLine(list, address.getFeatureName());
// putLine(list, address.getThoroughfare());
// putLine(list, address.getUrl());
// putLine(list, address.getPostalCode());
// putLine(list, address.getSubThoroughfare());
// putLine(list, address.getPremises());
// putLine(list, address.getSubAdminArea());
// putLine(list, address.getAdminArea());
// putLine(list, address.getCountryCode());
// putLine(list, address.getCountryName());
// putLine(list, address.getSubLocality());
// putLine(list, address.getLocality());
// putLine(list, address.getPhone());
// for (int i=0; i<=address.getMaxAddressLineIndex(); i++)
// {
// putLine(list, address.getAddressLine(i));
// }
// if (list.size() == 0) { list.add(Variable.getVariable().getCountry()); }
// return list;
// }
//
// private static void putLine(ArrayList<String> list, String line)
// {
// if (line == null) { return; }
// if (line.isEmpty()) { return; }
// if (list.contains(line)) { return; }
// list.add(line);
// }
//
// public static Address readFromPropEntry(Entry<Object, Object> entry)
// {
// Address addr = new Address(Locale.getDefault());
// addr.setAddressLine(0, entry.getKey().toString());
// String[] lines = entry.getValue().toString().split("\\" + STRING_SEP, -1);
// for (int i=0; i<(lines.length-2); i++)
// {
// addr.setAddressLine(i+1, lines[i]);
// }
// try
// { // Last two values are lat and lon!
// addr.setLatitude(Double.parseDouble(lines[lines.length-2]));
// addr.setLongitude(Double.parseDouble(lines[lines.length-1]));
// }
// catch (NumberFormatException e)
// {
// log("Can not read lat lon from stored Favourite!");
// return null;
// }
// return addr;
// }
//
// private static void log(String str)
// {
// Log.i(AddressLoc.class.getName(), str);
// }
// }
//
// Path: PocketMaps/app/src/main/java/com/junjunguo/pocketmaps/model/listeners/OnClickAddressListener.java
// public interface OnClickAddressListener {
// /**
// * tell Activity what to do when address is clicked
// *
// * @param view
// */
// void onClick(Address addr);
// }
|
import android.location.Address;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.junjunguo.pocketmaps.R;
import com.junjunguo.pocketmaps.geocoding.AddressLoc;
import com.junjunguo.pocketmaps.model.listeners.OnClickAddressListener;
import java.util.ArrayList;
import java.util.List;
|
ImageView addrDetailsButton;
public ViewHolder(View itemView, OnClickAddressListener onClickAddressListener, OnClickAddressListener onClickDetailsListener) {
super(itemView);
this.onClickAddressListener = onClickAddressListener;
this.onClickDetailsListener = onClickDetailsListener;
this.firstLine = (TextView) itemView.findViewById(R.id.mapFirstLineTxt);
this.secondLine = (TextView) itemView.findViewById(R.id.mapSecondLineTxt);
this.thirdLine = (TextView) itemView.findViewById(R.id.mapThirdLineTxt);
this.fourthLine = (TextView) itemView.findViewById(R.id.mapFourthLineTxt);
this.addrDetailsButton = (ImageView) itemView.findViewById(R.id.iconAddressDetail);
}
public void setItemData(final Address address) {
View.OnClickListener clickListener = new View.OnClickListener() {
public void onClick(View v) {
log("onClick: " + itemView.toString());
onClickAddressListener.onClick(address);
}
};
View.OnClickListener clickDetListener = new View.OnClickListener() {
public void onClick(View v) {
log("onClick: " + itemView.toString());
onClickDetailsListener.onClick(address);
}
};
firstLine.setOnClickListener(clickListener);
secondLine.setOnClickListener(clickListener);
thirdLine.setOnClickListener(clickListener);
fourthLine.setOnClickListener(clickListener);
addrDetailsButton.setOnClickListener(clickDetListener);
|
// Path: PocketMaps/app/src/main/java/com/junjunguo/pocketmaps/geocoding/AddressLoc.java
// public class AddressLoc
// {
// private static final char STRING_SEP = '|';
// private static final char STRING_SEP_ESC = '/';
//
// /** Adds the address to prop.
// * @param updateLocName The old name of address (=firstLine) to update **/
// public static void addToProp(Properties prop, Address address, String updateLocName)
// {
// if (updateLocName!=null) { prop.remove(updateLocName); }
// ArrayList<String> addr = getLines(address);
// StringBuilder sb = new StringBuilder();
// for (int i=1; i<addr.size(); i++)
// {
// sb.append(addr.get(i).replace(STRING_SEP, STRING_SEP_ESC));
// sb.append('|');
// }
// sb.append(address.getLatitude());
// sb.append('|');
// sb.append(address.getLongitude());
// String addrName = addr.get(0);
// if (prop.containsKey(addrName))
// {
// if (updateLocName!=null)
// { // Use old name instead of overriding!
// addrName = updateLocName;
// }
// else
// {
// int index = 0;
// while(prop.containsKey(addrName + "_" + index)) { index++; }
// addrName = addrName + "_" + index;
// }
// }
// prop.put(addrName, sb.toString());
// }
//
// /** Gets all lines from address.
// * @return Array with a length of min 1. **/
// public static ArrayList<String> getLines(Address address)
// {
// ArrayList<String> list = new ArrayList<String>();
// putLine(list, address.getFeatureName());
// putLine(list, address.getThoroughfare());
// putLine(list, address.getUrl());
// putLine(list, address.getPostalCode());
// putLine(list, address.getSubThoroughfare());
// putLine(list, address.getPremises());
// putLine(list, address.getSubAdminArea());
// putLine(list, address.getAdminArea());
// putLine(list, address.getCountryCode());
// putLine(list, address.getCountryName());
// putLine(list, address.getSubLocality());
// putLine(list, address.getLocality());
// putLine(list, address.getPhone());
// for (int i=0; i<=address.getMaxAddressLineIndex(); i++)
// {
// putLine(list, address.getAddressLine(i));
// }
// if (list.size() == 0) { list.add(Variable.getVariable().getCountry()); }
// return list;
// }
//
// private static void putLine(ArrayList<String> list, String line)
// {
// if (line == null) { return; }
// if (line.isEmpty()) { return; }
// if (list.contains(line)) { return; }
// list.add(line);
// }
//
// public static Address readFromPropEntry(Entry<Object, Object> entry)
// {
// Address addr = new Address(Locale.getDefault());
// addr.setAddressLine(0, entry.getKey().toString());
// String[] lines = entry.getValue().toString().split("\\" + STRING_SEP, -1);
// for (int i=0; i<(lines.length-2); i++)
// {
// addr.setAddressLine(i+1, lines[i]);
// }
// try
// { // Last two values are lat and lon!
// addr.setLatitude(Double.parseDouble(lines[lines.length-2]));
// addr.setLongitude(Double.parseDouble(lines[lines.length-1]));
// }
// catch (NumberFormatException e)
// {
// log("Can not read lat lon from stored Favourite!");
// return null;
// }
// return addr;
// }
//
// private static void log(String str)
// {
// Log.i(AddressLoc.class.getName(), str);
// }
// }
//
// Path: PocketMaps/app/src/main/java/com/junjunguo/pocketmaps/model/listeners/OnClickAddressListener.java
// public interface OnClickAddressListener {
// /**
// * tell Activity what to do when address is clicked
// *
// * @param view
// */
// void onClick(Address addr);
// }
// Path: PocketMaps/app/src/main/java/com/junjunguo/pocketmaps/fragments/MyAddressAdapter.java
import android.location.Address;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.junjunguo.pocketmaps.R;
import com.junjunguo.pocketmaps.geocoding.AddressLoc;
import com.junjunguo.pocketmaps.model.listeners.OnClickAddressListener;
import java.util.ArrayList;
import java.util.List;
ImageView addrDetailsButton;
public ViewHolder(View itemView, OnClickAddressListener onClickAddressListener, OnClickAddressListener onClickDetailsListener) {
super(itemView);
this.onClickAddressListener = onClickAddressListener;
this.onClickDetailsListener = onClickDetailsListener;
this.firstLine = (TextView) itemView.findViewById(R.id.mapFirstLineTxt);
this.secondLine = (TextView) itemView.findViewById(R.id.mapSecondLineTxt);
this.thirdLine = (TextView) itemView.findViewById(R.id.mapThirdLineTxt);
this.fourthLine = (TextView) itemView.findViewById(R.id.mapFourthLineTxt);
this.addrDetailsButton = (ImageView) itemView.findViewById(R.id.iconAddressDetail);
}
public void setItemData(final Address address) {
View.OnClickListener clickListener = new View.OnClickListener() {
public void onClick(View v) {
log("onClick: " + itemView.toString());
onClickAddressListener.onClick(address);
}
};
View.OnClickListener clickDetListener = new View.OnClickListener() {
public void onClick(View v) {
log("onClick: " + itemView.toString());
onClickDetailsListener.onClick(address);
}
};
firstLine.setOnClickListener(clickListener);
secondLine.setOnClickListener(clickListener);
thirdLine.setOnClickListener(clickListener);
fourthLine.setOnClickListener(clickListener);
addrDetailsButton.setOnClickListener(clickDetListener);
|
ArrayList<String> lines = AddressLoc.getLines(address);
|
junjunguo/PocketMaps
|
PocketMaps/app/src/main/java/com/junjunguo/pocketmaps/model/SportCategory.java
|
// Path: PocketMaps/app/src/main/java/com/junjunguo/pocketmaps/util/Calorie.java
// public class Calorie {
// /*
// * sport category, which defines the MET value
// */
//
// /** Slow with bike 10mph or 16kmh **/
// public final static double BIKE_SLOW = 4.0;
// /** Normal with bike 13mph or 20kmh **/
// public final static double BIKE_MID = 8.0;
// /** Fast with bike 15mph or 24kmh **/
// public final static double BIKE_FAST = 10.0;
// /** Slow walk 3mph or 5kmh **/
// public final static double WALK_SLOW = 3.0;
// /** Slow running 5mph or 8kmh **/
// public final static double RUN_SLOW = 8.0;
// /** Normal running 8mph or 12kmh **/
// public final static double RUN_MID = 13.5;
// /** Fast running 10mph or 16kmh **/
// public final static double RUN_FAST = 16.0;
// /** General driving with car **/
// public final static double CAR_DRIVE = 2.0;
//
// public enum Type {Bike, Car, Run};
//
// /**
// * default body weight by kg if not defined by user
// */
// public final static double weightKg = 77.0;
//
// public static double getMET(double speedKmh, Type type)
// {
// if (type == Type.Run)
// {
// if (speedKmh<6.5) { return WALK_SLOW; }
// if (speedKmh<10) { return RUN_SLOW; }
// if (speedKmh<14) { return RUN_MID; }
// return RUN_FAST;
// }
// else if (type == Type.Bike)
// {
// if (speedKmh<18) { return BIKE_SLOW; }
// if (speedKmh<22) { return BIKE_MID; }
// return BIKE_FAST;
// }
// return CAR_DRIVE;
// }
//
//
// /**
// * weightKg = 77.0
// *
// * @param activity: bicycling, running, walking
// * @param timeHour: hours
// * @return calorie burned (activity * weightKg * timeHour)
// */
// public static double calorieBurned(double activity, double timeHour) {
// return calorieBurned(activity, weightKg, timeHour);
// }
//
// /**
// * @param activity: bicycling, running, walking
// * @param weightKg: in kg
// * @param timeHour: hours
// * @return calorie burned (activity * weightKg * timeHour)
// */
// public static double calorieBurned(double activity, double weightKg, double timeHour) {
// return activity * weightKg * timeHour;
// }
//
// /**
// * use The Harris–Benedict equations revised by Roza and Shizgal in 1984. BMR
// *
// * @param activity: bicycling, running, walking
// * @param weightKg: in kg
// * @param timeHour: hours
// * @param heightCm: height in cm
// * @param age: age in years
// * @param men: true -> men ; false -> women
// * @return calorie burned (BMR * activity * timeHour)
// */
// public static double calorieBurned(double activity, double weightKg, double timeHour, double heightCm, double age,
// boolean men) {
// if (men) {
// return (88.362 + (13.397 * weightKg) + (4.799 * heightCm) - (5.677 * age)) * activity * timeHour;
// }
// return (447.593 + (9.247 * weightKg) + (3.098 * heightCm) - (4.330 * age)) * activity * timeHour;
// }
// }
|
import com.junjunguo.pocketmaps.util.Calorie;
|
package com.junjunguo.pocketmaps.model;
/**
* This file is part of PocketMaps
* <p>
* Created by GuoJunjun <junjunguo.com> on August 30, 2015.
*/
public class SportCategory {
private String text;
private Integer imageId;
|
// Path: PocketMaps/app/src/main/java/com/junjunguo/pocketmaps/util/Calorie.java
// public class Calorie {
// /*
// * sport category, which defines the MET value
// */
//
// /** Slow with bike 10mph or 16kmh **/
// public final static double BIKE_SLOW = 4.0;
// /** Normal with bike 13mph or 20kmh **/
// public final static double BIKE_MID = 8.0;
// /** Fast with bike 15mph or 24kmh **/
// public final static double BIKE_FAST = 10.0;
// /** Slow walk 3mph or 5kmh **/
// public final static double WALK_SLOW = 3.0;
// /** Slow running 5mph or 8kmh **/
// public final static double RUN_SLOW = 8.0;
// /** Normal running 8mph or 12kmh **/
// public final static double RUN_MID = 13.5;
// /** Fast running 10mph or 16kmh **/
// public final static double RUN_FAST = 16.0;
// /** General driving with car **/
// public final static double CAR_DRIVE = 2.0;
//
// public enum Type {Bike, Car, Run};
//
// /**
// * default body weight by kg if not defined by user
// */
// public final static double weightKg = 77.0;
//
// public static double getMET(double speedKmh, Type type)
// {
// if (type == Type.Run)
// {
// if (speedKmh<6.5) { return WALK_SLOW; }
// if (speedKmh<10) { return RUN_SLOW; }
// if (speedKmh<14) { return RUN_MID; }
// return RUN_FAST;
// }
// else if (type == Type.Bike)
// {
// if (speedKmh<18) { return BIKE_SLOW; }
// if (speedKmh<22) { return BIKE_MID; }
// return BIKE_FAST;
// }
// return CAR_DRIVE;
// }
//
//
// /**
// * weightKg = 77.0
// *
// * @param activity: bicycling, running, walking
// * @param timeHour: hours
// * @return calorie burned (activity * weightKg * timeHour)
// */
// public static double calorieBurned(double activity, double timeHour) {
// return calorieBurned(activity, weightKg, timeHour);
// }
//
// /**
// * @param activity: bicycling, running, walking
// * @param weightKg: in kg
// * @param timeHour: hours
// * @return calorie burned (activity * weightKg * timeHour)
// */
// public static double calorieBurned(double activity, double weightKg, double timeHour) {
// return activity * weightKg * timeHour;
// }
//
// /**
// * use The Harris–Benedict equations revised by Roza and Shizgal in 1984. BMR
// *
// * @param activity: bicycling, running, walking
// * @param weightKg: in kg
// * @param timeHour: hours
// * @param heightCm: height in cm
// * @param age: age in years
// * @param men: true -> men ; false -> women
// * @return calorie burned (BMR * activity * timeHour)
// */
// public static double calorieBurned(double activity, double weightKg, double timeHour, double heightCm, double age,
// boolean men) {
// if (men) {
// return (88.362 + (13.397 * weightKg) + (4.799 * heightCm) - (5.677 * age)) * activity * timeHour;
// }
// return (447.593 + (9.247 * weightKg) + (3.098 * heightCm) - (4.330 * age)) * activity * timeHour;
// }
// }
// Path: PocketMaps/app/src/main/java/com/junjunguo/pocketmaps/model/SportCategory.java
import com.junjunguo.pocketmaps.util.Calorie;
package com.junjunguo.pocketmaps.model;
/**
* This file is part of PocketMaps
* <p>
* Created by GuoJunjun <junjunguo.com> on August 30, 2015.
*/
public class SportCategory {
private String text;
private Integer imageId;
|
private Calorie.Type sportMET;
|
pjq/rpi
|
android/app/src/main/java/me/pjq/rpicar/widget/RadarView.java
|
// Path: android/app/src/main/java/me/pjq/rpicar/utils/Utils.java
// public class Utils {
// public static int[] Getrandomarray(int i, int i1) {
// int size = 11;
// int[] value = new int[size];
// for (int j = 0; j < size; j++) {
// value[j] = j;
// }
//
// return value;
// }
// }
|
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.SweepGradient;
import android.support.annotation.IntDef;
import android.util.AttributeSet;
import android.widget.FrameLayout;
import me.pjq.rpicar.utils.Utils;
|
// TODO Auto-generated method stub
setBackgroundColor(Color.TRANSPARENT);
//宽度=5,抗锯齿,描边效果的白色画笔
mPaintLine = new Paint();
mPaintLine.setStrokeWidth(5);
mPaintLine.setAntiAlias(true);
mPaintLine.setStyle(Paint.Style.STROKE);
mPaintLine.setColor(Color.WHITE);
//宽度=5,抗锯齿,描边效果的浅绿色画笔
mPaintCircle = new Paint();
mPaintCircle.setStrokeWidth(5);
mPaintCircle.setAntiAlias(true);
mPaintCircle.setStyle(Paint.Style.FILL);
mPaintCircle.setColor(0x99000000);
//暗绿色的画笔
mPaintSector = new Paint();
mPaintSector.setColor(0x9D00ff00);
mPaintSector.setAntiAlias(true);
mShader = new SweepGradient(viewSize / 2, viewSize / 2, Color.TRANSPARENT, Color.GREEN);
mPaintSector.setShader(mShader);
//白色实心画笔
mPaintPoint=new Paint();
mPaintPoint.setColor(Color.WHITE);
mPaintPoint.setStyle(Paint.Style.FILL);
//随机生成的点,模拟雷达扫描结果
|
// Path: android/app/src/main/java/me/pjq/rpicar/utils/Utils.java
// public class Utils {
// public static int[] Getrandomarray(int i, int i1) {
// int size = 11;
// int[] value = new int[size];
// for (int j = 0; j < size; j++) {
// value[j] = j;
// }
//
// return value;
// }
// }
// Path: android/app/src/main/java/me/pjq/rpicar/widget/RadarView.java
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.SweepGradient;
import android.support.annotation.IntDef;
import android.util.AttributeSet;
import android.widget.FrameLayout;
import me.pjq.rpicar.utils.Utils;
// TODO Auto-generated method stub
setBackgroundColor(Color.TRANSPARENT);
//宽度=5,抗锯齿,描边效果的白色画笔
mPaintLine = new Paint();
mPaintLine.setStrokeWidth(5);
mPaintLine.setAntiAlias(true);
mPaintLine.setStyle(Paint.Style.STROKE);
mPaintLine.setColor(Color.WHITE);
//宽度=5,抗锯齿,描边效果的浅绿色画笔
mPaintCircle = new Paint();
mPaintCircle.setStrokeWidth(5);
mPaintCircle.setAntiAlias(true);
mPaintCircle.setStyle(Paint.Style.FILL);
mPaintCircle.setColor(0x99000000);
//暗绿色的画笔
mPaintSector = new Paint();
mPaintSector.setColor(0x9D00ff00);
mPaintSector.setAntiAlias(true);
mShader = new SweepGradient(viewSize / 2, viewSize / 2, Color.TRANSPARENT, Color.GREEN);
mPaintSector.setShader(mShader);
//白色实心画笔
mPaintPoint=new Paint();
mPaintPoint.setColor(Color.WHITE);
mPaintPoint.setStyle(Paint.Style.FILL);
//随机生成的点,模拟雷达扫描结果
|
point_x = Utils.Getrandomarray(15, 300);
|
pjq/rpi
|
spring-server/src/main/java/me/pjq/Constants.java
|
// Path: spring-server/src/main/java/me/pjq/Utils/Log.java
// public class Log {
// static String dateFormat = "yyyy-MM-dd hh:mm:ss";
// static SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
// static boolean showLog = true;
//
// public static void log(String tag, String msg) {
// if (showLog) {
// String source = null;
// try {
// StackTraceElement st = Thread.currentThread().getStackTrace()[2];
// source = "[" + st.getFileName() + "] - " + st.getMethodName() + "("
// + st.getLineNumber() + ")";
// } catch (Exception e) {
// }
//
// System.out.println(fm.format(new Date()) + " - " + source + ":" + msg);
// }
// }
// }
//
// Path: spring-server/src/main/java/me/pjq/model/Config.java
// public class Config {
// public String deviceName;
// public String productKey;
// public String secret;
// public String pubTopic;
// public String subTopic;
//
// public String accessKeyId;
// public String accessKeySecret;
// public String phone;
// public String signName;
// public String templateCode;
// //10 seconds, interval for SensorStatus update.
// public long SENSOR_STATUS_UPDATE_INTERVAL;
// // duration for auto turn off the power via relay control
// public long RELAY_OFF_INTERVAL;
//
// public Config(String deviceName, String productKey, String secret) {
// this.deviceName = deviceName;
// this.productKey = productKey;
// this.secret = secret;
// //用于测试的topic
// pubTopic = "/" + productKey + "/" + deviceName + "/update";
// subTopic = "/" + productKey + "/" + deviceName + "/get";
// }
//
// public static Config getConfigRpiCarHome() {
// String deviceName = "RpiCarHome";
// String productKey = "tKB3pmbLvnA";
// String secret = "fT9ryVgfucZNs2g0VZkj8kzV3eNjY55E";
//
// return new Config(deviceName, productKey, secret);
// }
//
// public static Config getConfigRpiCarClient() {
// String deviceName = "RpiCarClient";
// String productKey = "tKB3pmbLvnA";
// String secret = "w7TT5kvx1xdzfVogH7RfUUto4kWoSCq4";
//
// return new Config(deviceName, productKey, secret);
// }
// }
|
import me.pjq.Utils.Log;
import me.pjq.model.Config;
import java.io.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Properties;
|
package me.pjq;
public enum Constants {
INSTANCE;
private static final String TAG = "Constants";
// public static String deviceName = "RpiCarHome";
// public static String productKey = "tKB3pmbLvnA";
// public static String secret = "fT9ryVgfucZNs2g0VZkj8kzV3eNjY55E";
// public static String deviceName = "RpiCarClient";
// public static String productKey = "tKB3pmbLvnA";
// public static String secret = "w7TT5kvx1xdzfVogH7RfUUto4kWoSCq4";
// public static String aK1="LTAICKNMlWB";
// public static String aK2="xm7GR";
// public static String accessKeyId = aK1+aK2;
// public static String accessKeySecret = "cMgi0pjAewppBdpESDlI3CXZpAKFwc";
// public static String phone = "18621517768";
// public static String signName = "树霉派IoT";
// public static String templateCode = "SMS_110310049";
//10 seconds, interval for SensorStatus update.
// public static long SENSOR_STATUS_UPDATE_INTERVAL = 10000;
// duration for auto turn off the power via relay control
// public static long RELAY_OFF_INTERVAL = 30 * 1000;
// public static String pubTopic = "/" + productKey + "/" + deviceName + "/update";
//用于测试的topic
// public static String subTopic = "/" + productKey + "/" + deviceName + "/get";
private static final String CONFIG_FILE = "config.properties";
private static final String CONFIG_FILE_DEFAULT = "./src/main/resources/config.properties";
|
// Path: spring-server/src/main/java/me/pjq/Utils/Log.java
// public class Log {
// static String dateFormat = "yyyy-MM-dd hh:mm:ss";
// static SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
// static boolean showLog = true;
//
// public static void log(String tag, String msg) {
// if (showLog) {
// String source = null;
// try {
// StackTraceElement st = Thread.currentThread().getStackTrace()[2];
// source = "[" + st.getFileName() + "] - " + st.getMethodName() + "("
// + st.getLineNumber() + ")";
// } catch (Exception e) {
// }
//
// System.out.println(fm.format(new Date()) + " - " + source + ":" + msg);
// }
// }
// }
//
// Path: spring-server/src/main/java/me/pjq/model/Config.java
// public class Config {
// public String deviceName;
// public String productKey;
// public String secret;
// public String pubTopic;
// public String subTopic;
//
// public String accessKeyId;
// public String accessKeySecret;
// public String phone;
// public String signName;
// public String templateCode;
// //10 seconds, interval for SensorStatus update.
// public long SENSOR_STATUS_UPDATE_INTERVAL;
// // duration for auto turn off the power via relay control
// public long RELAY_OFF_INTERVAL;
//
// public Config(String deviceName, String productKey, String secret) {
// this.deviceName = deviceName;
// this.productKey = productKey;
// this.secret = secret;
// //用于测试的topic
// pubTopic = "/" + productKey + "/" + deviceName + "/update";
// subTopic = "/" + productKey + "/" + deviceName + "/get";
// }
//
// public static Config getConfigRpiCarHome() {
// String deviceName = "RpiCarHome";
// String productKey = "tKB3pmbLvnA";
// String secret = "fT9ryVgfucZNs2g0VZkj8kzV3eNjY55E";
//
// return new Config(deviceName, productKey, secret);
// }
//
// public static Config getConfigRpiCarClient() {
// String deviceName = "RpiCarClient";
// String productKey = "tKB3pmbLvnA";
// String secret = "w7TT5kvx1xdzfVogH7RfUUto4kWoSCq4";
//
// return new Config(deviceName, productKey, secret);
// }
// }
// Path: spring-server/src/main/java/me/pjq/Constants.java
import me.pjq.Utils.Log;
import me.pjq.model.Config;
import java.io.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Properties;
package me.pjq;
public enum Constants {
INSTANCE;
private static final String TAG = "Constants";
// public static String deviceName = "RpiCarHome";
// public static String productKey = "tKB3pmbLvnA";
// public static String secret = "fT9ryVgfucZNs2g0VZkj8kzV3eNjY55E";
// public static String deviceName = "RpiCarClient";
// public static String productKey = "tKB3pmbLvnA";
// public static String secret = "w7TT5kvx1xdzfVogH7RfUUto4kWoSCq4";
// public static String aK1="LTAICKNMlWB";
// public static String aK2="xm7GR";
// public static String accessKeyId = aK1+aK2;
// public static String accessKeySecret = "cMgi0pjAewppBdpESDlI3CXZpAKFwc";
// public static String phone = "18621517768";
// public static String signName = "树霉派IoT";
// public static String templateCode = "SMS_110310049";
//10 seconds, interval for SensorStatus update.
// public static long SENSOR_STATUS_UPDATE_INTERVAL = 10000;
// duration for auto turn off the power via relay control
// public static long RELAY_OFF_INTERVAL = 30 * 1000;
// public static String pubTopic = "/" + productKey + "/" + deviceName + "/update";
//用于测试的topic
// public static String subTopic = "/" + productKey + "/" + deviceName + "/get";
private static final String CONFIG_FILE = "config.properties";
private static final String CONFIG_FILE_DEFAULT = "./src/main/resources/config.properties";
|
private Config config;
|
pjq/rpi
|
spring-server/src/main/java/me/pjq/Constants.java
|
// Path: spring-server/src/main/java/me/pjq/Utils/Log.java
// public class Log {
// static String dateFormat = "yyyy-MM-dd hh:mm:ss";
// static SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
// static boolean showLog = true;
//
// public static void log(String tag, String msg) {
// if (showLog) {
// String source = null;
// try {
// StackTraceElement st = Thread.currentThread().getStackTrace()[2];
// source = "[" + st.getFileName() + "] - " + st.getMethodName() + "("
// + st.getLineNumber() + ")";
// } catch (Exception e) {
// }
//
// System.out.println(fm.format(new Date()) + " - " + source + ":" + msg);
// }
// }
// }
//
// Path: spring-server/src/main/java/me/pjq/model/Config.java
// public class Config {
// public String deviceName;
// public String productKey;
// public String secret;
// public String pubTopic;
// public String subTopic;
//
// public String accessKeyId;
// public String accessKeySecret;
// public String phone;
// public String signName;
// public String templateCode;
// //10 seconds, interval for SensorStatus update.
// public long SENSOR_STATUS_UPDATE_INTERVAL;
// // duration for auto turn off the power via relay control
// public long RELAY_OFF_INTERVAL;
//
// public Config(String deviceName, String productKey, String secret) {
// this.deviceName = deviceName;
// this.productKey = productKey;
// this.secret = secret;
// //用于测试的topic
// pubTopic = "/" + productKey + "/" + deviceName + "/update";
// subTopic = "/" + productKey + "/" + deviceName + "/get";
// }
//
// public static Config getConfigRpiCarHome() {
// String deviceName = "RpiCarHome";
// String productKey = "tKB3pmbLvnA";
// String secret = "fT9ryVgfucZNs2g0VZkj8kzV3eNjY55E";
//
// return new Config(deviceName, productKey, secret);
// }
//
// public static Config getConfigRpiCarClient() {
// String deviceName = "RpiCarClient";
// String productKey = "tKB3pmbLvnA";
// String secret = "w7TT5kvx1xdzfVogH7RfUUto4kWoSCq4";
//
// return new Config(deviceName, productKey, secret);
// }
// }
|
import me.pjq.Utils.Log;
import me.pjq.model.Config;
import java.io.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Properties;
|
package me.pjq;
public enum Constants {
INSTANCE;
private static final String TAG = "Constants";
// public static String deviceName = "RpiCarHome";
// public static String productKey = "tKB3pmbLvnA";
// public static String secret = "fT9ryVgfucZNs2g0VZkj8kzV3eNjY55E";
// public static String deviceName = "RpiCarClient";
// public static String productKey = "tKB3pmbLvnA";
// public static String secret = "w7TT5kvx1xdzfVogH7RfUUto4kWoSCq4";
// public static String aK1="LTAICKNMlWB";
// public static String aK2="xm7GR";
// public static String accessKeyId = aK1+aK2;
// public static String accessKeySecret = "cMgi0pjAewppBdpESDlI3CXZpAKFwc";
// public static String phone = "18621517768";
// public static String signName = "树霉派IoT";
// public static String templateCode = "SMS_110310049";
//10 seconds, interval for SensorStatus update.
// public static long SENSOR_STATUS_UPDATE_INTERVAL = 10000;
// duration for auto turn off the power via relay control
// public static long RELAY_OFF_INTERVAL = 30 * 1000;
// public static String pubTopic = "/" + productKey + "/" + deviceName + "/update";
//用于测试的topic
// public static String subTopic = "/" + productKey + "/" + deviceName + "/get";
private static final String CONFIG_FILE = "config.properties";
private static final String CONFIG_FILE_DEFAULT = "./src/main/resources/config.properties";
private Config config;
public Config getConfig() {
return config;
}
private Constants() {
try {
config = getAllProperties();
} catch (IOException e) {
e.printStackTrace();
}
}
//读取Properties的全部信息
public static HashMap<String, String> getAllProperties(String filePath) throws IOException {
Properties pps = new Properties();
InputStream in = new BufferedInputStream(new FileInputStream(filePath));
pps.load(in);
Enumeration en = pps.propertyNames(); //得到配置文件的名字
HashMap<String, String> map = new HashMap<>();
while (en.hasMoreElements()) {
String strKey = (String) en.nextElement();
String strValue = pps.getProperty(strKey);
strValue = new String(strValue.getBytes("ISO-8859-1"), "utf-8");
|
// Path: spring-server/src/main/java/me/pjq/Utils/Log.java
// public class Log {
// static String dateFormat = "yyyy-MM-dd hh:mm:ss";
// static SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
// static boolean showLog = true;
//
// public static void log(String tag, String msg) {
// if (showLog) {
// String source = null;
// try {
// StackTraceElement st = Thread.currentThread().getStackTrace()[2];
// source = "[" + st.getFileName() + "] - " + st.getMethodName() + "("
// + st.getLineNumber() + ")";
// } catch (Exception e) {
// }
//
// System.out.println(fm.format(new Date()) + " - " + source + ":" + msg);
// }
// }
// }
//
// Path: spring-server/src/main/java/me/pjq/model/Config.java
// public class Config {
// public String deviceName;
// public String productKey;
// public String secret;
// public String pubTopic;
// public String subTopic;
//
// public String accessKeyId;
// public String accessKeySecret;
// public String phone;
// public String signName;
// public String templateCode;
// //10 seconds, interval for SensorStatus update.
// public long SENSOR_STATUS_UPDATE_INTERVAL;
// // duration for auto turn off the power via relay control
// public long RELAY_OFF_INTERVAL;
//
// public Config(String deviceName, String productKey, String secret) {
// this.deviceName = deviceName;
// this.productKey = productKey;
// this.secret = secret;
// //用于测试的topic
// pubTopic = "/" + productKey + "/" + deviceName + "/update";
// subTopic = "/" + productKey + "/" + deviceName + "/get";
// }
//
// public static Config getConfigRpiCarHome() {
// String deviceName = "RpiCarHome";
// String productKey = "tKB3pmbLvnA";
// String secret = "fT9ryVgfucZNs2g0VZkj8kzV3eNjY55E";
//
// return new Config(deviceName, productKey, secret);
// }
//
// public static Config getConfigRpiCarClient() {
// String deviceName = "RpiCarClient";
// String productKey = "tKB3pmbLvnA";
// String secret = "w7TT5kvx1xdzfVogH7RfUUto4kWoSCq4";
//
// return new Config(deviceName, productKey, secret);
// }
// }
// Path: spring-server/src/main/java/me/pjq/Constants.java
import me.pjq.Utils.Log;
import me.pjq.model.Config;
import java.io.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Properties;
package me.pjq;
public enum Constants {
INSTANCE;
private static final String TAG = "Constants";
// public static String deviceName = "RpiCarHome";
// public static String productKey = "tKB3pmbLvnA";
// public static String secret = "fT9ryVgfucZNs2g0VZkj8kzV3eNjY55E";
// public static String deviceName = "RpiCarClient";
// public static String productKey = "tKB3pmbLvnA";
// public static String secret = "w7TT5kvx1xdzfVogH7RfUUto4kWoSCq4";
// public static String aK1="LTAICKNMlWB";
// public static String aK2="xm7GR";
// public static String accessKeyId = aK1+aK2;
// public static String accessKeySecret = "cMgi0pjAewppBdpESDlI3CXZpAKFwc";
// public static String phone = "18621517768";
// public static String signName = "树霉派IoT";
// public static String templateCode = "SMS_110310049";
//10 seconds, interval for SensorStatus update.
// public static long SENSOR_STATUS_UPDATE_INTERVAL = 10000;
// duration for auto turn off the power via relay control
// public static long RELAY_OFF_INTERVAL = 30 * 1000;
// public static String pubTopic = "/" + productKey + "/" + deviceName + "/update";
//用于测试的topic
// public static String subTopic = "/" + productKey + "/" + deviceName + "/get";
private static final String CONFIG_FILE = "config.properties";
private static final String CONFIG_FILE_DEFAULT = "./src/main/resources/config.properties";
private Config config;
public Config getConfig() {
return config;
}
private Constants() {
try {
config = getAllProperties();
} catch (IOException e) {
e.printStackTrace();
}
}
//读取Properties的全部信息
public static HashMap<String, String> getAllProperties(String filePath) throws IOException {
Properties pps = new Properties();
InputStream in = new BufferedInputStream(new FileInputStream(filePath));
pps.load(in);
Enumeration en = pps.propertyNames(); //得到配置文件的名字
HashMap<String, String> map = new HashMap<>();
while (en.hasMoreElements()) {
String strKey = (String) en.nextElement();
String strValue = pps.getProperty(strKey);
strValue = new String(strValue.getBytes("ISO-8859-1"), "utf-8");
|
Log.log(TAG, strKey + "=" + strValue);
|
pjq/rpi
|
android/app/src/main/java/me/pjq/rpicar/Constants.java
|
// Path: android/app/src/main/java/me/pjq/rpicar/utils/Log.java
// public class Log {
// static String dateFormat = "yyyy-MM-dd hh:mm:ss";
// static SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
// static boolean showLog = true;
//
// public static void log(String tag, String msg) {
// if (showLog) {
// String source = null;
// try {
// StackTraceElement st = Thread.currentThread().getStackTrace()[2];
// source = "[" + st.getFileName() + "] - " + st.getMethodName() + "("
// + st.getLineNumber() + ")";
// } catch (Exception e) {
// }
//
// System.out.println(fm.format(new Date()) + " - " + source + ":" + msg);
// }
// }
// }
|
import java.io.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Properties;
import me.pjq.rpicar.utils.Log;
|
package me.pjq.rpicar;
public enum Constants {
INSTANCE;
private static final String TAG = "Constants";
public static String deviceName = "RpiCarHome";
public static String productKey = "tKB3pmbLvnA";
public static String secret = "fT9ryVgfucZNs2g0VZkj8kzV3eNjY55E";
// public static String deviceName = "RpiCarClient";
// public static String productKey = "tKB3pmbLvnA";
// public static String secret = "w7TT5kvx1xdzfVogH7RfUUto4kWoSCq4";
public static String aK1="LTAICKNMlWB";
public static String aK2="xm7GR";
public static String accessKeyId = "LTAICKNMlWBxm7GR";
public static String accessKeySecret = "cMgi0pjAewppBdpESDlI3CXZpAKFwc";
public static String phone = "18621517768";
public static String signName = "树霉派IoT";
public static String templateCode = "SMS_110310049";
public static String pubTopic = "/" + productKey + "/" + deviceName + "/update";
//用于测试的topic
public static String subTopic = "/" + productKey + "/" + deviceName + "/get";
// private static final String CONFIG_FILE = "./src/main/resources/config.properties";
private static final String CONFIG_FILE = "config.properties";
//10 seconds, interval for SensorStatus update.
public static final long SENSOR_STATUS_UPDATE_INTERVAL = 10000;
// long RELAY_OFF_INTERVAL = 5 * 60 * 1000;
// duration for auto turn off the power via relay control
public static long RELAY_OFF_INTERVAL = 30 * 1000;
private Constants() {
try {
|
// Path: android/app/src/main/java/me/pjq/rpicar/utils/Log.java
// public class Log {
// static String dateFormat = "yyyy-MM-dd hh:mm:ss";
// static SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
// static boolean showLog = true;
//
// public static void log(String tag, String msg) {
// if (showLog) {
// String source = null;
// try {
// StackTraceElement st = Thread.currentThread().getStackTrace()[2];
// source = "[" + st.getFileName() + "] - " + st.getMethodName() + "("
// + st.getLineNumber() + ")";
// } catch (Exception e) {
// }
//
// System.out.println(fm.format(new Date()) + " - " + source + ":" + msg);
// }
// }
// }
// Path: android/app/src/main/java/me/pjq/rpicar/Constants.java
import java.io.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Properties;
import me.pjq.rpicar.utils.Log;
package me.pjq.rpicar;
public enum Constants {
INSTANCE;
private static final String TAG = "Constants";
public static String deviceName = "RpiCarHome";
public static String productKey = "tKB3pmbLvnA";
public static String secret = "fT9ryVgfucZNs2g0VZkj8kzV3eNjY55E";
// public static String deviceName = "RpiCarClient";
// public static String productKey = "tKB3pmbLvnA";
// public static String secret = "w7TT5kvx1xdzfVogH7RfUUto4kWoSCq4";
public static String aK1="LTAICKNMlWB";
public static String aK2="xm7GR";
public static String accessKeyId = "LTAICKNMlWBxm7GR";
public static String accessKeySecret = "cMgi0pjAewppBdpESDlI3CXZpAKFwc";
public static String phone = "18621517768";
public static String signName = "树霉派IoT";
public static String templateCode = "SMS_110310049";
public static String pubTopic = "/" + productKey + "/" + deviceName + "/update";
//用于测试的topic
public static String subTopic = "/" + productKey + "/" + deviceName + "/get";
// private static final String CONFIG_FILE = "./src/main/resources/config.properties";
private static final String CONFIG_FILE = "config.properties";
//10 seconds, interval for SensorStatus update.
public static final long SENSOR_STATUS_UPDATE_INTERVAL = 10000;
// long RELAY_OFF_INTERVAL = 5 * 60 * 1000;
// duration for auto turn off the power via relay control
public static long RELAY_OFF_INTERVAL = 30 * 1000;
private Constants() {
try {
|
Log.log(TAG, "init: " + CONFIG_FILE);
|
zxcpro/zing
|
zing-server/src/main/java/org/zxc/zing/server/remote/NettyServer.java
|
// Path: zing-common/src/main/java/org/zxc/zing/common/handler/NettyDecoder.java
// public class NettyDecoder extends ByteToMessageDecoder{
//
// private static final Logger log = LoggerFactory.getLogger(NettyDecoder.class);
//
// @Override
// protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
//
// log.info("try decode:"+in.toString());
//
// if (in.readableBytes() < 4) {
// log.info("no enough readable bytes");
// return;
// }
//
// int dataLength = in.readInt();
// if (dataLength < 0) {
// ctx.close();
// }
//
// log.info("try decode data length:"+dataLength);
//
// if (in.readableBytes() < dataLength) {
// in.resetReaderIndex();
// }
//
// log.info("try decode doDecode");
//
// byte[] data = new byte[dataLength];
// in.readBytes(data);
//
// Object deserialized = Serializer.deserialize(data);
// out.add(deserialized);
//
// }
// }
//
// Path: zing-common/src/main/java/org/zxc/zing/common/handler/NettyEncoder.java
// public class NettyEncoder extends MessageToByteEncoder {
//
// private static final Logger log = LoggerFactory.getLogger(NettyEncoder.class);
//
// @Override
// protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
//
// log.info("encoding start");
//
// byte[] bytes = Serializer.serialize(msg);
// out.writeInt(bytes.length);
// out.writeBytes(bytes);
//
// log.info("msg encoded length:"+bytes.length);
//
// }
// }
|
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zxc.zing.common.handler.NettyDecoder;
import org.zxc.zing.common.handler.NettyEncoder;
|
package org.zxc.zing.server.remote;
/**
* Created by xuanchen.zhao on 16-1-17.
*/
public class NettyServer {
private static final Logger log = LoggerFactory.getLogger(NettyServer.class);
private static volatile boolean started = false;
public static void start(int port) {
if (!started) {
synchronized (NettyServer.class) {
if (!started) {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
|
// Path: zing-common/src/main/java/org/zxc/zing/common/handler/NettyDecoder.java
// public class NettyDecoder extends ByteToMessageDecoder{
//
// private static final Logger log = LoggerFactory.getLogger(NettyDecoder.class);
//
// @Override
// protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
//
// log.info("try decode:"+in.toString());
//
// if (in.readableBytes() < 4) {
// log.info("no enough readable bytes");
// return;
// }
//
// int dataLength = in.readInt();
// if (dataLength < 0) {
// ctx.close();
// }
//
// log.info("try decode data length:"+dataLength);
//
// if (in.readableBytes() < dataLength) {
// in.resetReaderIndex();
// }
//
// log.info("try decode doDecode");
//
// byte[] data = new byte[dataLength];
// in.readBytes(data);
//
// Object deserialized = Serializer.deserialize(data);
// out.add(deserialized);
//
// }
// }
//
// Path: zing-common/src/main/java/org/zxc/zing/common/handler/NettyEncoder.java
// public class NettyEncoder extends MessageToByteEncoder {
//
// private static final Logger log = LoggerFactory.getLogger(NettyEncoder.class);
//
// @Override
// protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
//
// log.info("encoding start");
//
// byte[] bytes = Serializer.serialize(msg);
// out.writeInt(bytes.length);
// out.writeBytes(bytes);
//
// log.info("msg encoded length:"+bytes.length);
//
// }
// }
// Path: zing-server/src/main/java/org/zxc/zing/server/remote/NettyServer.java
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zxc.zing.common.handler.NettyDecoder;
import org.zxc.zing.common.handler.NettyEncoder;
package org.zxc.zing.server.remote;
/**
* Created by xuanchen.zhao on 16-1-17.
*/
public class NettyServer {
private static final Logger log = LoggerFactory.getLogger(NettyServer.class);
private static volatile boolean started = false;
public static void start(int port) {
if (!started) {
synchronized (NettyServer.class) {
if (!started) {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
|
ch.pipeline().addLast(new NettyDecoder(), new NettyEncoder(), new NettyServerHandler());
|
zxcpro/zing
|
zing-server/src/main/java/org/zxc/zing/server/remote/NettyServer.java
|
// Path: zing-common/src/main/java/org/zxc/zing/common/handler/NettyDecoder.java
// public class NettyDecoder extends ByteToMessageDecoder{
//
// private static final Logger log = LoggerFactory.getLogger(NettyDecoder.class);
//
// @Override
// protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
//
// log.info("try decode:"+in.toString());
//
// if (in.readableBytes() < 4) {
// log.info("no enough readable bytes");
// return;
// }
//
// int dataLength = in.readInt();
// if (dataLength < 0) {
// ctx.close();
// }
//
// log.info("try decode data length:"+dataLength);
//
// if (in.readableBytes() < dataLength) {
// in.resetReaderIndex();
// }
//
// log.info("try decode doDecode");
//
// byte[] data = new byte[dataLength];
// in.readBytes(data);
//
// Object deserialized = Serializer.deserialize(data);
// out.add(deserialized);
//
// }
// }
//
// Path: zing-common/src/main/java/org/zxc/zing/common/handler/NettyEncoder.java
// public class NettyEncoder extends MessageToByteEncoder {
//
// private static final Logger log = LoggerFactory.getLogger(NettyEncoder.class);
//
// @Override
// protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
//
// log.info("encoding start");
//
// byte[] bytes = Serializer.serialize(msg);
// out.writeInt(bytes.length);
// out.writeBytes(bytes);
//
// log.info("msg encoded length:"+bytes.length);
//
// }
// }
|
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zxc.zing.common.handler.NettyDecoder;
import org.zxc.zing.common.handler.NettyEncoder;
|
package org.zxc.zing.server.remote;
/**
* Created by xuanchen.zhao on 16-1-17.
*/
public class NettyServer {
private static final Logger log = LoggerFactory.getLogger(NettyServer.class);
private static volatile boolean started = false;
public static void start(int port) {
if (!started) {
synchronized (NettyServer.class) {
if (!started) {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
|
// Path: zing-common/src/main/java/org/zxc/zing/common/handler/NettyDecoder.java
// public class NettyDecoder extends ByteToMessageDecoder{
//
// private static final Logger log = LoggerFactory.getLogger(NettyDecoder.class);
//
// @Override
// protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
//
// log.info("try decode:"+in.toString());
//
// if (in.readableBytes() < 4) {
// log.info("no enough readable bytes");
// return;
// }
//
// int dataLength = in.readInt();
// if (dataLength < 0) {
// ctx.close();
// }
//
// log.info("try decode data length:"+dataLength);
//
// if (in.readableBytes() < dataLength) {
// in.resetReaderIndex();
// }
//
// log.info("try decode doDecode");
//
// byte[] data = new byte[dataLength];
// in.readBytes(data);
//
// Object deserialized = Serializer.deserialize(data);
// out.add(deserialized);
//
// }
// }
//
// Path: zing-common/src/main/java/org/zxc/zing/common/handler/NettyEncoder.java
// public class NettyEncoder extends MessageToByteEncoder {
//
// private static final Logger log = LoggerFactory.getLogger(NettyEncoder.class);
//
// @Override
// protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
//
// log.info("encoding start");
//
// byte[] bytes = Serializer.serialize(msg);
// out.writeInt(bytes.length);
// out.writeBytes(bytes);
//
// log.info("msg encoded length:"+bytes.length);
//
// }
// }
// Path: zing-server/src/main/java/org/zxc/zing/server/remote/NettyServer.java
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zxc.zing.common.handler.NettyDecoder;
import org.zxc.zing.common.handler.NettyEncoder;
package org.zxc.zing.server.remote;
/**
* Created by xuanchen.zhao on 16-1-17.
*/
public class NettyServer {
private static final Logger log = LoggerFactory.getLogger(NettyServer.class);
private static volatile boolean started = false;
public static void start(int port) {
if (!started) {
synchronized (NettyServer.class) {
if (!started) {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
|
ch.pipeline().addLast(new NettyDecoder(), new NettyEncoder(), new NettyServerHandler());
|
zxcpro/zing
|
zing-server/src/main/java/org/zxc/zing/server/remote/RemoteServiceBean.java
|
// Path: zing-server/src/main/java/org/zxc/zing/server/RemoteServiceServer.java
// public class RemoteServiceServer {
//
// private static final Logger log = LoggerFactory.getLogger(RemoteServiceServer.class);
//
// private static volatile boolean started = false;
//
// private static String ipAddress = ConfigManager.getInstance().getProperty(Constants.SERVER_IP_ADDRESS_CONFIG_KEY);
//
// private static int port = Strings.isNullOrEmpty(ConfigManager.getInstance().getProperty(Constants.SERVER_PORT_CONFIG_KEY)) ?
// Constants.SERVER_DEFAULT_PORT :
// Integer.valueOf(ConfigManager.getInstance().getProperty(Constants.SERVER_PORT_CONFIG_KEY));
//
//
// private static ConcurrentHashMap<String, Object> serviceImplMap = new ConcurrentHashMap<String, Object>();
//
// static {
// try {
// bootstrap();
// } catch (Exception e) {
// log.error("Server start error:"+e.getMessage(), e);
// System.exit(1);
// }
// }
//
// public static void addService(String serviceName, Object serviceImpl) {
// serviceImplMap.putIfAbsent(serviceName, serviceImpl);
// RegistryManager.publishService(serviceName, ipAddress, port);
// }
//
// public static void bootstrap() throws Exception {
// log.info("try bootstrap state:"+started);
// if (!started) {
// synchronized (RemoteServiceServer.class) {
// if (!started) {
// doStart();
// }
// }
// }
// log.info("started");
// }
//
// private static void doStart() throws Exception {
// log.info("do start server");
// NettyServer.start(port);
// RegistryManager.start();
// }
//
// public static Object getActualServiceImpl(String serviceName) {
// return serviceImplMap.get(serviceName);
// }
//
// }
|
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zxc.zing.server.RemoteServiceServer;
|
package org.zxc.zing.server.remote;
/**
* Created by xuanchen.zhao on 15-12-16.
*/
public class RemoteServiceBean {
private static final Logger log = LoggerFactory.getLogger(RemoteServiceBean.class);
private String serviceName;
private Object serviceImpl;
public void init() {
|
// Path: zing-server/src/main/java/org/zxc/zing/server/RemoteServiceServer.java
// public class RemoteServiceServer {
//
// private static final Logger log = LoggerFactory.getLogger(RemoteServiceServer.class);
//
// private static volatile boolean started = false;
//
// private static String ipAddress = ConfigManager.getInstance().getProperty(Constants.SERVER_IP_ADDRESS_CONFIG_KEY);
//
// private static int port = Strings.isNullOrEmpty(ConfigManager.getInstance().getProperty(Constants.SERVER_PORT_CONFIG_KEY)) ?
// Constants.SERVER_DEFAULT_PORT :
// Integer.valueOf(ConfigManager.getInstance().getProperty(Constants.SERVER_PORT_CONFIG_KEY));
//
//
// private static ConcurrentHashMap<String, Object> serviceImplMap = new ConcurrentHashMap<String, Object>();
//
// static {
// try {
// bootstrap();
// } catch (Exception e) {
// log.error("Server start error:"+e.getMessage(), e);
// System.exit(1);
// }
// }
//
// public static void addService(String serviceName, Object serviceImpl) {
// serviceImplMap.putIfAbsent(serviceName, serviceImpl);
// RegistryManager.publishService(serviceName, ipAddress, port);
// }
//
// public static void bootstrap() throws Exception {
// log.info("try bootstrap state:"+started);
// if (!started) {
// synchronized (RemoteServiceServer.class) {
// if (!started) {
// doStart();
// }
// }
// }
// log.info("started");
// }
//
// private static void doStart() throws Exception {
// log.info("do start server");
// NettyServer.start(port);
// RegistryManager.start();
// }
//
// public static Object getActualServiceImpl(String serviceName) {
// return serviceImplMap.get(serviceName);
// }
//
// }
// Path: zing-server/src/main/java/org/zxc/zing/server/remote/RemoteServiceBean.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zxc.zing.server.RemoteServiceServer;
package org.zxc.zing.server.remote;
/**
* Created by xuanchen.zhao on 15-12-16.
*/
public class RemoteServiceBean {
private static final Logger log = LoggerFactory.getLogger(RemoteServiceBean.class);
private String serviceName;
private Object serviceImpl;
public void init() {
|
RemoteServiceServer.addService(serviceName, serviceImpl);
|
zxcpro/zing
|
zing-common/src/main/java/org/zxc/zing/common/registry/ProviderNodeEventListener.java
|
// Path: zing-common/src/main/java/org/zxc/zing/common/constant/Constants.java
// public class Constants {
// public final static int SERVER_DEFAULT_PORT = 4080;
//
// public final static String SERVER_IP_ADDRESS_CONFIG_KEY = "server.address.ip";
//
// public final static String SERVER_PORT_CONFIG_KEY = "server.address.port";
//
// public final static String ZOOKEEPER_ADDRESS = "registry.zookeeper.address";
//
// public final static String ZOOKEEPER_PATH_SEPARATOR = "/";
//
// public final static String SERVICE_ZK_PATH_PREFIX = "/zing/service";
//
// public final static String SERVICE_ZK_PATH_FORMAT = SERVICE_ZK_PATH_PREFIX+"/%s";
// }
//
// Path: zing-common/src/main/java/org/zxc/zing/common/util/ZookeeperPathUtils.java
// public class ZookeeperPathUtils {
//
// private static final int PROVIDER_INFO_NODE_DEPTH = 4;
// private static final int SERVICE_NAME_ZK_PATH_DEPTH = 3;
//
// public static String formatProviderPath(String serviceName, String ip, int port) {
// StringBuilder pathBuilder = new StringBuilder();
//
// String serviceZkPath = String.format(Constants.SERVICE_ZK_PATH_FORMAT, serviceName);
// pathBuilder.append(serviceZkPath);
// pathBuilder.append("/");
//
// pathBuilder.append(ip);
// pathBuilder.append(":");
// pathBuilder.append(port);
//
// return pathBuilder.toString();
// }
//
// public static boolean isServiceProviderNode(String nodePath) {
// return ZookeeperPathUtils.zkNodeDepth(nodePath) == PROVIDER_INFO_NODE_DEPTH;
// }
//
// public static int zkNodeDepth(String nodePath) {
// if (Strings.isNullOrEmpty(nodePath) || "/".equals(nodePath)) {
// return 0;
// }
// if (!nodePath.startsWith("/")) {
// throw new IllegalArgumentException("zookeeper path should start with /!");
// }
// String pathWithoutFirstSlash = nodePath.substring(1);
// return Iterables.size(Splitter.on(Constants.ZOOKEEPER_PATH_SEPARATOR).split(pathWithoutFirstSlash));
// }
//
// public static String getServiceNameFromProviderZkPath(String providerZkPath) {
// String pathWithoutFirstSlash = providerZkPath.substring(1);
// List<String> parts = Lists.newArrayList(Splitter.on(Constants.ZOOKEEPER_PATH_SEPARATOR).split(pathWithoutFirstSlash));
// return parts.get(SERVICE_NAME_ZK_PATH_DEPTH - 1);
// }
//
// }
|
import com.google.common.base.Strings;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import org.apache.curator.framework.recipes.cache.TreeCacheListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zxc.zing.common.constant.Constants;
import org.zxc.zing.common.util.ZookeeperPathUtils;
|
package org.zxc.zing.common.registry;
/**
* Created by xuanchen.zhao on 16-1-17.
*/
public class ProviderNodeEventListener implements TreeCacheListener {
private static final Logger log = LoggerFactory.getLogger(ProviderNodeEventListener.class);
@Override
public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception {
log.info("curator event received:"+event);
if (!isServiceProviderNodeChangeEvent(event)) {
return;
}
|
// Path: zing-common/src/main/java/org/zxc/zing/common/constant/Constants.java
// public class Constants {
// public final static int SERVER_DEFAULT_PORT = 4080;
//
// public final static String SERVER_IP_ADDRESS_CONFIG_KEY = "server.address.ip";
//
// public final static String SERVER_PORT_CONFIG_KEY = "server.address.port";
//
// public final static String ZOOKEEPER_ADDRESS = "registry.zookeeper.address";
//
// public final static String ZOOKEEPER_PATH_SEPARATOR = "/";
//
// public final static String SERVICE_ZK_PATH_PREFIX = "/zing/service";
//
// public final static String SERVICE_ZK_PATH_FORMAT = SERVICE_ZK_PATH_PREFIX+"/%s";
// }
//
// Path: zing-common/src/main/java/org/zxc/zing/common/util/ZookeeperPathUtils.java
// public class ZookeeperPathUtils {
//
// private static final int PROVIDER_INFO_NODE_DEPTH = 4;
// private static final int SERVICE_NAME_ZK_PATH_DEPTH = 3;
//
// public static String formatProviderPath(String serviceName, String ip, int port) {
// StringBuilder pathBuilder = new StringBuilder();
//
// String serviceZkPath = String.format(Constants.SERVICE_ZK_PATH_FORMAT, serviceName);
// pathBuilder.append(serviceZkPath);
// pathBuilder.append("/");
//
// pathBuilder.append(ip);
// pathBuilder.append(":");
// pathBuilder.append(port);
//
// return pathBuilder.toString();
// }
//
// public static boolean isServiceProviderNode(String nodePath) {
// return ZookeeperPathUtils.zkNodeDepth(nodePath) == PROVIDER_INFO_NODE_DEPTH;
// }
//
// public static int zkNodeDepth(String nodePath) {
// if (Strings.isNullOrEmpty(nodePath) || "/".equals(nodePath)) {
// return 0;
// }
// if (!nodePath.startsWith("/")) {
// throw new IllegalArgumentException("zookeeper path should start with /!");
// }
// String pathWithoutFirstSlash = nodePath.substring(1);
// return Iterables.size(Splitter.on(Constants.ZOOKEEPER_PATH_SEPARATOR).split(pathWithoutFirstSlash));
// }
//
// public static String getServiceNameFromProviderZkPath(String providerZkPath) {
// String pathWithoutFirstSlash = providerZkPath.substring(1);
// List<String> parts = Lists.newArrayList(Splitter.on(Constants.ZOOKEEPER_PATH_SEPARATOR).split(pathWithoutFirstSlash));
// return parts.get(SERVICE_NAME_ZK_PATH_DEPTH - 1);
// }
//
// }
// Path: zing-common/src/main/java/org/zxc/zing/common/registry/ProviderNodeEventListener.java
import com.google.common.base.Strings;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import org.apache.curator.framework.recipes.cache.TreeCacheListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zxc.zing.common.constant.Constants;
import org.zxc.zing.common.util.ZookeeperPathUtils;
package org.zxc.zing.common.registry;
/**
* Created by xuanchen.zhao on 16-1-17.
*/
public class ProviderNodeEventListener implements TreeCacheListener {
private static final Logger log = LoggerFactory.getLogger(ProviderNodeEventListener.class);
@Override
public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception {
log.info("curator event received:"+event);
if (!isServiceProviderNodeChangeEvent(event)) {
return;
}
|
String serviceName = ZookeeperPathUtils.getServiceNameFromProviderZkPath(event.getData().getPath());
|
zxcpro/zing
|
zing-common/src/main/java/org/zxc/zing/common/registry/ProviderNodeEventListener.java
|
// Path: zing-common/src/main/java/org/zxc/zing/common/constant/Constants.java
// public class Constants {
// public final static int SERVER_DEFAULT_PORT = 4080;
//
// public final static String SERVER_IP_ADDRESS_CONFIG_KEY = "server.address.ip";
//
// public final static String SERVER_PORT_CONFIG_KEY = "server.address.port";
//
// public final static String ZOOKEEPER_ADDRESS = "registry.zookeeper.address";
//
// public final static String ZOOKEEPER_PATH_SEPARATOR = "/";
//
// public final static String SERVICE_ZK_PATH_PREFIX = "/zing/service";
//
// public final static String SERVICE_ZK_PATH_FORMAT = SERVICE_ZK_PATH_PREFIX+"/%s";
// }
//
// Path: zing-common/src/main/java/org/zxc/zing/common/util/ZookeeperPathUtils.java
// public class ZookeeperPathUtils {
//
// private static final int PROVIDER_INFO_NODE_DEPTH = 4;
// private static final int SERVICE_NAME_ZK_PATH_DEPTH = 3;
//
// public static String formatProviderPath(String serviceName, String ip, int port) {
// StringBuilder pathBuilder = new StringBuilder();
//
// String serviceZkPath = String.format(Constants.SERVICE_ZK_PATH_FORMAT, serviceName);
// pathBuilder.append(serviceZkPath);
// pathBuilder.append("/");
//
// pathBuilder.append(ip);
// pathBuilder.append(":");
// pathBuilder.append(port);
//
// return pathBuilder.toString();
// }
//
// public static boolean isServiceProviderNode(String nodePath) {
// return ZookeeperPathUtils.zkNodeDepth(nodePath) == PROVIDER_INFO_NODE_DEPTH;
// }
//
// public static int zkNodeDepth(String nodePath) {
// if (Strings.isNullOrEmpty(nodePath) || "/".equals(nodePath)) {
// return 0;
// }
// if (!nodePath.startsWith("/")) {
// throw new IllegalArgumentException("zookeeper path should start with /!");
// }
// String pathWithoutFirstSlash = nodePath.substring(1);
// return Iterables.size(Splitter.on(Constants.ZOOKEEPER_PATH_SEPARATOR).split(pathWithoutFirstSlash));
// }
//
// public static String getServiceNameFromProviderZkPath(String providerZkPath) {
// String pathWithoutFirstSlash = providerZkPath.substring(1);
// List<String> parts = Lists.newArrayList(Splitter.on(Constants.ZOOKEEPER_PATH_SEPARATOR).split(pathWithoutFirstSlash));
// return parts.get(SERVICE_NAME_ZK_PATH_DEPTH - 1);
// }
//
// }
|
import com.google.common.base.Strings;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import org.apache.curator.framework.recipes.cache.TreeCacheListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zxc.zing.common.constant.Constants;
import org.zxc.zing.common.util.ZookeeperPathUtils;
|
package org.zxc.zing.common.registry;
/**
* Created by xuanchen.zhao on 16-1-17.
*/
public class ProviderNodeEventListener implements TreeCacheListener {
private static final Logger log = LoggerFactory.getLogger(ProviderNodeEventListener.class);
@Override
public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception {
log.info("curator event received:"+event);
if (!isServiceProviderNodeChangeEvent(event)) {
return;
}
String serviceName = ZookeeperPathUtils.getServiceNameFromProviderZkPath(event.getData().getPath());
if (Strings.isNullOrEmpty(serviceName)) {
return;
}
ProviderStateListenerManager.getInstance().onProviderChange(serviceName);
}
private boolean isServiceProviderNodeChangeEvent(TreeCacheEvent event) {
if (event == null || event.getData() == null) {
return false;
}
String nodePath = event.getData().getPath();
|
// Path: zing-common/src/main/java/org/zxc/zing/common/constant/Constants.java
// public class Constants {
// public final static int SERVER_DEFAULT_PORT = 4080;
//
// public final static String SERVER_IP_ADDRESS_CONFIG_KEY = "server.address.ip";
//
// public final static String SERVER_PORT_CONFIG_KEY = "server.address.port";
//
// public final static String ZOOKEEPER_ADDRESS = "registry.zookeeper.address";
//
// public final static String ZOOKEEPER_PATH_SEPARATOR = "/";
//
// public final static String SERVICE_ZK_PATH_PREFIX = "/zing/service";
//
// public final static String SERVICE_ZK_PATH_FORMAT = SERVICE_ZK_PATH_PREFIX+"/%s";
// }
//
// Path: zing-common/src/main/java/org/zxc/zing/common/util/ZookeeperPathUtils.java
// public class ZookeeperPathUtils {
//
// private static final int PROVIDER_INFO_NODE_DEPTH = 4;
// private static final int SERVICE_NAME_ZK_PATH_DEPTH = 3;
//
// public static String formatProviderPath(String serviceName, String ip, int port) {
// StringBuilder pathBuilder = new StringBuilder();
//
// String serviceZkPath = String.format(Constants.SERVICE_ZK_PATH_FORMAT, serviceName);
// pathBuilder.append(serviceZkPath);
// pathBuilder.append("/");
//
// pathBuilder.append(ip);
// pathBuilder.append(":");
// pathBuilder.append(port);
//
// return pathBuilder.toString();
// }
//
// public static boolean isServiceProviderNode(String nodePath) {
// return ZookeeperPathUtils.zkNodeDepth(nodePath) == PROVIDER_INFO_NODE_DEPTH;
// }
//
// public static int zkNodeDepth(String nodePath) {
// if (Strings.isNullOrEmpty(nodePath) || "/".equals(nodePath)) {
// return 0;
// }
// if (!nodePath.startsWith("/")) {
// throw new IllegalArgumentException("zookeeper path should start with /!");
// }
// String pathWithoutFirstSlash = nodePath.substring(1);
// return Iterables.size(Splitter.on(Constants.ZOOKEEPER_PATH_SEPARATOR).split(pathWithoutFirstSlash));
// }
//
// public static String getServiceNameFromProviderZkPath(String providerZkPath) {
// String pathWithoutFirstSlash = providerZkPath.substring(1);
// List<String> parts = Lists.newArrayList(Splitter.on(Constants.ZOOKEEPER_PATH_SEPARATOR).split(pathWithoutFirstSlash));
// return parts.get(SERVICE_NAME_ZK_PATH_DEPTH - 1);
// }
//
// }
// Path: zing-common/src/main/java/org/zxc/zing/common/registry/ProviderNodeEventListener.java
import com.google.common.base.Strings;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import org.apache.curator.framework.recipes.cache.TreeCacheListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zxc.zing.common.constant.Constants;
import org.zxc.zing.common.util.ZookeeperPathUtils;
package org.zxc.zing.common.registry;
/**
* Created by xuanchen.zhao on 16-1-17.
*/
public class ProviderNodeEventListener implements TreeCacheListener {
private static final Logger log = LoggerFactory.getLogger(ProviderNodeEventListener.class);
@Override
public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception {
log.info("curator event received:"+event);
if (!isServiceProviderNodeChangeEvent(event)) {
return;
}
String serviceName = ZookeeperPathUtils.getServiceNameFromProviderZkPath(event.getData().getPath());
if (Strings.isNullOrEmpty(serviceName)) {
return;
}
ProviderStateListenerManager.getInstance().onProviderChange(serviceName);
}
private boolean isServiceProviderNodeChangeEvent(TreeCacheEvent event) {
if (event == null || event.getData() == null) {
return false;
}
String nodePath = event.getData().getPath();
|
if (!nodePath.startsWith(Constants.SERVICE_ZK_PATH_PREFIX)) {
|
zxcpro/zing
|
zing-server/src/main/java/org/zxc/zing/server/remote/NettyServerHandler.java
|
// Path: zing-common/src/main/java/org/zxc/zing/common/entity/RemoteRequest.java
// public class RemoteRequest implements Serializable{
//
// private String requestId;
// private String serviceName;
// private String methodName;
// private Class<?>[] parameterTypes;
// private Object[] arguments;
//
// public String getRequestId() {
// return requestId;
// }
//
// public void setRequestId(String requestId) {
// this.requestId = requestId;
// }
//
// public String getServiceName() {
// return serviceName;
// }
//
// public void setServiceName(String serviceName) {
// this.serviceName = serviceName;
// }
//
// public String getMethodName() {
// return methodName;
// }
//
// public void setMethodName(String methodName) {
// this.methodName = methodName;
// }
//
// public Class<?>[] getParameterTypes() {
// return parameterTypes;
// }
//
// public void setParameterTypes(Class<?>[] parameterTypes) {
// this.parameterTypes = parameterTypes;
// }
//
// public Object[] getArguments() {
// return arguments;
// }
//
// public void setArguments(Object[] arguments) {
// this.arguments = arguments;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("RemoteRequest{");
// sb.append("requestId='").append(requestId).append('\'');
// sb.append(", serviceName='").append(serviceName).append('\'');
// sb.append(", methodName='").append(methodName).append('\'');
// sb.append(", parameterTypes=").append(Arrays.toString(parameterTypes));
// sb.append(", arguments=").append(Arrays.toString(arguments));
// sb.append('}');
// return sb.toString();
// }
// }
//
// Path: zing-common/src/main/java/org/zxc/zing/common/entity/RemoteResponse.java
// public class RemoteResponse implements Serializable{
//
// private String requestId;
// private int responseCode;
// private Object responseValue;
//
// public String getRequestId() {
// return requestId;
// }
//
// public void setRequestId(String requestId) {
// this.requestId = requestId;
// }
//
// public int getResponseCode() {
// return responseCode;
// }
//
// public void setResponseCode(int responseCode) {
// this.responseCode = responseCode;
// }
//
// public Object getResponseValue() {
// return responseValue;
// }
//
// public void setResponseValue(Object responseValue) {
// this.responseValue = responseValue;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("RemoteResponse{");
// sb.append("requestId='").append(requestId).append('\'');
// sb.append(", responseCode=").append(responseCode);
// sb.append(", responseValue=").append(responseValue);
// sb.append('}');
// return sb.toString();
// }
// }
//
// Path: zing-server/src/main/java/org/zxc/zing/server/RemoteServiceServer.java
// public class RemoteServiceServer {
//
// private static final Logger log = LoggerFactory.getLogger(RemoteServiceServer.class);
//
// private static volatile boolean started = false;
//
// private static String ipAddress = ConfigManager.getInstance().getProperty(Constants.SERVER_IP_ADDRESS_CONFIG_KEY);
//
// private static int port = Strings.isNullOrEmpty(ConfigManager.getInstance().getProperty(Constants.SERVER_PORT_CONFIG_KEY)) ?
// Constants.SERVER_DEFAULT_PORT :
// Integer.valueOf(ConfigManager.getInstance().getProperty(Constants.SERVER_PORT_CONFIG_KEY));
//
//
// private static ConcurrentHashMap<String, Object> serviceImplMap = new ConcurrentHashMap<String, Object>();
//
// static {
// try {
// bootstrap();
// } catch (Exception e) {
// log.error("Server start error:"+e.getMessage(), e);
// System.exit(1);
// }
// }
//
// public static void addService(String serviceName, Object serviceImpl) {
// serviceImplMap.putIfAbsent(serviceName, serviceImpl);
// RegistryManager.publishService(serviceName, ipAddress, port);
// }
//
// public static void bootstrap() throws Exception {
// log.info("try bootstrap state:"+started);
// if (!started) {
// synchronized (RemoteServiceServer.class) {
// if (!started) {
// doStart();
// }
// }
// }
// log.info("started");
// }
//
// private static void doStart() throws Exception {
// log.info("do start server");
// NettyServer.start(port);
// RegistryManager.start();
// }
//
// public static Object getActualServiceImpl(String serviceName) {
// return serviceImplMap.get(serviceName);
// }
//
// }
|
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zxc.zing.common.entity.RemoteRequest;
import org.zxc.zing.common.entity.RemoteResponse;
import org.zxc.zing.server.RemoteServiceServer;
import java.lang.reflect.Method;
|
package org.zxc.zing.server.remote;
/**
* Created by xuanchen.zhao on 15-12-16.
*/
public class NettyServerHandler extends SimpleChannelInboundHandler<RemoteRequest> {
private static final Logger log = LoggerFactory.getLogger(NettyServerHandler.class);
@Override
protected void channelRead0(ChannelHandlerContext ctx, RemoteRequest request) throws Exception {
|
// Path: zing-common/src/main/java/org/zxc/zing/common/entity/RemoteRequest.java
// public class RemoteRequest implements Serializable{
//
// private String requestId;
// private String serviceName;
// private String methodName;
// private Class<?>[] parameterTypes;
// private Object[] arguments;
//
// public String getRequestId() {
// return requestId;
// }
//
// public void setRequestId(String requestId) {
// this.requestId = requestId;
// }
//
// public String getServiceName() {
// return serviceName;
// }
//
// public void setServiceName(String serviceName) {
// this.serviceName = serviceName;
// }
//
// public String getMethodName() {
// return methodName;
// }
//
// public void setMethodName(String methodName) {
// this.methodName = methodName;
// }
//
// public Class<?>[] getParameterTypes() {
// return parameterTypes;
// }
//
// public void setParameterTypes(Class<?>[] parameterTypes) {
// this.parameterTypes = parameterTypes;
// }
//
// public Object[] getArguments() {
// return arguments;
// }
//
// public void setArguments(Object[] arguments) {
// this.arguments = arguments;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("RemoteRequest{");
// sb.append("requestId='").append(requestId).append('\'');
// sb.append(", serviceName='").append(serviceName).append('\'');
// sb.append(", methodName='").append(methodName).append('\'');
// sb.append(", parameterTypes=").append(Arrays.toString(parameterTypes));
// sb.append(", arguments=").append(Arrays.toString(arguments));
// sb.append('}');
// return sb.toString();
// }
// }
//
// Path: zing-common/src/main/java/org/zxc/zing/common/entity/RemoteResponse.java
// public class RemoteResponse implements Serializable{
//
// private String requestId;
// private int responseCode;
// private Object responseValue;
//
// public String getRequestId() {
// return requestId;
// }
//
// public void setRequestId(String requestId) {
// this.requestId = requestId;
// }
//
// public int getResponseCode() {
// return responseCode;
// }
//
// public void setResponseCode(int responseCode) {
// this.responseCode = responseCode;
// }
//
// public Object getResponseValue() {
// return responseValue;
// }
//
// public void setResponseValue(Object responseValue) {
// this.responseValue = responseValue;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("RemoteResponse{");
// sb.append("requestId='").append(requestId).append('\'');
// sb.append(", responseCode=").append(responseCode);
// sb.append(", responseValue=").append(responseValue);
// sb.append('}');
// return sb.toString();
// }
// }
//
// Path: zing-server/src/main/java/org/zxc/zing/server/RemoteServiceServer.java
// public class RemoteServiceServer {
//
// private static final Logger log = LoggerFactory.getLogger(RemoteServiceServer.class);
//
// private static volatile boolean started = false;
//
// private static String ipAddress = ConfigManager.getInstance().getProperty(Constants.SERVER_IP_ADDRESS_CONFIG_KEY);
//
// private static int port = Strings.isNullOrEmpty(ConfigManager.getInstance().getProperty(Constants.SERVER_PORT_CONFIG_KEY)) ?
// Constants.SERVER_DEFAULT_PORT :
// Integer.valueOf(ConfigManager.getInstance().getProperty(Constants.SERVER_PORT_CONFIG_KEY));
//
//
// private static ConcurrentHashMap<String, Object> serviceImplMap = new ConcurrentHashMap<String, Object>();
//
// static {
// try {
// bootstrap();
// } catch (Exception e) {
// log.error("Server start error:"+e.getMessage(), e);
// System.exit(1);
// }
// }
//
// public static void addService(String serviceName, Object serviceImpl) {
// serviceImplMap.putIfAbsent(serviceName, serviceImpl);
// RegistryManager.publishService(serviceName, ipAddress, port);
// }
//
// public static void bootstrap() throws Exception {
// log.info("try bootstrap state:"+started);
// if (!started) {
// synchronized (RemoteServiceServer.class) {
// if (!started) {
// doStart();
// }
// }
// }
// log.info("started");
// }
//
// private static void doStart() throws Exception {
// log.info("do start server");
// NettyServer.start(port);
// RegistryManager.start();
// }
//
// public static Object getActualServiceImpl(String serviceName) {
// return serviceImplMap.get(serviceName);
// }
//
// }
// Path: zing-server/src/main/java/org/zxc/zing/server/remote/NettyServerHandler.java
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zxc.zing.common.entity.RemoteRequest;
import org.zxc.zing.common.entity.RemoteResponse;
import org.zxc.zing.server.RemoteServiceServer;
import java.lang.reflect.Method;
package org.zxc.zing.server.remote;
/**
* Created by xuanchen.zhao on 15-12-16.
*/
public class NettyServerHandler extends SimpleChannelInboundHandler<RemoteRequest> {
private static final Logger log = LoggerFactory.getLogger(NettyServerHandler.class);
@Override
protected void channelRead0(ChannelHandlerContext ctx, RemoteRequest request) throws Exception {
|
Object actualServiceImpl = RemoteServiceServer.getActualServiceImpl(request.getServiceName());
|
zxcpro/zing
|
zing-server/src/main/java/org/zxc/zing/server/remote/NettyServerHandler.java
|
// Path: zing-common/src/main/java/org/zxc/zing/common/entity/RemoteRequest.java
// public class RemoteRequest implements Serializable{
//
// private String requestId;
// private String serviceName;
// private String methodName;
// private Class<?>[] parameterTypes;
// private Object[] arguments;
//
// public String getRequestId() {
// return requestId;
// }
//
// public void setRequestId(String requestId) {
// this.requestId = requestId;
// }
//
// public String getServiceName() {
// return serviceName;
// }
//
// public void setServiceName(String serviceName) {
// this.serviceName = serviceName;
// }
//
// public String getMethodName() {
// return methodName;
// }
//
// public void setMethodName(String methodName) {
// this.methodName = methodName;
// }
//
// public Class<?>[] getParameterTypes() {
// return parameterTypes;
// }
//
// public void setParameterTypes(Class<?>[] parameterTypes) {
// this.parameterTypes = parameterTypes;
// }
//
// public Object[] getArguments() {
// return arguments;
// }
//
// public void setArguments(Object[] arguments) {
// this.arguments = arguments;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("RemoteRequest{");
// sb.append("requestId='").append(requestId).append('\'');
// sb.append(", serviceName='").append(serviceName).append('\'');
// sb.append(", methodName='").append(methodName).append('\'');
// sb.append(", parameterTypes=").append(Arrays.toString(parameterTypes));
// sb.append(", arguments=").append(Arrays.toString(arguments));
// sb.append('}');
// return sb.toString();
// }
// }
//
// Path: zing-common/src/main/java/org/zxc/zing/common/entity/RemoteResponse.java
// public class RemoteResponse implements Serializable{
//
// private String requestId;
// private int responseCode;
// private Object responseValue;
//
// public String getRequestId() {
// return requestId;
// }
//
// public void setRequestId(String requestId) {
// this.requestId = requestId;
// }
//
// public int getResponseCode() {
// return responseCode;
// }
//
// public void setResponseCode(int responseCode) {
// this.responseCode = responseCode;
// }
//
// public Object getResponseValue() {
// return responseValue;
// }
//
// public void setResponseValue(Object responseValue) {
// this.responseValue = responseValue;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("RemoteResponse{");
// sb.append("requestId='").append(requestId).append('\'');
// sb.append(", responseCode=").append(responseCode);
// sb.append(", responseValue=").append(responseValue);
// sb.append('}');
// return sb.toString();
// }
// }
//
// Path: zing-server/src/main/java/org/zxc/zing/server/RemoteServiceServer.java
// public class RemoteServiceServer {
//
// private static final Logger log = LoggerFactory.getLogger(RemoteServiceServer.class);
//
// private static volatile boolean started = false;
//
// private static String ipAddress = ConfigManager.getInstance().getProperty(Constants.SERVER_IP_ADDRESS_CONFIG_KEY);
//
// private static int port = Strings.isNullOrEmpty(ConfigManager.getInstance().getProperty(Constants.SERVER_PORT_CONFIG_KEY)) ?
// Constants.SERVER_DEFAULT_PORT :
// Integer.valueOf(ConfigManager.getInstance().getProperty(Constants.SERVER_PORT_CONFIG_KEY));
//
//
// private static ConcurrentHashMap<String, Object> serviceImplMap = new ConcurrentHashMap<String, Object>();
//
// static {
// try {
// bootstrap();
// } catch (Exception e) {
// log.error("Server start error:"+e.getMessage(), e);
// System.exit(1);
// }
// }
//
// public static void addService(String serviceName, Object serviceImpl) {
// serviceImplMap.putIfAbsent(serviceName, serviceImpl);
// RegistryManager.publishService(serviceName, ipAddress, port);
// }
//
// public static void bootstrap() throws Exception {
// log.info("try bootstrap state:"+started);
// if (!started) {
// synchronized (RemoteServiceServer.class) {
// if (!started) {
// doStart();
// }
// }
// }
// log.info("started");
// }
//
// private static void doStart() throws Exception {
// log.info("do start server");
// NettyServer.start(port);
// RegistryManager.start();
// }
//
// public static Object getActualServiceImpl(String serviceName) {
// return serviceImplMap.get(serviceName);
// }
//
// }
|
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zxc.zing.common.entity.RemoteRequest;
import org.zxc.zing.common.entity.RemoteResponse;
import org.zxc.zing.server.RemoteServiceServer;
import java.lang.reflect.Method;
|
package org.zxc.zing.server.remote;
/**
* Created by xuanchen.zhao on 15-12-16.
*/
public class NettyServerHandler extends SimpleChannelInboundHandler<RemoteRequest> {
private static final Logger log = LoggerFactory.getLogger(NettyServerHandler.class);
@Override
protected void channelRead0(ChannelHandlerContext ctx, RemoteRequest request) throws Exception {
Object actualServiceImpl = RemoteServiceServer.getActualServiceImpl(request.getServiceName());
if (actualServiceImpl != null) {
|
// Path: zing-common/src/main/java/org/zxc/zing/common/entity/RemoteRequest.java
// public class RemoteRequest implements Serializable{
//
// private String requestId;
// private String serviceName;
// private String methodName;
// private Class<?>[] parameterTypes;
// private Object[] arguments;
//
// public String getRequestId() {
// return requestId;
// }
//
// public void setRequestId(String requestId) {
// this.requestId = requestId;
// }
//
// public String getServiceName() {
// return serviceName;
// }
//
// public void setServiceName(String serviceName) {
// this.serviceName = serviceName;
// }
//
// public String getMethodName() {
// return methodName;
// }
//
// public void setMethodName(String methodName) {
// this.methodName = methodName;
// }
//
// public Class<?>[] getParameterTypes() {
// return parameterTypes;
// }
//
// public void setParameterTypes(Class<?>[] parameterTypes) {
// this.parameterTypes = parameterTypes;
// }
//
// public Object[] getArguments() {
// return arguments;
// }
//
// public void setArguments(Object[] arguments) {
// this.arguments = arguments;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("RemoteRequest{");
// sb.append("requestId='").append(requestId).append('\'');
// sb.append(", serviceName='").append(serviceName).append('\'');
// sb.append(", methodName='").append(methodName).append('\'');
// sb.append(", parameterTypes=").append(Arrays.toString(parameterTypes));
// sb.append(", arguments=").append(Arrays.toString(arguments));
// sb.append('}');
// return sb.toString();
// }
// }
//
// Path: zing-common/src/main/java/org/zxc/zing/common/entity/RemoteResponse.java
// public class RemoteResponse implements Serializable{
//
// private String requestId;
// private int responseCode;
// private Object responseValue;
//
// public String getRequestId() {
// return requestId;
// }
//
// public void setRequestId(String requestId) {
// this.requestId = requestId;
// }
//
// public int getResponseCode() {
// return responseCode;
// }
//
// public void setResponseCode(int responseCode) {
// this.responseCode = responseCode;
// }
//
// public Object getResponseValue() {
// return responseValue;
// }
//
// public void setResponseValue(Object responseValue) {
// this.responseValue = responseValue;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("RemoteResponse{");
// sb.append("requestId='").append(requestId).append('\'');
// sb.append(", responseCode=").append(responseCode);
// sb.append(", responseValue=").append(responseValue);
// sb.append('}');
// return sb.toString();
// }
// }
//
// Path: zing-server/src/main/java/org/zxc/zing/server/RemoteServiceServer.java
// public class RemoteServiceServer {
//
// private static final Logger log = LoggerFactory.getLogger(RemoteServiceServer.class);
//
// private static volatile boolean started = false;
//
// private static String ipAddress = ConfigManager.getInstance().getProperty(Constants.SERVER_IP_ADDRESS_CONFIG_KEY);
//
// private static int port = Strings.isNullOrEmpty(ConfigManager.getInstance().getProperty(Constants.SERVER_PORT_CONFIG_KEY)) ?
// Constants.SERVER_DEFAULT_PORT :
// Integer.valueOf(ConfigManager.getInstance().getProperty(Constants.SERVER_PORT_CONFIG_KEY));
//
//
// private static ConcurrentHashMap<String, Object> serviceImplMap = new ConcurrentHashMap<String, Object>();
//
// static {
// try {
// bootstrap();
// } catch (Exception e) {
// log.error("Server start error:"+e.getMessage(), e);
// System.exit(1);
// }
// }
//
// public static void addService(String serviceName, Object serviceImpl) {
// serviceImplMap.putIfAbsent(serviceName, serviceImpl);
// RegistryManager.publishService(serviceName, ipAddress, port);
// }
//
// public static void bootstrap() throws Exception {
// log.info("try bootstrap state:"+started);
// if (!started) {
// synchronized (RemoteServiceServer.class) {
// if (!started) {
// doStart();
// }
// }
// }
// log.info("started");
// }
//
// private static void doStart() throws Exception {
// log.info("do start server");
// NettyServer.start(port);
// RegistryManager.start();
// }
//
// public static Object getActualServiceImpl(String serviceName) {
// return serviceImplMap.get(serviceName);
// }
//
// }
// Path: zing-server/src/main/java/org/zxc/zing/server/remote/NettyServerHandler.java
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zxc.zing.common.entity.RemoteRequest;
import org.zxc.zing.common.entity.RemoteResponse;
import org.zxc.zing.server.RemoteServiceServer;
import java.lang.reflect.Method;
package org.zxc.zing.server.remote;
/**
* Created by xuanchen.zhao on 15-12-16.
*/
public class NettyServerHandler extends SimpleChannelInboundHandler<RemoteRequest> {
private static final Logger log = LoggerFactory.getLogger(NettyServerHandler.class);
@Override
protected void channelRead0(ChannelHandlerContext ctx, RemoteRequest request) throws Exception {
Object actualServiceImpl = RemoteServiceServer.getActualServiceImpl(request.getServiceName());
if (actualServiceImpl != null) {
|
RemoteResponse response = new RemoteResponse();
|
zxcpro/zing
|
zing-demo/src/main/java/org/zxc/zing/demo/impl/DemoServiceImpl.java
|
// Path: zing-demo/src/main/java/org/zxc/zing/demo/api/DemoService.java
// public interface DemoService {
// String echo(String input);
// MessageDTO loadObject(int messageId);
// }
//
// Path: zing-demo/src/main/java/org/zxc/zing/demo/api/MessageDTO.java
// public class MessageDTO implements Serializable{
// private int messageId;
// private String content;
//
// public int getMessageId() {
// return messageId;
// }
//
// public void setMessageId(int messageId) {
// this.messageId = messageId;
// }
//
// public String getContent() {
// return content;
// }
//
// public void setContent(String content) {
// this.content = content;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("MessageDTO{");
// sb.append("messageId=").append(messageId);
// sb.append(", content='").append(content).append('\'');
// sb.append('}');
// return sb.toString();
// }
// }
|
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zxc.zing.demo.api.DemoService;
import org.zxc.zing.demo.api.MessageDTO;
|
package org.zxc.zing.demo.impl;
/**
* Created by xuanchen.zhao on 15-12-8.
*/
public class DemoServiceImpl implements DemoService {
private static final Logger log = LoggerFactory.getLogger(DemoServiceImpl.class);
@Override
public String echo(String input) {
return "echo:"+input;
}
@Override
|
// Path: zing-demo/src/main/java/org/zxc/zing/demo/api/DemoService.java
// public interface DemoService {
// String echo(String input);
// MessageDTO loadObject(int messageId);
// }
//
// Path: zing-demo/src/main/java/org/zxc/zing/demo/api/MessageDTO.java
// public class MessageDTO implements Serializable{
// private int messageId;
// private String content;
//
// public int getMessageId() {
// return messageId;
// }
//
// public void setMessageId(int messageId) {
// this.messageId = messageId;
// }
//
// public String getContent() {
// return content;
// }
//
// public void setContent(String content) {
// this.content = content;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("MessageDTO{");
// sb.append("messageId=").append(messageId);
// sb.append(", content='").append(content).append('\'');
// sb.append('}');
// return sb.toString();
// }
// }
// Path: zing-demo/src/main/java/org/zxc/zing/demo/impl/DemoServiceImpl.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zxc.zing.demo.api.DemoService;
import org.zxc.zing.demo.api.MessageDTO;
package org.zxc.zing.demo.impl;
/**
* Created by xuanchen.zhao on 15-12-8.
*/
public class DemoServiceImpl implements DemoService {
private static final Logger log = LoggerFactory.getLogger(DemoServiceImpl.class);
@Override
public String echo(String input) {
return "echo:"+input;
}
@Override
|
public MessageDTO loadObject(int messageId) {
|
zxcpro/zing
|
zing-common/src/main/java/org/zxc/zing/common/util/ZookeeperPathUtils.java
|
// Path: zing-common/src/main/java/org/zxc/zing/common/constant/Constants.java
// public class Constants {
// public final static int SERVER_DEFAULT_PORT = 4080;
//
// public final static String SERVER_IP_ADDRESS_CONFIG_KEY = "server.address.ip";
//
// public final static String SERVER_PORT_CONFIG_KEY = "server.address.port";
//
// public final static String ZOOKEEPER_ADDRESS = "registry.zookeeper.address";
//
// public final static String ZOOKEEPER_PATH_SEPARATOR = "/";
//
// public final static String SERVICE_ZK_PATH_PREFIX = "/zing/service";
//
// public final static String SERVICE_ZK_PATH_FORMAT = SERVICE_ZK_PATH_PREFIX+"/%s";
// }
|
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import org.zxc.zing.common.constant.Constants;
import java.util.List;
|
package org.zxc.zing.common.util;
/**
* Created by xuanchen.zhao on 16-1-24.
*/
public class ZookeeperPathUtils {
private static final int PROVIDER_INFO_NODE_DEPTH = 4;
private static final int SERVICE_NAME_ZK_PATH_DEPTH = 3;
public static String formatProviderPath(String serviceName, String ip, int port) {
StringBuilder pathBuilder = new StringBuilder();
|
// Path: zing-common/src/main/java/org/zxc/zing/common/constant/Constants.java
// public class Constants {
// public final static int SERVER_DEFAULT_PORT = 4080;
//
// public final static String SERVER_IP_ADDRESS_CONFIG_KEY = "server.address.ip";
//
// public final static String SERVER_PORT_CONFIG_KEY = "server.address.port";
//
// public final static String ZOOKEEPER_ADDRESS = "registry.zookeeper.address";
//
// public final static String ZOOKEEPER_PATH_SEPARATOR = "/";
//
// public final static String SERVICE_ZK_PATH_PREFIX = "/zing/service";
//
// public final static String SERVICE_ZK_PATH_FORMAT = SERVICE_ZK_PATH_PREFIX+"/%s";
// }
// Path: zing-common/src/main/java/org/zxc/zing/common/util/ZookeeperPathUtils.java
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import org.zxc.zing.common.constant.Constants;
import java.util.List;
package org.zxc.zing.common.util;
/**
* Created by xuanchen.zhao on 16-1-24.
*/
public class ZookeeperPathUtils {
private static final int PROVIDER_INFO_NODE_DEPTH = 4;
private static final int SERVICE_NAME_ZK_PATH_DEPTH = 3;
public static String formatProviderPath(String serviceName, String ip, int port) {
StringBuilder pathBuilder = new StringBuilder();
|
String serviceZkPath = String.format(Constants.SERVICE_ZK_PATH_FORMAT, serviceName);
|
zxcpro/zing
|
zing-client/src/main/java/org/zxc/zing/client/provider/ServiceProviderManager.java
|
// Path: zing-common/src/main/java/org/zxc/zing/common/entity/ProviderInfo.java
// public class ProviderInfo {
// private String address;
// private int port;
//
// public ProviderInfo(String address, int port) {
// this.address = address;
// this.port = port;
// }
//
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ProviderInfo that = (ProviderInfo) o;
//
// if (port != that.port) return false;
// if (!address.equals(that.address)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = address.hashCode();
// result = 31 * result + port;
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("ProviderInfo{");
// sb.append("address='").append(address).append('\'');
// sb.append(", port=").append(port);
// sb.append('}');
// return sb.toString();
// }
// }
//
// Path: zing-common/src/main/java/org/zxc/zing/common/registry/ProviderStateListenerManager.java
// public class ProviderStateListenerManager implements ProviderStateListener{
//
// private static final ProviderStateListenerManager INSTANCE = new ProviderStateListenerManager();
//
// public static ProviderStateListenerManager getInstance() {
// return INSTANCE;
// }
//
// private final List<ProviderStateListener> listeners = Lists.newArrayList();
//
// public void registerProviderStateListener(ProviderStateListener listener) {
// listeners.add(listener);
// }
//
//
// @Override
// public void onProviderChange(String serviceName) {
// for (ProviderStateListener listener : listeners) {
// listener.onProviderChange(serviceName);
// }
// }
// }
//
// Path: zing-common/src/main/java/org/zxc/zing/common/registry/RegistryManager.java
// public class RegistryManager {
//
// private static final Logger log = LoggerFactory.getLogger(RegistryManager.class);
//
// private static CuratorFramework client;
//
// private static Executor curatorEventThreadPool = Executors.newFixedThreadPool(100);
//
// private static volatile boolean started = false;
//
// public static void start() throws Exception {
// if (!started) {
// synchronized (RegistryManager.class) {
// if (!started) {
// String zookeeperAddress = ConfigManager.getInstance().getProperty(Constants.ZOOKEEPER_ADDRESS);
//
// RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
// client = CuratorFrameworkFactory.newClient(zookeeperAddress, retryPolicy);
//
// client.start();
//
// TreeCache treeCache = TreeCache.newBuilder(client, Constants.SERVICE_ZK_PATH_PREFIX).setCacheData(false).build();
// treeCache.getListenable().addListener(new ProviderNodeEventListener(), curatorEventThreadPool);
// treeCache.start();
//
// started = client.blockUntilConnected(1000, TimeUnit.MILLISECONDS);
// }
// }
// }
// }
//
// public static boolean publishService(String serviceName, String ip, int port) {
// if (!started) {
// throw new IllegalStateException("registry is not started.");
// }
//
// if (Strings.isNullOrEmpty(ip)) {
// throw new IllegalStateException("local ip address not configured yet!");
// }
//
// String currentServerPath = ZookeeperPathUtils.formatProviderPath(serviceName, ip, port);
// try {
// String result = client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(currentServerPath);
// if (Strings.isNullOrEmpty(result)) {
// log.error("error when add service to zk:"+result);
// return false;
// }
// return true;
// } catch (KeeperException.NodeExistsException nee) {
// log.warn("target service "+currentServerPath+" already exists in zk");
// return true;
// } catch (Exception e) {
// log.error("error when add service to zk:"+e.getMessage(), e);
// return false;
// }
// }
//
// public static List<ProviderInfo> loadServerListOfService(String serviceName) {
// if (!started) {
// throw new IllegalStateException("registry is not started.");
// }
//
// try {
// List<String> stringList = client.getChildren().watched().forPath(String.format(Constants.SERVICE_ZK_PATH_FORMAT, serviceName));
// List<ProviderInfo> providerInfoList = Lists.transform(stringList, ServerStr2ProviderInfoTransformer.INSTANCE);
// return Lists.newArrayList(providerInfoList);
// } catch (Exception e) {
// log.error("Error when getting server list from registry:"+e.getMessage(), e);
// return Collections.emptyList();
// }
// }
// }
|
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zxc.zing.common.entity.ProviderInfo;
import org.zxc.zing.common.registry.ProviderStateListenerManager;
import org.zxc.zing.common.registry.RegistryManager;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
|
package org.zxc.zing.client.provider;
/**
* Created by xuanchen.zhao on 15-12-11.
*/
public class ServiceProviderManager {
private static final Logger log = LoggerFactory.getLogger(ServiceProviderManager.class);
|
// Path: zing-common/src/main/java/org/zxc/zing/common/entity/ProviderInfo.java
// public class ProviderInfo {
// private String address;
// private int port;
//
// public ProviderInfo(String address, int port) {
// this.address = address;
// this.port = port;
// }
//
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ProviderInfo that = (ProviderInfo) o;
//
// if (port != that.port) return false;
// if (!address.equals(that.address)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = address.hashCode();
// result = 31 * result + port;
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("ProviderInfo{");
// sb.append("address='").append(address).append('\'');
// sb.append(", port=").append(port);
// sb.append('}');
// return sb.toString();
// }
// }
//
// Path: zing-common/src/main/java/org/zxc/zing/common/registry/ProviderStateListenerManager.java
// public class ProviderStateListenerManager implements ProviderStateListener{
//
// private static final ProviderStateListenerManager INSTANCE = new ProviderStateListenerManager();
//
// public static ProviderStateListenerManager getInstance() {
// return INSTANCE;
// }
//
// private final List<ProviderStateListener> listeners = Lists.newArrayList();
//
// public void registerProviderStateListener(ProviderStateListener listener) {
// listeners.add(listener);
// }
//
//
// @Override
// public void onProviderChange(String serviceName) {
// for (ProviderStateListener listener : listeners) {
// listener.onProviderChange(serviceName);
// }
// }
// }
//
// Path: zing-common/src/main/java/org/zxc/zing/common/registry/RegistryManager.java
// public class RegistryManager {
//
// private static final Logger log = LoggerFactory.getLogger(RegistryManager.class);
//
// private static CuratorFramework client;
//
// private static Executor curatorEventThreadPool = Executors.newFixedThreadPool(100);
//
// private static volatile boolean started = false;
//
// public static void start() throws Exception {
// if (!started) {
// synchronized (RegistryManager.class) {
// if (!started) {
// String zookeeperAddress = ConfigManager.getInstance().getProperty(Constants.ZOOKEEPER_ADDRESS);
//
// RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
// client = CuratorFrameworkFactory.newClient(zookeeperAddress, retryPolicy);
//
// client.start();
//
// TreeCache treeCache = TreeCache.newBuilder(client, Constants.SERVICE_ZK_PATH_PREFIX).setCacheData(false).build();
// treeCache.getListenable().addListener(new ProviderNodeEventListener(), curatorEventThreadPool);
// treeCache.start();
//
// started = client.blockUntilConnected(1000, TimeUnit.MILLISECONDS);
// }
// }
// }
// }
//
// public static boolean publishService(String serviceName, String ip, int port) {
// if (!started) {
// throw new IllegalStateException("registry is not started.");
// }
//
// if (Strings.isNullOrEmpty(ip)) {
// throw new IllegalStateException("local ip address not configured yet!");
// }
//
// String currentServerPath = ZookeeperPathUtils.formatProviderPath(serviceName, ip, port);
// try {
// String result = client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(currentServerPath);
// if (Strings.isNullOrEmpty(result)) {
// log.error("error when add service to zk:"+result);
// return false;
// }
// return true;
// } catch (KeeperException.NodeExistsException nee) {
// log.warn("target service "+currentServerPath+" already exists in zk");
// return true;
// } catch (Exception e) {
// log.error("error when add service to zk:"+e.getMessage(), e);
// return false;
// }
// }
//
// public static List<ProviderInfo> loadServerListOfService(String serviceName) {
// if (!started) {
// throw new IllegalStateException("registry is not started.");
// }
//
// try {
// List<String> stringList = client.getChildren().watched().forPath(String.format(Constants.SERVICE_ZK_PATH_FORMAT, serviceName));
// List<ProviderInfo> providerInfoList = Lists.transform(stringList, ServerStr2ProviderInfoTransformer.INSTANCE);
// return Lists.newArrayList(providerInfoList);
// } catch (Exception e) {
// log.error("Error when getting server list from registry:"+e.getMessage(), e);
// return Collections.emptyList();
// }
// }
// }
// Path: zing-client/src/main/java/org/zxc/zing/client/provider/ServiceProviderManager.java
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zxc.zing.common.entity.ProviderInfo;
import org.zxc.zing.common.registry.ProviderStateListenerManager;
import org.zxc.zing.common.registry.RegistryManager;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
package org.zxc.zing.client.provider;
/**
* Created by xuanchen.zhao on 15-12-11.
*/
public class ServiceProviderManager {
private static final Logger log = LoggerFactory.getLogger(ServiceProviderManager.class);
|
private static Map<String, Set<ProviderInfo>> serviceServerMap = new ConcurrentHashMap<String, Set<ProviderInfo>>();
|
zxcpro/zing
|
zing-client/src/main/java/org/zxc/zing/client/provider/ServiceProviderManager.java
|
// Path: zing-common/src/main/java/org/zxc/zing/common/entity/ProviderInfo.java
// public class ProviderInfo {
// private String address;
// private int port;
//
// public ProviderInfo(String address, int port) {
// this.address = address;
// this.port = port;
// }
//
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ProviderInfo that = (ProviderInfo) o;
//
// if (port != that.port) return false;
// if (!address.equals(that.address)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = address.hashCode();
// result = 31 * result + port;
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("ProviderInfo{");
// sb.append("address='").append(address).append('\'');
// sb.append(", port=").append(port);
// sb.append('}');
// return sb.toString();
// }
// }
//
// Path: zing-common/src/main/java/org/zxc/zing/common/registry/ProviderStateListenerManager.java
// public class ProviderStateListenerManager implements ProviderStateListener{
//
// private static final ProviderStateListenerManager INSTANCE = new ProviderStateListenerManager();
//
// public static ProviderStateListenerManager getInstance() {
// return INSTANCE;
// }
//
// private final List<ProviderStateListener> listeners = Lists.newArrayList();
//
// public void registerProviderStateListener(ProviderStateListener listener) {
// listeners.add(listener);
// }
//
//
// @Override
// public void onProviderChange(String serviceName) {
// for (ProviderStateListener listener : listeners) {
// listener.onProviderChange(serviceName);
// }
// }
// }
//
// Path: zing-common/src/main/java/org/zxc/zing/common/registry/RegistryManager.java
// public class RegistryManager {
//
// private static final Logger log = LoggerFactory.getLogger(RegistryManager.class);
//
// private static CuratorFramework client;
//
// private static Executor curatorEventThreadPool = Executors.newFixedThreadPool(100);
//
// private static volatile boolean started = false;
//
// public static void start() throws Exception {
// if (!started) {
// synchronized (RegistryManager.class) {
// if (!started) {
// String zookeeperAddress = ConfigManager.getInstance().getProperty(Constants.ZOOKEEPER_ADDRESS);
//
// RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
// client = CuratorFrameworkFactory.newClient(zookeeperAddress, retryPolicy);
//
// client.start();
//
// TreeCache treeCache = TreeCache.newBuilder(client, Constants.SERVICE_ZK_PATH_PREFIX).setCacheData(false).build();
// treeCache.getListenable().addListener(new ProviderNodeEventListener(), curatorEventThreadPool);
// treeCache.start();
//
// started = client.blockUntilConnected(1000, TimeUnit.MILLISECONDS);
// }
// }
// }
// }
//
// public static boolean publishService(String serviceName, String ip, int port) {
// if (!started) {
// throw new IllegalStateException("registry is not started.");
// }
//
// if (Strings.isNullOrEmpty(ip)) {
// throw new IllegalStateException("local ip address not configured yet!");
// }
//
// String currentServerPath = ZookeeperPathUtils.formatProviderPath(serviceName, ip, port);
// try {
// String result = client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(currentServerPath);
// if (Strings.isNullOrEmpty(result)) {
// log.error("error when add service to zk:"+result);
// return false;
// }
// return true;
// } catch (KeeperException.NodeExistsException nee) {
// log.warn("target service "+currentServerPath+" already exists in zk");
// return true;
// } catch (Exception e) {
// log.error("error when add service to zk:"+e.getMessage(), e);
// return false;
// }
// }
//
// public static List<ProviderInfo> loadServerListOfService(String serviceName) {
// if (!started) {
// throw new IllegalStateException("registry is not started.");
// }
//
// try {
// List<String> stringList = client.getChildren().watched().forPath(String.format(Constants.SERVICE_ZK_PATH_FORMAT, serviceName));
// List<ProviderInfo> providerInfoList = Lists.transform(stringList, ServerStr2ProviderInfoTransformer.INSTANCE);
// return Lists.newArrayList(providerInfoList);
// } catch (Exception e) {
// log.error("Error when getting server list from registry:"+e.getMessage(), e);
// return Collections.emptyList();
// }
// }
// }
|
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zxc.zing.common.entity.ProviderInfo;
import org.zxc.zing.common.registry.ProviderStateListenerManager;
import org.zxc.zing.common.registry.RegistryManager;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
|
package org.zxc.zing.client.provider;
/**
* Created by xuanchen.zhao on 15-12-11.
*/
public class ServiceProviderManager {
private static final Logger log = LoggerFactory.getLogger(ServiceProviderManager.class);
private static Map<String, Set<ProviderInfo>> serviceServerMap = new ConcurrentHashMap<String, Set<ProviderInfo>>();
static {
try {
bootstrap();
} catch (Exception e) {
log.error("client start error:"+e.getMessage(), e);
System.exit(1);
}
}
public static void bootstrap() throws Exception {
|
// Path: zing-common/src/main/java/org/zxc/zing/common/entity/ProviderInfo.java
// public class ProviderInfo {
// private String address;
// private int port;
//
// public ProviderInfo(String address, int port) {
// this.address = address;
// this.port = port;
// }
//
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ProviderInfo that = (ProviderInfo) o;
//
// if (port != that.port) return false;
// if (!address.equals(that.address)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = address.hashCode();
// result = 31 * result + port;
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("ProviderInfo{");
// sb.append("address='").append(address).append('\'');
// sb.append(", port=").append(port);
// sb.append('}');
// return sb.toString();
// }
// }
//
// Path: zing-common/src/main/java/org/zxc/zing/common/registry/ProviderStateListenerManager.java
// public class ProviderStateListenerManager implements ProviderStateListener{
//
// private static final ProviderStateListenerManager INSTANCE = new ProviderStateListenerManager();
//
// public static ProviderStateListenerManager getInstance() {
// return INSTANCE;
// }
//
// private final List<ProviderStateListener> listeners = Lists.newArrayList();
//
// public void registerProviderStateListener(ProviderStateListener listener) {
// listeners.add(listener);
// }
//
//
// @Override
// public void onProviderChange(String serviceName) {
// for (ProviderStateListener listener : listeners) {
// listener.onProviderChange(serviceName);
// }
// }
// }
//
// Path: zing-common/src/main/java/org/zxc/zing/common/registry/RegistryManager.java
// public class RegistryManager {
//
// private static final Logger log = LoggerFactory.getLogger(RegistryManager.class);
//
// private static CuratorFramework client;
//
// private static Executor curatorEventThreadPool = Executors.newFixedThreadPool(100);
//
// private static volatile boolean started = false;
//
// public static void start() throws Exception {
// if (!started) {
// synchronized (RegistryManager.class) {
// if (!started) {
// String zookeeperAddress = ConfigManager.getInstance().getProperty(Constants.ZOOKEEPER_ADDRESS);
//
// RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
// client = CuratorFrameworkFactory.newClient(zookeeperAddress, retryPolicy);
//
// client.start();
//
// TreeCache treeCache = TreeCache.newBuilder(client, Constants.SERVICE_ZK_PATH_PREFIX).setCacheData(false).build();
// treeCache.getListenable().addListener(new ProviderNodeEventListener(), curatorEventThreadPool);
// treeCache.start();
//
// started = client.blockUntilConnected(1000, TimeUnit.MILLISECONDS);
// }
// }
// }
// }
//
// public static boolean publishService(String serviceName, String ip, int port) {
// if (!started) {
// throw new IllegalStateException("registry is not started.");
// }
//
// if (Strings.isNullOrEmpty(ip)) {
// throw new IllegalStateException("local ip address not configured yet!");
// }
//
// String currentServerPath = ZookeeperPathUtils.formatProviderPath(serviceName, ip, port);
// try {
// String result = client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(currentServerPath);
// if (Strings.isNullOrEmpty(result)) {
// log.error("error when add service to zk:"+result);
// return false;
// }
// return true;
// } catch (KeeperException.NodeExistsException nee) {
// log.warn("target service "+currentServerPath+" already exists in zk");
// return true;
// } catch (Exception e) {
// log.error("error when add service to zk:"+e.getMessage(), e);
// return false;
// }
// }
//
// public static List<ProviderInfo> loadServerListOfService(String serviceName) {
// if (!started) {
// throw new IllegalStateException("registry is not started.");
// }
//
// try {
// List<String> stringList = client.getChildren().watched().forPath(String.format(Constants.SERVICE_ZK_PATH_FORMAT, serviceName));
// List<ProviderInfo> providerInfoList = Lists.transform(stringList, ServerStr2ProviderInfoTransformer.INSTANCE);
// return Lists.newArrayList(providerInfoList);
// } catch (Exception e) {
// log.error("Error when getting server list from registry:"+e.getMessage(), e);
// return Collections.emptyList();
// }
// }
// }
// Path: zing-client/src/main/java/org/zxc/zing/client/provider/ServiceProviderManager.java
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zxc.zing.common.entity.ProviderInfo;
import org.zxc.zing.common.registry.ProviderStateListenerManager;
import org.zxc.zing.common.registry.RegistryManager;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
package org.zxc.zing.client.provider;
/**
* Created by xuanchen.zhao on 15-12-11.
*/
public class ServiceProviderManager {
private static final Logger log = LoggerFactory.getLogger(ServiceProviderManager.class);
private static Map<String, Set<ProviderInfo>> serviceServerMap = new ConcurrentHashMap<String, Set<ProviderInfo>>();
static {
try {
bootstrap();
} catch (Exception e) {
log.error("client start error:"+e.getMessage(), e);
System.exit(1);
}
}
public static void bootstrap() throws Exception {
|
ProviderStateListenerManager.getInstance().registerProviderStateListener(new ClientProviderStateListener());
|
zxcpro/zing
|
zing-client/src/main/java/org/zxc/zing/client/provider/ServiceProviderManager.java
|
// Path: zing-common/src/main/java/org/zxc/zing/common/entity/ProviderInfo.java
// public class ProviderInfo {
// private String address;
// private int port;
//
// public ProviderInfo(String address, int port) {
// this.address = address;
// this.port = port;
// }
//
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ProviderInfo that = (ProviderInfo) o;
//
// if (port != that.port) return false;
// if (!address.equals(that.address)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = address.hashCode();
// result = 31 * result + port;
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("ProviderInfo{");
// sb.append("address='").append(address).append('\'');
// sb.append(", port=").append(port);
// sb.append('}');
// return sb.toString();
// }
// }
//
// Path: zing-common/src/main/java/org/zxc/zing/common/registry/ProviderStateListenerManager.java
// public class ProviderStateListenerManager implements ProviderStateListener{
//
// private static final ProviderStateListenerManager INSTANCE = new ProviderStateListenerManager();
//
// public static ProviderStateListenerManager getInstance() {
// return INSTANCE;
// }
//
// private final List<ProviderStateListener> listeners = Lists.newArrayList();
//
// public void registerProviderStateListener(ProviderStateListener listener) {
// listeners.add(listener);
// }
//
//
// @Override
// public void onProviderChange(String serviceName) {
// for (ProviderStateListener listener : listeners) {
// listener.onProviderChange(serviceName);
// }
// }
// }
//
// Path: zing-common/src/main/java/org/zxc/zing/common/registry/RegistryManager.java
// public class RegistryManager {
//
// private static final Logger log = LoggerFactory.getLogger(RegistryManager.class);
//
// private static CuratorFramework client;
//
// private static Executor curatorEventThreadPool = Executors.newFixedThreadPool(100);
//
// private static volatile boolean started = false;
//
// public static void start() throws Exception {
// if (!started) {
// synchronized (RegistryManager.class) {
// if (!started) {
// String zookeeperAddress = ConfigManager.getInstance().getProperty(Constants.ZOOKEEPER_ADDRESS);
//
// RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
// client = CuratorFrameworkFactory.newClient(zookeeperAddress, retryPolicy);
//
// client.start();
//
// TreeCache treeCache = TreeCache.newBuilder(client, Constants.SERVICE_ZK_PATH_PREFIX).setCacheData(false).build();
// treeCache.getListenable().addListener(new ProviderNodeEventListener(), curatorEventThreadPool);
// treeCache.start();
//
// started = client.blockUntilConnected(1000, TimeUnit.MILLISECONDS);
// }
// }
// }
// }
//
// public static boolean publishService(String serviceName, String ip, int port) {
// if (!started) {
// throw new IllegalStateException("registry is not started.");
// }
//
// if (Strings.isNullOrEmpty(ip)) {
// throw new IllegalStateException("local ip address not configured yet!");
// }
//
// String currentServerPath = ZookeeperPathUtils.formatProviderPath(serviceName, ip, port);
// try {
// String result = client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(currentServerPath);
// if (Strings.isNullOrEmpty(result)) {
// log.error("error when add service to zk:"+result);
// return false;
// }
// return true;
// } catch (KeeperException.NodeExistsException nee) {
// log.warn("target service "+currentServerPath+" already exists in zk");
// return true;
// } catch (Exception e) {
// log.error("error when add service to zk:"+e.getMessage(), e);
// return false;
// }
// }
//
// public static List<ProviderInfo> loadServerListOfService(String serviceName) {
// if (!started) {
// throw new IllegalStateException("registry is not started.");
// }
//
// try {
// List<String> stringList = client.getChildren().watched().forPath(String.format(Constants.SERVICE_ZK_PATH_FORMAT, serviceName));
// List<ProviderInfo> providerInfoList = Lists.transform(stringList, ServerStr2ProviderInfoTransformer.INSTANCE);
// return Lists.newArrayList(providerInfoList);
// } catch (Exception e) {
// log.error("Error when getting server list from registry:"+e.getMessage(), e);
// return Collections.emptyList();
// }
// }
// }
|
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zxc.zing.common.entity.ProviderInfo;
import org.zxc.zing.common.registry.ProviderStateListenerManager;
import org.zxc.zing.common.registry.RegistryManager;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
|
package org.zxc.zing.client.provider;
/**
* Created by xuanchen.zhao on 15-12-11.
*/
public class ServiceProviderManager {
private static final Logger log = LoggerFactory.getLogger(ServiceProviderManager.class);
private static Map<String, Set<ProviderInfo>> serviceServerMap = new ConcurrentHashMap<String, Set<ProviderInfo>>();
static {
try {
bootstrap();
} catch (Exception e) {
log.error("client start error:"+e.getMessage(), e);
System.exit(1);
}
}
public static void bootstrap() throws Exception {
ProviderStateListenerManager.getInstance().registerProviderStateListener(new ClientProviderStateListener());
|
// Path: zing-common/src/main/java/org/zxc/zing/common/entity/ProviderInfo.java
// public class ProviderInfo {
// private String address;
// private int port;
//
// public ProviderInfo(String address, int port) {
// this.address = address;
// this.port = port;
// }
//
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ProviderInfo that = (ProviderInfo) o;
//
// if (port != that.port) return false;
// if (!address.equals(that.address)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = address.hashCode();
// result = 31 * result + port;
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("ProviderInfo{");
// sb.append("address='").append(address).append('\'');
// sb.append(", port=").append(port);
// sb.append('}');
// return sb.toString();
// }
// }
//
// Path: zing-common/src/main/java/org/zxc/zing/common/registry/ProviderStateListenerManager.java
// public class ProviderStateListenerManager implements ProviderStateListener{
//
// private static final ProviderStateListenerManager INSTANCE = new ProviderStateListenerManager();
//
// public static ProviderStateListenerManager getInstance() {
// return INSTANCE;
// }
//
// private final List<ProviderStateListener> listeners = Lists.newArrayList();
//
// public void registerProviderStateListener(ProviderStateListener listener) {
// listeners.add(listener);
// }
//
//
// @Override
// public void onProviderChange(String serviceName) {
// for (ProviderStateListener listener : listeners) {
// listener.onProviderChange(serviceName);
// }
// }
// }
//
// Path: zing-common/src/main/java/org/zxc/zing/common/registry/RegistryManager.java
// public class RegistryManager {
//
// private static final Logger log = LoggerFactory.getLogger(RegistryManager.class);
//
// private static CuratorFramework client;
//
// private static Executor curatorEventThreadPool = Executors.newFixedThreadPool(100);
//
// private static volatile boolean started = false;
//
// public static void start() throws Exception {
// if (!started) {
// synchronized (RegistryManager.class) {
// if (!started) {
// String zookeeperAddress = ConfigManager.getInstance().getProperty(Constants.ZOOKEEPER_ADDRESS);
//
// RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
// client = CuratorFrameworkFactory.newClient(zookeeperAddress, retryPolicy);
//
// client.start();
//
// TreeCache treeCache = TreeCache.newBuilder(client, Constants.SERVICE_ZK_PATH_PREFIX).setCacheData(false).build();
// treeCache.getListenable().addListener(new ProviderNodeEventListener(), curatorEventThreadPool);
// treeCache.start();
//
// started = client.blockUntilConnected(1000, TimeUnit.MILLISECONDS);
// }
// }
// }
// }
//
// public static boolean publishService(String serviceName, String ip, int port) {
// if (!started) {
// throw new IllegalStateException("registry is not started.");
// }
//
// if (Strings.isNullOrEmpty(ip)) {
// throw new IllegalStateException("local ip address not configured yet!");
// }
//
// String currentServerPath = ZookeeperPathUtils.formatProviderPath(serviceName, ip, port);
// try {
// String result = client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(currentServerPath);
// if (Strings.isNullOrEmpty(result)) {
// log.error("error when add service to zk:"+result);
// return false;
// }
// return true;
// } catch (KeeperException.NodeExistsException nee) {
// log.warn("target service "+currentServerPath+" already exists in zk");
// return true;
// } catch (Exception e) {
// log.error("error when add service to zk:"+e.getMessage(), e);
// return false;
// }
// }
//
// public static List<ProviderInfo> loadServerListOfService(String serviceName) {
// if (!started) {
// throw new IllegalStateException("registry is not started.");
// }
//
// try {
// List<String> stringList = client.getChildren().watched().forPath(String.format(Constants.SERVICE_ZK_PATH_FORMAT, serviceName));
// List<ProviderInfo> providerInfoList = Lists.transform(stringList, ServerStr2ProviderInfoTransformer.INSTANCE);
// return Lists.newArrayList(providerInfoList);
// } catch (Exception e) {
// log.error("Error when getting server list from registry:"+e.getMessage(), e);
// return Collections.emptyList();
// }
// }
// }
// Path: zing-client/src/main/java/org/zxc/zing/client/provider/ServiceProviderManager.java
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zxc.zing.common.entity.ProviderInfo;
import org.zxc.zing.common.registry.ProviderStateListenerManager;
import org.zxc.zing.common.registry.RegistryManager;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
package org.zxc.zing.client.provider;
/**
* Created by xuanchen.zhao on 15-12-11.
*/
public class ServiceProviderManager {
private static final Logger log = LoggerFactory.getLogger(ServiceProviderManager.class);
private static Map<String, Set<ProviderInfo>> serviceServerMap = new ConcurrentHashMap<String, Set<ProviderInfo>>();
static {
try {
bootstrap();
} catch (Exception e) {
log.error("client start error:"+e.getMessage(), e);
System.exit(1);
}
}
public static void bootstrap() throws Exception {
ProviderStateListenerManager.getInstance().registerProviderStateListener(new ClientProviderStateListener());
|
RegistryManager.start();
|
zxcpro/zing
|
zing-common/src/test/java/com/zxc/zing/common/registry/RegistryManagerTest.java
|
// Path: zing-common/src/main/java/org/zxc/zing/common/entity/ProviderInfo.java
// public class ProviderInfo {
// private String address;
// private int port;
//
// public ProviderInfo(String address, int port) {
// this.address = address;
// this.port = port;
// }
//
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ProviderInfo that = (ProviderInfo) o;
//
// if (port != that.port) return false;
// if (!address.equals(that.address)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = address.hashCode();
// result = 31 * result + port;
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("ProviderInfo{");
// sb.append("address='").append(address).append('\'');
// sb.append(", port=").append(port);
// sb.append('}');
// return sb.toString();
// }
// }
//
// Path: zing-common/src/main/java/org/zxc/zing/common/registry/RegistryManager.java
// public class RegistryManager {
//
// private static final Logger log = LoggerFactory.getLogger(RegistryManager.class);
//
// private static CuratorFramework client;
//
// private static Executor curatorEventThreadPool = Executors.newFixedThreadPool(100);
//
// private static volatile boolean started = false;
//
// public static void start() throws Exception {
// if (!started) {
// synchronized (RegistryManager.class) {
// if (!started) {
// String zookeeperAddress = ConfigManager.getInstance().getProperty(Constants.ZOOKEEPER_ADDRESS);
//
// RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
// client = CuratorFrameworkFactory.newClient(zookeeperAddress, retryPolicy);
//
// client.start();
//
// TreeCache treeCache = TreeCache.newBuilder(client, Constants.SERVICE_ZK_PATH_PREFIX).setCacheData(false).build();
// treeCache.getListenable().addListener(new ProviderNodeEventListener(), curatorEventThreadPool);
// treeCache.start();
//
// started = client.blockUntilConnected(1000, TimeUnit.MILLISECONDS);
// }
// }
// }
// }
//
// public static boolean publishService(String serviceName, String ip, int port) {
// if (!started) {
// throw new IllegalStateException("registry is not started.");
// }
//
// if (Strings.isNullOrEmpty(ip)) {
// throw new IllegalStateException("local ip address not configured yet!");
// }
//
// String currentServerPath = ZookeeperPathUtils.formatProviderPath(serviceName, ip, port);
// try {
// String result = client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(currentServerPath);
// if (Strings.isNullOrEmpty(result)) {
// log.error("error when add service to zk:"+result);
// return false;
// }
// return true;
// } catch (KeeperException.NodeExistsException nee) {
// log.warn("target service "+currentServerPath+" already exists in zk");
// return true;
// } catch (Exception e) {
// log.error("error when add service to zk:"+e.getMessage(), e);
// return false;
// }
// }
//
// public static List<ProviderInfo> loadServerListOfService(String serviceName) {
// if (!started) {
// throw new IllegalStateException("registry is not started.");
// }
//
// try {
// List<String> stringList = client.getChildren().watched().forPath(String.format(Constants.SERVICE_ZK_PATH_FORMAT, serviceName));
// List<ProviderInfo> providerInfoList = Lists.transform(stringList, ServerStr2ProviderInfoTransformer.INSTANCE);
// return Lists.newArrayList(providerInfoList);
// } catch (Exception e) {
// log.error("Error when getting server list from registry:"+e.getMessage(), e);
// return Collections.emptyList();
// }
// }
// }
|
import org.zxc.zing.common.entity.ProviderInfo;
import org.zxc.zing.common.registry.RegistryManager;
import java.util.List;
|
package com.zxc.zing.common.registry;
/**
* Created by xuanchen.zhao on 16-1-17.
*/
public class RegistryManagerTest {
public static void main(String[] args) throws Exception {
|
// Path: zing-common/src/main/java/org/zxc/zing/common/entity/ProviderInfo.java
// public class ProviderInfo {
// private String address;
// private int port;
//
// public ProviderInfo(String address, int port) {
// this.address = address;
// this.port = port;
// }
//
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ProviderInfo that = (ProviderInfo) o;
//
// if (port != that.port) return false;
// if (!address.equals(that.address)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = address.hashCode();
// result = 31 * result + port;
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("ProviderInfo{");
// sb.append("address='").append(address).append('\'');
// sb.append(", port=").append(port);
// sb.append('}');
// return sb.toString();
// }
// }
//
// Path: zing-common/src/main/java/org/zxc/zing/common/registry/RegistryManager.java
// public class RegistryManager {
//
// private static final Logger log = LoggerFactory.getLogger(RegistryManager.class);
//
// private static CuratorFramework client;
//
// private static Executor curatorEventThreadPool = Executors.newFixedThreadPool(100);
//
// private static volatile boolean started = false;
//
// public static void start() throws Exception {
// if (!started) {
// synchronized (RegistryManager.class) {
// if (!started) {
// String zookeeperAddress = ConfigManager.getInstance().getProperty(Constants.ZOOKEEPER_ADDRESS);
//
// RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
// client = CuratorFrameworkFactory.newClient(zookeeperAddress, retryPolicy);
//
// client.start();
//
// TreeCache treeCache = TreeCache.newBuilder(client, Constants.SERVICE_ZK_PATH_PREFIX).setCacheData(false).build();
// treeCache.getListenable().addListener(new ProviderNodeEventListener(), curatorEventThreadPool);
// treeCache.start();
//
// started = client.blockUntilConnected(1000, TimeUnit.MILLISECONDS);
// }
// }
// }
// }
//
// public static boolean publishService(String serviceName, String ip, int port) {
// if (!started) {
// throw new IllegalStateException("registry is not started.");
// }
//
// if (Strings.isNullOrEmpty(ip)) {
// throw new IllegalStateException("local ip address not configured yet!");
// }
//
// String currentServerPath = ZookeeperPathUtils.formatProviderPath(serviceName, ip, port);
// try {
// String result = client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(currentServerPath);
// if (Strings.isNullOrEmpty(result)) {
// log.error("error when add service to zk:"+result);
// return false;
// }
// return true;
// } catch (KeeperException.NodeExistsException nee) {
// log.warn("target service "+currentServerPath+" already exists in zk");
// return true;
// } catch (Exception e) {
// log.error("error when add service to zk:"+e.getMessage(), e);
// return false;
// }
// }
//
// public static List<ProviderInfo> loadServerListOfService(String serviceName) {
// if (!started) {
// throw new IllegalStateException("registry is not started.");
// }
//
// try {
// List<String> stringList = client.getChildren().watched().forPath(String.format(Constants.SERVICE_ZK_PATH_FORMAT, serviceName));
// List<ProviderInfo> providerInfoList = Lists.transform(stringList, ServerStr2ProviderInfoTransformer.INSTANCE);
// return Lists.newArrayList(providerInfoList);
// } catch (Exception e) {
// log.error("Error when getting server list from registry:"+e.getMessage(), e);
// return Collections.emptyList();
// }
// }
// }
// Path: zing-common/src/test/java/com/zxc/zing/common/registry/RegistryManagerTest.java
import org.zxc.zing.common.entity.ProviderInfo;
import org.zxc.zing.common.registry.RegistryManager;
import java.util.List;
package com.zxc.zing.common.registry;
/**
* Created by xuanchen.zhao on 16-1-17.
*/
public class RegistryManagerTest {
public static void main(String[] args) throws Exception {
|
RegistryManager.start();
|
zxcpro/zing
|
zing-common/src/test/java/com/zxc/zing/common/registry/RegistryManagerTest.java
|
// Path: zing-common/src/main/java/org/zxc/zing/common/entity/ProviderInfo.java
// public class ProviderInfo {
// private String address;
// private int port;
//
// public ProviderInfo(String address, int port) {
// this.address = address;
// this.port = port;
// }
//
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ProviderInfo that = (ProviderInfo) o;
//
// if (port != that.port) return false;
// if (!address.equals(that.address)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = address.hashCode();
// result = 31 * result + port;
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("ProviderInfo{");
// sb.append("address='").append(address).append('\'');
// sb.append(", port=").append(port);
// sb.append('}');
// return sb.toString();
// }
// }
//
// Path: zing-common/src/main/java/org/zxc/zing/common/registry/RegistryManager.java
// public class RegistryManager {
//
// private static final Logger log = LoggerFactory.getLogger(RegistryManager.class);
//
// private static CuratorFramework client;
//
// private static Executor curatorEventThreadPool = Executors.newFixedThreadPool(100);
//
// private static volatile boolean started = false;
//
// public static void start() throws Exception {
// if (!started) {
// synchronized (RegistryManager.class) {
// if (!started) {
// String zookeeperAddress = ConfigManager.getInstance().getProperty(Constants.ZOOKEEPER_ADDRESS);
//
// RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
// client = CuratorFrameworkFactory.newClient(zookeeperAddress, retryPolicy);
//
// client.start();
//
// TreeCache treeCache = TreeCache.newBuilder(client, Constants.SERVICE_ZK_PATH_PREFIX).setCacheData(false).build();
// treeCache.getListenable().addListener(new ProviderNodeEventListener(), curatorEventThreadPool);
// treeCache.start();
//
// started = client.blockUntilConnected(1000, TimeUnit.MILLISECONDS);
// }
// }
// }
// }
//
// public static boolean publishService(String serviceName, String ip, int port) {
// if (!started) {
// throw new IllegalStateException("registry is not started.");
// }
//
// if (Strings.isNullOrEmpty(ip)) {
// throw new IllegalStateException("local ip address not configured yet!");
// }
//
// String currentServerPath = ZookeeperPathUtils.formatProviderPath(serviceName, ip, port);
// try {
// String result = client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(currentServerPath);
// if (Strings.isNullOrEmpty(result)) {
// log.error("error when add service to zk:"+result);
// return false;
// }
// return true;
// } catch (KeeperException.NodeExistsException nee) {
// log.warn("target service "+currentServerPath+" already exists in zk");
// return true;
// } catch (Exception e) {
// log.error("error when add service to zk:"+e.getMessage(), e);
// return false;
// }
// }
//
// public static List<ProviderInfo> loadServerListOfService(String serviceName) {
// if (!started) {
// throw new IllegalStateException("registry is not started.");
// }
//
// try {
// List<String> stringList = client.getChildren().watched().forPath(String.format(Constants.SERVICE_ZK_PATH_FORMAT, serviceName));
// List<ProviderInfo> providerInfoList = Lists.transform(stringList, ServerStr2ProviderInfoTransformer.INSTANCE);
// return Lists.newArrayList(providerInfoList);
// } catch (Exception e) {
// log.error("Error when getting server list from registry:"+e.getMessage(), e);
// return Collections.emptyList();
// }
// }
// }
|
import org.zxc.zing.common.entity.ProviderInfo;
import org.zxc.zing.common.registry.RegistryManager;
import java.util.List;
|
package com.zxc.zing.common.registry;
/**
* Created by xuanchen.zhao on 16-1-17.
*/
public class RegistryManagerTest {
public static void main(String[] args) throws Exception {
RegistryManager.start();
RegistryManager.publishService("org.zxc.zing.demo.api.DemoService", "127.0.0.1", 4080);
|
// Path: zing-common/src/main/java/org/zxc/zing/common/entity/ProviderInfo.java
// public class ProviderInfo {
// private String address;
// private int port;
//
// public ProviderInfo(String address, int port) {
// this.address = address;
// this.port = port;
// }
//
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ProviderInfo that = (ProviderInfo) o;
//
// if (port != that.port) return false;
// if (!address.equals(that.address)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = address.hashCode();
// result = 31 * result + port;
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("ProviderInfo{");
// sb.append("address='").append(address).append('\'');
// sb.append(", port=").append(port);
// sb.append('}');
// return sb.toString();
// }
// }
//
// Path: zing-common/src/main/java/org/zxc/zing/common/registry/RegistryManager.java
// public class RegistryManager {
//
// private static final Logger log = LoggerFactory.getLogger(RegistryManager.class);
//
// private static CuratorFramework client;
//
// private static Executor curatorEventThreadPool = Executors.newFixedThreadPool(100);
//
// private static volatile boolean started = false;
//
// public static void start() throws Exception {
// if (!started) {
// synchronized (RegistryManager.class) {
// if (!started) {
// String zookeeperAddress = ConfigManager.getInstance().getProperty(Constants.ZOOKEEPER_ADDRESS);
//
// RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
// client = CuratorFrameworkFactory.newClient(zookeeperAddress, retryPolicy);
//
// client.start();
//
// TreeCache treeCache = TreeCache.newBuilder(client, Constants.SERVICE_ZK_PATH_PREFIX).setCacheData(false).build();
// treeCache.getListenable().addListener(new ProviderNodeEventListener(), curatorEventThreadPool);
// treeCache.start();
//
// started = client.blockUntilConnected(1000, TimeUnit.MILLISECONDS);
// }
// }
// }
// }
//
// public static boolean publishService(String serviceName, String ip, int port) {
// if (!started) {
// throw new IllegalStateException("registry is not started.");
// }
//
// if (Strings.isNullOrEmpty(ip)) {
// throw new IllegalStateException("local ip address not configured yet!");
// }
//
// String currentServerPath = ZookeeperPathUtils.formatProviderPath(serviceName, ip, port);
// try {
// String result = client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(currentServerPath);
// if (Strings.isNullOrEmpty(result)) {
// log.error("error when add service to zk:"+result);
// return false;
// }
// return true;
// } catch (KeeperException.NodeExistsException nee) {
// log.warn("target service "+currentServerPath+" already exists in zk");
// return true;
// } catch (Exception e) {
// log.error("error when add service to zk:"+e.getMessage(), e);
// return false;
// }
// }
//
// public static List<ProviderInfo> loadServerListOfService(String serviceName) {
// if (!started) {
// throw new IllegalStateException("registry is not started.");
// }
//
// try {
// List<String> stringList = client.getChildren().watched().forPath(String.format(Constants.SERVICE_ZK_PATH_FORMAT, serviceName));
// List<ProviderInfo> providerInfoList = Lists.transform(stringList, ServerStr2ProviderInfoTransformer.INSTANCE);
// return Lists.newArrayList(providerInfoList);
// } catch (Exception e) {
// log.error("Error when getting server list from registry:"+e.getMessage(), e);
// return Collections.emptyList();
// }
// }
// }
// Path: zing-common/src/test/java/com/zxc/zing/common/registry/RegistryManagerTest.java
import org.zxc.zing.common.entity.ProviderInfo;
import org.zxc.zing.common.registry.RegistryManager;
import java.util.List;
package com.zxc.zing.common.registry;
/**
* Created by xuanchen.zhao on 16-1-17.
*/
public class RegistryManagerTest {
public static void main(String[] args) throws Exception {
RegistryManager.start();
RegistryManager.publishService("org.zxc.zing.demo.api.DemoService", "127.0.0.1", 4080);
|
List<ProviderInfo> providerInfos = RegistryManager.loadServerListOfService("org.zxc.zing.demo.api.DemoService");
|
zxcpro/zing
|
zing-client/src/main/java/org/zxc/zing/client/proxy/ServiceProxyBeanFactory.java
|
// Path: zing-client/src/main/java/org/zxc/zing/client/provider/ServiceProviderManager.java
// public class ServiceProviderManager {
//
// private static final Logger log = LoggerFactory.getLogger(ServiceProviderManager.class);
//
// private static Map<String, Set<ProviderInfo>> serviceServerMap = new ConcurrentHashMap<String, Set<ProviderInfo>>();
//
// static {
// try {
// bootstrap();
// } catch (Exception e) {
// log.error("client start error:"+e.getMessage(), e);
// System.exit(1);
// }
// }
//
// public static void bootstrap() throws Exception {
// ProviderStateListenerManager.getInstance().registerProviderStateListener(new ClientProviderStateListener());
// RegistryManager.start();
// }
//
// public static ProviderInfo getProvider(String serviceName) {
// Set<ProviderInfo> providerInfoSet = serviceServerMap.get(serviceName);
//
// if (CollectionUtils.isEmpty(providerInfoSet)) {
// throw new RuntimeException("no service provider found in registry");
// }
//
// List<ProviderInfo> providerInfoList = Lists.newArrayList(providerInfoSet);
// int randomIndex = new Random().nextInt(providerInfoList.size());
// return providerInfoList.get(randomIndex);
// }
//
// public static void initServerListOfService(String serviceName) {
// log.debug("client start load "+serviceName+" service provider list from zk");
//
// List<ProviderInfo> providerInfoList = RegistryManager.loadServerListOfService(serviceName);
// log.debug("client load "+serviceName+" service provider list from zk:"+providerInfoList);
//
// log.debug("client serviceServerMap before load:"+serviceServerMap);
//
// Set<ProviderInfo> providerInfoSet = new HashSet<ProviderInfo>(providerInfoList);
// serviceServerMap.put(serviceName, providerInfoSet);
//
// log.debug("client serviceServerMap after load:"+serviceServerMap);
// }
// }
|
import com.google.common.reflect.Reflection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zxc.zing.client.provider.ServiceProviderManager;
|
package org.zxc.zing.client.proxy;
/**
* Created by xuanchen.zhao on 15-12-10.
*/
public class ServiceProxyBeanFactory {
private static final Logger log = LoggerFactory.getLogger(ServiceProxyBeanFactory.class);
public static Object getService(String serviceName) throws ClassNotFoundException {
Class<?> serviceClass = Class.forName(serviceName);
|
// Path: zing-client/src/main/java/org/zxc/zing/client/provider/ServiceProviderManager.java
// public class ServiceProviderManager {
//
// private static final Logger log = LoggerFactory.getLogger(ServiceProviderManager.class);
//
// private static Map<String, Set<ProviderInfo>> serviceServerMap = new ConcurrentHashMap<String, Set<ProviderInfo>>();
//
// static {
// try {
// bootstrap();
// } catch (Exception e) {
// log.error("client start error:"+e.getMessage(), e);
// System.exit(1);
// }
// }
//
// public static void bootstrap() throws Exception {
// ProviderStateListenerManager.getInstance().registerProviderStateListener(new ClientProviderStateListener());
// RegistryManager.start();
// }
//
// public static ProviderInfo getProvider(String serviceName) {
// Set<ProviderInfo> providerInfoSet = serviceServerMap.get(serviceName);
//
// if (CollectionUtils.isEmpty(providerInfoSet)) {
// throw new RuntimeException("no service provider found in registry");
// }
//
// List<ProviderInfo> providerInfoList = Lists.newArrayList(providerInfoSet);
// int randomIndex = new Random().nextInt(providerInfoList.size());
// return providerInfoList.get(randomIndex);
// }
//
// public static void initServerListOfService(String serviceName) {
// log.debug("client start load "+serviceName+" service provider list from zk");
//
// List<ProviderInfo> providerInfoList = RegistryManager.loadServerListOfService(serviceName);
// log.debug("client load "+serviceName+" service provider list from zk:"+providerInfoList);
//
// log.debug("client serviceServerMap before load:"+serviceServerMap);
//
// Set<ProviderInfo> providerInfoSet = new HashSet<ProviderInfo>(providerInfoList);
// serviceServerMap.put(serviceName, providerInfoSet);
//
// log.debug("client serviceServerMap after load:"+serviceServerMap);
// }
// }
// Path: zing-client/src/main/java/org/zxc/zing/client/proxy/ServiceProxyBeanFactory.java
import com.google.common.reflect.Reflection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zxc.zing.client.provider.ServiceProviderManager;
package org.zxc.zing.client.proxy;
/**
* Created by xuanchen.zhao on 15-12-10.
*/
public class ServiceProxyBeanFactory {
private static final Logger log = LoggerFactory.getLogger(ServiceProxyBeanFactory.class);
public static Object getService(String serviceName) throws ClassNotFoundException {
Class<?> serviceClass = Class.forName(serviceName);
|
ServiceProviderManager.initServerListOfService(serviceName);
|
zxcpro/zing
|
zing-common/src/main/java/org/zxc/zing/common/handler/NettyEncoder.java
|
// Path: zing-common/src/main/java/org/zxc/zing/common/serialize/Serializer.java
// public class Serializer {
//
// private static final Logger log = LoggerFactory.getLogger(Serializer.class);
//
//
// public static byte[] serialize(Object obj) throws IOException {
// ByteArrayOutputStream bos = new ByteArrayOutputStream();
// Hessian2Output out = new Hessian2Output(bos);
// out.writeObject(obj);
// out.close();
// return bos.toByteArray();
// }
//
// public static Object deserialize(byte[] data) throws IOException {
// ByteArrayInputStream bis = new ByteArrayInputStream(data);
// Hessian2Input in = new Hessian2Input(bis);
// return in.readObject();
// }
// }
|
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zxc.zing.common.serialize.Serializer;
|
package org.zxc.zing.common.handler;
/**
* Created by xuanchen.zhao on 15-12-15.
*/
public class NettyEncoder extends MessageToByteEncoder {
private static final Logger log = LoggerFactory.getLogger(NettyEncoder.class);
@Override
protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
log.info("encoding start");
|
// Path: zing-common/src/main/java/org/zxc/zing/common/serialize/Serializer.java
// public class Serializer {
//
// private static final Logger log = LoggerFactory.getLogger(Serializer.class);
//
//
// public static byte[] serialize(Object obj) throws IOException {
// ByteArrayOutputStream bos = new ByteArrayOutputStream();
// Hessian2Output out = new Hessian2Output(bos);
// out.writeObject(obj);
// out.close();
// return bos.toByteArray();
// }
//
// public static Object deserialize(byte[] data) throws IOException {
// ByteArrayInputStream bis = new ByteArrayInputStream(data);
// Hessian2Input in = new Hessian2Input(bis);
// return in.readObject();
// }
// }
// Path: zing-common/src/main/java/org/zxc/zing/common/handler/NettyEncoder.java
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zxc.zing.common.serialize.Serializer;
package org.zxc.zing.common.handler;
/**
* Created by xuanchen.zhao on 15-12-15.
*/
public class NettyEncoder extends MessageToByteEncoder {
private static final Logger log = LoggerFactory.getLogger(NettyEncoder.class);
@Override
protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
log.info("encoding start");
|
byte[] bytes = Serializer.serialize(msg);
|
zxcpro/zing
|
zing-demo/src/main/java/org/zxc/zing/demo/test/client/DemoClientTest.java
|
// Path: zing-demo/src/main/java/org/zxc/zing/demo/api/DemoService.java
// public interface DemoService {
// String echo(String input);
// MessageDTO loadObject(int messageId);
// }
//
// Path: zing-demo/src/main/java/org/zxc/zing/demo/api/MessageDTO.java
// public class MessageDTO implements Serializable{
// private int messageId;
// private String content;
//
// public int getMessageId() {
// return messageId;
// }
//
// public void setMessageId(int messageId) {
// this.messageId = messageId;
// }
//
// public String getContent() {
// return content;
// }
//
// public void setContent(String content) {
// this.content = content;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("MessageDTO{");
// sb.append("messageId=").append(messageId);
// sb.append(", content='").append(content).append('\'');
// sb.append('}');
// return sb.toString();
// }
// }
|
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.zxc.zing.demo.api.DemoService;
import org.zxc.zing.demo.api.MessageDTO;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
|
package org.zxc.zing.demo.test.client;
/**
* Created by xuanchen.zhao on 15-12-11.
*/
public class DemoClientTest {
private static DemoService demoService;
public static void main(String[] args) throws InterruptedException {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath*:config/spring/applicationContext-client.xml");
demoService = (DemoService) context.getBean("demoService");
test();
testLoadMessageObject();
testBatchInvocation();
}
public static void test() throws InterruptedException {
String result = demoService.echo("Hello World!");
System.out.println(result);
}
public static void testLoadMessageObject(){
|
// Path: zing-demo/src/main/java/org/zxc/zing/demo/api/DemoService.java
// public interface DemoService {
// String echo(String input);
// MessageDTO loadObject(int messageId);
// }
//
// Path: zing-demo/src/main/java/org/zxc/zing/demo/api/MessageDTO.java
// public class MessageDTO implements Serializable{
// private int messageId;
// private String content;
//
// public int getMessageId() {
// return messageId;
// }
//
// public void setMessageId(int messageId) {
// this.messageId = messageId;
// }
//
// public String getContent() {
// return content;
// }
//
// public void setContent(String content) {
// this.content = content;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("MessageDTO{");
// sb.append("messageId=").append(messageId);
// sb.append(", content='").append(content).append('\'');
// sb.append('}');
// return sb.toString();
// }
// }
// Path: zing-demo/src/main/java/org/zxc/zing/demo/test/client/DemoClientTest.java
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.zxc.zing.demo.api.DemoService;
import org.zxc.zing.demo.api.MessageDTO;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
package org.zxc.zing.demo.test.client;
/**
* Created by xuanchen.zhao on 15-12-11.
*/
public class DemoClientTest {
private static DemoService demoService;
public static void main(String[] args) throws InterruptedException {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath*:config/spring/applicationContext-client.xml");
demoService = (DemoService) context.getBean("demoService");
test();
testLoadMessageObject();
testBatchInvocation();
}
public static void test() throws InterruptedException {
String result = demoService.echo("Hello World!");
System.out.println(result);
}
public static void testLoadMessageObject(){
|
MessageDTO messageDTO = demoService.loadObject(1);
|
zxcpro/zing
|
zing-common/src/main/java/org/zxc/zing/common/handler/NettyDecoder.java
|
// Path: zing-common/src/main/java/org/zxc/zing/common/serialize/Serializer.java
// public class Serializer {
//
// private static final Logger log = LoggerFactory.getLogger(Serializer.class);
//
//
// public static byte[] serialize(Object obj) throws IOException {
// ByteArrayOutputStream bos = new ByteArrayOutputStream();
// Hessian2Output out = new Hessian2Output(bos);
// out.writeObject(obj);
// out.close();
// return bos.toByteArray();
// }
//
// public static Object deserialize(byte[] data) throws IOException {
// ByteArrayInputStream bis = new ByteArrayInputStream(data);
// Hessian2Input in = new Hessian2Input(bis);
// return in.readObject();
// }
// }
|
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zxc.zing.common.serialize.Serializer;
import java.util.List;
|
package org.zxc.zing.common.handler;
/**
* Created by xuanchen.zhao on 15-12-15.
*/
public class NettyDecoder extends ByteToMessageDecoder{
private static final Logger log = LoggerFactory.getLogger(NettyDecoder.class);
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
log.info("try decode:"+in.toString());
if (in.readableBytes() < 4) {
log.info("no enough readable bytes");
return;
}
int dataLength = in.readInt();
if (dataLength < 0) {
ctx.close();
}
log.info("try decode data length:"+dataLength);
if (in.readableBytes() < dataLength) {
in.resetReaderIndex();
}
log.info("try decode doDecode");
byte[] data = new byte[dataLength];
in.readBytes(data);
|
// Path: zing-common/src/main/java/org/zxc/zing/common/serialize/Serializer.java
// public class Serializer {
//
// private static final Logger log = LoggerFactory.getLogger(Serializer.class);
//
//
// public static byte[] serialize(Object obj) throws IOException {
// ByteArrayOutputStream bos = new ByteArrayOutputStream();
// Hessian2Output out = new Hessian2Output(bos);
// out.writeObject(obj);
// out.close();
// return bos.toByteArray();
// }
//
// public static Object deserialize(byte[] data) throws IOException {
// ByteArrayInputStream bis = new ByteArrayInputStream(data);
// Hessian2Input in = new Hessian2Input(bis);
// return in.readObject();
// }
// }
// Path: zing-common/src/main/java/org/zxc/zing/common/handler/NettyDecoder.java
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zxc.zing.common.serialize.Serializer;
import java.util.List;
package org.zxc.zing.common.handler;
/**
* Created by xuanchen.zhao on 15-12-15.
*/
public class NettyDecoder extends ByteToMessageDecoder{
private static final Logger log = LoggerFactory.getLogger(NettyDecoder.class);
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
log.info("try decode:"+in.toString());
if (in.readableBytes() < 4) {
log.info("no enough readable bytes");
return;
}
int dataLength = in.readInt();
if (dataLength < 0) {
ctx.close();
}
log.info("try decode data length:"+dataLength);
if (in.readableBytes() < dataLength) {
in.resetReaderIndex();
}
log.info("try decode doDecode");
byte[] data = new byte[dataLength];
in.readBytes(data);
|
Object deserialized = Serializer.deserialize(data);
|
4FunApp/4Fun
|
client/FourFun/app/src/main/java/com/joker/fourfun/di/component/AppComponent.java
|
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/FourFun.java
// public class FourFun extends Application {
// private static FourFun instance;
//
// public static FourFun getInstance() {
// return instance;
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// instance = this;
// if (LeakCanary.isInAnalyzerProcess(this)) {
// return;
// }
// LeakCanary.install(this);
// }
//
// public Context getContext() {
// return instance.getApplicationContext();
// }
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/di/module/AppModule.java
// @Module
// public class AppModule {
// private Application application;
//
// public AppModule(Application application) {
// this.application = application;
// }
//
// @Singleton
// @Provides
// FourFun provideFourFun() {
// return (FourFun) this.application;
// }
//
// @Singleton
// @Provides
// RetrofitUtil provideRetrofitUtil() {
// return new RetrofitUtil();
// }
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/utils/RetrofitUtil.java
// public class RetrofitUtil {
// public static final int DEFAULT_TIMEOUT = 10;
// public static final String BASE_URL = "http://www.icodes.vip/4Fun/";
// private static Retrofit mRetrofit;
//
// public RetrofitUtil() {
// mRetrofit = new Retrofit.Builder().baseUrl(BASE_URL)
// .client(initOkHttp())
// .addConverterFactory(GsonConverterFactory.create())
// .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
// .build();
// }
//
// private OkHttpClient initOkHttp() {
// OkHttpClient.Builder builder = new OkHttpClient.Builder();
// Interceptor cacheInterceptor = new Interceptor() {
// @Override
// public Response intercept(Chain chain) throws IOException {
// Request request = chain.request();
// if (!SystemUtil.isNetworkConnected()) {
// request = request.newBuilder()
// .cacheControl(CacheControl.FORCE_CACHE)
// .build();
// }
// Response response = chain.proceed(request);
// if (SystemUtil.isNetworkConnected()) {
// int maxAge = 0;
// // 有网络时, 不缓存, 最大保存时长为0
// response.newBuilder()
// .header("Cache-Control", "public, max-age=" + maxAge)
// .removeHeader("Pragma")
// .build();
// } else {
// // 无网络时,设置超时为4周
// int maxStale = 60 * 60 * 24 * 28;
// response.newBuilder()
// .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
// .removeHeader("Pragma")
// .build();
// }
//
// return response;
// }
// };
// if (BuildConfig.DEBUG) {
// HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
// interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// builder.addInterceptor(interceptor);
// }
// File cacheFile = new File(FourFun.getInstance().getCacheDir().getPath());
// // 设置缓存文件 20MB
// Cache cache = new Cache(cacheFile, 1024 * 1024 * 20);
// return builder
// .addInterceptor(cacheInterceptor)
// .addNetworkInterceptor(cacheInterceptor)
// .cache(cache)
// .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
// .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
// .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
// .retryOnConnectionFailure(true)
// .build();
// }
//
// public <T> T create(Class<T> service) {
// return mRetrofit.create(service);
// }
// }
|
import com.joker.fourfun.FourFun;
import com.joker.fourfun.di.module.AppModule;
import com.joker.fourfun.utils.RetrofitUtil;
import javax.inject.Singleton;
import dagger.Component;
|
package com.joker.fourfun.di.component;
/**
* Created by joker on 2016/11/28.
*/
@Singleton
@Component(modules = AppModule.class)
public abstract class AppComponent {
private static AppComponent mComponent;
public static AppComponent getInstance() {
if (mComponent == null) {
synchronized (AppComponent.class) {
if (mComponent == null) {
|
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/FourFun.java
// public class FourFun extends Application {
// private static FourFun instance;
//
// public static FourFun getInstance() {
// return instance;
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// instance = this;
// if (LeakCanary.isInAnalyzerProcess(this)) {
// return;
// }
// LeakCanary.install(this);
// }
//
// public Context getContext() {
// return instance.getApplicationContext();
// }
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/di/module/AppModule.java
// @Module
// public class AppModule {
// private Application application;
//
// public AppModule(Application application) {
// this.application = application;
// }
//
// @Singleton
// @Provides
// FourFun provideFourFun() {
// return (FourFun) this.application;
// }
//
// @Singleton
// @Provides
// RetrofitUtil provideRetrofitUtil() {
// return new RetrofitUtil();
// }
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/utils/RetrofitUtil.java
// public class RetrofitUtil {
// public static final int DEFAULT_TIMEOUT = 10;
// public static final String BASE_URL = "http://www.icodes.vip/4Fun/";
// private static Retrofit mRetrofit;
//
// public RetrofitUtil() {
// mRetrofit = new Retrofit.Builder().baseUrl(BASE_URL)
// .client(initOkHttp())
// .addConverterFactory(GsonConverterFactory.create())
// .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
// .build();
// }
//
// private OkHttpClient initOkHttp() {
// OkHttpClient.Builder builder = new OkHttpClient.Builder();
// Interceptor cacheInterceptor = new Interceptor() {
// @Override
// public Response intercept(Chain chain) throws IOException {
// Request request = chain.request();
// if (!SystemUtil.isNetworkConnected()) {
// request = request.newBuilder()
// .cacheControl(CacheControl.FORCE_CACHE)
// .build();
// }
// Response response = chain.proceed(request);
// if (SystemUtil.isNetworkConnected()) {
// int maxAge = 0;
// // 有网络时, 不缓存, 最大保存时长为0
// response.newBuilder()
// .header("Cache-Control", "public, max-age=" + maxAge)
// .removeHeader("Pragma")
// .build();
// } else {
// // 无网络时,设置超时为4周
// int maxStale = 60 * 60 * 24 * 28;
// response.newBuilder()
// .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
// .removeHeader("Pragma")
// .build();
// }
//
// return response;
// }
// };
// if (BuildConfig.DEBUG) {
// HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
// interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// builder.addInterceptor(interceptor);
// }
// File cacheFile = new File(FourFun.getInstance().getCacheDir().getPath());
// // 设置缓存文件 20MB
// Cache cache = new Cache(cacheFile, 1024 * 1024 * 20);
// return builder
// .addInterceptor(cacheInterceptor)
// .addNetworkInterceptor(cacheInterceptor)
// .cache(cache)
// .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
// .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
// .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
// .retryOnConnectionFailure(true)
// .build();
// }
//
// public <T> T create(Class<T> service) {
// return mRetrofit.create(service);
// }
// }
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/di/component/AppComponent.java
import com.joker.fourfun.FourFun;
import com.joker.fourfun.di.module.AppModule;
import com.joker.fourfun.utils.RetrofitUtil;
import javax.inject.Singleton;
import dagger.Component;
package com.joker.fourfun.di.component;
/**
* Created by joker on 2016/11/28.
*/
@Singleton
@Component(modules = AppModule.class)
public abstract class AppComponent {
private static AppComponent mComponent;
public static AppComponent getInstance() {
if (mComponent == null) {
synchronized (AppComponent.class) {
if (mComponent == null) {
|
mComponent = DaggerAppComponent.builder().appModule(new AppModule(FourFun.getInstance
|
4FunApp/4Fun
|
client/FourFun/app/src/main/java/com/joker/fourfun/di/component/AppComponent.java
|
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/FourFun.java
// public class FourFun extends Application {
// private static FourFun instance;
//
// public static FourFun getInstance() {
// return instance;
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// instance = this;
// if (LeakCanary.isInAnalyzerProcess(this)) {
// return;
// }
// LeakCanary.install(this);
// }
//
// public Context getContext() {
// return instance.getApplicationContext();
// }
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/di/module/AppModule.java
// @Module
// public class AppModule {
// private Application application;
//
// public AppModule(Application application) {
// this.application = application;
// }
//
// @Singleton
// @Provides
// FourFun provideFourFun() {
// return (FourFun) this.application;
// }
//
// @Singleton
// @Provides
// RetrofitUtil provideRetrofitUtil() {
// return new RetrofitUtil();
// }
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/utils/RetrofitUtil.java
// public class RetrofitUtil {
// public static final int DEFAULT_TIMEOUT = 10;
// public static final String BASE_URL = "http://www.icodes.vip/4Fun/";
// private static Retrofit mRetrofit;
//
// public RetrofitUtil() {
// mRetrofit = new Retrofit.Builder().baseUrl(BASE_URL)
// .client(initOkHttp())
// .addConverterFactory(GsonConverterFactory.create())
// .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
// .build();
// }
//
// private OkHttpClient initOkHttp() {
// OkHttpClient.Builder builder = new OkHttpClient.Builder();
// Interceptor cacheInterceptor = new Interceptor() {
// @Override
// public Response intercept(Chain chain) throws IOException {
// Request request = chain.request();
// if (!SystemUtil.isNetworkConnected()) {
// request = request.newBuilder()
// .cacheControl(CacheControl.FORCE_CACHE)
// .build();
// }
// Response response = chain.proceed(request);
// if (SystemUtil.isNetworkConnected()) {
// int maxAge = 0;
// // 有网络时, 不缓存, 最大保存时长为0
// response.newBuilder()
// .header("Cache-Control", "public, max-age=" + maxAge)
// .removeHeader("Pragma")
// .build();
// } else {
// // 无网络时,设置超时为4周
// int maxStale = 60 * 60 * 24 * 28;
// response.newBuilder()
// .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
// .removeHeader("Pragma")
// .build();
// }
//
// return response;
// }
// };
// if (BuildConfig.DEBUG) {
// HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
// interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// builder.addInterceptor(interceptor);
// }
// File cacheFile = new File(FourFun.getInstance().getCacheDir().getPath());
// // 设置缓存文件 20MB
// Cache cache = new Cache(cacheFile, 1024 * 1024 * 20);
// return builder
// .addInterceptor(cacheInterceptor)
// .addNetworkInterceptor(cacheInterceptor)
// .cache(cache)
// .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
// .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
// .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
// .retryOnConnectionFailure(true)
// .build();
// }
//
// public <T> T create(Class<T> service) {
// return mRetrofit.create(service);
// }
// }
|
import com.joker.fourfun.FourFun;
import com.joker.fourfun.di.module.AppModule;
import com.joker.fourfun.utils.RetrofitUtil;
import javax.inject.Singleton;
import dagger.Component;
|
package com.joker.fourfun.di.component;
/**
* Created by joker on 2016/11/28.
*/
@Singleton
@Component(modules = AppModule.class)
public abstract class AppComponent {
private static AppComponent mComponent;
public static AppComponent getInstance() {
if (mComponent == null) {
synchronized (AppComponent.class) {
if (mComponent == null) {
mComponent = DaggerAppComponent.builder().appModule(new AppModule(FourFun.getInstance
())).build();
}
}
}
return mComponent;
}
public abstract FourFun fourFun();
|
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/FourFun.java
// public class FourFun extends Application {
// private static FourFun instance;
//
// public static FourFun getInstance() {
// return instance;
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// instance = this;
// if (LeakCanary.isInAnalyzerProcess(this)) {
// return;
// }
// LeakCanary.install(this);
// }
//
// public Context getContext() {
// return instance.getApplicationContext();
// }
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/di/module/AppModule.java
// @Module
// public class AppModule {
// private Application application;
//
// public AppModule(Application application) {
// this.application = application;
// }
//
// @Singleton
// @Provides
// FourFun provideFourFun() {
// return (FourFun) this.application;
// }
//
// @Singleton
// @Provides
// RetrofitUtil provideRetrofitUtil() {
// return new RetrofitUtil();
// }
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/utils/RetrofitUtil.java
// public class RetrofitUtil {
// public static final int DEFAULT_TIMEOUT = 10;
// public static final String BASE_URL = "http://www.icodes.vip/4Fun/";
// private static Retrofit mRetrofit;
//
// public RetrofitUtil() {
// mRetrofit = new Retrofit.Builder().baseUrl(BASE_URL)
// .client(initOkHttp())
// .addConverterFactory(GsonConverterFactory.create())
// .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
// .build();
// }
//
// private OkHttpClient initOkHttp() {
// OkHttpClient.Builder builder = new OkHttpClient.Builder();
// Interceptor cacheInterceptor = new Interceptor() {
// @Override
// public Response intercept(Chain chain) throws IOException {
// Request request = chain.request();
// if (!SystemUtil.isNetworkConnected()) {
// request = request.newBuilder()
// .cacheControl(CacheControl.FORCE_CACHE)
// .build();
// }
// Response response = chain.proceed(request);
// if (SystemUtil.isNetworkConnected()) {
// int maxAge = 0;
// // 有网络时, 不缓存, 最大保存时长为0
// response.newBuilder()
// .header("Cache-Control", "public, max-age=" + maxAge)
// .removeHeader("Pragma")
// .build();
// } else {
// // 无网络时,设置超时为4周
// int maxStale = 60 * 60 * 24 * 28;
// response.newBuilder()
// .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
// .removeHeader("Pragma")
// .build();
// }
//
// return response;
// }
// };
// if (BuildConfig.DEBUG) {
// HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
// interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// builder.addInterceptor(interceptor);
// }
// File cacheFile = new File(FourFun.getInstance().getCacheDir().getPath());
// // 设置缓存文件 20MB
// Cache cache = new Cache(cacheFile, 1024 * 1024 * 20);
// return builder
// .addInterceptor(cacheInterceptor)
// .addNetworkInterceptor(cacheInterceptor)
// .cache(cache)
// .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
// .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
// .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
// .retryOnConnectionFailure(true)
// .build();
// }
//
// public <T> T create(Class<T> service) {
// return mRetrofit.create(service);
// }
// }
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/di/component/AppComponent.java
import com.joker.fourfun.FourFun;
import com.joker.fourfun.di.module.AppModule;
import com.joker.fourfun.utils.RetrofitUtil;
import javax.inject.Singleton;
import dagger.Component;
package com.joker.fourfun.di.component;
/**
* Created by joker on 2016/11/28.
*/
@Singleton
@Component(modules = AppModule.class)
public abstract class AppComponent {
private static AppComponent mComponent;
public static AppComponent getInstance() {
if (mComponent == null) {
synchronized (AppComponent.class) {
if (mComponent == null) {
mComponent = DaggerAppComponent.builder().appModule(new AppModule(FourFun.getInstance
())).build();
}
}
}
return mComponent;
}
public abstract FourFun fourFun();
|
public abstract RetrofitUtil retrofitUtil();
|
4FunApp/4Fun
|
client/FourFun/app/src/main/java/com/joker/fourfun/widget/DividerItemDecoration.java
|
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/utils/SystemUtil.java
// public class SystemUtil {
// public static final String RUNNING_FONT = "running_font.ttf";
// private static Toast mToast;
//
// private SystemUtil() {
// }
//
// /**
// * 网络是否连接
// *
// * @return
// */
// public static boolean isNetworkConnected() {
// ConnectivityManager connectivityManager = (ConnectivityManager) FourFun.getInstance()
// .getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
// return connectivityManager.getActiveNetworkInfo() != null;
// }
//
// /**
// * 获取项目缓存路径
// * @return
// */
// public static String getCacheFileDirPath() {
// Logger.e(FourFun.getInstance().getApplicationContext().getCacheDir().getPath());
// Logger.e(FourFun.getInstance().getApplicationContext().getCacheDir().getAbsolutePath());
// return FourFun.getInstance().getApplicationContext().getCacheDir().getPath();
// }
//
// /**
// * toast 优化显示
// *
// * @param content
// */
// public static void showToast(Context context, String content) {
// if (mToast == null) {
// mToast = Toast.makeText(FourFun.getInstance().getContext(), content, Toast
// .LENGTH_SHORT);
// } else {
// mToast.setText(content);
// }
//
// mToast.show();
// }
//
// /**
// * 取消 toast
// */
// public static void cancelToast() {
// if (mToast != null) {
// mToast.cancel();
// }
// }
//
// /**
// * 前几天的日期
// *
// * @param before 和今天相差的天数
// * @return
// */
// public static String beforeToday(int before) {
// Date now = new Date();
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA); //设置时间格式
//
// if (before < 0) {
// Calendar calendar = Calendar.getInstance();
// calendar.setTime(now);
// calendar.add(Calendar.DATE, before);
// now = calendar.getTime();
// }
//
// return sdf.format(now);
// }
//
// /**
// * 像素转 sp
// *
// * @param context
// * @param textSizePixel
// * @return
// */
// public static int px2sp(Context context, float textSizePixel) {
// final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
// return (int) (textSizePixel / fontScale + 0.5f);
// }
//
// /**
// * sp 转 px
// *
// * @param context
// * @param textSizeSp
// * @return
// */
// public static float sp2px(Context context, float textSizeSp) {
// final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
// return (int) (textSizeSp * fontScale + 0.5f);
// }
//
// /**
// * dp 转 px
// *
// * @param dp
// * @return
// */
// public static int dp2px(float dp) {
// float DENSITY = Resources.getSystem().getDisplayMetrics().density;
// return Math.round(dp * DENSITY);
// }
//
// public static Typeface getTypeface(Context context) {
// return Typeface.createFromAsset(context.getAssets(), "fonts/" + RUNNING_FONT);
// }
//
// /**
// * 输入流转文件
// * @param file
// * @param stream
// */
// public static void inputStream2file(File file, InputStream stream) {
// OutputStream os = null;
// try {
// os = new FileOutputStream(file);
// int bytesRead = 0;
// byte[] buffer = new byte[1024];
// while ((bytesRead = stream.read(buffer)) != -1) {
// os.write(buffer, 0, bytesRead);
// }
//
// os.close();
// stream.close();
// } catch (IOException e) {
// e.printStackTrace();
// } finally {
// try {
// if (os != null) {
// os.close();
// }
// if (stream != null) {
// stream.close();
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }
// }
|
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.ItemDecoration;
import android.view.View;
import com.joker.fourfun.utils.SystemUtil;
|
package com.joker.fourfun.widget;
/**
* Created by joker on 2016/12/20.
*/
public class DividerItemDecoration extends ItemDecoration {
int mSpace;
/**
* @param space 传入的值,其单位视为dp
*/
public DividerItemDecoration(int space) {
|
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/utils/SystemUtil.java
// public class SystemUtil {
// public static final String RUNNING_FONT = "running_font.ttf";
// private static Toast mToast;
//
// private SystemUtil() {
// }
//
// /**
// * 网络是否连接
// *
// * @return
// */
// public static boolean isNetworkConnected() {
// ConnectivityManager connectivityManager = (ConnectivityManager) FourFun.getInstance()
// .getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
// return connectivityManager.getActiveNetworkInfo() != null;
// }
//
// /**
// * 获取项目缓存路径
// * @return
// */
// public static String getCacheFileDirPath() {
// Logger.e(FourFun.getInstance().getApplicationContext().getCacheDir().getPath());
// Logger.e(FourFun.getInstance().getApplicationContext().getCacheDir().getAbsolutePath());
// return FourFun.getInstance().getApplicationContext().getCacheDir().getPath();
// }
//
// /**
// * toast 优化显示
// *
// * @param content
// */
// public static void showToast(Context context, String content) {
// if (mToast == null) {
// mToast = Toast.makeText(FourFun.getInstance().getContext(), content, Toast
// .LENGTH_SHORT);
// } else {
// mToast.setText(content);
// }
//
// mToast.show();
// }
//
// /**
// * 取消 toast
// */
// public static void cancelToast() {
// if (mToast != null) {
// mToast.cancel();
// }
// }
//
// /**
// * 前几天的日期
// *
// * @param before 和今天相差的天数
// * @return
// */
// public static String beforeToday(int before) {
// Date now = new Date();
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA); //设置时间格式
//
// if (before < 0) {
// Calendar calendar = Calendar.getInstance();
// calendar.setTime(now);
// calendar.add(Calendar.DATE, before);
// now = calendar.getTime();
// }
//
// return sdf.format(now);
// }
//
// /**
// * 像素转 sp
// *
// * @param context
// * @param textSizePixel
// * @return
// */
// public static int px2sp(Context context, float textSizePixel) {
// final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
// return (int) (textSizePixel / fontScale + 0.5f);
// }
//
// /**
// * sp 转 px
// *
// * @param context
// * @param textSizeSp
// * @return
// */
// public static float sp2px(Context context, float textSizeSp) {
// final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
// return (int) (textSizeSp * fontScale + 0.5f);
// }
//
// /**
// * dp 转 px
// *
// * @param dp
// * @return
// */
// public static int dp2px(float dp) {
// float DENSITY = Resources.getSystem().getDisplayMetrics().density;
// return Math.round(dp * DENSITY);
// }
//
// public static Typeface getTypeface(Context context) {
// return Typeface.createFromAsset(context.getAssets(), "fonts/" + RUNNING_FONT);
// }
//
// /**
// * 输入流转文件
// * @param file
// * @param stream
// */
// public static void inputStream2file(File file, InputStream stream) {
// OutputStream os = null;
// try {
// os = new FileOutputStream(file);
// int bytesRead = 0;
// byte[] buffer = new byte[1024];
// while ((bytesRead = stream.read(buffer)) != -1) {
// os.write(buffer, 0, bytesRead);
// }
//
// os.close();
// stream.close();
// } catch (IOException e) {
// e.printStackTrace();
// } finally {
// try {
// if (os != null) {
// os.close();
// }
// if (stream != null) {
// stream.close();
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }
// }
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/widget/DividerItemDecoration.java
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.ItemDecoration;
import android.view.View;
import com.joker.fourfun.utils.SystemUtil;
package com.joker.fourfun.widget;
/**
* Created by joker on 2016/12/20.
*/
public class DividerItemDecoration extends ItemDecoration {
int mSpace;
/**
* @param space 传入的值,其单位视为dp
*/
public DividerItemDecoration(int space) {
|
this.mSpace = SystemUtil.dp2px(space);
|
4FunApp/4Fun
|
client/FourFun/app/src/main/java/com/joker/fourfun/utils/RxUtil.java
|
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/model/LoginInfo.java
// public class LoginInfo {
// /**
// * error : false
// * result : [{"userName":"1","password":"1","sex":0,"code":1051}]
// */
// /**
// * userName : 1
// * password : 1
// * sex : 0
// * code : 1051
// */
// private String userName;
// private String password;
// private int sex;
// private int code;
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public int getSex() {
// return sex;
// }
//
// public void setSex(int sex) {
// this.sex = sex;
// }
//
// public int getCode() {
// return code;
// }
//
// public void setCode(int code) {
// this.code = code;
// }
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/net/LoginException.java
// public class LoginException extends RuntimeException {
// public static final int LOGIN_PASSWORD_ERROR_CODE = 1025;
// public static final int LOGIN_USER_ERROR_CODE = 1026;
// public static final int REGISTER_USER_REPEAT_ERROR_CODE = 1027;
// public static final String LOGIN_PASSWORD_ERROR_MESSAGE = "密码错误,请重试";
// public static final String LOGIN_USER_ERROR_MESSAGE = "用户名不存在";
// public static final String REGISTER_USER_REPEAT_ERROR_MESSAGE = "用户已注册";
//
//
// public LoginException(int code) {
// this(getLoginExceptionMessage(code));
// }
//
// public LoginException(String message) {
// super(message);
// }
//
// private static String getLoginExceptionMessage(int code) {
// String message = "";
// switch (code) {
// case LOGIN_PASSWORD_ERROR_CODE:
// message = LOGIN_PASSWORD_ERROR_MESSAGE;
// break;
// case LOGIN_USER_ERROR_CODE:
// message = LOGIN_USER_ERROR_MESSAGE;
// break;
// case REGISTER_USER_REPEAT_ERROR_CODE:
// message = REGISTER_USER_REPEAT_ERROR_MESSAGE;
// break;
// default:
// message = "未知错误";
// break;
// }
//
// return message;
// }
// }
|
import com.joker.fourfun.model.LoginInfo;
import com.joker.fourfun.net.LoginException;
import com.orhanobut.logger.Logger;
import org.reactivestreams.Publisher;
import java.util.List;
import java.util.concurrent.TimeUnit;
import io.reactivex.Flowable;
import io.reactivex.FlowableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
|
package com.joker.fourfun.utils;
/**
* Created by joker on 2016/11/28.
*/
public class RxUtil {
/**
* rxjava 线程封装
*
* @param <T>
* @return
*/
public static <T> FlowableTransformer<T, T> rxSchedulerTransformer() {
return new FlowableTransformer<T, T>() {
@Override
public Publisher<T> apply(Flowable<T> upstream) {
return upstream
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
};
}
/**
* rxjava 超时抛出异常
*
* @param <T>
* @return
*/
public static <T> FlowableTransformer<T, T> rxTimeoutTransformer() {
return new FlowableTransformer<T, T>() {
@Override
public Publisher<T> apply(Flowable<T> upstream) {
return upstream.timeout(3, TimeUnit.SECONDS);
}
};
}
/**
* 登录注册状态校验
*
* @param code
* @return
*/
|
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/model/LoginInfo.java
// public class LoginInfo {
// /**
// * error : false
// * result : [{"userName":"1","password":"1","sex":0,"code":1051}]
// */
// /**
// * userName : 1
// * password : 1
// * sex : 0
// * code : 1051
// */
// private String userName;
// private String password;
// private int sex;
// private int code;
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public int getSex() {
// return sex;
// }
//
// public void setSex(int sex) {
// this.sex = sex;
// }
//
// public int getCode() {
// return code;
// }
//
// public void setCode(int code) {
// this.code = code;
// }
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/net/LoginException.java
// public class LoginException extends RuntimeException {
// public static final int LOGIN_PASSWORD_ERROR_CODE = 1025;
// public static final int LOGIN_USER_ERROR_CODE = 1026;
// public static final int REGISTER_USER_REPEAT_ERROR_CODE = 1027;
// public static final String LOGIN_PASSWORD_ERROR_MESSAGE = "密码错误,请重试";
// public static final String LOGIN_USER_ERROR_MESSAGE = "用户名不存在";
// public static final String REGISTER_USER_REPEAT_ERROR_MESSAGE = "用户已注册";
//
//
// public LoginException(int code) {
// this(getLoginExceptionMessage(code));
// }
//
// public LoginException(String message) {
// super(message);
// }
//
// private static String getLoginExceptionMessage(int code) {
// String message = "";
// switch (code) {
// case LOGIN_PASSWORD_ERROR_CODE:
// message = LOGIN_PASSWORD_ERROR_MESSAGE;
// break;
// case LOGIN_USER_ERROR_CODE:
// message = LOGIN_USER_ERROR_MESSAGE;
// break;
// case REGISTER_USER_REPEAT_ERROR_CODE:
// message = REGISTER_USER_REPEAT_ERROR_MESSAGE;
// break;
// default:
// message = "未知错误";
// break;
// }
//
// return message;
// }
// }
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/utils/RxUtil.java
import com.joker.fourfun.model.LoginInfo;
import com.joker.fourfun.net.LoginException;
import com.orhanobut.logger.Logger;
import org.reactivestreams.Publisher;
import java.util.List;
import java.util.concurrent.TimeUnit;
import io.reactivex.Flowable;
import io.reactivex.FlowableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
package com.joker.fourfun.utils;
/**
* Created by joker on 2016/11/28.
*/
public class RxUtil {
/**
* rxjava 线程封装
*
* @param <T>
* @return
*/
public static <T> FlowableTransformer<T, T> rxSchedulerTransformer() {
return new FlowableTransformer<T, T>() {
@Override
public Publisher<T> apply(Flowable<T> upstream) {
return upstream
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
};
}
/**
* rxjava 超时抛出异常
*
* @param <T>
* @return
*/
public static <T> FlowableTransformer<T, T> rxTimeoutTransformer() {
return new FlowableTransformer<T, T>() {
@Override
public Publisher<T> apply(Flowable<T> upstream) {
return upstream.timeout(3, TimeUnit.SECONDS);
}
};
}
/**
* 登录注册状态校验
*
* @param code
* @return
*/
|
public static FlowableTransformer<List<LoginInfo>, LoginInfo> rxStateCheck(final int code) {
|
4FunApp/4Fun
|
client/FourFun/app/src/main/java/com/joker/fourfun/utils/RxUtil.java
|
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/model/LoginInfo.java
// public class LoginInfo {
// /**
// * error : false
// * result : [{"userName":"1","password":"1","sex":0,"code":1051}]
// */
// /**
// * userName : 1
// * password : 1
// * sex : 0
// * code : 1051
// */
// private String userName;
// private String password;
// private int sex;
// private int code;
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public int getSex() {
// return sex;
// }
//
// public void setSex(int sex) {
// this.sex = sex;
// }
//
// public int getCode() {
// return code;
// }
//
// public void setCode(int code) {
// this.code = code;
// }
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/net/LoginException.java
// public class LoginException extends RuntimeException {
// public static final int LOGIN_PASSWORD_ERROR_CODE = 1025;
// public static final int LOGIN_USER_ERROR_CODE = 1026;
// public static final int REGISTER_USER_REPEAT_ERROR_CODE = 1027;
// public static final String LOGIN_PASSWORD_ERROR_MESSAGE = "密码错误,请重试";
// public static final String LOGIN_USER_ERROR_MESSAGE = "用户名不存在";
// public static final String REGISTER_USER_REPEAT_ERROR_MESSAGE = "用户已注册";
//
//
// public LoginException(int code) {
// this(getLoginExceptionMessage(code));
// }
//
// public LoginException(String message) {
// super(message);
// }
//
// private static String getLoginExceptionMessage(int code) {
// String message = "";
// switch (code) {
// case LOGIN_PASSWORD_ERROR_CODE:
// message = LOGIN_PASSWORD_ERROR_MESSAGE;
// break;
// case LOGIN_USER_ERROR_CODE:
// message = LOGIN_USER_ERROR_MESSAGE;
// break;
// case REGISTER_USER_REPEAT_ERROR_CODE:
// message = REGISTER_USER_REPEAT_ERROR_MESSAGE;
// break;
// default:
// message = "未知错误";
// break;
// }
//
// return message;
// }
// }
|
import com.joker.fourfun.model.LoginInfo;
import com.joker.fourfun.net.LoginException;
import com.orhanobut.logger.Logger;
import org.reactivestreams.Publisher;
import java.util.List;
import java.util.concurrent.TimeUnit;
import io.reactivex.Flowable;
import io.reactivex.FlowableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
|
package com.joker.fourfun.utils;
/**
* Created by joker on 2016/11/28.
*/
public class RxUtil {
/**
* rxjava 线程封装
*
* @param <T>
* @return
*/
public static <T> FlowableTransformer<T, T> rxSchedulerTransformer() {
return new FlowableTransformer<T, T>() {
@Override
public Publisher<T> apply(Flowable<T> upstream) {
return upstream
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
};
}
/**
* rxjava 超时抛出异常
*
* @param <T>
* @return
*/
public static <T> FlowableTransformer<T, T> rxTimeoutTransformer() {
return new FlowableTransformer<T, T>() {
@Override
public Publisher<T> apply(Flowable<T> upstream) {
return upstream.timeout(3, TimeUnit.SECONDS);
}
};
}
/**
* 登录注册状态校验
*
* @param code
* @return
*/
public static FlowableTransformer<List<LoginInfo>, LoginInfo> rxStateCheck(final int code) {
return new FlowableTransformer<List<LoginInfo>, LoginInfo>() {
@Override
public Publisher<LoginInfo> apply(Flowable<List<LoginInfo>> upstream) {
return upstream
.map(new Function<List<LoginInfo>, LoginInfo>() {
@Override
public LoginInfo apply(List<LoginInfo> loginInfos) throws Exception {
int serverCode = loginInfos.get(0).getCode();
if (serverCode != code) {
|
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/model/LoginInfo.java
// public class LoginInfo {
// /**
// * error : false
// * result : [{"userName":"1","password":"1","sex":0,"code":1051}]
// */
// /**
// * userName : 1
// * password : 1
// * sex : 0
// * code : 1051
// */
// private String userName;
// private String password;
// private int sex;
// private int code;
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public int getSex() {
// return sex;
// }
//
// public void setSex(int sex) {
// this.sex = sex;
// }
//
// public int getCode() {
// return code;
// }
//
// public void setCode(int code) {
// this.code = code;
// }
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/net/LoginException.java
// public class LoginException extends RuntimeException {
// public static final int LOGIN_PASSWORD_ERROR_CODE = 1025;
// public static final int LOGIN_USER_ERROR_CODE = 1026;
// public static final int REGISTER_USER_REPEAT_ERROR_CODE = 1027;
// public static final String LOGIN_PASSWORD_ERROR_MESSAGE = "密码错误,请重试";
// public static final String LOGIN_USER_ERROR_MESSAGE = "用户名不存在";
// public static final String REGISTER_USER_REPEAT_ERROR_MESSAGE = "用户已注册";
//
//
// public LoginException(int code) {
// this(getLoginExceptionMessage(code));
// }
//
// public LoginException(String message) {
// super(message);
// }
//
// private static String getLoginExceptionMessage(int code) {
// String message = "";
// switch (code) {
// case LOGIN_PASSWORD_ERROR_CODE:
// message = LOGIN_PASSWORD_ERROR_MESSAGE;
// break;
// case LOGIN_USER_ERROR_CODE:
// message = LOGIN_USER_ERROR_MESSAGE;
// break;
// case REGISTER_USER_REPEAT_ERROR_CODE:
// message = REGISTER_USER_REPEAT_ERROR_MESSAGE;
// break;
// default:
// message = "未知错误";
// break;
// }
//
// return message;
// }
// }
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/utils/RxUtil.java
import com.joker.fourfun.model.LoginInfo;
import com.joker.fourfun.net.LoginException;
import com.orhanobut.logger.Logger;
import org.reactivestreams.Publisher;
import java.util.List;
import java.util.concurrent.TimeUnit;
import io.reactivex.Flowable;
import io.reactivex.FlowableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
package com.joker.fourfun.utils;
/**
* Created by joker on 2016/11/28.
*/
public class RxUtil {
/**
* rxjava 线程封装
*
* @param <T>
* @return
*/
public static <T> FlowableTransformer<T, T> rxSchedulerTransformer() {
return new FlowableTransformer<T, T>() {
@Override
public Publisher<T> apply(Flowable<T> upstream) {
return upstream
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
};
}
/**
* rxjava 超时抛出异常
*
* @param <T>
* @return
*/
public static <T> FlowableTransformer<T, T> rxTimeoutTransformer() {
return new FlowableTransformer<T, T>() {
@Override
public Publisher<T> apply(Flowable<T> upstream) {
return upstream.timeout(3, TimeUnit.SECONDS);
}
};
}
/**
* 登录注册状态校验
*
* @param code
* @return
*/
public static FlowableTransformer<List<LoginInfo>, LoginInfo> rxStateCheck(final int code) {
return new FlowableTransformer<List<LoginInfo>, LoginInfo>() {
@Override
public Publisher<LoginInfo> apply(Flowable<List<LoginInfo>> upstream) {
return upstream
.map(new Function<List<LoginInfo>, LoginInfo>() {
@Override
public LoginInfo apply(List<LoginInfo> loginInfos) throws Exception {
int serverCode = loginInfos.get(0).getCode();
if (serverCode != code) {
|
throw new LoginException(serverCode);
|
4FunApp/4Fun
|
server/4FunServer/src/com/mollychin/utils/JDBCUtil.java
|
// Path: server/4FunServer/src/com/mollychin/utils/ConstantsUtil.java
// public final static String PASSWORD = "123456";
//
// Path: server/4FunServer/src/com/mollychin/utils/ConstantsUtil.java
// public final static String ROOT_URL = "jdbc:mysql://localhost:3306/"
// + DATABASE_NAME;
//
// Path: server/4FunServer/src/com/mollychin/utils/ConstantsUtil.java
// public final static String USER = "root";
//
// Path: server/4FunServer/src/com/mollychin/bean/User.java
// public class User {
// private String userName;
// private String password;
// private int sex;
// private String email;
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public int getSex() {
// return sex;
// }
//
// public void setSex(int sex) {
// this.sex = sex;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
// }
|
import static com.mollychin.utils.ConstantsUtil.PASSWORD;
import static com.mollychin.utils.ConstantsUtil.ROOT_URL;
import static com.mollychin.utils.ConstantsUtil.USER;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.gson.Gson;
import com.mollychin.bean.User;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
|
package com.mollychin.utils;
public class JDBCUtil {
// 连接
public static Connection getConnection() throws Exception {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
|
// Path: server/4FunServer/src/com/mollychin/utils/ConstantsUtil.java
// public final static String PASSWORD = "123456";
//
// Path: server/4FunServer/src/com/mollychin/utils/ConstantsUtil.java
// public final static String ROOT_URL = "jdbc:mysql://localhost:3306/"
// + DATABASE_NAME;
//
// Path: server/4FunServer/src/com/mollychin/utils/ConstantsUtil.java
// public final static String USER = "root";
//
// Path: server/4FunServer/src/com/mollychin/bean/User.java
// public class User {
// private String userName;
// private String password;
// private int sex;
// private String email;
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public int getSex() {
// return sex;
// }
//
// public void setSex(int sex) {
// this.sex = sex;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
// }
// Path: server/4FunServer/src/com/mollychin/utils/JDBCUtil.java
import static com.mollychin.utils.ConstantsUtil.PASSWORD;
import static com.mollychin.utils.ConstantsUtil.ROOT_URL;
import static com.mollychin.utils.ConstantsUtil.USER;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.gson.Gson;
import com.mollychin.bean.User;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
package com.mollychin.utils;
public class JDBCUtil {
// 连接
public static Connection getConnection() throws Exception {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
|
return DriverManager.getConnection(ROOT_URL, USER, PASSWORD);
|
4FunApp/4Fun
|
server/4FunServer/src/com/mollychin/utils/JDBCUtil.java
|
// Path: server/4FunServer/src/com/mollychin/utils/ConstantsUtil.java
// public final static String PASSWORD = "123456";
//
// Path: server/4FunServer/src/com/mollychin/utils/ConstantsUtil.java
// public final static String ROOT_URL = "jdbc:mysql://localhost:3306/"
// + DATABASE_NAME;
//
// Path: server/4FunServer/src/com/mollychin/utils/ConstantsUtil.java
// public final static String USER = "root";
//
// Path: server/4FunServer/src/com/mollychin/bean/User.java
// public class User {
// private String userName;
// private String password;
// private int sex;
// private String email;
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public int getSex() {
// return sex;
// }
//
// public void setSex(int sex) {
// this.sex = sex;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
// }
|
import static com.mollychin.utils.ConstantsUtil.PASSWORD;
import static com.mollychin.utils.ConstantsUtil.ROOT_URL;
import static com.mollychin.utils.ConstantsUtil.USER;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.gson.Gson;
import com.mollychin.bean.User;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
|
package com.mollychin.utils;
public class JDBCUtil {
// 连接
public static Connection getConnection() throws Exception {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
|
// Path: server/4FunServer/src/com/mollychin/utils/ConstantsUtil.java
// public final static String PASSWORD = "123456";
//
// Path: server/4FunServer/src/com/mollychin/utils/ConstantsUtil.java
// public final static String ROOT_URL = "jdbc:mysql://localhost:3306/"
// + DATABASE_NAME;
//
// Path: server/4FunServer/src/com/mollychin/utils/ConstantsUtil.java
// public final static String USER = "root";
//
// Path: server/4FunServer/src/com/mollychin/bean/User.java
// public class User {
// private String userName;
// private String password;
// private int sex;
// private String email;
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public int getSex() {
// return sex;
// }
//
// public void setSex(int sex) {
// this.sex = sex;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
// }
// Path: server/4FunServer/src/com/mollychin/utils/JDBCUtil.java
import static com.mollychin.utils.ConstantsUtil.PASSWORD;
import static com.mollychin.utils.ConstantsUtil.ROOT_URL;
import static com.mollychin.utils.ConstantsUtil.USER;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.gson.Gson;
import com.mollychin.bean.User;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
package com.mollychin.utils;
public class JDBCUtil {
// 连接
public static Connection getConnection() throws Exception {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
|
return DriverManager.getConnection(ROOT_URL, USER, PASSWORD);
|
4FunApp/4Fun
|
server/4FunServer/src/com/mollychin/utils/JDBCUtil.java
|
// Path: server/4FunServer/src/com/mollychin/utils/ConstantsUtil.java
// public final static String PASSWORD = "123456";
//
// Path: server/4FunServer/src/com/mollychin/utils/ConstantsUtil.java
// public final static String ROOT_URL = "jdbc:mysql://localhost:3306/"
// + DATABASE_NAME;
//
// Path: server/4FunServer/src/com/mollychin/utils/ConstantsUtil.java
// public final static String USER = "root";
//
// Path: server/4FunServer/src/com/mollychin/bean/User.java
// public class User {
// private String userName;
// private String password;
// private int sex;
// private String email;
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public int getSex() {
// return sex;
// }
//
// public void setSex(int sex) {
// this.sex = sex;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
// }
|
import static com.mollychin.utils.ConstantsUtil.PASSWORD;
import static com.mollychin.utils.ConstantsUtil.ROOT_URL;
import static com.mollychin.utils.ConstantsUtil.USER;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.gson.Gson;
import com.mollychin.bean.User;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
|
package com.mollychin.utils;
public class JDBCUtil {
// 连接
public static Connection getConnection() throws Exception {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
|
// Path: server/4FunServer/src/com/mollychin/utils/ConstantsUtil.java
// public final static String PASSWORD = "123456";
//
// Path: server/4FunServer/src/com/mollychin/utils/ConstantsUtil.java
// public final static String ROOT_URL = "jdbc:mysql://localhost:3306/"
// + DATABASE_NAME;
//
// Path: server/4FunServer/src/com/mollychin/utils/ConstantsUtil.java
// public final static String USER = "root";
//
// Path: server/4FunServer/src/com/mollychin/bean/User.java
// public class User {
// private String userName;
// private String password;
// private int sex;
// private String email;
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public int getSex() {
// return sex;
// }
//
// public void setSex(int sex) {
// this.sex = sex;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
// }
// Path: server/4FunServer/src/com/mollychin/utils/JDBCUtil.java
import static com.mollychin.utils.ConstantsUtil.PASSWORD;
import static com.mollychin.utils.ConstantsUtil.ROOT_URL;
import static com.mollychin.utils.ConstantsUtil.USER;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.gson.Gson;
import com.mollychin.bean.User;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
package com.mollychin.utils;
public class JDBCUtil {
// 连接
public static Connection getConnection() throws Exception {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
|
return DriverManager.getConnection(ROOT_URL, USER, PASSWORD);
|
4FunApp/4Fun
|
server/4FunServer/src/com/mollychin/utils/JDBCUtil.java
|
// Path: server/4FunServer/src/com/mollychin/utils/ConstantsUtil.java
// public final static String PASSWORD = "123456";
//
// Path: server/4FunServer/src/com/mollychin/utils/ConstantsUtil.java
// public final static String ROOT_URL = "jdbc:mysql://localhost:3306/"
// + DATABASE_NAME;
//
// Path: server/4FunServer/src/com/mollychin/utils/ConstantsUtil.java
// public final static String USER = "root";
//
// Path: server/4FunServer/src/com/mollychin/bean/User.java
// public class User {
// private String userName;
// private String password;
// private int sex;
// private String email;
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public int getSex() {
// return sex;
// }
//
// public void setSex(int sex) {
// this.sex = sex;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
// }
|
import static com.mollychin.utils.ConstantsUtil.PASSWORD;
import static com.mollychin.utils.ConstantsUtil.ROOT_URL;
import static com.mollychin.utils.ConstantsUtil.USER;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.gson.Gson;
import com.mollychin.bean.User;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
|
JSONObject object = new JSONObject();
boolean error = true;
// json 数组
JSONArray array = new JSONArray();
// 获取列数
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();
// 遍历ResultSet中的每条数据
while (rs.next()) {
int row = rs.getRow() - 1;
ResultSet data = selectData(sqlList.get(row));
JSONObject jsonObj = new JSONObject();
// 遍历每一列
for (int i = 1; i <= columnCount; i++) {
String columnName = metaData.getColumnLabel(i);
Object value = columnName.equals("actor") ? resultSet2JSONArray(data)
: rs.getString(columnName);
jsonObj.put(columnName, value);
}
array.put(jsonObj);
}
if (array.length() > 0) {
error = !error;
}
object.put("error", error);
object.put("result", array);
return object.toString();
}
|
// Path: server/4FunServer/src/com/mollychin/utils/ConstantsUtil.java
// public final static String PASSWORD = "123456";
//
// Path: server/4FunServer/src/com/mollychin/utils/ConstantsUtil.java
// public final static String ROOT_URL = "jdbc:mysql://localhost:3306/"
// + DATABASE_NAME;
//
// Path: server/4FunServer/src/com/mollychin/utils/ConstantsUtil.java
// public final static String USER = "root";
//
// Path: server/4FunServer/src/com/mollychin/bean/User.java
// public class User {
// private String userName;
// private String password;
// private int sex;
// private String email;
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public int getSex() {
// return sex;
// }
//
// public void setSex(int sex) {
// this.sex = sex;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
// }
// Path: server/4FunServer/src/com/mollychin/utils/JDBCUtil.java
import static com.mollychin.utils.ConstantsUtil.PASSWORD;
import static com.mollychin.utils.ConstantsUtil.ROOT_URL;
import static com.mollychin.utils.ConstantsUtil.USER;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.gson.Gson;
import com.mollychin.bean.User;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
JSONObject object = new JSONObject();
boolean error = true;
// json 数组
JSONArray array = new JSONArray();
// 获取列数
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();
// 遍历ResultSet中的每条数据
while (rs.next()) {
int row = rs.getRow() - 1;
ResultSet data = selectData(sqlList.get(row));
JSONObject jsonObj = new JSONObject();
// 遍历每一列
for (int i = 1; i <= columnCount; i++) {
String columnName = metaData.getColumnLabel(i);
Object value = columnName.equals("actor") ? resultSet2JSONArray(data)
: rs.getString(columnName);
jsonObj.put(columnName, value);
}
array.put(jsonObj);
}
if (array.length() > 0) {
error = !error;
}
object.put("error", error);
object.put("result", array);
return object.toString();
}
|
public static void addUser(User user) throws Exception {
|
4FunApp/4Fun
|
client/FourFun/app/src/main/java/com/joker/fourfun/presenter/contract/MovieDetailContract.java
|
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/base/BasePresenter.java
// public interface BasePresenter<T extends BaseView> {
// void attach(T mView);
//
// void detach();
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/base/BaseView.java
// public interface BaseView {
// void showError(String message);
// }
|
import com.joker.fourfun.base.BasePresenter;
import com.joker.fourfun.base.BaseView;
import com.joker.fourfun.model.Movie;
|
package com.joker.fourfun.presenter.contract;
/**
* Created by joker on 2017/1/3.
*/
public interface MovieDetailContract {
interface View extends BaseView {
void showContent(Movie movie);
}
|
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/base/BasePresenter.java
// public interface BasePresenter<T extends BaseView> {
// void attach(T mView);
//
// void detach();
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/base/BaseView.java
// public interface BaseView {
// void showError(String message);
// }
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/presenter/contract/MovieDetailContract.java
import com.joker.fourfun.base.BasePresenter;
import com.joker.fourfun.base.BaseView;
import com.joker.fourfun.model.Movie;
package com.joker.fourfun.presenter.contract;
/**
* Created by joker on 2017/1/3.
*/
public interface MovieDetailContract {
interface View extends BaseView {
void showContent(Movie movie);
}
|
interface Presenter extends BasePresenter<View> {
|
4FunApp/4Fun
|
client/FourFun/app/src/main/java/com/joker/fourfun/presenter/contract/PictureContract.java
|
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/base/BasePresenter.java
// public interface BasePresenter<T extends BaseView> {
// void attach(T mView);
//
// void detach();
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/base/BaseView.java
// public interface BaseView {
// void showError(String message);
// }
|
import com.joker.fourfun.base.BasePresenter;
import com.joker.fourfun.base.BaseView;
|
package com.joker.fourfun.presenter.contract;
/**
* Created by joker on 2016/12/5.
*/
public interface PictureContract {
interface View extends BaseView {
}
|
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/base/BasePresenter.java
// public interface BasePresenter<T extends BaseView> {
// void attach(T mView);
//
// void detach();
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/base/BaseView.java
// public interface BaseView {
// void showError(String message);
// }
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/presenter/contract/PictureContract.java
import com.joker.fourfun.base.BasePresenter;
import com.joker.fourfun.base.BaseView;
package com.joker.fourfun.presenter.contract;
/**
* Created by joker on 2016/12/5.
*/
public interface PictureContract {
interface View extends BaseView {
}
|
interface Presenter extends BasePresenter<View> {
|
4FunApp/4Fun
|
client/FourFun/app/src/main/java/com/joker/fourfun/presenter/contract/MainContract.java
|
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/base/BasePresenter.java
// public interface BasePresenter<T extends BaseView> {
// void attach(T mView);
//
// void detach();
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/base/BaseView.java
// public interface BaseView {
// void showError(String message);
// }
|
import com.joker.fourfun.base.BasePresenter;
import com.joker.fourfun.base.BaseView;
|
package com.joker.fourfun.presenter.contract;
/**
* Created by joker on 2016/11/30.
*/
public interface MainContract {
interface View extends BaseView {
}
|
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/base/BasePresenter.java
// public interface BasePresenter<T extends BaseView> {
// void attach(T mView);
//
// void detach();
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/base/BaseView.java
// public interface BaseView {
// void showError(String message);
// }
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/presenter/contract/MainContract.java
import com.joker.fourfun.base.BasePresenter;
import com.joker.fourfun.base.BaseView;
package com.joker.fourfun.presenter.contract;
/**
* Created by joker on 2016/11/30.
*/
public interface MainContract {
interface View extends BaseView {
}
|
interface Presenter extends BasePresenter<View> {
|
4FunApp/4Fun
|
client/FourFun/app/src/main/java/com/joker/fourfun/base/BaseMvpActivity.java
|
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/di/component/ActivityComponent.java
// @PerActivity
// @Component(dependencies = AppComponent.class, modules = ActivityModule.class)
// public interface ActivityComponent {
// AppCompatActivity activity();
//
// void inject(SplashActivity activity);
//
// void inject(MainActivity activity);
//
// void inject(PictureDetailActivity activity);
//
// void inject(LoginActivity activity);
//
// void inject(RegisterActivity activity);
//
// void inject(MovieDetailActivity activity);
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/di/component/AppComponent.java
// @Singleton
// @Component(modules = AppModule.class)
// public abstract class AppComponent {
// private static AppComponent mComponent;
//
// public static AppComponent getInstance() {
// if (mComponent == null) {
// synchronized (AppComponent.class) {
// if (mComponent == null) {
// mComponent = DaggerAppComponent.builder().appModule(new AppModule(FourFun.getInstance
// ())).build();
// }
// }
// }
//
// return mComponent;
// }
//
// public abstract FourFun fourFun();
//
// public abstract RetrofitUtil retrofitUtil();
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/di/module/ActivityModule.java
// @Module
// public class ActivityModule {
// private AppCompatActivity mActivity;
//
// public ActivityModule(AppCompatActivity appCompatActivity) {
// mActivity = appCompatActivity;
// }
//
// @Provides
// @PerActivity
// AppCompatActivity provideActivity() {
// return mActivity;
// }
// }
|
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.joker.fourfun.di.component.ActivityComponent;
import com.joker.fourfun.di.component.AppComponent;
import com.joker.fourfun.di.component.DaggerActivityComponent;
import com.joker.fourfun.di.module.ActivityModule;
import javax.inject.Inject;
import butterknife.ButterKnife;
|
package com.joker.fourfun.base;
public abstract class BaseMvpActivity<V extends BaseView, T extends BaseMvpPresenter<V>> extends
AppCompatActivity {
@Inject
protected T mPresenter;
@Override
@SuppressWarnings("unchecked")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentViewAndInject(savedInstanceState);
ButterKnife.bind(this);
// mPresenter = initPresenter();
mPresenter.attach((V) this);
}
|
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/di/component/ActivityComponent.java
// @PerActivity
// @Component(dependencies = AppComponent.class, modules = ActivityModule.class)
// public interface ActivityComponent {
// AppCompatActivity activity();
//
// void inject(SplashActivity activity);
//
// void inject(MainActivity activity);
//
// void inject(PictureDetailActivity activity);
//
// void inject(LoginActivity activity);
//
// void inject(RegisterActivity activity);
//
// void inject(MovieDetailActivity activity);
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/di/component/AppComponent.java
// @Singleton
// @Component(modules = AppModule.class)
// public abstract class AppComponent {
// private static AppComponent mComponent;
//
// public static AppComponent getInstance() {
// if (mComponent == null) {
// synchronized (AppComponent.class) {
// if (mComponent == null) {
// mComponent = DaggerAppComponent.builder().appModule(new AppModule(FourFun.getInstance
// ())).build();
// }
// }
// }
//
// return mComponent;
// }
//
// public abstract FourFun fourFun();
//
// public abstract RetrofitUtil retrofitUtil();
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/di/module/ActivityModule.java
// @Module
// public class ActivityModule {
// private AppCompatActivity mActivity;
//
// public ActivityModule(AppCompatActivity appCompatActivity) {
// mActivity = appCompatActivity;
// }
//
// @Provides
// @PerActivity
// AppCompatActivity provideActivity() {
// return mActivity;
// }
// }
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/base/BaseMvpActivity.java
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.joker.fourfun.di.component.ActivityComponent;
import com.joker.fourfun.di.component.AppComponent;
import com.joker.fourfun.di.component.DaggerActivityComponent;
import com.joker.fourfun.di.module.ActivityModule;
import javax.inject.Inject;
import butterknife.ButterKnife;
package com.joker.fourfun.base;
public abstract class BaseMvpActivity<V extends BaseView, T extends BaseMvpPresenter<V>> extends
AppCompatActivity {
@Inject
protected T mPresenter;
@Override
@SuppressWarnings("unchecked")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentViewAndInject(savedInstanceState);
ButterKnife.bind(this);
// mPresenter = initPresenter();
mPresenter.attach((V) this);
}
|
protected ActivityComponent getComponent() {
|
4FunApp/4Fun
|
client/FourFun/app/src/main/java/com/joker/fourfun/base/BaseMvpActivity.java
|
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/di/component/ActivityComponent.java
// @PerActivity
// @Component(dependencies = AppComponent.class, modules = ActivityModule.class)
// public interface ActivityComponent {
// AppCompatActivity activity();
//
// void inject(SplashActivity activity);
//
// void inject(MainActivity activity);
//
// void inject(PictureDetailActivity activity);
//
// void inject(LoginActivity activity);
//
// void inject(RegisterActivity activity);
//
// void inject(MovieDetailActivity activity);
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/di/component/AppComponent.java
// @Singleton
// @Component(modules = AppModule.class)
// public abstract class AppComponent {
// private static AppComponent mComponent;
//
// public static AppComponent getInstance() {
// if (mComponent == null) {
// synchronized (AppComponent.class) {
// if (mComponent == null) {
// mComponent = DaggerAppComponent.builder().appModule(new AppModule(FourFun.getInstance
// ())).build();
// }
// }
// }
//
// return mComponent;
// }
//
// public abstract FourFun fourFun();
//
// public abstract RetrofitUtil retrofitUtil();
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/di/module/ActivityModule.java
// @Module
// public class ActivityModule {
// private AppCompatActivity mActivity;
//
// public ActivityModule(AppCompatActivity appCompatActivity) {
// mActivity = appCompatActivity;
// }
//
// @Provides
// @PerActivity
// AppCompatActivity provideActivity() {
// return mActivity;
// }
// }
|
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.joker.fourfun.di.component.ActivityComponent;
import com.joker.fourfun.di.component.AppComponent;
import com.joker.fourfun.di.component.DaggerActivityComponent;
import com.joker.fourfun.di.module.ActivityModule;
import javax.inject.Inject;
import butterknife.ButterKnife;
|
package com.joker.fourfun.base;
public abstract class BaseMvpActivity<V extends BaseView, T extends BaseMvpPresenter<V>> extends
AppCompatActivity {
@Inject
protected T mPresenter;
@Override
@SuppressWarnings("unchecked")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentViewAndInject(savedInstanceState);
ButterKnife.bind(this);
// mPresenter = initPresenter();
mPresenter.attach((V) this);
}
protected ActivityComponent getComponent() {
|
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/di/component/ActivityComponent.java
// @PerActivity
// @Component(dependencies = AppComponent.class, modules = ActivityModule.class)
// public interface ActivityComponent {
// AppCompatActivity activity();
//
// void inject(SplashActivity activity);
//
// void inject(MainActivity activity);
//
// void inject(PictureDetailActivity activity);
//
// void inject(LoginActivity activity);
//
// void inject(RegisterActivity activity);
//
// void inject(MovieDetailActivity activity);
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/di/component/AppComponent.java
// @Singleton
// @Component(modules = AppModule.class)
// public abstract class AppComponent {
// private static AppComponent mComponent;
//
// public static AppComponent getInstance() {
// if (mComponent == null) {
// synchronized (AppComponent.class) {
// if (mComponent == null) {
// mComponent = DaggerAppComponent.builder().appModule(new AppModule(FourFun.getInstance
// ())).build();
// }
// }
// }
//
// return mComponent;
// }
//
// public abstract FourFun fourFun();
//
// public abstract RetrofitUtil retrofitUtil();
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/di/module/ActivityModule.java
// @Module
// public class ActivityModule {
// private AppCompatActivity mActivity;
//
// public ActivityModule(AppCompatActivity appCompatActivity) {
// mActivity = appCompatActivity;
// }
//
// @Provides
// @PerActivity
// AppCompatActivity provideActivity() {
// return mActivity;
// }
// }
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/base/BaseMvpActivity.java
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.joker.fourfun.di.component.ActivityComponent;
import com.joker.fourfun.di.component.AppComponent;
import com.joker.fourfun.di.component.DaggerActivityComponent;
import com.joker.fourfun.di.module.ActivityModule;
import javax.inject.Inject;
import butterknife.ButterKnife;
package com.joker.fourfun.base;
public abstract class BaseMvpActivity<V extends BaseView, T extends BaseMvpPresenter<V>> extends
AppCompatActivity {
@Inject
protected T mPresenter;
@Override
@SuppressWarnings("unchecked")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentViewAndInject(savedInstanceState);
ButterKnife.bind(this);
// mPresenter = initPresenter();
mPresenter.attach((V) this);
}
protected ActivityComponent getComponent() {
|
return DaggerActivityComponent.builder().activityModule(getModule()).appComponent(AppComponent
|
4FunApp/4Fun
|
client/FourFun/app/src/main/java/com/joker/fourfun/base/BaseMvpActivity.java
|
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/di/component/ActivityComponent.java
// @PerActivity
// @Component(dependencies = AppComponent.class, modules = ActivityModule.class)
// public interface ActivityComponent {
// AppCompatActivity activity();
//
// void inject(SplashActivity activity);
//
// void inject(MainActivity activity);
//
// void inject(PictureDetailActivity activity);
//
// void inject(LoginActivity activity);
//
// void inject(RegisterActivity activity);
//
// void inject(MovieDetailActivity activity);
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/di/component/AppComponent.java
// @Singleton
// @Component(modules = AppModule.class)
// public abstract class AppComponent {
// private static AppComponent mComponent;
//
// public static AppComponent getInstance() {
// if (mComponent == null) {
// synchronized (AppComponent.class) {
// if (mComponent == null) {
// mComponent = DaggerAppComponent.builder().appModule(new AppModule(FourFun.getInstance
// ())).build();
// }
// }
// }
//
// return mComponent;
// }
//
// public abstract FourFun fourFun();
//
// public abstract RetrofitUtil retrofitUtil();
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/di/module/ActivityModule.java
// @Module
// public class ActivityModule {
// private AppCompatActivity mActivity;
//
// public ActivityModule(AppCompatActivity appCompatActivity) {
// mActivity = appCompatActivity;
// }
//
// @Provides
// @PerActivity
// AppCompatActivity provideActivity() {
// return mActivity;
// }
// }
|
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.joker.fourfun.di.component.ActivityComponent;
import com.joker.fourfun.di.component.AppComponent;
import com.joker.fourfun.di.component.DaggerActivityComponent;
import com.joker.fourfun.di.module.ActivityModule;
import javax.inject.Inject;
import butterknife.ButterKnife;
|
package com.joker.fourfun.base;
public abstract class BaseMvpActivity<V extends BaseView, T extends BaseMvpPresenter<V>> extends
AppCompatActivity {
@Inject
protected T mPresenter;
@Override
@SuppressWarnings("unchecked")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentViewAndInject(savedInstanceState);
ButterKnife.bind(this);
// mPresenter = initPresenter();
mPresenter.attach((V) this);
}
protected ActivityComponent getComponent() {
return DaggerActivityComponent.builder().activityModule(getModule()).appComponent(AppComponent
.getInstance()).build();
}
|
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/di/component/ActivityComponent.java
// @PerActivity
// @Component(dependencies = AppComponent.class, modules = ActivityModule.class)
// public interface ActivityComponent {
// AppCompatActivity activity();
//
// void inject(SplashActivity activity);
//
// void inject(MainActivity activity);
//
// void inject(PictureDetailActivity activity);
//
// void inject(LoginActivity activity);
//
// void inject(RegisterActivity activity);
//
// void inject(MovieDetailActivity activity);
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/di/component/AppComponent.java
// @Singleton
// @Component(modules = AppModule.class)
// public abstract class AppComponent {
// private static AppComponent mComponent;
//
// public static AppComponent getInstance() {
// if (mComponent == null) {
// synchronized (AppComponent.class) {
// if (mComponent == null) {
// mComponent = DaggerAppComponent.builder().appModule(new AppModule(FourFun.getInstance
// ())).build();
// }
// }
// }
//
// return mComponent;
// }
//
// public abstract FourFun fourFun();
//
// public abstract RetrofitUtil retrofitUtil();
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/di/module/ActivityModule.java
// @Module
// public class ActivityModule {
// private AppCompatActivity mActivity;
//
// public ActivityModule(AppCompatActivity appCompatActivity) {
// mActivity = appCompatActivity;
// }
//
// @Provides
// @PerActivity
// AppCompatActivity provideActivity() {
// return mActivity;
// }
// }
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/base/BaseMvpActivity.java
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.joker.fourfun.di.component.ActivityComponent;
import com.joker.fourfun.di.component.AppComponent;
import com.joker.fourfun.di.component.DaggerActivityComponent;
import com.joker.fourfun.di.module.ActivityModule;
import javax.inject.Inject;
import butterknife.ButterKnife;
package com.joker.fourfun.base;
public abstract class BaseMvpActivity<V extends BaseView, T extends BaseMvpPresenter<V>> extends
AppCompatActivity {
@Inject
protected T mPresenter;
@Override
@SuppressWarnings("unchecked")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentViewAndInject(savedInstanceState);
ButterKnife.bind(this);
// mPresenter = initPresenter();
mPresenter.attach((V) this);
}
protected ActivityComponent getComponent() {
return DaggerActivityComponent.builder().activityModule(getModule()).appComponent(AppComponent
.getInstance()).build();
}
|
protected ActivityModule getModule() {
|
4FunApp/4Fun
|
client/FourFun/app/src/main/java/com/joker/fourfun/presenter/contract/PictureDetailContract.java
|
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/base/BasePresenter.java
// public interface BasePresenter<T extends BaseView> {
// void attach(T mView);
//
// void detach();
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/base/BaseView.java
// public interface BaseView {
// void showError(String message);
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/model/Picture.java
// public class Picture implements Parcelable {
// /**
// * result : [{"picUrl":"/uploads/160903/161128/1-16112Q62024415.jpg","picDate":"27 Nov 2016 ",
// * "pubTime":"发布时间:2016-11-28 16:08","authorWork":"Grand-Central-Terminal",
// * "picDescription":"等待中有欢乐,有焦虑,有\u201c无可奈何\u201d与\u201c迫不及待\u201d,等待中包含人间百味。"},
// * {"picUrl":"/uploads/150129/161126/1-16112622162Y20.jpg","picDate":"26 Nov 2016 ",
// * "pubTime":"发布时间:2016-11-26 22:16","authorWork":"路过德黑兰",
// * "picDescription
// * ":"很多时候,人们内心所认为的可能并不是事实的真相,但还是宁愿去按照自己的思维逻辑来认识这个世界,认识自己的生活,到最后,可能我们就是带着这份误解,过完了此生。"},
// * {"picUrl":"/uploads/150129/161126/1-16112622154TC.jpg","picDate":"25 Nov 2016 ",
// * "pubTime":"发布时间:2016-11-26 22:15","authorWork":"探索",
// * "picDescription":"一流的情人永远不必殉陨,永远不会失恋,因为\u201c我爱你,与你何涉\u201d。"}]
// * error : false
// */
// public static final Creator<Picture> CREATOR = new Creator<Picture>() {
// @Override
// public Picture createFromParcel(Parcel source) {
// return new Picture(source);
// }
//
// @Override
// public Picture[] newArray(int size) {
// return new Picture[size];
// }
// };
// /**
// * picUrl : /uploads/160903/161128/1-16112Q62024415.jpg
// * picDate : 27 Nov 2016
// * VOL:VOL.1514
// * pubTime : 发布时间:2016-11-28 16:08
// * authorWork : Grand-Central-Terminal
// * picDescription : 等待中有欢乐,有焦虑,有“无可奈何”与“迫不及待”,等待中包含人间百味。
// */
//
// private String VOL;
// private String picUrl;
// private String picDate;
// private String pubTime;
// private String authorWork;
// private String picDescription;
//
// public Picture() {
// }
//
// protected Picture(Parcel in) {
// this.VOL = in.readString();
// this.picUrl = in.readString();
// this.picDate = in.readString();
// this.pubTime = in.readString();
// this.authorWork = in.readString();
// this.picDescription = in.readString();
// }
//
// public String getVOL() {
// return VOL;
// }
//
// public void setVOL(String VOL) {
// this.VOL = VOL;
// }
//
// public String getPicUrl() {
// return picUrl;
// }
//
// public void setPicUrl(String picUrl) {
// this.picUrl = picUrl;
// }
//
// public String getPicDate() {
// return picDate;
// }
//
// public void setPicDate(String picDate) {
// this.picDate = picDate;
// }
//
// public String getPubTime() {
// return pubTime;
// }
//
// public void setPubTime(String pubTime) {
// this.pubTime = pubTime;
// }
//
// public String getAuthorWork() {
// return authorWork;
// }
//
// public void setAuthorWork(String authorWork) {
// this.authorWork = authorWork;
// }
//
// public String getPicDescription() {
// return picDescription;
// }
//
// public void setPicDescription(String picDescription) {
// this.picDescription = picDescription;
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(this.VOL);
// dest.writeString(this.picUrl);
// dest.writeString(this.picDate);
// dest.writeString(this.pubTime);
// dest.writeString(this.authorWork);
// dest.writeString(this.picDescription);
// }
// }
|
import com.joker.fourfun.base.BasePresenter;
import com.joker.fourfun.base.BaseView;
import com.joker.fourfun.model.Picture;
|
package com.joker.fourfun.presenter.contract;
/**
* Created by joker on 2016/12/29.
*/
public interface PictureDetailContract {
interface View extends BaseView {
|
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/base/BasePresenter.java
// public interface BasePresenter<T extends BaseView> {
// void attach(T mView);
//
// void detach();
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/base/BaseView.java
// public interface BaseView {
// void showError(String message);
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/model/Picture.java
// public class Picture implements Parcelable {
// /**
// * result : [{"picUrl":"/uploads/160903/161128/1-16112Q62024415.jpg","picDate":"27 Nov 2016 ",
// * "pubTime":"发布时间:2016-11-28 16:08","authorWork":"Grand-Central-Terminal",
// * "picDescription":"等待中有欢乐,有焦虑,有\u201c无可奈何\u201d与\u201c迫不及待\u201d,等待中包含人间百味。"},
// * {"picUrl":"/uploads/150129/161126/1-16112622162Y20.jpg","picDate":"26 Nov 2016 ",
// * "pubTime":"发布时间:2016-11-26 22:16","authorWork":"路过德黑兰",
// * "picDescription
// * ":"很多时候,人们内心所认为的可能并不是事实的真相,但还是宁愿去按照自己的思维逻辑来认识这个世界,认识自己的生活,到最后,可能我们就是带着这份误解,过完了此生。"},
// * {"picUrl":"/uploads/150129/161126/1-16112622154TC.jpg","picDate":"25 Nov 2016 ",
// * "pubTime":"发布时间:2016-11-26 22:15","authorWork":"探索",
// * "picDescription":"一流的情人永远不必殉陨,永远不会失恋,因为\u201c我爱你,与你何涉\u201d。"}]
// * error : false
// */
// public static final Creator<Picture> CREATOR = new Creator<Picture>() {
// @Override
// public Picture createFromParcel(Parcel source) {
// return new Picture(source);
// }
//
// @Override
// public Picture[] newArray(int size) {
// return new Picture[size];
// }
// };
// /**
// * picUrl : /uploads/160903/161128/1-16112Q62024415.jpg
// * picDate : 27 Nov 2016
// * VOL:VOL.1514
// * pubTime : 发布时间:2016-11-28 16:08
// * authorWork : Grand-Central-Terminal
// * picDescription : 等待中有欢乐,有焦虑,有“无可奈何”与“迫不及待”,等待中包含人间百味。
// */
//
// private String VOL;
// private String picUrl;
// private String picDate;
// private String pubTime;
// private String authorWork;
// private String picDescription;
//
// public Picture() {
// }
//
// protected Picture(Parcel in) {
// this.VOL = in.readString();
// this.picUrl = in.readString();
// this.picDate = in.readString();
// this.pubTime = in.readString();
// this.authorWork = in.readString();
// this.picDescription = in.readString();
// }
//
// public String getVOL() {
// return VOL;
// }
//
// public void setVOL(String VOL) {
// this.VOL = VOL;
// }
//
// public String getPicUrl() {
// return picUrl;
// }
//
// public void setPicUrl(String picUrl) {
// this.picUrl = picUrl;
// }
//
// public String getPicDate() {
// return picDate;
// }
//
// public void setPicDate(String picDate) {
// this.picDate = picDate;
// }
//
// public String getPubTime() {
// return pubTime;
// }
//
// public void setPubTime(String pubTime) {
// this.pubTime = pubTime;
// }
//
// public String getAuthorWork() {
// return authorWork;
// }
//
// public void setAuthorWork(String authorWork) {
// this.authorWork = authorWork;
// }
//
// public String getPicDescription() {
// return picDescription;
// }
//
// public void setPicDescription(String picDescription) {
// this.picDescription = picDescription;
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(this.VOL);
// dest.writeString(this.picUrl);
// dest.writeString(this.picDate);
// dest.writeString(this.pubTime);
// dest.writeString(this.authorWork);
// dest.writeString(this.picDescription);
// }
// }
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/presenter/contract/PictureDetailContract.java
import com.joker.fourfun.base.BasePresenter;
import com.joker.fourfun.base.BaseView;
import com.joker.fourfun.model.Picture;
package com.joker.fourfun.presenter.contract;
/**
* Created by joker on 2016/12/29.
*/
public interface PictureDetailContract {
interface View extends BaseView {
|
void showContent(Picture picture);
|
4FunApp/4Fun
|
client/FourFun/app/src/main/java/com/joker/fourfun/presenter/contract/PictureDetailContract.java
|
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/base/BasePresenter.java
// public interface BasePresenter<T extends BaseView> {
// void attach(T mView);
//
// void detach();
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/base/BaseView.java
// public interface BaseView {
// void showError(String message);
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/model/Picture.java
// public class Picture implements Parcelable {
// /**
// * result : [{"picUrl":"/uploads/160903/161128/1-16112Q62024415.jpg","picDate":"27 Nov 2016 ",
// * "pubTime":"发布时间:2016-11-28 16:08","authorWork":"Grand-Central-Terminal",
// * "picDescription":"等待中有欢乐,有焦虑,有\u201c无可奈何\u201d与\u201c迫不及待\u201d,等待中包含人间百味。"},
// * {"picUrl":"/uploads/150129/161126/1-16112622162Y20.jpg","picDate":"26 Nov 2016 ",
// * "pubTime":"发布时间:2016-11-26 22:16","authorWork":"路过德黑兰",
// * "picDescription
// * ":"很多时候,人们内心所认为的可能并不是事实的真相,但还是宁愿去按照自己的思维逻辑来认识这个世界,认识自己的生活,到最后,可能我们就是带着这份误解,过完了此生。"},
// * {"picUrl":"/uploads/150129/161126/1-16112622154TC.jpg","picDate":"25 Nov 2016 ",
// * "pubTime":"发布时间:2016-11-26 22:15","authorWork":"探索",
// * "picDescription":"一流的情人永远不必殉陨,永远不会失恋,因为\u201c我爱你,与你何涉\u201d。"}]
// * error : false
// */
// public static final Creator<Picture> CREATOR = new Creator<Picture>() {
// @Override
// public Picture createFromParcel(Parcel source) {
// return new Picture(source);
// }
//
// @Override
// public Picture[] newArray(int size) {
// return new Picture[size];
// }
// };
// /**
// * picUrl : /uploads/160903/161128/1-16112Q62024415.jpg
// * picDate : 27 Nov 2016
// * VOL:VOL.1514
// * pubTime : 发布时间:2016-11-28 16:08
// * authorWork : Grand-Central-Terminal
// * picDescription : 等待中有欢乐,有焦虑,有“无可奈何”与“迫不及待”,等待中包含人间百味。
// */
//
// private String VOL;
// private String picUrl;
// private String picDate;
// private String pubTime;
// private String authorWork;
// private String picDescription;
//
// public Picture() {
// }
//
// protected Picture(Parcel in) {
// this.VOL = in.readString();
// this.picUrl = in.readString();
// this.picDate = in.readString();
// this.pubTime = in.readString();
// this.authorWork = in.readString();
// this.picDescription = in.readString();
// }
//
// public String getVOL() {
// return VOL;
// }
//
// public void setVOL(String VOL) {
// this.VOL = VOL;
// }
//
// public String getPicUrl() {
// return picUrl;
// }
//
// public void setPicUrl(String picUrl) {
// this.picUrl = picUrl;
// }
//
// public String getPicDate() {
// return picDate;
// }
//
// public void setPicDate(String picDate) {
// this.picDate = picDate;
// }
//
// public String getPubTime() {
// return pubTime;
// }
//
// public void setPubTime(String pubTime) {
// this.pubTime = pubTime;
// }
//
// public String getAuthorWork() {
// return authorWork;
// }
//
// public void setAuthorWork(String authorWork) {
// this.authorWork = authorWork;
// }
//
// public String getPicDescription() {
// return picDescription;
// }
//
// public void setPicDescription(String picDescription) {
// this.picDescription = picDescription;
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(this.VOL);
// dest.writeString(this.picUrl);
// dest.writeString(this.picDate);
// dest.writeString(this.pubTime);
// dest.writeString(this.authorWork);
// dest.writeString(this.picDescription);
// }
// }
|
import com.joker.fourfun.base.BasePresenter;
import com.joker.fourfun.base.BaseView;
import com.joker.fourfun.model.Picture;
|
package com.joker.fourfun.presenter.contract;
/**
* Created by joker on 2016/12/29.
*/
public interface PictureDetailContract {
interface View extends BaseView {
void showContent(Picture picture);
}
|
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/base/BasePresenter.java
// public interface BasePresenter<T extends BaseView> {
// void attach(T mView);
//
// void detach();
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/base/BaseView.java
// public interface BaseView {
// void showError(String message);
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/model/Picture.java
// public class Picture implements Parcelable {
// /**
// * result : [{"picUrl":"/uploads/160903/161128/1-16112Q62024415.jpg","picDate":"27 Nov 2016 ",
// * "pubTime":"发布时间:2016-11-28 16:08","authorWork":"Grand-Central-Terminal",
// * "picDescription":"等待中有欢乐,有焦虑,有\u201c无可奈何\u201d与\u201c迫不及待\u201d,等待中包含人间百味。"},
// * {"picUrl":"/uploads/150129/161126/1-16112622162Y20.jpg","picDate":"26 Nov 2016 ",
// * "pubTime":"发布时间:2016-11-26 22:16","authorWork":"路过德黑兰",
// * "picDescription
// * ":"很多时候,人们内心所认为的可能并不是事实的真相,但还是宁愿去按照自己的思维逻辑来认识这个世界,认识自己的生活,到最后,可能我们就是带着这份误解,过完了此生。"},
// * {"picUrl":"/uploads/150129/161126/1-16112622154TC.jpg","picDate":"25 Nov 2016 ",
// * "pubTime":"发布时间:2016-11-26 22:15","authorWork":"探索",
// * "picDescription":"一流的情人永远不必殉陨,永远不会失恋,因为\u201c我爱你,与你何涉\u201d。"}]
// * error : false
// */
// public static final Creator<Picture> CREATOR = new Creator<Picture>() {
// @Override
// public Picture createFromParcel(Parcel source) {
// return new Picture(source);
// }
//
// @Override
// public Picture[] newArray(int size) {
// return new Picture[size];
// }
// };
// /**
// * picUrl : /uploads/160903/161128/1-16112Q62024415.jpg
// * picDate : 27 Nov 2016
// * VOL:VOL.1514
// * pubTime : 发布时间:2016-11-28 16:08
// * authorWork : Grand-Central-Terminal
// * picDescription : 等待中有欢乐,有焦虑,有“无可奈何”与“迫不及待”,等待中包含人间百味。
// */
//
// private String VOL;
// private String picUrl;
// private String picDate;
// private String pubTime;
// private String authorWork;
// private String picDescription;
//
// public Picture() {
// }
//
// protected Picture(Parcel in) {
// this.VOL = in.readString();
// this.picUrl = in.readString();
// this.picDate = in.readString();
// this.pubTime = in.readString();
// this.authorWork = in.readString();
// this.picDescription = in.readString();
// }
//
// public String getVOL() {
// return VOL;
// }
//
// public void setVOL(String VOL) {
// this.VOL = VOL;
// }
//
// public String getPicUrl() {
// return picUrl;
// }
//
// public void setPicUrl(String picUrl) {
// this.picUrl = picUrl;
// }
//
// public String getPicDate() {
// return picDate;
// }
//
// public void setPicDate(String picDate) {
// this.picDate = picDate;
// }
//
// public String getPubTime() {
// return pubTime;
// }
//
// public void setPubTime(String pubTime) {
// this.pubTime = pubTime;
// }
//
// public String getAuthorWork() {
// return authorWork;
// }
//
// public void setAuthorWork(String authorWork) {
// this.authorWork = authorWork;
// }
//
// public String getPicDescription() {
// return picDescription;
// }
//
// public void setPicDescription(String picDescription) {
// this.picDescription = picDescription;
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(this.VOL);
// dest.writeString(this.picUrl);
// dest.writeString(this.picDate);
// dest.writeString(this.pubTime);
// dest.writeString(this.authorWork);
// dest.writeString(this.picDescription);
// }
// }
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/presenter/contract/PictureDetailContract.java
import com.joker.fourfun.base.BasePresenter;
import com.joker.fourfun.base.BaseView;
import com.joker.fourfun.model.Picture;
package com.joker.fourfun.presenter.contract;
/**
* Created by joker on 2016/12/29.
*/
public interface PictureDetailContract {
interface View extends BaseView {
void showContent(Picture picture);
}
|
interface Presenter extends BasePresenter<View> {
|
4FunApp/4Fun
|
client/FourFun/app/src/main/java/com/joker/fourfun/presenter/contract/SplashContract.java
|
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/base/BasePresenter.java
// public interface BasePresenter<T extends BaseView> {
// void attach(T mView);
//
// void detach();
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/base/BaseView.java
// public interface BaseView {
// void showError(String message);
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/model/Picture.java
// public class Picture implements Parcelable {
// /**
// * result : [{"picUrl":"/uploads/160903/161128/1-16112Q62024415.jpg","picDate":"27 Nov 2016 ",
// * "pubTime":"发布时间:2016-11-28 16:08","authorWork":"Grand-Central-Terminal",
// * "picDescription":"等待中有欢乐,有焦虑,有\u201c无可奈何\u201d与\u201c迫不及待\u201d,等待中包含人间百味。"},
// * {"picUrl":"/uploads/150129/161126/1-16112622162Y20.jpg","picDate":"26 Nov 2016 ",
// * "pubTime":"发布时间:2016-11-26 22:16","authorWork":"路过德黑兰",
// * "picDescription
// * ":"很多时候,人们内心所认为的可能并不是事实的真相,但还是宁愿去按照自己的思维逻辑来认识这个世界,认识自己的生活,到最后,可能我们就是带着这份误解,过完了此生。"},
// * {"picUrl":"/uploads/150129/161126/1-16112622154TC.jpg","picDate":"25 Nov 2016 ",
// * "pubTime":"发布时间:2016-11-26 22:15","authorWork":"探索",
// * "picDescription":"一流的情人永远不必殉陨,永远不会失恋,因为\u201c我爱你,与你何涉\u201d。"}]
// * error : false
// */
// public static final Creator<Picture> CREATOR = new Creator<Picture>() {
// @Override
// public Picture createFromParcel(Parcel source) {
// return new Picture(source);
// }
//
// @Override
// public Picture[] newArray(int size) {
// return new Picture[size];
// }
// };
// /**
// * picUrl : /uploads/160903/161128/1-16112Q62024415.jpg
// * picDate : 27 Nov 2016
// * VOL:VOL.1514
// * pubTime : 发布时间:2016-11-28 16:08
// * authorWork : Grand-Central-Terminal
// * picDescription : 等待中有欢乐,有焦虑,有“无可奈何”与“迫不及待”,等待中包含人间百味。
// */
//
// private String VOL;
// private String picUrl;
// private String picDate;
// private String pubTime;
// private String authorWork;
// private String picDescription;
//
// public Picture() {
// }
//
// protected Picture(Parcel in) {
// this.VOL = in.readString();
// this.picUrl = in.readString();
// this.picDate = in.readString();
// this.pubTime = in.readString();
// this.authorWork = in.readString();
// this.picDescription = in.readString();
// }
//
// public String getVOL() {
// return VOL;
// }
//
// public void setVOL(String VOL) {
// this.VOL = VOL;
// }
//
// public String getPicUrl() {
// return picUrl;
// }
//
// public void setPicUrl(String picUrl) {
// this.picUrl = picUrl;
// }
//
// public String getPicDate() {
// return picDate;
// }
//
// public void setPicDate(String picDate) {
// this.picDate = picDate;
// }
//
// public String getPubTime() {
// return pubTime;
// }
//
// public void setPubTime(String pubTime) {
// this.pubTime = pubTime;
// }
//
// public String getAuthorWork() {
// return authorWork;
// }
//
// public void setAuthorWork(String authorWork) {
// this.authorWork = authorWork;
// }
//
// public String getPicDescription() {
// return picDescription;
// }
//
// public void setPicDescription(String picDescription) {
// this.picDescription = picDescription;
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(this.VOL);
// dest.writeString(this.picUrl);
// dest.writeString(this.picDate);
// dest.writeString(this.pubTime);
// dest.writeString(this.authorWork);
// dest.writeString(this.picDescription);
// }
// }
|
import com.joker.fourfun.base.BasePresenter;
import com.joker.fourfun.base.BaseView;
import com.joker.fourfun.model.Picture;
|
package com.joker.fourfun.presenter.contract;
/**
* Created by joker on 2016/11/27.
*/
public interface SplashContract {
interface View extends BaseView {
void showZhihuPic(String url);
void setMediaBackground(String url);
|
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/base/BasePresenter.java
// public interface BasePresenter<T extends BaseView> {
// void attach(T mView);
//
// void detach();
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/base/BaseView.java
// public interface BaseView {
// void showError(String message);
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/model/Picture.java
// public class Picture implements Parcelable {
// /**
// * result : [{"picUrl":"/uploads/160903/161128/1-16112Q62024415.jpg","picDate":"27 Nov 2016 ",
// * "pubTime":"发布时间:2016-11-28 16:08","authorWork":"Grand-Central-Terminal",
// * "picDescription":"等待中有欢乐,有焦虑,有\u201c无可奈何\u201d与\u201c迫不及待\u201d,等待中包含人间百味。"},
// * {"picUrl":"/uploads/150129/161126/1-16112622162Y20.jpg","picDate":"26 Nov 2016 ",
// * "pubTime":"发布时间:2016-11-26 22:16","authorWork":"路过德黑兰",
// * "picDescription
// * ":"很多时候,人们内心所认为的可能并不是事实的真相,但还是宁愿去按照自己的思维逻辑来认识这个世界,认识自己的生活,到最后,可能我们就是带着这份误解,过完了此生。"},
// * {"picUrl":"/uploads/150129/161126/1-16112622154TC.jpg","picDate":"25 Nov 2016 ",
// * "pubTime":"发布时间:2016-11-26 22:15","authorWork":"探索",
// * "picDescription":"一流的情人永远不必殉陨,永远不会失恋,因为\u201c我爱你,与你何涉\u201d。"}]
// * error : false
// */
// public static final Creator<Picture> CREATOR = new Creator<Picture>() {
// @Override
// public Picture createFromParcel(Parcel source) {
// return new Picture(source);
// }
//
// @Override
// public Picture[] newArray(int size) {
// return new Picture[size];
// }
// };
// /**
// * picUrl : /uploads/160903/161128/1-16112Q62024415.jpg
// * picDate : 27 Nov 2016
// * VOL:VOL.1514
// * pubTime : 发布时间:2016-11-28 16:08
// * authorWork : Grand-Central-Terminal
// * picDescription : 等待中有欢乐,有焦虑,有“无可奈何”与“迫不及待”,等待中包含人间百味。
// */
//
// private String VOL;
// private String picUrl;
// private String picDate;
// private String pubTime;
// private String authorWork;
// private String picDescription;
//
// public Picture() {
// }
//
// protected Picture(Parcel in) {
// this.VOL = in.readString();
// this.picUrl = in.readString();
// this.picDate = in.readString();
// this.pubTime = in.readString();
// this.authorWork = in.readString();
// this.picDescription = in.readString();
// }
//
// public String getVOL() {
// return VOL;
// }
//
// public void setVOL(String VOL) {
// this.VOL = VOL;
// }
//
// public String getPicUrl() {
// return picUrl;
// }
//
// public void setPicUrl(String picUrl) {
// this.picUrl = picUrl;
// }
//
// public String getPicDate() {
// return picDate;
// }
//
// public void setPicDate(String picDate) {
// this.picDate = picDate;
// }
//
// public String getPubTime() {
// return pubTime;
// }
//
// public void setPubTime(String pubTime) {
// this.pubTime = pubTime;
// }
//
// public String getAuthorWork() {
// return authorWork;
// }
//
// public void setAuthorWork(String authorWork) {
// this.authorWork = authorWork;
// }
//
// public String getPicDescription() {
// return picDescription;
// }
//
// public void setPicDescription(String picDescription) {
// this.picDescription = picDescription;
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(this.VOL);
// dest.writeString(this.picUrl);
// dest.writeString(this.picDate);
// dest.writeString(this.pubTime);
// dest.writeString(this.authorWork);
// dest.writeString(this.picDescription);
// }
// }
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/presenter/contract/SplashContract.java
import com.joker.fourfun.base.BasePresenter;
import com.joker.fourfun.base.BaseView;
import com.joker.fourfun.model.Picture;
package com.joker.fourfun.presenter.contract;
/**
* Created by joker on 2016/11/27.
*/
public interface SplashContract {
interface View extends BaseView {
void showZhihuPic(String url);
void setMediaBackground(String url);
|
void setPictureOne(Picture picture);
|
4FunApp/4Fun
|
client/FourFun/app/src/main/java/com/joker/fourfun/presenter/contract/SplashContract.java
|
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/base/BasePresenter.java
// public interface BasePresenter<T extends BaseView> {
// void attach(T mView);
//
// void detach();
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/base/BaseView.java
// public interface BaseView {
// void showError(String message);
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/model/Picture.java
// public class Picture implements Parcelable {
// /**
// * result : [{"picUrl":"/uploads/160903/161128/1-16112Q62024415.jpg","picDate":"27 Nov 2016 ",
// * "pubTime":"发布时间:2016-11-28 16:08","authorWork":"Grand-Central-Terminal",
// * "picDescription":"等待中有欢乐,有焦虑,有\u201c无可奈何\u201d与\u201c迫不及待\u201d,等待中包含人间百味。"},
// * {"picUrl":"/uploads/150129/161126/1-16112622162Y20.jpg","picDate":"26 Nov 2016 ",
// * "pubTime":"发布时间:2016-11-26 22:16","authorWork":"路过德黑兰",
// * "picDescription
// * ":"很多时候,人们内心所认为的可能并不是事实的真相,但还是宁愿去按照自己的思维逻辑来认识这个世界,认识自己的生活,到最后,可能我们就是带着这份误解,过完了此生。"},
// * {"picUrl":"/uploads/150129/161126/1-16112622154TC.jpg","picDate":"25 Nov 2016 ",
// * "pubTime":"发布时间:2016-11-26 22:15","authorWork":"探索",
// * "picDescription":"一流的情人永远不必殉陨,永远不会失恋,因为\u201c我爱你,与你何涉\u201d。"}]
// * error : false
// */
// public static final Creator<Picture> CREATOR = new Creator<Picture>() {
// @Override
// public Picture createFromParcel(Parcel source) {
// return new Picture(source);
// }
//
// @Override
// public Picture[] newArray(int size) {
// return new Picture[size];
// }
// };
// /**
// * picUrl : /uploads/160903/161128/1-16112Q62024415.jpg
// * picDate : 27 Nov 2016
// * VOL:VOL.1514
// * pubTime : 发布时间:2016-11-28 16:08
// * authorWork : Grand-Central-Terminal
// * picDescription : 等待中有欢乐,有焦虑,有“无可奈何”与“迫不及待”,等待中包含人间百味。
// */
//
// private String VOL;
// private String picUrl;
// private String picDate;
// private String pubTime;
// private String authorWork;
// private String picDescription;
//
// public Picture() {
// }
//
// protected Picture(Parcel in) {
// this.VOL = in.readString();
// this.picUrl = in.readString();
// this.picDate = in.readString();
// this.pubTime = in.readString();
// this.authorWork = in.readString();
// this.picDescription = in.readString();
// }
//
// public String getVOL() {
// return VOL;
// }
//
// public void setVOL(String VOL) {
// this.VOL = VOL;
// }
//
// public String getPicUrl() {
// return picUrl;
// }
//
// public void setPicUrl(String picUrl) {
// this.picUrl = picUrl;
// }
//
// public String getPicDate() {
// return picDate;
// }
//
// public void setPicDate(String picDate) {
// this.picDate = picDate;
// }
//
// public String getPubTime() {
// return pubTime;
// }
//
// public void setPubTime(String pubTime) {
// this.pubTime = pubTime;
// }
//
// public String getAuthorWork() {
// return authorWork;
// }
//
// public void setAuthorWork(String authorWork) {
// this.authorWork = authorWork;
// }
//
// public String getPicDescription() {
// return picDescription;
// }
//
// public void setPicDescription(String picDescription) {
// this.picDescription = picDescription;
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(this.VOL);
// dest.writeString(this.picUrl);
// dest.writeString(this.picDate);
// dest.writeString(this.pubTime);
// dest.writeString(this.authorWork);
// dest.writeString(this.picDescription);
// }
// }
|
import com.joker.fourfun.base.BasePresenter;
import com.joker.fourfun.base.BaseView;
import com.joker.fourfun.model.Picture;
|
package com.joker.fourfun.presenter.contract;
/**
* Created by joker on 2016/11/27.
*/
public interface SplashContract {
interface View extends BaseView {
void showZhihuPic(String url);
void setMediaBackground(String url);
void setPictureOne(Picture picture);
}
|
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/base/BasePresenter.java
// public interface BasePresenter<T extends BaseView> {
// void attach(T mView);
//
// void detach();
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/base/BaseView.java
// public interface BaseView {
// void showError(String message);
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/model/Picture.java
// public class Picture implements Parcelable {
// /**
// * result : [{"picUrl":"/uploads/160903/161128/1-16112Q62024415.jpg","picDate":"27 Nov 2016 ",
// * "pubTime":"发布时间:2016-11-28 16:08","authorWork":"Grand-Central-Terminal",
// * "picDescription":"等待中有欢乐,有焦虑,有\u201c无可奈何\u201d与\u201c迫不及待\u201d,等待中包含人间百味。"},
// * {"picUrl":"/uploads/150129/161126/1-16112622162Y20.jpg","picDate":"26 Nov 2016 ",
// * "pubTime":"发布时间:2016-11-26 22:16","authorWork":"路过德黑兰",
// * "picDescription
// * ":"很多时候,人们内心所认为的可能并不是事实的真相,但还是宁愿去按照自己的思维逻辑来认识这个世界,认识自己的生活,到最后,可能我们就是带着这份误解,过完了此生。"},
// * {"picUrl":"/uploads/150129/161126/1-16112622154TC.jpg","picDate":"25 Nov 2016 ",
// * "pubTime":"发布时间:2016-11-26 22:15","authorWork":"探索",
// * "picDescription":"一流的情人永远不必殉陨,永远不会失恋,因为\u201c我爱你,与你何涉\u201d。"}]
// * error : false
// */
// public static final Creator<Picture> CREATOR = new Creator<Picture>() {
// @Override
// public Picture createFromParcel(Parcel source) {
// return new Picture(source);
// }
//
// @Override
// public Picture[] newArray(int size) {
// return new Picture[size];
// }
// };
// /**
// * picUrl : /uploads/160903/161128/1-16112Q62024415.jpg
// * picDate : 27 Nov 2016
// * VOL:VOL.1514
// * pubTime : 发布时间:2016-11-28 16:08
// * authorWork : Grand-Central-Terminal
// * picDescription : 等待中有欢乐,有焦虑,有“无可奈何”与“迫不及待”,等待中包含人间百味。
// */
//
// private String VOL;
// private String picUrl;
// private String picDate;
// private String pubTime;
// private String authorWork;
// private String picDescription;
//
// public Picture() {
// }
//
// protected Picture(Parcel in) {
// this.VOL = in.readString();
// this.picUrl = in.readString();
// this.picDate = in.readString();
// this.pubTime = in.readString();
// this.authorWork = in.readString();
// this.picDescription = in.readString();
// }
//
// public String getVOL() {
// return VOL;
// }
//
// public void setVOL(String VOL) {
// this.VOL = VOL;
// }
//
// public String getPicUrl() {
// return picUrl;
// }
//
// public void setPicUrl(String picUrl) {
// this.picUrl = picUrl;
// }
//
// public String getPicDate() {
// return picDate;
// }
//
// public void setPicDate(String picDate) {
// this.picDate = picDate;
// }
//
// public String getPubTime() {
// return pubTime;
// }
//
// public void setPubTime(String pubTime) {
// this.pubTime = pubTime;
// }
//
// public String getAuthorWork() {
// return authorWork;
// }
//
// public void setAuthorWork(String authorWork) {
// this.authorWork = authorWork;
// }
//
// public String getPicDescription() {
// return picDescription;
// }
//
// public void setPicDescription(String picDescription) {
// this.picDescription = picDescription;
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(this.VOL);
// dest.writeString(this.picUrl);
// dest.writeString(this.picDate);
// dest.writeString(this.pubTime);
// dest.writeString(this.authorWork);
// dest.writeString(this.picDescription);
// }
// }
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/presenter/contract/SplashContract.java
import com.joker.fourfun.base.BasePresenter;
import com.joker.fourfun.base.BaseView;
import com.joker.fourfun.model.Picture;
package com.joker.fourfun.presenter.contract;
/**
* Created by joker on 2016/11/27.
*/
public interface SplashContract {
interface View extends BaseView {
void showZhihuPic(String url);
void setMediaBackground(String url);
void setPictureOne(Picture picture);
}
|
interface Presenter extends BasePresenter<View> {
|
4FunApp/4Fun
|
client/FourFun/app/src/main/java/com/joker/fourfun/presenter/contract/LoginContract.java
|
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/base/BasePresenter.java
// public interface BasePresenter<T extends BaseView> {
// void attach(T mView);
//
// void detach();
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/base/BaseView.java
// public interface BaseView {
// void showError(String message);
// }
|
import com.joker.fourfun.base.BasePresenter;
import com.joker.fourfun.base.BaseView;
|
package com.joker.fourfun.presenter.contract;
/**
* Created by joker on 2016/12/30.
*/
public interface LoginContract {
interface View extends BaseView {
void loginSuccess(String message);
void usernameEmpty();
void passwordEmpty();
}
|
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/base/BasePresenter.java
// public interface BasePresenter<T extends BaseView> {
// void attach(T mView);
//
// void detach();
// }
//
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/base/BaseView.java
// public interface BaseView {
// void showError(String message);
// }
// Path: client/FourFun/app/src/main/java/com/joker/fourfun/presenter/contract/LoginContract.java
import com.joker.fourfun.base.BasePresenter;
import com.joker.fourfun.base.BaseView;
package com.joker.fourfun.presenter.contract;
/**
* Created by joker on 2016/12/30.
*/
public interface LoginContract {
interface View extends BaseView {
void loginSuccess(String message);
void usernameEmpty();
void passwordEmpty();
}
|
interface Presenter extends BasePresenter<View> {
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.