file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
JavaField.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/element/java/JavaField.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.element.java; import java.lang.reflect.Field; import io.cocolabs.pz.zdoc.element.IField; import io.cocolabs.pz.zdoc.element.mod.MemberModifier; /** * This class represents a wrapped {@link Field} object. */ public class JavaField implements IField { private final String name; private final JavaClass type; private final MemberModifier modifier; private final String comment; public JavaField(JavaClass type, String name, MemberModifier modifier, String comment) { this.name = name; this.type = type; this.modifier = modifier; this.comment = comment; } public JavaField(JavaClass type, String name, MemberModifier modifier) { this(type, name, modifier, ""); } public JavaField(Class<?> type, String name, MemberModifier modifier) { this(new JavaClass(type), name, modifier, ""); } public JavaField(Field field) { this.name = field.getName(); this.type = new JavaClass(field.getType()); this.modifier = new MemberModifier(field.getModifiers()); this.comment = ""; } @Override public String toString() { return (modifier.toString() + ' ' + type.getName() + ' ' + getName()).trim(); } @Override public JavaClass getType() { return type; } @Override public String getName() { return name; } @Override public MemberModifier getModifier() { return modifier; } @Override public String getComment() { return comment; } @SuppressWarnings("ReferenceEquality") public boolean equals(JavaField field, boolean shallow) { if (shallow) { if (this == field) { return true; } if (field == null) { return false; } if (!name.equals(field.name)) { return false; } if (!type.equals(field.type, true)) { return false; } return modifier.equals(field.modifier); } else return equals(field); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof JavaField)) { return false; } JavaField jField = (JavaField) obj; if (name.equals(jField.name) && type.equals(jField.type)) { return true; } return modifier.equals(jField.modifier); } @Override public int hashCode() { int result = 31 * name.hashCode() + type.hashCode(); return 31 * result + modifier.hashCode(); } }
3,033
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
JavaClass.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/element/java/JavaClass.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.element.java; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.UnmodifiableView; import io.cocolabs.pz.zdoc.element.IClass; import io.cocolabs.pz.zdoc.element.SignatureToken; /** * This class represents a parsed Java class. */ public class JavaClass implements IClass, SignatureToken { private final Class<?> clazz; private final List<JavaClass> typeParameters; public JavaClass(Class<?> clazz, @Nullable List<JavaClass> typeParameters) { this.clazz = clazz; this.typeParameters = Collections.unmodifiableList( Optional.ofNullable(typeParameters).orElse(new ArrayList<>()) ); } public JavaClass(Class<?> clazz, @Nullable JavaClass typeParameter) { this(clazz, Collections.singletonList(typeParameter)); } public JavaClass(Class<?> clazz, int typeParameterCount) { this(clazz, getUnknownTypeParameterList(typeParameterCount)); } public JavaClass(Class<?> clazz) { this.clazz = clazz; int length = clazz.getTypeParameters().length; this.typeParameters = Collections.unmodifiableList( length != 0 ? getUnknownTypeParameterList(length) : new ArrayList<>() ); } static @UnmodifiableView List<JavaClass> getUnknownTypeParameterList(int size) { List<JavaClass> result = new ArrayList<>(); for (int i = 0; i < size; i++) { result.add(null); } return Collections.unmodifiableList(result); } public static String getPathForClass(Class<?> clazz) { if (clazz.getPackage() != null) { char[] className = clazz.getName().toCharArray(); char[] cClassPath = new char[className.length]; for (int i = 0; i < className.length; i++) { char c = className[i]; if (c == '.') { cClassPath[i] = '/'; } else if (c == '$') { cClassPath[i] = '.'; } else cClassPath[i] = c; } return new String(cClassPath); } else return ""; } public Class<?> getClazz() { return clazz; } @Override public String getName() { return clazz.getTypeName(); } @Override public @UnmodifiableView List<JavaClass> getTypeParameters() { return typeParameters; } private String readTypeParameter(int index) { JavaClass parameter = typeParameters.get(index); return parameter != null ? parameter.toString() : "?"; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getName()); if (!typeParameters.isEmpty()) { sb.append('<'); sb.append(readTypeParameter(0)); for (int i = 1; i < typeParameters.size(); i++) { sb.append(", ").append(readTypeParameter(i)); } sb.append('>'); } return sb.toString(); } @SuppressWarnings("ReferenceEquality") public boolean equals(JavaClass jClass, boolean shallow) { if (shallow) { if (this == jClass) { return true; } if (jClass == null) { return false; } if (!clazz.equals(jClass.clazz)) { return false; } return typeParameters.size() == jClass.typeParameters.size(); } else return equals(jClass); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof JavaClass)) { return false; } JavaClass jClass = (JavaClass) obj; return clazz.equals(jClass.clazz) && jClass.typeParameters.equals(typeParameters); } @Override public int hashCode() { return 31 * clazz.hashCode() + typeParameters.hashCode(); } }
4,236
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
JavaParameter.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/element/java/JavaParameter.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.element.java; import java.lang.reflect.Parameter; import io.cocolabs.pz.zdoc.element.IParameter; import io.cocolabs.pz.zdoc.element.SignatureToken; public class JavaParameter implements IParameter, SignatureToken { private final JavaClass type; private final String name, comment; public JavaParameter(JavaClass type, String name, String comment) { this.type = type; this.name = name; this.comment = comment; } public JavaParameter(JavaClass type, String name) { this(type, name, ""); } public JavaParameter(Class<?> type, String name, String comment) { this(new JavaClass(type), name, comment); } public JavaParameter(Class<?> type, String name) { this(type, name, ""); } public JavaParameter(Parameter parameter) { this(new JavaClass(parameter.getType()), parameter.getName(), ""); } @Override public String toString() { return (type.toString() + ' ' + getName()).trim(); } @Override public String getAsVarArg() { String sType = type.toString(); if (sType.endsWith("[]")) { sType = sType.substring(0, sType.length() - 2); } return (sType + "... " + getName()).trim(); } @Override public String getComment() { return comment; } @Override public JavaClass getType() { return type; } @Override public String getName() { return name; } @SuppressWarnings("ReferenceEquality") public boolean equals(JavaParameter param, boolean shallow) { if (shallow) { if (this == param) { return true; } if (param == null) { return false; } return type.equals(param.type, true); } else return equals(param); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof JavaParameter)) { return false; } JavaParameter param = (JavaParameter) obj; return name.equals(param.name) && type.equals(param.type); } @Override public int hashCode() { return 31 * type.hashCode() + name.hashCode(); } }
2,735
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
LuaMethod.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/element/lua/LuaMethod.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.element.lua; import java.util.*; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Unmodifiable; import org.jetbrains.annotations.UnmodifiableView; import io.cocolabs.pz.zdoc.element.IMethod; import io.cocolabs.pz.zdoc.element.IReturnType; import io.cocolabs.pz.zdoc.element.mod.AccessModifierKey; import io.cocolabs.pz.zdoc.element.mod.MemberModifier; import io.cocolabs.pz.zdoc.lang.lua.*; import io.cocolabs.pz.zdoc.logger.Logger; /** * This class represents a parsed Lua method. */ public class LuaMethod implements IMethod, Annotated { private final @Nullable LuaClass owner; private final String name; private final ReturnType returnType; private final List<LuaParameter> params; private final MemberModifier modifier; private final boolean hasVarArg; private final List<EmmyLua> annotations; private final String comment; private LuaMethod(Builder builder) { this.name = EmmyLua.getSafeLuaName(builder.name); this.owner = builder.owner; this.returnType = builder.returnType != null ? builder.returnType : new ReturnType("void"); this.modifier = builder.modifier != null ? builder.modifier : MemberModifier.UNDECLARED; this.params = Collections.unmodifiableList(builder.params); List<EmmyLua> annotations = new ArrayList<>(); if (!modifier.hasAccess(AccessModifierKey.DEFAULT)) { annotations.add(new EmmyLuaAccess(modifier.getAccess())); } if (builder.hasVarArg) { if (!params.isEmpty()) { // annotate last parameter as variadic argument for (int i = 0, size = params.size() - 1; i < size; i++) { annotations.addAll(params.get(i).getAnnotations()); } LuaParameter param = params.get(params.size() - 1); annotations.add(new EmmyLuaVarArg(param.getType(), param.getComment())); } else { builder.hasVarArg = false; Logger.error("Method %s marked with hasVarArg with no parameters", toString()); } } else params.forEach(p -> annotations.addAll(p.getAnnotations())); annotations.add(new EmmyLuaReturn(returnType)); if (builder.overloads != null) { for (LuaMethod overload : builder.overloads) { if (!overload.getName().equals(name)) { String format = "Unexpected Lua method overload name '%s' for method '%s'"; Logger.error(format, overload.getName(), name); } else annotations.add(new EmmyLuaOverload(overload.params)); } } this.annotations = Collections.unmodifiableList(annotations); this.hasVarArg = builder.hasVarArg; this.comment = builder.comment; } public void appendParameterSignature(StringBuilder sb) { if (params.size() > 0) { int lastElementIndex = params.size() - 1; // method has 2 or more parameters if (lastElementIndex > 0) { sb.append(params.get(0).getName()); for (int i = 1; i < lastElementIndex; i++) { sb.append(", ").append(params.get(i).getName()); } sb.append(", "); } if (!hasVarArg()) { sb.append(params.get(lastElementIndex).getName()); } // method has variadic argument else sb.append("..."); } } public @Nullable LuaClass getOwner() { return owner; } @Override public String toString() { StringBuilder sb = new StringBuilder(); appendParameterSignature(sb); return String.format("%s%s(%s)", owner != null ? owner.getName() + ':' : "", getName(), sb.toString()); } @Override public String getName() { return name; } @Override public MemberModifier getModifier() { return modifier; } @Override public String getComment() { return comment; } @Override public LuaType getReturnType() { return returnType; } @Override public @UnmodifiableView List<LuaParameter> getParams() { return params; } @Override public boolean hasVarArg() { return hasVarArg; } @Override public @Unmodifiable List<EmmyLua> getAnnotations() { return annotations; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof LuaMethod)) { return false; } LuaMethod luaMethod = (LuaMethod) obj; if (!Objects.equals(owner, luaMethod.owner)) { return false; } if (!name.equals(luaMethod.name)) { return false; } if (!returnType.equals(luaMethod.returnType)) { return false; } if (!params.equals(luaMethod.params)) { return false; } if (hasVarArg != luaMethod.hasVarArg) { return false; } return modifier.equals(luaMethod.modifier); } @Override public int hashCode() { int result = owner != null ? owner.hashCode() : 0; result = 31 * result + name.hashCode(); result = 31 * result + returnType.hashCode(); result = 31 * result + params.hashCode(); result = 31 * result + modifier.hashCode(); return 31 * result + (hasVarArg ? 1 : 0); } public static class Builder { private final String name; private @Nullable LuaClass owner; private @Nullable MemberModifier modifier; private @Nullable ReturnType returnType; private @Nullable Set<LuaMethod> overloads; private List<LuaParameter> params = new ArrayList<>(); private boolean hasVarArg = false; private String comment = ""; private Builder(String name) { this.name = name; } public static Builder create(String name) { return new Builder(name); } public Builder withOwner(@Nullable LuaClass owner) { this.owner = owner; return this; } public Builder withModifier(MemberModifier modifier) { this.modifier = modifier; return this; } public Builder withReturnType(LuaType returnType, String comment) { this.returnType = new ReturnType(returnType, comment); return this; } public Builder withReturnType(LuaType returnType) { this.returnType = new ReturnType(returnType, ""); return this; } public Builder withVarArg(boolean hasVarArg) { this.hasVarArg = hasVarArg; return this; } public Builder withComment(String comment) { this.comment = comment; return this; } public Builder withParams(List<LuaParameter> params) { this.params = params; return this; } public Builder withParams(LuaParameter...params) { this.params = new ArrayList<>(Arrays.asList(params)); return this; } public Builder withOverloads(Set<LuaMethod> overloads) { this.overloads = overloads; return this; } public LuaMethod build() { return new LuaMethod(this); } } public static class ReturnType extends LuaType implements IReturnType { private final String comment; public ReturnType(String name, List<LuaType> otherTypes, String comment) { super(name, otherTypes); this.comment = comment; } public ReturnType(String name) { super(name); this.comment = ""; } public ReturnType(LuaType type, String comment) { this(type.name, type.getTypeParameters(), comment); } @Override public String getComment() { return comment; } } public static class OverloadMethodComparator implements Comparator<LuaMethod> { @Override public int compare(LuaMethod o1, LuaMethod o2) { int result = Integer.compare(o1.getParams().size(), o2.getParams().size()); return result != 0 ? result : (o1.equals(o2) ? 0 : -1); } } }
7,914
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
LuaField.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/element/lua/LuaField.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.element.lua; import java.util.Collections; import java.util.List; import org.jetbrains.annotations.Unmodifiable; import io.cocolabs.pz.zdoc.element.IField; import io.cocolabs.pz.zdoc.element.mod.AccessModifierKey; import io.cocolabs.pz.zdoc.element.mod.MemberModifier; import io.cocolabs.pz.zdoc.lang.lua.EmmyLua; import io.cocolabs.pz.zdoc.lang.lua.EmmyLuaField; public class LuaField implements IField, Annotated { private final String name; private final LuaType type; private final MemberModifier modifier; private final String comment; private final List<EmmyLua> annotations; public LuaField(LuaType type, String name, MemberModifier modifier, String comment) { this.type = type; this.name = EmmyLua.getSafeLuaName(name); this.modifier = modifier; if (!modifier.hasAccess(AccessModifierKey.DEFAULT)) { this.annotations = Collections.singletonList( new EmmyLuaField(this.name, modifier.getAccess().name, type, comment)); } else this.annotations = Collections.singletonList(new EmmyLuaField(this.name, type, comment)); this.comment = comment; } public LuaField(LuaType type, String name, MemberModifier modifier) { this(type, name, modifier, ""); } @Override public String toString() { return (type.name + ' ' + name).trim(); } @Override public LuaType getType() { return type; } @Override public String getName() { return name; } @Override public MemberModifier getModifier() { return modifier; } @Override public String getComment() { return comment; } @Override public @Unmodifiable List<EmmyLua> getAnnotations() { return annotations; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof LuaField)) { return false; } LuaField luaField = (LuaField) obj; if (!name.equals(luaField.name)) { return false; } if (!type.equals(luaField.type)) { return false; } return modifier.equals(luaField.modifier); } @Override public int hashCode() { int result = 31 * name.hashCode() + type.hashCode(); result = 31 * result + type.hashCode(); return 31 * result + modifier.hashCode(); } }
2,938
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
Annotated.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/element/lua/Annotated.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.element.lua; import java.util.List; import org.jetbrains.annotations.Unmodifiable; import io.cocolabs.pz.zdoc.lang.lua.EmmyLua; public interface Annotated { @Unmodifiable List<EmmyLua> getAnnotations(); }
989
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
LuaClass.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/element/lua/LuaClass.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.element.lua; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Unmodifiable; import io.cocolabs.pz.zdoc.element.IClass; import io.cocolabs.pz.zdoc.lang.lua.EmmyLua; import io.cocolabs.pz.zdoc.lang.lua.EmmyLuaClass; /** * This class represents a parsed lua class reference. */ public class LuaClass implements IClass, Annotated { private final String type; private final String conventional; private final @Nullable String parentType; private final List<EmmyLua> annotations; public LuaClass(String type, @Nullable String parentType) { this.type = type; this.conventional = getConventionalName(type); /* * ensure that parent type is different then base type, this check * can be handled elsewhere but we should do it here to ensure safety */ this.parentType = !type.equals(parentType) ? parentType : null; this.annotations = Collections.singletonList(new EmmyLuaClass(type, getParentType())); } public LuaClass(String type) { this(type, null); } /** * {@code LuaClass} type names follow official Lua lexical conventions: * <blockquote> * Names (also called identifiers) in Lua can be any string of Latin letters, * Arabic-Indic digits, and underscores, not beginning with a digit and not being a * reserved word. Identifiers are used to name variables, table fields, and labels. * </blockquote> * * @see <a href="https://www.lua.org/manual/5.4/manual.html#3.1">Lua Lexical Conventions</a> */ private static String getConventionalName(String name) { String result = name; if (result.contains(".")) { result = result.replace('.', '_'); } if (Character.isDigit(result.charAt(0))) { result = '_' + result.substring(1); } return EmmyLua.getSafeLuaName(result); } public @Nullable String getParentType() { return parentType; } @Override public String getName() { return type; } public String getConventionalName() { return conventional; } @Override public List<IClass> getTypeParameters() { return new ArrayList<>(); } @Override public String toString() { return parentType != null ? type + " : " + parentType : type; } @Override public @Unmodifiable List<EmmyLua> getAnnotations() { return annotations; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof LuaClass)) { return false; } LuaClass luaClass = (LuaClass) obj; if (!type.equals(luaClass.type)) { return false; } return Objects.equals(parentType, luaClass.parentType); } @Override public int hashCode() { return 31 * type.hashCode() + (parentType != null ? parentType.hashCode() : 0); } }
3,555
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
LuaType.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/element/lua/LuaType.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.element.lua; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.jetbrains.annotations.UnmodifiableView; import com.google.common.collect.ImmutableList; import io.cocolabs.pz.zdoc.element.IClass; public class LuaType implements IClass { final String name; private final @UnmodifiableView List<LuaType> otherTypes; public LuaType(String name, List<LuaType> otherTypes) { this.name = name; this.otherTypes = Collections.unmodifiableList(otherTypes); } public LuaType(String name, LuaType otherType) { this.name = name; this.otherTypes = ImmutableList.of(otherType); } public LuaType(String name) { this(name, new ArrayList<>()); } @Override public String getName() { return name; } @Override public @UnmodifiableView List<LuaType> getTypeParameters() { return otherTypes; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof LuaType)) { return false; } LuaType luaType = (LuaType) obj; if (!name.equals(luaType.name)) { return false; } return otherTypes.equals(luaType.otherTypes); } @Override public int hashCode() { return 31 * name.hashCode() + otherTypes.hashCode(); } }
2,018
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
LuaParameter.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/element/lua/LuaParameter.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.element.lua; import java.util.Collections; import java.util.List; import org.jetbrains.annotations.Unmodifiable; import io.cocolabs.pz.zdoc.element.IParameter; import io.cocolabs.pz.zdoc.lang.lua.EmmyLua; import io.cocolabs.pz.zdoc.lang.lua.EmmyLuaParam; public class LuaParameter implements IParameter, Annotated { private final LuaType type; private final String name, comment; private final List<EmmyLua> annotations; public LuaParameter(LuaType type, String name, String comment) { this.type = type; this.name = EmmyLua.getSafeLuaName(name); this.comment = comment; this.annotations = Collections.singletonList(new EmmyLuaParam(this.name, type, comment)); } public LuaParameter(LuaType type, String name) { this(type, name, ""); } @Override public String toString() { return (type.getName() + ' ' + name).trim(); } @Override public String getAsVarArg() { return "..."; } @Override public String getComment() { return comment; } @Override public LuaType getType() { return type; } @Override public String getName() { return name; } @Override public @Unmodifiable List<EmmyLua> getAnnotations() { return annotations; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof LuaParameter)) { return false; } LuaParameter that = (LuaParameter) obj; if (!type.equals(that.type)) { return false; } return name.equals(that.name); } @Override public int hashCode() { return 31 * type.hashCode() + name.hashCode(); } }
2,337
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
AccessModifierKey.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/element/mod/AccessModifierKey.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.element.mod; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.stream.Collectors; import org.jetbrains.annotations.Nullable; public enum AccessModifierKey { PUBLIC("public", Modifier.PUBLIC), PROTECTED("protected", Modifier.PROTECTED), PRIVATE("private", Modifier.PRIVATE), DEFAULT("", 0x00000000); private static final AccessModifierKey[] VALUES = Arrays.stream(AccessModifierKey.values()) .filter(v -> v != DEFAULT).collect(Collectors.toList()).toArray(new AccessModifierKey[]{}); public final String name; final int value; AccessModifierKey(String name, int value) { this.name = name; this.value = value; } public static AccessModifierKey get(@Nullable String name) { if (name == null) { return DEFAULT; } // trim the name before comparison final String findName = name.trim(); return Arrays.stream(VALUES).filter(v -> v.name.equals(findName)) .findFirst().orElse(DEFAULT); } public static AccessModifierKey get(int modifiers) { return Arrays.stream(VALUES).filter(v -> (modifiers & v.value) != 0) .findFirst().orElse(DEFAULT); } @Override public String toString() { return name; } }
1,953
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
ModifierKey.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/element/mod/ModifierKey.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.element.mod; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import org.apache.commons.collections4.list.SetUniqueList; public enum ModifierKey { STATIC("static", Modifier.STATIC), ABSTRACT("abstract", Modifier.ABSTRACT), FINAL("final", Modifier.FINAL), VOLATILE("volatile", Modifier.VOLATILE), SYNCHRONIZED("synchronized", Modifier.SYNCHRONIZED), UNDECLARED("", 0x00000000); private static final ModifierKey[] VALUES = Arrays.stream(ModifierKey.values()) .filter(v -> v != UNDECLARED).collect(Collectors.toList()).toArray(new ModifierKey[]{}); public final String name; final int value; ModifierKey(String name, int value) { this.name = name; this.value = value; } public static SetUniqueList<ModifierKey> get(String... elements) { List<ModifierKey> result = new ArrayList<>(); for (String element : elements) { Arrays.stream(VALUES).filter(v -> v.name.equals(element)) .findFirst().ifPresent(result::add); } if (result.isEmpty()) { result.add(UNDECLARED); } return SetUniqueList.setUniqueList(result); } public static SetUniqueList<ModifierKey> get(int modifiers) { List<ModifierKey> result = Arrays.stream(ModifierKey.values()) .filter(v -> (modifiers & v.value) != 0) .collect(Collectors.toList()); if (result.isEmpty()) { result.add(UNDECLARED); } return SetUniqueList.setUniqueList(result); } @Override public String toString() { return name; } }
2,315
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
MemberModifier.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/element/mod/MemberModifier.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.element.mod; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import org.apache.commons.collections4.list.SetUniqueList; import org.jetbrains.annotations.Unmodifiable; public class MemberModifier { public static final MemberModifier UNDECLARED = new MemberModifier(AccessModifierKey.DEFAULT, ModifierKey.UNDECLARED); private final AccessModifierKey access; private final SetUniqueList<ModifierKey> modifiers; public MemberModifier(AccessModifierKey accessKey, List<ModifierKey> modifierKeys) { this.access = accessKey; this.modifiers = SetUniqueList.setUniqueList(modifierKeys); /* * if no modifiers present mark as undeclared, * otherwise make sure modifier is not marked as undeclared */ if (this.modifiers.isEmpty()) { this.modifiers.add(ModifierKey.UNDECLARED); } else if (this.modifiers.size() > 1) { this.modifiers.remove(ModifierKey.UNDECLARED); } } public MemberModifier(AccessModifierKey accessKey, ModifierKey... modifierKeys) { this(accessKey, Arrays.stream(modifierKeys).collect(Collectors.toList())); } public MemberModifier(int modifiers) { this(AccessModifierKey.get(modifiers), ModifierKey.get(modifiers)); } public AccessModifierKey getAccess() { return access; } @Unmodifiable List<ModifierKey> getModifiers() { return Collections.unmodifiableList(modifiers); } public boolean hasAccess(AccessModifierKey key) { return access == key; } public boolean isModifierUndeclared() { return modifiers.contains(ModifierKey.UNDECLARED); } public boolean hasModifiers(ModifierKey... keys) { return Arrays.stream(keys).allMatch(modifiers::contains); } public boolean matchesModifiers(ModifierKey... keys) { return modifiers.equals(Arrays.asList(keys)); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(access.name).append(' '); modifiers.forEach(m -> sb.append(m.toString()).append(' ')); return sb.toString().trim(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof MemberModifier)) { return false; } MemberModifier modifier = (MemberModifier) obj; return access == modifier.access && modifiers.equals(modifier.modifiers); } @Override public int hashCode() { return 31 * access.hashCode() + modifiers.hashCode(); } }
3,188
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
ZomboidJavaDoc.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/doc/ZomboidJavaDoc.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.doc; import java.util.Collections; import java.util.List; import java.util.Set; import org.apache.commons.lang3.Validate; import org.jetbrains.annotations.UnmodifiableView; import io.cocolabs.pz.zdoc.element.java.JavaClass; import io.cocolabs.pz.zdoc.element.java.JavaField; import io.cocolabs.pz.zdoc.element.java.JavaMethod; public class ZomboidJavaDoc implements ZomboidDoc { private final JavaClass clazz; private final @UnmodifiableView List<JavaField> fields; private final @UnmodifiableView Set<JavaMethod> methods; public ZomboidJavaDoc(JavaClass clazz, List<JavaField> fields, Set<JavaMethod> methods) { this.clazz = clazz; this.fields = Collections.unmodifiableList(Validate.noNullElements(fields)); this.methods = Collections.unmodifiableSet(Validate.noNullElements(methods)); } @Override public JavaClass getClazz() { return clazz; } @Override public String getName() { return clazz.getName(); } @Override public @UnmodifiableView List<JavaField> getFields() { return fields; } @Override public @UnmodifiableView Set<JavaMethod> getMethods() { return methods; } }
1,896
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
ZomboidDoc.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/doc/ZomboidDoc.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.doc; import java.util.List; import java.util.Set; import org.jetbrains.annotations.UnmodifiableView; import io.cocolabs.pz.zdoc.element.IClass; import io.cocolabs.pz.zdoc.element.IField; import io.cocolabs.pz.zdoc.element.IMethod; public interface ZomboidDoc { IClass getClazz(); String getName(); @UnmodifiableView List<? extends IField> getFields(); @UnmodifiableView Set<? extends IMethod> getMethods(); }
1,202
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
ZomboidLuaDoc.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/doc/ZomboidLuaDoc.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.doc; import java.io.File; import java.io.IOException; import java.util.*; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import org.jetbrains.annotations.UnmodifiableView; import com.google.common.base.Splitter; import io.cocolabs.pz.zdoc.Main; import io.cocolabs.pz.zdoc.compile.JavaCompiler; import io.cocolabs.pz.zdoc.compile.LuaCompiler; import io.cocolabs.pz.zdoc.element.IMember; import io.cocolabs.pz.zdoc.element.lua.Annotated; import io.cocolabs.pz.zdoc.element.lua.LuaClass; import io.cocolabs.pz.zdoc.element.lua.LuaField; import io.cocolabs.pz.zdoc.element.lua.LuaMethod; import io.cocolabs.pz.zdoc.lang.lua.EmmyLua; import io.cocolabs.pz.zdoc.logger.Logger; public class ZomboidLuaDoc implements ZomboidDoc { private final LuaClass clazz; private final @UnmodifiableView List<LuaField> fields; private final @UnmodifiableView Set<LuaMethod> methods; public ZomboidLuaDoc(LuaClass clazz, List<LuaField> fields, Set<LuaMethod> methods) { this.clazz = clazz; this.fields = Collections.unmodifiableList(Validate.noNullElements(fields)); this.methods = Collections.unmodifiableSet(Validate.noNullElements(overloadMethods(methods))); } public ZomboidLuaDoc(LuaClass clazz) { this(clazz, new ArrayList<>(), new HashSet<>()); } private static void appendAnnotations(StringBuilder sb, Annotated element) { List<EmmyLua> annotations = element.getAnnotations(); if (annotations.size() > 0) { sb.append(annotations.get(0).toString()); for (int i = 1; i < annotations.size(); i++) { sb.append('\n').append(annotations.get(i).toString()); } sb.append('\n'); } } private static void appendComments(StringBuilder sb, IMember member) { String comment = member.getComment(); if (!StringUtils.isBlank(comment)) { List<String> comments = Splitter.onPattern("(\\r\\n|\\r|\\n)").splitToList(comment); int commentCount = comments.size(); if (commentCount > 0) { sb.append("---").append(comments.get(0).trim()); for (int i = 1; i < commentCount; i++) { sb.append("\n---\n---").append(comments.get(i).trim()); } sb.append('\n'); } } } public static void writeGlobalTypesToFile(File file) throws IOException { Logger.detail("Writing global lua types to file..."); StringBuilder sb = new StringBuilder(); Set<LuaClass> globalTypes = LuaCompiler.getGlobalTypes(); for (LuaClass type : globalTypes) { ZomboidLuaDoc.appendAnnotations(sb, type); sb.append(type.getConventionalName()).append(" = {}\n\n"); } FileUtils.write(file, sb.toString(), Main.CHARSET, false); Logger.info("Compiled %d global lua types", globalTypes.size()); } public void writeToFile(File file) throws IOException { Logger.detail("Writing %s to %s...", getName(), file.getName()); StringBuilder sb = new StringBuilder(); ZomboidLuaDoc.appendAnnotations(sb, clazz); // TODO: static fields should be written as actual fields (not just annotations) for (LuaField field : fields) { ZomboidLuaDoc.appendAnnotations(sb, field); } sb.append(clazz.getConventionalName()).append(" = {}\n\n"); for (LuaMethod method : methods) { ZomboidLuaDoc.appendComments(sb, method); ZomboidLuaDoc.appendAnnotations(sb, method); sb.append("function "); // global methods need to be declared outside tables String parentType = clazz.getParentType(); if (parentType == null || !parentType.equals(JavaCompiler.GLOBAL_OBJECT_CLASS)) { sb.append(clazz.getConventionalName()).append(':'); } sb.append(method.getName()).append('('); method.appendParameterSignature(sb); sb.append(") end\n\n"); } sb.deleteCharAt(sb.length() - 1); FileUtils.write(file, sb.toString(), Main.CHARSET, false); } private Set<LuaMethod> overloadMethods(Set<LuaMethod> luaMethods) { // list of overload methods for each lua method Map<String, Set<LuaMethod>> overloadData = new LinkedHashMap<>(); for (LuaMethod method : luaMethods) { String methodName = method.getName(); Set<LuaMethod> overloadEntry = overloadData.get(methodName); if (overloadEntry == null) { Comparator<LuaMethod> comparator = new LuaMethod.OverloadMethodComparator(); SortedSet<LuaMethod> overloadMethods = new TreeSet<>(comparator); overloadMethods.add(method); overloadData.put(methodName, overloadMethods); } else overloadEntry.add(method); } Set<LuaMethod> result = new LinkedHashSet<>(); for (Map.Entry<String, Set<LuaMethod>> entry : overloadData.entrySet()) { Set<LuaMethod> methods = entry.getValue(); if (methods.size() > 1) { // use iterator so we can replace the method entry Iterator<LuaMethod> iter = methods.iterator(); /* * add annotations to first method (as sorted by OverloadMethodComparator) * to be written to file because EmmyLua displays in IntelliJ IDEA structure * only first overloaded method occurance it finds, everything else is ignored. */ LuaMethod method = iter.next(); /* * replace the first method with a copied method with overloded method entries, * this is the only difference between the old and newly created method */ methods.remove(method); methods.add(LuaMethod.Builder.create(method.getName()) .withOwner(method.getOwner()).withModifier(method.getModifier()) .withReturnType(method.getReturnType()).withOverloads(methods) .withParams(method.getParams()).withVarArg(method.hasVarArg()) .withComment(method.getComment()).build() ); } result.addAll(methods); } return result; } @Override public LuaClass getClazz() { return clazz; } @Override public String getName() { return clazz.getConventionalName(); } @Override public @UnmodifiableView List<LuaField> getFields() { return fields; } @Override public @UnmodifiableView Set<LuaMethod> getMethods() { return methods; } }
6,728
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
ZomboidAPIDoc.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/doc/ZomboidAPIDoc.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.doc; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; import org.apache.commons.io.FilenameUtils; import org.jetbrains.annotations.Nullable; import org.jsoup.HttpStatusException; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import io.cocolabs.pz.zdoc.Main; import io.cocolabs.pz.zdoc.util.Utils; /** * This class represents a parsed JavaDoc document. */ public class ZomboidAPIDoc { private static final URL API_URL = Utils.getURL("https://projectzomboid.com/modding"); private final Document document; private final String name; private ZomboidAPIDoc(Document document, String name) { this.document = document; this.name = name; } /** * Get Project Zomboid API page from resolved {@code URL} for given path. * * @param path path to API page <i>(does not need to have an extension)</i>. * @return new {@code ZomboidDoc} instance wrapping a parsed {@code HTML} document * representing API page for given path, or {@code null} if the API website * returned status code {@code 404} (page not found). * * @throws IOException if {@link Jsoup} encountered an error while executing GET request. */ public static @Nullable ZomboidAPIDoc getPage(Path path) throws IOException { try { String apiUrl = resolveURL(path.toString().replace('\\', '/')).toString(); return new ZomboidAPIDoc(Jsoup.connect(apiUrl).get(), path.getFileName().toString()); } catch (IOException e) { if (e instanceof HttpStatusException && ((HttpStatusException) e).getStatusCode() == 404) { return null; } else throw e; } } /** * Get Project Zomboid API page for given path. * * @param path path to API page in local file system. * @return new {@code ZomboidDoc} instance wrapping a parsed {@code HTML} * document representing local API page for given path. * * @throws IOException if {@link Jsoup} could not find the API document. */ static ZomboidAPIDoc getLocalPage(Path path) throws IOException { return new ZomboidAPIDoc(Jsoup.parse(path.toFile(), Main.CHARSET), path.getFileName().toString()); } /** * <p> * Resolve API url from the given path. If the given path can be parsed as an {@code URL} * the parsed {@code URL} object will be returned, otherwise if the path represents a * local file path it will be concatenated to the end of modding API URL. * </p> * <p><i> * Note that the resolved API URL always has to point to a HTML document, * which means that the resulting URL is guaranteed to point to a file with * an {@code .html} extension even if the user did not specify it. * </i></p> * * @throws IllegalArgumentException if the given path is not a valid {@code Path} * or {@code URL} object or if given path represents an {@code URL} object and * is not a valid Project Zomboid modding API link. */ public static URL resolveURL(String path) { URL url = Utils.getURLOrNull(path); if (url != null) { if (!isValidURL(url)) { throw new IllegalArgumentException("Invalid modding API url: " + url.toString()); } else return url; } Path pPath = Utils.getPathOrNull(path); if (pPath != null) { String ext = FilenameUtils.getExtension(pPath.getFileName().toString()); return Utils.getURL(API_URL, "modding", ext.equals("html") ? path : path + ".html"); } else throw new IllegalArgumentException(String.format("Cannot resolve api URL - " + "argument \"%s\" is not a valid Path or URL", path)); } public static Path resolveURLPath(String url) { URL uUrl = Utils.getURLOrNull(url); if (uUrl != null && isValidURL(uUrl)) { return Paths.get("/modding").relativize(Paths.get(uUrl.getPath())); } else throw new IllegalArgumentException(String.format("Cannot resolve API URL path, " + "argument \"%s\" is not a valid URL object", url)); } public static boolean isValidURL(URL url) { Path urlPath = Paths.get(url.getPath()); URL host = Utils.getURLBase(url); URL segment, target; if (urlPath.getNameCount() > 0) { segment = Utils.getURL(host, urlPath.getName(0).toString()); target = API_URL; } else { segment = host; target = Utils.getURLBase(API_URL); } try { // use URI comparison because URL equivalent is flawed if (!segment.toURI().equals(target.toURI())) { return false; } } catch (URISyntaxException e) { throw new RuntimeException(e); } return true; } public Document getDocument() { return document; } public String getName() { return name; } }
5,364
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
MethodDetail.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/doc/detail/MethodDetail.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.doc.detail; import java.util.*; import java.util.stream.Collectors; import org.apache.commons.collections4.list.SetUniqueList; import org.apache.logging.log4j.util.Strings; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import com.google.common.base.Splitter; import io.cocolabs.pz.zdoc.doc.ZomboidAPIDoc; import io.cocolabs.pz.zdoc.element.java.JavaClass; import io.cocolabs.pz.zdoc.element.java.JavaMethod; import io.cocolabs.pz.zdoc.element.java.JavaParameter; import io.cocolabs.pz.zdoc.element.mod.AccessModifierKey; import io.cocolabs.pz.zdoc.element.mod.MemberModifier; import io.cocolabs.pz.zdoc.element.mod.ModifierKey; import io.cocolabs.pz.zdoc.logger.Logger; import io.cocolabs.pz.zdoc.util.ParseUtils; public class MethodDetail extends Detail<JavaMethod> { public MethodDetail(ZomboidAPIDoc document) throws DetailParsingException { super("method.detail", document); } @Override protected List<JavaMethod> parse() throws DetailParsingException { Elements detail = getDetail(); List<JavaMethod> result = new ArrayList<>(); for (Element blockList : detail) { Element listHeader = blockList.getElementsByTag("h4").first(); String listName = listHeader != null ? listHeader.text() : "unknown"; Element eSignature = blockList.getElementsByTag("pre").first(); if (eSignature == null) { Logger.error("Unable to find method signature for method: " + listName); continue; } // parse method block and label comments StringBuilder commentBuilder = new StringBuilder(); Elements commentBlocks = blockList.getElementsByClass("block"); if (!commentBlocks.isEmpty()) { commentBuilder.append(commentBlocks.get(0).wholeText()); /* * normally there should only be one comment block per element * but check for additional blocks just to be on the safe side */ for (int i = 1; i < commentBlocks.size(); i++) { commentBuilder.append('\n').append(commentBlocks.get(i).text()); } } String returnTypeComment = ""; Map<String, String> paramComments = new HashMap<>(); Map<Element, Elements> descriptionList = new HashMap<>(); Elements ddElements = new Elements(); for (Element element : blockList.getAllElements()) { // description list title if (element.tagName().equals("dt")) { ddElements = new Elements(); descriptionList.put(element, ddElements); } // description list elements else if (element.tagName().equals("dd")) { ddElements.add(element); } } for (Map.Entry<Element, Elements> entry : descriptionList.entrySet()) { Element listTitle = entry.getKey(); Elements listEntries = entry.getValue(); if (listEntries.isEmpty()) { Logger.debug(String.format("Missing list elements for title '%s'", listTitle.text())); continue; } Element titleContainer = listTitle.getElementsByTag("span").first(); // we're expecting to find list title in span container if (titleContainer == null) { Logger.error(String.format("Unexpected description list title '%s'", listTitle)); continue; } String className = titleContainer.className(); // include override method documentation //noinspection IfCanBeSwitch if (className.equals("overrideSpecifyLabel")) { if (commentBuilder.length() > 0) { commentBuilder.append('\n'); } commentBuilder.append(listTitle.text()); Element overrideLabelElement = listEntries.get(0); commentBuilder.append('\n').append(overrideLabelElement.text()); } // include method return value documentation else if (className.equals("returnLabel")) { Element returnLabelElement = listEntries.get(0); returnTypeComment = returnLabelElement.text(); } // include method parameter documentation else if (className.equals("paramLabel")) { for (Element listEntry : listEntries) { Element eParamName = listEntry.getElementsByTag("code").first(); if (eParamName == null) { Logger.error(String.format("No paramLabel name found '%s'", listEntry)); continue; } String sParamName = eParamName.text(); int stringIndex = sParamName.length() + 3; String sListEntry = listEntry.text(); // make sure parameter comment exists before trimming if (stringIndex <= sListEntry.length()) { // trim element text to get only parameter comment String paramText = sListEntry.substring(stringIndex); if (!Strings.isBlank(paramText)) { paramComments.put(sParamName, paramText); } } } } } String methodComment = commentBuilder.toString(); if (!methodComment.isEmpty()) { Logger.debug("Parsed detail comment: \"" + result + "\""); } Signature signature = new Signature(qualifyZomboidClassElements(eSignature), methodComment); JavaClass type = TypeSignatureParser.parse(signature.returnType); if (type == null) { String msg = "Excluding method (%s) from detail, class %s does not exist"; Logger.detail(String.format(msg, signature.toString(), signature.returnType)); continue; } // rawParams is a list of parameter without comments List<JavaParameter> rawParams = new ArrayList<>(); boolean isVarArgs = false; if (!signature.params.isEmpty()) { try { MethodSignatureParser parser = new MethodSignatureParser(signature.params); rawParams = parser.parse(); isVarArgs = parser.isVarArg(); } catch (SignatureParsingException e) { String msg = "Excluding method (%s) from detail - %s."; Logger.printf(e.getLogLevel(), String.format(msg, signature.toString(), e.getMessage())); continue; } } // match parameters with their respected comments List<JavaParameter> params = new ArrayList<>(); for (int i = 0; i < rawParams.size(); i++) { JavaParameter param = rawParams.get(i); String comment = paramComments.get(param.getName()); if (comment != null) { params.add(i, new JavaParameter(param.getType(), param.getName(), comment)); } // when no comment was found use raw parameter else params.add(i, param); } result.add(JavaMethod.Builder.create(signature.name) .withReturnType(type, returnTypeComment).withModifier(signature.modifier) .withParams(params).withVarArgs(isVarArgs).withComment(signature.comment).build()); } return result; } @Override public Set<JavaMethod> getEntries(String name) { return getEntries().stream().filter(e -> e.getName().equals(name)).collect(Collectors.toSet()); } static class Signature extends DetailSignature { final MemberModifier modifier; final String returnType, name, params, comment; Signature(String signatureText, String detailComment) throws SignatureParsingException { super(signatureText); Logger.debug("Parsing method signature: " + signature); List<String> elements = Splitter.onPattern("\\s+").splitToList(signature); if (elements.size() < 2) { throw new SignatureParsingException(signature, "missing one or more elements"); } int index = 0; /* * parse signature annotation (optional) */ String element = elements.get(index); String annotation = element.charAt(0) == '@' ? element.substring(index++) : ""; /* * parse signature access modifier (optional) */ AccessModifierKey access = AccessModifierKey.get(elements.get(index)); if (access != AccessModifierKey.DEFAULT) { index += 1; } /* * parse signature non-access modifier (optional) */ SetUniqueList<ModifierKey> modifierKeys = SetUniqueList.setUniqueList(new ArrayList<>()); for (; index < elements.size(); index++) { Collection<ModifierKey> foundKeys = ModifierKey.get(elements.get(index)); if (!foundKeys.contains(ModifierKey.UNDECLARED)) { modifierKeys.addAll(foundKeys); } else break; } if (modifierKeys.isEmpty()) { modifierKeys.add(ModifierKey.UNDECLARED); } this.modifier = new MemberModifier(access, modifierKeys); /* * parse signature type and name */ String type; if (index < elements.size()) { type = elements.get(index); } else throw new SignatureParsingException(signature, "missing element type"); this.returnType = type; String name = null; StringBuilder sb = new StringBuilder(); for (char c : elements.get(index += 1).toCharArray()) { if (c == '(') { name = ParseUtils.flushStringBuilder(sb); } else sb.append(c); } if (name == null) { throw new SignatureParsingException(signature, "missing element name"); } this.name = name; /* * parse signature parameters */ String paramsSegment = sb.toString(); if (paramsSegment.charAt(0) != ')') { String params = null; for (index += 1; index < elements.size() && params == null; index++) { sb.append(" "); for (char c : elements.get(index).toCharArray()) { if (c == ')') { params = ParseUtils.flushStringBuilder(sb); } else sb.append(c); } } if (params == null) { // most probably dealing with vararg parameter here if (paramsSegment.endsWith(")")) { params = ParseUtils.flushStringBuilder(sb.deleteCharAt(sb.length() - 1)); } else throw new SignatureParsingException(signature, "malformed element params"); } this.params = params; } else { index += 1; sb.deleteCharAt(0); this.params = ""; } /* * parse signature comment (optional) */ for (; index < elements.size(); index++) { sb.append(" ").append(elements.get(index)); } String tComment = sb.toString().trim(); if (!annotation.isEmpty()) { String commentSuffix = "This method is annotated as " + annotation; tComment = tComment.isEmpty() ? commentSuffix : tComment + '\n' + commentSuffix; } if (detailComment != null && !detailComment.isEmpty()) { tComment += !tComment.isEmpty() ? '\n' + detailComment : detailComment; } this.comment = tComment; } Signature(String signatureText) throws SignatureParsingException { this(signatureText, ""); } private Signature(Element element, String comment) throws SignatureParsingException { this(element.text(), comment); } } }
11,103
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
Detail.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/doc/detail/Detail.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.doc.detail; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.Set; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.UnmodifiableView; import org.jsoup.nodes.Element; import org.jsoup.nodes.TextNode; import org.jsoup.select.Elements; import org.springframework.util.ClassUtils; import io.cocolabs.pz.zdoc.doc.ZomboidAPIDoc; import io.cocolabs.pz.zdoc.element.IMember; public abstract class Detail<T extends IMember> { final String name; private final ZomboidAPIDoc document; private final List<T> entries; Detail(String name, ZomboidAPIDoc document) throws DetailParsingException { this.name = name; this.document = document; this.entries = Collections.unmodifiableList(parse()); } Elements getDetail() { Optional<Element> detailElement = document.getDocument().getElementsByTag("a") .stream().filter(e -> e.hasAttr("name") && e.attr("name").equals(name)).findFirst(); if (detailElement.isPresent()) { return detailElement.get().parent().getElementsByTag("ul"); } else return new Elements(); } Element qualifyZomboidClassElements(Element element) throws DetailParsingException { for (Element e : element.getElementsByTag("a")) { List<TextNode> textNodes = e.textNodes(); if (textNodes.size() != 1) { String format = "Unexpected number of hyperlink text nodes (%s)"; throw new DetailParsingException(this, String.format(format, textNodes.size())); } TextNode textNode = textNodes.get(0); String absUrl = e.absUrl("href"); if (StringUtils.isBlank(absUrl)) { String format = "Missing href for node \"%s\""; throw new DetailParsingException(this, String.format(format, textNode.text())); } String urlPath = ZomboidAPIDoc.resolveURLPath(absUrl).toString(); /* * remove file extension from API URL * "/zombie/Zombie.html" -> "/zombie/Zombie" */ urlPath = urlPath.substring(0, FilenameUtils.indexOfExtension(urlPath)); /* * ClassUtils#convertResourcePathToClassName path parameter * needs to be in Unix format, otherwise we get a malformed return value */ String packagePath = urlPath.replace('\\', '/'); /* * methods that retrieve class from name have problems finding * deeply nested classes (depth of 2 or more) for package paths * that dont use dollar signs ($) to indicate inner classes */ int periodDelimitersFound = 0; char[] cPackagePath = packagePath.toCharArray(); for (int i = 0; i < cPackagePath.length; i++) { if (cPackagePath[i] == '.') { periodDelimitersFound += 1; if (periodDelimitersFound >= 2) { cPackagePath[i] = '$'; } } } textNode.text(ClassUtils.convertResourcePathToClassName(new String(cPackagePath))); } return element; } public @UnmodifiableView List<T> getEntries() { return entries; } public abstract Set<T> getEntries(String name); protected abstract List<T> parse() throws DetailParsingException; }
3,837
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
MethodSignatureParser.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/doc/detail/MethodSignatureParser.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.doc.detail; import java.util.List; import io.cocolabs.pz.zdoc.element.java.JavaClass; import io.cocolabs.pz.zdoc.element.java.JavaParameter; import io.cocolabs.pz.zdoc.util.Utils; public class MethodSignatureParser extends SignatureParser<JavaParameter> { private boolean isVarArg = false; MethodSignatureParser(String signature) { super(signature); } @Override List<JavaParameter> parse() throws SignatureParsingException { JavaClass type = null; char[] charArray = signature.toCharArray(); for (; index.get() < charArray.length; index.getAndIncrement()) { char c = charArray[index.get()]; if (c == '<') { index.incrementAndGet(); String className = flush(); try { Class<?> typeClass = Utils.getClassForName(className); type = new JavaClass(typeClass, new TypeSignatureParser(signature, index).parse()); } catch (ClassNotFoundException e) { throwExceptionUnknownClass(className); } } else if (c == ',') { if (type == null) { throw new MalformedSignatureException(signature, "expected type to not be null"); } result.add(new JavaParameter(type, flush())); } else if (c == ' ') { if (type == null || builder.length() != 0) { String className = flush(); try { type = new JavaClass(Utils.getClassForName(className)); } catch (ClassNotFoundException e1) { // parameter is a variadic argument if (className.endsWith("...")) { // skip if builder string was already consumed by type if (className.length() != 3) { try { className = className.substring(0, className.length() - 3); type = new JavaClass(Utils.getClassForName(className)); } catch (ClassNotFoundException e2) { throwExceptionUnknownClass(className); } } isVarArg = true; } else throwExceptionUnknownClass(className); } } } else if (c != '>') { builder.append(c); } } if (builder.length() > 0) { String param = flush(); if (type == null) { String message = String.format("Parameter \"%s\" is missing type", param); throw new MalformedSignatureException(signature, message); } result.add(new JavaParameter(type, param)); } return result; } boolean isVarArg() { return isVarArg; } private void throwExceptionUnknownClass(String className) throws SignatureParsingException { throw new SignatureParsingException(signature, "unknown class: " + className); } }
3,323
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
DetailSignature.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/doc/detail/DetailSignature.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.doc.detail; import org.jsoup.nodes.Element; abstract class DetailSignature { final String signature; DetailSignature(String signature) { this.signature = normalizeSignature(signature); } /** * Normalize given signature text: * <ul> * <li>Convert non-breaking space ({@code &nbsp}) to whitespace.</li> * <li>Convert newlines to whitespace.</li> * <li>Remove consecutive whitespaces.</li> * </ul> * * @param text {@code String} to normalize. * @return normalized text. */ private static String normalizeSignature(String text) { StringBuilder sb = new StringBuilder(); char lastChar = 0; for (char c : text.toCharArray()) { // convert &nbsp and newlines to whitespace if (c == 160 || c == '\r' || c == '\n') { c = ' '; } // remove consecutive whitespaces if (lastChar == ' ' && c == ' ') { continue; } sb.append(c); lastChar = c; } return sb.toString(); } /** * Gets the combined text of the given element and all its children. * Whitespace is normalized and trimmed. The normalization process also * includes converting non-breaking space ({@code &nbsp}) and newlines to whitespace. * * @param element {@code Element} text to normalize. * @return normalized and trimmed text or empty text if none. * * @see Element#text() */ static String normalizeElement(Element element) { return normalizeSignature(element.text()); } @Override public String toString() { return signature; } }
2,264
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
FieldDetail.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/doc/detail/FieldDetail.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.doc.detail; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Set; import org.apache.commons.collections4.list.SetUniqueList; import org.jetbrains.annotations.Nullable; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import com.google.common.base.Splitter; import com.google.common.collect.Sets; import io.cocolabs.pz.zdoc.doc.ZomboidAPIDoc; import io.cocolabs.pz.zdoc.element.java.JavaClass; import io.cocolabs.pz.zdoc.element.java.JavaField; import io.cocolabs.pz.zdoc.element.mod.AccessModifierKey; import io.cocolabs.pz.zdoc.element.mod.MemberModifier; import io.cocolabs.pz.zdoc.element.mod.ModifierKey; import io.cocolabs.pz.zdoc.logger.Logger; public class FieldDetail extends Detail<JavaField> { public FieldDetail(ZomboidAPIDoc document) throws DetailParsingException { super("field.detail", document); } @Override protected List<JavaField> parse() { Elements detail = getDetail(); List<JavaField> result = new ArrayList<>(); for (Element blockList : detail) { Element header = blockList.getElementsByTag("h4").first(); String name = header != null ? header.text() : "unknown"; // parse field block comment StringBuilder commentBuilder = new StringBuilder(); Elements commentBlocks = blockList.getElementsByClass("block"); if (!commentBlocks.isEmpty()) { commentBuilder.append(commentBlocks.get(0).wholeText()); /* * normally there should only be one comment block per element * but check for additional blocks just to be on the safe side */ for (int i = 1; i < commentBlocks.size(); i++) { commentBuilder.append('\n').append(commentBlocks.get(i).text()); } } String fieldComment = commentBuilder.toString(); if (!fieldComment.isEmpty()) { Logger.debug("Parsed detail comment: \"" + result + "\""); } Signature signature; try { Element eSignature = blockList.getElementsByTag("pre").first(); if (eSignature == null) { throw new DetailParsingException("Unable to find field signature for field: " + name); } signature = new Signature(qualifyZomboidClassElements(eSignature), fieldComment); } catch (DetailParsingException e) { Logger.error(e.getMessage()); continue; } JavaClass type = TypeSignatureParser.parse(signature.type); if (type != null) { result.add(new JavaField(type, signature.name, signature.modifier, signature.comment)); } else Logger.detail(String.format("Excluding field (%s) from detail, " + "class %s does not exist", signature.toString(), signature.type)); } return result; } public @Nullable JavaField getEntry(String name) { return getEntries().stream().filter(e -> e.getName().equals(name)).findFirst().orElse(null); } @Override public Set<JavaField> getEntries(String name) { return Sets.newHashSet(getEntry(name)); } static class Signature extends DetailSignature { final MemberModifier modifier; final String type, name, comment; Signature(String signatureText, String detailComment) throws SignatureParsingException { super(signatureText); Logger.debug("Parsing field signature: " + signature); List<String> elements = Splitter.onPattern("\\s+").splitToList(signature); if (elements.size() < 2) { throw new SignatureParsingException(signature, "missing one or more elements"); } int index = 0; /* * parse signature access modifier (optional) */ AccessModifierKey access = AccessModifierKey.get(elements.get(0)); if (access != AccessModifierKey.DEFAULT) { index = 1; } /* * parse signature non-access modifier (optional) */ SetUniqueList<ModifierKey> modifierKeys = SetUniqueList.setUniqueList(new ArrayList<>()); for (; index < elements.size(); index++) { Collection<ModifierKey> foundKeys = ModifierKey.get(elements.get(index)); if (!foundKeys.contains(ModifierKey.UNDECLARED)) { modifierKeys.addAll(foundKeys); } else break; } if (modifierKeys.isEmpty()) { modifierKeys.add(ModifierKey.UNDECLARED); } this.modifier = new MemberModifier(access, modifierKeys); /* * parse signature type and name */ String[] data = new String[]{ "type", "name" }; for (int i = 0; i < data.length; i++, index++) { if (index < elements.size()) { data[i] = elements.get(index); } else throw new SignatureParsingException(signature, "missing element " + data[0]); } this.type = data[0]; this.name = data[1]; /* * parse signature comment (optional) */ String sComment = ""; if (index < elements.size()) { StringBuilder sb = new StringBuilder(); for (; index < elements.size(); index++) { sb.append(elements.get(index)).append(" "); } sb.deleteCharAt(sb.length() - 1); sComment = sb.toString(); } if (detailComment != null && !detailComment.isEmpty()) { sComment += !sComment.isEmpty() ? '\n' + detailComment : detailComment; } this.comment = sComment; } Signature(String signatureText) throws SignatureParsingException { this(signatureText, ""); } private Signature(Element element, String comment) throws SignatureParsingException { this(element.text(), comment); } } }
6,050
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
MalformedSignatureException.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/doc/detail/MalformedSignatureException.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.doc.detail; import org.apache.logging.log4j.Level; class MalformedSignatureException extends SignatureParsingException { MalformedSignatureException(String signature, String message) { super(String.format("Malformed signature \"%s\" (%s)", signature, message)); } @Override Level getLogLevel() { return Level.ERROR; } }
1,112
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
SignatureParser.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/doc/detail/SignatureParser.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.doc.detail; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.jetbrains.annotations.Nullable; import io.cocolabs.pz.zdoc.element.SignatureToken; import io.cocolabs.pz.zdoc.element.java.JavaClass; import io.cocolabs.pz.zdoc.logger.Logger; import io.cocolabs.pz.zdoc.util.ParseUtils; import io.cocolabs.pz.zdoc.util.Utils; abstract class SignatureParser<T extends SignatureToken> { final String signature; final StringBuilder builder; final AtomicInteger index; final List<T> result; SignatureParser(String signature, AtomicInteger index) { this.signature = signature; this.builder = new StringBuilder(); this.result = new ArrayList<>(); this.index = index; } SignatureParser(String signature) { this(signature, new AtomicInteger()); } static @Nullable JavaClass getClassForName(String name) { try { return new JavaClass(Utils.getClassForName(name)); } catch (ClassNotFoundException e) { Logger.debug("Failed to get class for name: " + name); } return null; } String flush() { return ParseUtils.flushStringBuilder(builder); } abstract List<T> parse() throws SignatureParsingException; }
1,977
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
SignatureParsingException.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/doc/detail/SignatureParsingException.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.doc.detail; import org.apache.logging.log4j.Level; import io.cocolabs.pz.zdoc.logger.Logger; class SignatureParsingException extends DetailParsingException { SignatureParsingException(String signature, String message) { super(String.format("Failed to parse signature \"%s\" (%s)", signature, message)); } SignatureParsingException(String message) { super(message); } Level getLogLevel() { return Logger.VERBOSE; } }
1,213
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
DetailParsingException.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/doc/detail/DetailParsingException.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.doc.detail; public class DetailParsingException extends Exception { DetailParsingException(String message) { super(message); } DetailParsingException(Detail<?> detail, String message) { this(String.format("Failed to parse detail \"%s\". %s", detail.name, message)); } }
1,060
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
TypeSignatureParser.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/doc/detail/TypeSignatureParser.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.doc.detail; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.jetbrains.annotations.Nullable; import io.cocolabs.pz.zdoc.element.java.JavaClass; class TypeSignatureParser extends SignatureParser<JavaClass> { private TypeSignatureParser(String signature) { super(signature); } TypeSignatureParser(String signature, AtomicInteger index) { super(signature, index); } static @Nullable JavaClass parse(String signature) { List<JavaClass> result = new TypeSignatureParser(signature).parse(); return !result.isEmpty() ? result.get(0) : null; } @Override List<JavaClass> parse() { char[] charArray = signature.toCharArray(); for (; index.get() < charArray.length; index.getAndIncrement()) { char c = charArray[index.get()]; if (c == '<') { index.incrementAndGet(); String className = flush(); JavaClass type = getClassForName(className); List<JavaClass> params = new TypeSignatureParser(signature, index).parse(); result.add(type != null ? new JavaClass(type.getClazz(), params) : null); } else if (c == ',') { flushToResult(); } else if (c == '>') { return flushToResult(); } else if (c != ' ') { builder.append(c); } } if (result.isEmpty() && builder.length() > 0) { result.add(getClassForName(builder.toString())); } return result; } private List<JavaClass> flushToResult() { String name = flush(); if (!name.isEmpty()) { result.add(getClassForName(name)); } return result; } }
2,307
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
Command.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/cmd/Command.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.cmd; import java.util.Arrays; import java.util.stream.Collectors; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.jetbrains.annotations.Nullable; /** * All available application commands. */ @SuppressWarnings("ImmutableEnumChecker") public enum Command { HELP("help", "", new Options(), "print command usage info"), VERSION("version", new Options(), "prints game installation version"), ANNOTATE("annotate", CommandOptions.LUA_OPTIONS, "annotate vanilla Lua with EmmyLua"), COMPILE("compile", CommandOptions.JAVA_OPTIONS, "compile Lua library from modding API"); static { /* Add options (used only to print help) from static context to * help command since enums are not fully instantiated yet */ Arrays.stream(Command.values()).filter(c -> c != Command.HELP).collect(Collectors.toSet()) .forEach(c -> HELP.options.addOption(Option.builder(c.name).desc(c.help).build())); } /** Used to parse the command from application arguments. */ final String name; /** Optional used to prefix printed commands in help context. */ final String prefix; /** Possible options for this command. */ final Options options; /** Command description printed with help command. */ final String help; Command(String name, String prefix, Options options, String help) { this.name = name; this.prefix = prefix; this.options = options; this.help = help; } Command(String name, Options options, String help) { this(name, HelpFormatter.DEFAULT_OPT_PREFIX, options, help); } /** * Returns command that matches the given name. */ public static @Nullable Command get(String name) { for (Command value : Command.values()) { if (value.name.equals(name)) { return value; } } return null; } /** * Returns command that matches first array element. * * @return first array element or {@code null} if no matching command was found. * * @throws IllegalArgumentException if argument array is empty. */ public static @Nullable Command parse(String[] args) { if (args.length > 0) { return get(args[0]); } throw new IllegalArgumentException("Unable to parse command, argument array is empty."); } /** * Returns command that matches first array element. * * @param fromIndex index to reference the first element from. * @return first array element or {@code null} if no matching command was found. * * @throws IllegalArgumentException if argument array is empty. * @see #parse(String[]) */ public static @Nullable Command parse(String[] args, int fromIndex) { if (args.length > fromIndex) { return get(args[fromIndex]); } throw new IllegalArgumentException(String.format("Unable to parse command from array, " + "index %d is out of bounds for array size %d", fromIndex, args.length)); } public String getName() { return name; } public Options getOptions() { return options; } }
3,752
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
CommandOptions.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/cmd/CommandOptions.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.cmd; import java.io.File; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; final class CommandOptions { static final Option INPUT_OPTION = Option.builder("i").longOpt("input-path").desc("input directory path") .type(File.class).required(true).hasArg().argName("path") .valueSeparator(' ').build(); static final Option OUTPUT_OPTION = Option.builder("o").longOpt("output-path").desc("output directory path") .type(File.class).required(true).hasArg().argName("path") .valueSeparator(' ').build(); static final Option EXCLUDE_CLASS_OPTION = Option.builder("e").longOpt("exclude-class") .desc("list of classes (separated by commas) " + "to exclude classes from document generation") .required(false).hasArg().argName("list").valueSeparator(' ').build(); static final Option ONLY_ANNOTATED_OPTION = Option.builder("s").longOpt("only-annotated") .desc("only include classes that were annotated") .required(false).build(); static final Options LUA_OPTIONS = new Options(); static final Options JAVA_OPTIONS = new Options(); static { LUA_OPTIONS.addOption(clone(INPUT_OPTION)) .addOption(clone(OUTPUT_OPTION)) .addOption(clone(EXCLUDE_CLASS_OPTION)) .addOption(ONLY_ANNOTATED_OPTION); JAVA_OPTIONS.addOption(clone(INPUT_OPTION)) .addOption(clone(OUTPUT_OPTION)) .addOption(EXCLUDE_CLASS_OPTION); } private static Option clone(Option option) { return (Option) option.clone(); } }
2,285
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
CommandParser.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/cmd/CommandParser.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.cmd; import java.util.Properties; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; class CommandParser extends DefaultParser { @Override public CommandLine parse(Options options, String[] arguments) throws ParseException { return new CommandLine(super.parse(options, arguments)); } @Override public CommandLine parse(Options options, String[] arguments, boolean stopAtNonOption) throws ParseException { return new CommandLine(super.parse(options, arguments, stopAtNonOption)); } @Override public CommandLine parse(Options options, String[] arguments, Properties properties) throws ParseException { return new CommandLine(super.parse(options, arguments, properties)); } @Override public CommandLine parse(Options options, String[] arguments, Properties properties, boolean stopAtNonOption) throws ParseException { return new CommandLine(super.parse(options, arguments, properties, stopAtNonOption)); } }
1,798
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
CommandLine.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/cmd/CommandLine.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.cmd; import java.io.BufferedWriter; import java.io.File; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.jetbrains.annotations.Nullable; import com.google.common.collect.Sets; import io.cocolabs.pz.zdoc.compile.LuaAnnotator; /** * Apache Commons {@code CommandLine} wrapper providing additional methods. */ public class CommandLine extends org.apache.commons.cli.CommandLine { /** Used to parse application arguments to find command options. */ private static final CommandParser PARSER = new CommandParser(); CommandLine(org.apache.commons.cli.CommandLine cmdLine) { Arrays.stream(cmdLine.getOptions()).forEach(this::addOption); Arrays.stream(cmdLine.getArgs()).forEach(this::addArg); } public static CommandLine parse(Options options, String[] args) throws ParseException { return PARSER.parse(options, args); } /** * Prints help text for the given {@code Command}. * * @see HelpFormatter#printHelp(String cmdLineSyntax, String header, * Options options, String footer, boolean autoUsage) HelpFormatter.printHelp(...) */ public static void printHelp(Command command) { HelpFormatter formatter = new HelpFormatter(); formatter.setOptPrefix(command.prefix); formatter.printHelp(command.name, command.help, command.options, "", true); } /** * Prints help text for the given array of commands. * * @see HelpFormatter#printHelp(PrintWriter pw, int width, String cmdLineSyntax, String header, * Options options, int leftPad, int descPad, String footer, boolean autoUsage) * HelpFormatter.printHelp(...) */ public static void printHelp(Command[] commands) { //noinspection UseOfSystemOutOrSystemErr OutputStreamWriter osw = new OutputStreamWriter(System.out, StandardCharsets.UTF_8); try (PrintWriter pw = new PrintWriter(new BufferedWriter(osw))) { pw.println("See 'help <command>' to read about a specific command"); for (Command command : commands) { HelpFormatter ft = new HelpFormatter(); ft.setOptPrefix(command.prefix); pw.println(); ft.printHelp(pw, ft.getWidth(), command.name, command.help, command.options, ft.getLeftPadding(), ft.getDescPadding(), "", true); } pw.flush(); } } /** * Return {@code true} if {@link Command#ANNOTATE} should include only lua classes that were * successfully annotated by {@link LuaAnnotator LuaAnnotator}. */ public boolean includeOnlyAnnotated() { return hasOption(CommandOptions.ONLY_ANNOTATED_OPTION.getOpt()); } /** * Returns class names to exclude from compilation process. * * @return {@code Set} of class names specified in command options to exclude from * compilation process or an empty list if exclude option has not been set. * * @see CommandOptions#EXCLUDE_CLASS_OPTION */ public Set<String> getExcludedClasses() { Option excludeOpt = CommandOptions.EXCLUDE_CLASS_OPTION; if (hasOption(excludeOpt.getOpt())) { String value = getParsedValue(excludeOpt, String.class); return Sets.newHashSet(value.split(",")); } return new HashSet<>(); } /** * Returns input path specified in command options. */ public Path getInputPath() { return getParsedValue(CommandOptions.INPUT_OPTION, File.class).toPath(); } /** * Returns command operation output path. * * @return output path specified in command options or {@code null} if * output command option was not specified. */ public @Nullable Path getOutputPath() { File outputFile = getParsedValue(CommandOptions.OUTPUT_OPTION, File.class); return outputFile != null ? outputFile.toPath() : null; } @SuppressWarnings("unchecked") private <T> T getParsedValue(Option option, Class<T> type) throws IllegalArgumentException { String sOption = option.getOpt(); try { return type.cast(getParsedOptionValue(sOption)); } catch (ParseException | ClassCastException e) { throw new IllegalArgumentException(String.format("An error occurred while " + "parsing option value for option \"%s\"", getOptionValue(sOption))); } } }
5,149
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
ICompiler.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/compile/ICompiler.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.compile; import java.util.Set; import io.cocolabs.pz.zdoc.doc.ZomboidDoc; interface ICompiler<T extends ZomboidDoc> { /** * Compile code represented by {@code ZomboidDoc} documents. * * @return {@code Set} of compiled documents. * * @throws CompilerException if an error occurred during compilation. */ Set<T> compile() throws CompilerException; }
1,145
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
LuaAnnotator.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/compile/LuaAnnotator.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.compile; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; import io.cocolabs.pz.zdoc.Main; import io.cocolabs.pz.zdoc.element.lua.LuaClass; import io.cocolabs.pz.zdoc.lang.lua.EmmyLuaClass; import io.cocolabs.pz.zdoc.logger.Logger; import io.cocolabs.pz.zdoc.util.ParseUtils; public class LuaAnnotator { /** * <p>Matches a line containing lua table declaration.</p> * <p>There are two capturing group that matches the table name and declaration type.</p> * <blockquote> * <p>Capturing groups: * <ul> * <li>group 1<sup>?</sup>: line indentation</li> * <li>group 2<sup>+</sup>: table name</li> * <li>group 3<sup>?</sup>: parent type name</li> * <li>group 4<sup>?</sup>: declaration type <i>(new or derive)</i></li> * </ul> * </p> * <p>Example: * <pre> * String table1 = "NewTestTable = ISTestTable:new(\"TestTable\")"; * String table2 = "DerivedTestTable = ISTestTable:derive(\"TestTable\")"; * String table3 = "DeclaredTestTable = {}"; * Matcher matcher = ZomboidLuaDoc.LUA_TABLE_DECLARATION.matcher(table1); * assert matcher.find() {@code &&} matcher.group(2).equals("NewTestTable"); * assert matcher.group(3).equals("ISTestTable") {@code &&} matcher.group(4).equals("new"); * matcher = ZomboidLuaDoc.LUA_TABLE_DECLARATION.matcher(table2); * assert matcher.find() {@code &&} matcher.group(2).equals("DerivedTestTable"); * assert matcher.group(3).equals("ISTestTable") {@code &&} matcher.group(4).equals("derive"); * matcher = ZomboidLuaDoc.LUA_TABLE_DECLARATION.matcher(table3); * assert matcher.find() && matcher.group(2).equals("DeclaredTestTable"); * assert matcher.group(3) == null && matcher.group(4) == null * </pre> * </p> * </blockquote> */ static final Pattern LUA_TABLE_DECLARATION = Pattern.compile( "^(\\s+)?(\\w+)\\s*=(?:\\s*([^\\s]+):(new|derive)\\(|.*\\s*).*$" ); /** * <p>Annotate Lua class representing the given file with {@link EmmyLuaClass} annotations. * The method reads the file line by line and searches for a table declaration that matches * the name of the given file and annotates it with an {@code EmmyLuaClass} annotation by * inserting it one line above the declaration line. The entire content of the file * alongside the annotation line is copied in returned {@code List}.</p> * <p>This process is further defined with {@code AnnotateRules}:</p> * <ul> * <li>If {@code AnnotateRules} specifies inclusion rules for this file, the file is parsed * until finding all matching table entries defined as rule property values. * See <a href="../doc/ZomboidLuaDoc.AnnotateRules.html#include">Inclusion rules</a>. * </li> * <li>The file will <b>not</b> be annotated if the table name is contained in the * {@code Set} of excluded classes in {@code AnnotateRules}, otherwise the {@code Set} will * be mutated to include the matched table name to make it more convenient when working in loops. * See <a href="../doc/ZomboidLuaDoc.AnnotateRules.html#exclude">Exclusion rules</a>. * </li> * </ul> * * @param file {@code File} to annotate the class for. * @param content {@code List} to copy the annotated contents of given {@code File} line by line. * Since the list is mutated in the annotation process, passing an <i>immutable</i> list * implementation would throw an {@code UnsupportedOperationException}. * @param rules rules to apply in the annotation process. * @return {@code AnnotateResult} specifying the result of annotation process. * * @throws FileNotFoundException if the given {@code File} does not exist. * @throws IOException if an I/O exception was thrown while reading file. * @throws UnsupportedOperationException if content {@code List} or exclusion rules {@code Set} * is an immutable {@code Collection} implementation. */ public static AnnotateResult annotate(File file, List<String> content, AnnotateRules rules) throws IOException { if (!file.exists()) { throw new FileNotFoundException(file.getPath()); } List<String> input = FileUtils.readLines(file, Main.CHARSET); if (input.size() == 0) { return AnnotateResult.SKIPPED_FILE_EMPTY; } Set<String> include = new HashSet<>(); String tableName = FilenameUtils.removeExtension(file.getName()); String includeValue = (String) rules.include.get(tableName); /* * include rules are intended to override inferred main table, * either use the supplied list of rules or table name */ if (includeValue != null) { if (!StringUtils.isBlank(includeValue)) { include.addAll(Arrays.asList(includeValue.split(","))); } // if property value is blank the file is meant to be ignored else return AnnotateResult.SKIPPED_FILE_IGNORED; } else include.add(tableName); final int includeCountMax = include.size(); int includeCount = 0, excludeCount = 0; boolean foundNonBlankLine = false; // true if file is not empty for (int i = 0; i < input.size(); i++) { String line = input.get(i); if (StringUtils.isBlank(line)) { content.add(line); continue; } /* evaluate if file content is consistent of only blank lines, * this could be done in stream but would be inefficient to * deal with streams and iterate over file content twice */ else if (!foundNonBlankLine) { foundNonBlankLine = true; } /* * skip regex matching if all elements were already annotated, * just continue copying file content to list */ if (!include.isEmpty()) { Matcher match = LUA_TABLE_DECLARATION.matcher(line); if (match.find()) { String matchedName = match.group(2); if (include.contains(matchedName)) { LuaClass luaClass = new LuaClass(matchedName, match.group(3)); if (!rules.exclude.contains(luaClass.getName())) { // make sure we are not on the first line if (i > 0 && EmmyLuaClass.isAnnotation(input.get(i - 1))) { content.remove(i - 1); } /* take indentation in consideration just in case * the table declaration is indented (should not normally be the case) */ String indentation = ParseUtils.getOptionalMatchedGroup(match, 1); content.add(indentation + luaClass.getAnnotations().get(0)); rules.exclude.add(luaClass.getName()); include.remove(matchedName); includeCount += 1; } else excludeCount += 1; } } } content.add(line); } Logger.debug(String.format("Annotation process finished - " + "included (%d/%d), excluded %d", includeCount, includeCountMax, excludeCount) ); if (!foundNonBlankLine) { return AnnotateResult.SKIPPED_FILE_EMPTY; } else if (excludeCount == includeCountMax) { return AnnotateResult.ALL_EXCLUDED; } else if (includeCount == includeCountMax) { return AnnotateResult.ALL_INCLUDED; } else if (excludeCount == 0 && includeCount == 0) { return AnnotateResult.NO_MATCH; } else return AnnotateResult.PARTIAL_INCLUSION; } /** * Annotate Lua class representing the given file with {@link EmmyLuaClass} annotation. * * @param file {@code File} to annotate the class for. * @param content {@code List} to copy the annotated contents of given {@code File} line by line. * @return {@code AnnotateResult} specifying the result of annotation process. * * @throws FileNotFoundException if the given {@code File} does not exist. * @throws IOException if an I/O exception was thrown while reading file. * @see #annotate(File, List, AnnotateRules) */ static AnnotateResult annotate(File file, List<String> content) throws IOException { return LuaAnnotator.annotate(file, content, new AnnotateRules()); } public enum AnnotateResult { /** Indicates that annotation process was skipped because target file was empty. */ SKIPPED_FILE_EMPTY, /** Indicated that annotation process was skipped because target file is ignored. */ SKIPPED_FILE_IGNORED, /** Indicates that all annotation elements were excluded. */ ALL_EXCLUDED, /** Indicates that all annotation elements were included. */ ALL_INCLUDED, /** Indicates that some elements were excluded. */ PARTIAL_INCLUSION, /** Indicates that no elements were matched. */ NO_MATCH } /** * This class represents annotation process rules. * <h3><a id="include">Include entries</a></h3> * {@code Properties} that hold inclusion rules for annotation process. * <ul> * <li>Left-hand side (key) represents filenames.</li> * <li>Right-hand side (value) represents class names to include. * <ul> * <li>Side accepts single and multiple name entries.</li> * <li>Multiple entries are separated with comma delimiter.</li> * <li>Blank entry instructs the process to skip the entry.</li> * </ul></li> * </ul> * <h2><a id="exclude">Exclude entries</a></h2> * <p>{@code Set} that holds exclusion rules for annotation process.</p> * <ul> * <li>Entries here represent class names to exclude.</li> * <li>{@code Set} is mutated in the annotation process so initializing this variable * with an Immutable {@code Set} will result in a {@code UnsupportedOperationsException}. * </li> * </ul> * * @see #annotate(File, List, AnnotateRules) */ public static class AnnotateRules { private final Properties include; private final Set<String> exclude; public AnnotateRules(Properties include, Set<String> exclude) { this.include = include; this.exclude = exclude; } AnnotateRules(Properties include) { this(include, new HashSet<>()); } AnnotateRules(Set<String> exclude) { this(new Properties(), exclude); } AnnotateRules() { this.include = new Properties(); this.exclude = new HashSet<>(); } } }
10,777
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
JavaCompiler.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/compile/JavaCompiler.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.compile; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.nio.file.Paths; import java.util.*; import org.apache.commons.collections4.PredicateUtils; import org.apache.commons.collections4.list.PredicatedList; import org.apache.commons.collections4.set.PredicatedSet; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.reflect.ConstructorUtils; import org.apache.commons.lang3.reflect.FieldUtils; import org.apache.commons.lang3.reflect.MethodUtils; import org.apache.logging.log4j.util.Strings; import org.jetbrains.annotations.Nullable; import io.cocolabs.pz.zdoc.Main; import io.cocolabs.pz.zdoc.doc.ZomboidAPIDoc; import io.cocolabs.pz.zdoc.doc.ZomboidJavaDoc; import io.cocolabs.pz.zdoc.doc.detail.DetailParsingException; import io.cocolabs.pz.zdoc.doc.detail.FieldDetail; import io.cocolabs.pz.zdoc.doc.detail.MethodDetail; import io.cocolabs.pz.zdoc.element.java.JavaClass; import io.cocolabs.pz.zdoc.element.java.JavaField; import io.cocolabs.pz.zdoc.element.java.JavaMethod; import io.cocolabs.pz.zdoc.element.mod.MemberModifier; import io.cocolabs.pz.zdoc.logger.Logger; import io.cocolabs.pz.zdoc.util.Utils; public class JavaCompiler implements ICompiler<ZomboidJavaDoc> { public static final String GLOBAL_OBJECT_CLASS = "zombie.Lua.LuaManager.GlobalObject"; private static final File SERIALIZE_LUA = new File("serialize.lua"); private final Properties localClassProperties; private final Set<Class<?>> exposedJavaClasses; private final Set<String> excludedClasses; public JavaCompiler(Set<String> excludedClasses) throws CompilerException { try { // these properties values will override local class paths localClassProperties = Utils.getProperties("javaclass.properties"); /* * serialize.lua file is required by J2SEPlatform when setting up environment, * it is searched in project root directory and it will not be available there * when running from IDE, so we have to make it available for runtime session */ Logger.debug("Initializing JavaCompiler..."); if (!SERIALIZE_LUA.exists()) { Logger.debug("Did not find serialize.lua file in root directory"); try (InputStream iStream = Main.CLASS_LOADER.getResourceAsStream(SERIALIZE_LUA.getPath())) { if (iStream == null) { throw new IllegalStateException("Unable to find serialize.lua file"); } Logger.debug("Copying serialize.lua file to root directory"); FileUtils.copyToFile(iStream, SERIALIZE_LUA); if (!SERIALIZE_LUA.exists()) { throw new IOException("Unable to copy serialize.lua to root directory"); } } } exposedJavaClasses = Collections.unmodifiableSet(getExposedJava()); /* * delete serialize.lua file, we don't need it anymore, * use deleteOnExit() only as a last resort if we can't delete right now */ if (!SERIALIZE_LUA.delete()) { Logger.warn("Unable to delete serialize.lua, deleting on JVM exit"); SERIALIZE_LUA.deleteOnExit(); } } catch (IOException e) { throw new RuntimeException(e); } catch (ReflectiveOperationException e) { throw new CompilerException("Error occurred while reading exposed java", e); } this.excludedClasses = excludedClasses; } static List<JavaField> compileJavaFields(Class<?> clazz, @Nullable ZomboidAPIDoc doc) throws DetailParsingException { Logger.debug("Start compiling java fields for " + clazz.getName()); List<JavaField> result = PredicatedList.predicatedList( new ArrayList<>(), PredicateUtils.notNullPredicate() ); FieldDetail fieldDetail = doc != null ? new FieldDetail(doc) : null; for (Field field : clazz.getDeclaredFields()) { String fieldName = field.getName(); Logger.debug("Start compiling field %s...", fieldName); // synthetic fields are generated by compiler for internal purposes if (field.isSynthetic()) { continue; } int typeParamCount = field.getType().getTypeParameters().length; /* * if the field is a parameterized type we are not going to be able * to determine the exact type due to runtime erasure, so try to * use the field data from online API page if possible */ Logger.debug("Field has %d type parameters", typeParamCount); JavaClass jField = new JavaClass(field.getType()); if (doc != null) { Logger.debug("Searching for field in document %s", doc.getName()); JavaField docField = fieldDetail.getEntry(field.getName()); if (docField != null) { /* extra care has to be taken to ensure that we are dealing with exactly * the same object since API documentation is often out of date */ Logger.debug("Found mathing detail field entry with name %s", docField.getName()); if (docField.getType().equals(jField, true)) { /* matching field was found, use field data pulled from API page * with written type parameters instead of declared field */ result.add(docField); continue; } else Logger.debug("Detail entry (%s) did not match field", docField.getType()); } String format = "Didn't find matching field \"%s\" in document \"%s\""; Logger.detail(String.format(format, field.getName(), doc.getName())); } /* when no matching field or API page was found, construct new JavaField * with same properties as declared field but make parameterized types null */ MemberModifier modifier = new MemberModifier(field.getModifiers()); result.add(new JavaField(jField, field.getName(), modifier)); } Logger.debug("Finished compiling %d fields", result.size()); return result; } static Set<JavaMethod> compileJavaMethods(Class<?> clazz, @Nullable ZomboidAPIDoc doc) throws DetailParsingException { Logger.debug("Start compiling java methods for " + clazz.getName()); Set<JavaMethod> result = PredicatedSet.predicatedSet( new HashSet<>(), PredicateUtils.notNullPredicate() ); MethodDetail methodDetail = doc != null ? new MethodDetail(doc) : null; for (Method method : clazz.getDeclaredMethods()) { String methodName = method.getName(); Logger.debug("Start compiling method %s...", methodName); // synthetic methods are generated by compiler for internal purposes if (method.isSynthetic()) { Logger.debug("Found synthetic method, will not compile"); continue; } JavaMethod jMethod = new JavaMethod(method); if (doc != null) { Logger.debug("Searching for method in document %s", doc.getName()); JavaMethod matchedMethod = null; Set<JavaMethod> methodEntries = methodDetail.getEntries(method.getName()); Iterator<JavaMethod> iterator = methodEntries.iterator(); while (matchedMethod == null && iterator.hasNext()) { JavaMethod entry = iterator.next(); if (entry.equals(jMethod, true)) { matchedMethod = entry; } } if (matchedMethod != null) { result.add(matchedMethod); continue; } String format = "Didn't find matching method \"%s\" in document \"%s\""; Logger.detail(String.format(format, methodName, doc.getName())); } else Logger.debug("Constructing method from JavaMethod instance"); result.add(jMethod); } Logger.debug("Finished compiling %d methods", result.size()); return result; } /** * Initialize {@code LuaManager} and return a set of exposed Java classes. * * @return a set of exposed Java classes. * * @throws RuntimeException if the private field ({@code LuaManager.Exposer#exposed}) * holding the set of exposed Java classes could not be found. */ @SuppressWarnings("unchecked") static HashSet<Class<?>> getExposedJava() throws ReflectiveOperationException { /* use exclusively reflection to define classes and interact * with class objects to allow CI workflow to compile project */ Logger.debug("Reading exposed java classes..."); Class<?> luaManager = Utils.getClassForName("zombie.Lua.LuaManager"); Class<?> zombieCore = Utils.getClassForName("zombie.core.Core"); Class<?> j2SEPlatform = Utils.getClassForName("se.krka.kahlua.j2se.J2SEPlatform"); Class<?> kahluaConverterManager = Utils.getClassForName( "se.krka.kahlua.converter.KahluaConverterManager" ); Class<?> kahluaPlatform = Utils.getClassForName("se.krka.kahlua.vm.Platform"); Class<?> kahluaTable = Utils.getClassForName("se.krka.kahlua.vm.KahluaTable"); Class<?> exposerClass = Arrays.stream(luaManager.getDeclaredClasses()) .filter(c -> c.getName().equals("zombie.Lua.LuaManager$Exposer")) .findFirst().orElseThrow(ClassNotFoundException::new); Object platform = ConstructorUtils.invokeConstructor(j2SEPlatform); Method newEnvironment = j2SEPlatform.getDeclaredMethod("newEnvironment"); Constructor<?> constructor = exposerClass.getDeclaredConstructor( kahluaConverterManager, // se.krka.kahlua.converter.KahluaConverterManager kahluaPlatform, // se.krka.kahlua.vm.Platform kahluaTable // se.krka.kahlua.vm.KahluaTable ); constructor.setAccessible(true); Object exposer = constructor.newInstance( ConstructorUtils.invokeConstructor(kahluaConverterManager), j2SEPlatform.cast(platform), newEnvironment.invoke(platform) ); Method exposeAll = MethodUtils.getMatchingMethod(exposerClass, "exposeAll"); exposeAll.setAccessible(true); try { Field dDebug = zombieCore.getDeclaredField("bDebug"); FieldUtils.writeStaticField(dDebug, true); exposeAll.invoke(exposer); } catch (InvocationTargetException e) { // this is expected } HashSet<Class<?>> result = (HashSet<Class<?>>) FieldUtils.readDeclaredField( exposer, "exposed", true ); // class containing global exposed methods Logger.debug("Including global methods from %s", GLOBAL_OBJECT_CLASS); result.add(Utils.getClassForName(GLOBAL_OBJECT_CLASS)); return result; } @Override public Set<ZomboidJavaDoc> compile() { Logger.info("Start compiling java classes..."); Set<ZomboidJavaDoc> result = new HashSet<>(); for (Class<?> exposedClass : exposedJavaClasses) { String exposedClassName = exposedClass.getName(); if (excludedClasses.removeIf(ec -> ec.equals(exposedClassName))) { Logger.detail("Excluding exposed class %s", exposedClassName); continue; } Logger.info("Compiling exposed class %s...", exposedClassName); String classPath = JavaClass.getPathForClass(exposedClass); String localClassPath = (String) localClassProperties.get(classPath); boolean expectMissingApiPage = false; // path values defined in properties override class path if (localClassPath != null) { if (Strings.isNotBlank(localClassPath)) { classPath = localClassPath; } else expectMissingApiPage = true; } if (!classPath.isEmpty()) { @Nullable ZomboidAPIDoc document = null; try { // do not try to get zomboid documentation for JDK classes if (!classPath.startsWith("java/")) { Logger.debug(String.format("Getting API page for class \"%s\"", classPath)); document = ZomboidAPIDoc.getPage(Paths.get(classPath)); if (document == null) { if (!expectMissingApiPage) { Logger.warn(String.format("Unable to find API page for path %s", classPath)); } } else if (expectMissingApiPage) { Logger.warn(String.format("Expected to find missing API page for path %s", classPath)); } } } catch (IOException e) { String msg = "Error occurred while getting API page for path %s"; Logger.error(String.format(msg, classPath), e); } JavaClass javaClass = new JavaClass(exposedClass); List<JavaField> javaFields; try { javaFields = compileJavaFields(exposedClass, document); } catch (DetailParsingException e) { String msg = "Error occurred while compiling java fields for document %s"; Logger.error(String.format(msg, Objects.requireNonNull(document).getName()), e); continue; } Set<JavaMethod> javaMethods; try { javaMethods = compileJavaMethods(exposedClass, document); } catch (DetailParsingException e) { String msg = "Error occurred while compiling java methods for document %s"; Logger.error(String.format(msg, Objects.requireNonNull(document).getName()), e); continue; } result.add(new ZomboidJavaDoc(javaClass, javaFields, javaMethods)); Logger.detail("Compiled java class %s with %d fields and %d methods", exposedClassName, javaFields.size(), javaMethods.size()); } else Logger.error(String.format("Unable to find path for Java class \"%s\", " + "might be an internal class.", exposedClass.getName())); } Logger.info("Finished compiling %d/%d java classes", result.size(), exposedJavaClasses.size()); return result; } }
13,734
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
LuaCompiler.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/compile/LuaCompiler.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.compile; import java.util.*; import org.apache.commons.collections4.PredicateUtils; import org.apache.commons.collections4.set.PredicatedSet; import org.jetbrains.annotations.UnmodifiableView; import com.google.common.base.Splitter; import io.cocolabs.pz.zdoc.doc.ZomboidJavaDoc; import io.cocolabs.pz.zdoc.doc.ZomboidLuaDoc; import io.cocolabs.pz.zdoc.element.IClass; import io.cocolabs.pz.zdoc.element.IField; import io.cocolabs.pz.zdoc.element.IParameter; import io.cocolabs.pz.zdoc.element.java.JavaClass; import io.cocolabs.pz.zdoc.element.java.JavaMethod; import io.cocolabs.pz.zdoc.element.lua.*; import io.cocolabs.pz.zdoc.logger.Logger; public class LuaCompiler implements ICompiler<ZomboidLuaDoc> { private static final Map<String, LuaClass> GLOBAL_CLASSES = new HashMap<>(); private static final Map<String, LuaClass> CACHED_CLASSES = new HashMap<>(); private static final Map<String, LuaClass> GLOBAL_TYPES = new HashMap<>(); private static final Map<String, LuaType> CACHED_TYPES = new HashMap<>(); private final @UnmodifiableView Set<ZomboidJavaDoc> javaDocs; public LuaCompiler(Set<ZomboidJavaDoc> javaDocs) { this.javaDocs = Collections.unmodifiableSet(javaDocs); } private static LuaType resolveLuaType(IClass iClass) throws CompilerException { List<LuaType> otherTypes = new ArrayList<>(); for (IClass typeParam : iClass.getTypeParameters()) { String typeName = "Unknown"; if (typeParam != null) { String paramName = typeParam.getName(); LuaType cachedType = CACHED_TYPES.get(paramName); if (cachedType == null) { LuaClass globalClass = GLOBAL_CLASSES.get(paramName); if (globalClass == null) { typeName = resolveClassName(paramName); registerGlobalType(typeParam, typeName); } else typeName = cacheType(typeParam, globalClass.getName()).getName(); } else typeName = cachedType.getName(); } otherTypes.add(new LuaType(typeName)); } String luaType, className = iClass.getName(); LuaType cachedType = CACHED_TYPES.get(className); if (cachedType == null) { LuaClass globalClass = GLOBAL_CLASSES.get(className); if (globalClass == null) { luaType = resolveClassName(className); registerGlobalType(iClass, luaType); } else luaType = cacheType(iClass, globalClass.getName()).getName(); } else luaType = cachedType.getName(); return new LuaType(luaType, otherTypes); } private static LuaType cacheType(IClass clazz, String type) { LuaType result = new LuaType(type); CACHED_TYPES.put(clazz.getName(), result); Logger.debug("Caching lua type (class: %s, type: %s)", clazz.getName(), type); return result; } private static void registerGlobalType(IClass clazz, String type) throws CompilerException { LuaCompiler.cacheType(clazz, type); LuaClass globalTypeLuaClass; Class<?> typeClass = ((JavaClass) clazz).getClazz(); if (typeClass.isArray()) { typeClass = typeClass.getComponentType(); String typeName = typeClass.getTypeName(); // don't register if already registered if (isRegisteredGlobal(typeName)) { return; } String className = resolveClassName(typeName).replaceAll("\\[]", ""); String typeClassName = typeClass.getCanonicalName().replaceAll("\\[]", ""); LuaClass luaClass = new LuaClass(className, typeClassName); type = luaClass.getName(); globalTypeLuaClass = luaClass; } else globalTypeLuaClass = new LuaClass(type, typeClass.getCanonicalName()); GLOBAL_TYPES.put(type, globalTypeLuaClass); Logger.debug("Registering global lua type (key: %s, value: %s", type, globalTypeLuaClass); } private static LuaClass resolveLuaClass(String name) throws CompilerException { LuaClass cachedClass = CACHED_CLASSES.get(name); if (cachedClass == null) { String parentType = name.replace('$', '.'); LuaClass result = new LuaClass(resolveClassName(name), parentType); GLOBAL_CLASSES.put(result.getName(), result); Logger.debug("Caching global class (key: %s, value: %s)", result.getName(), result); CACHED_CLASSES.put(name, result); Logger.debug("Caching class (key: %s, value: %s)", name, result); CACHED_TYPES.put(name, new LuaType(result.getName())); Logger.debug("Caching lua type (class: %s, type: %s)", name, result); return result; } else return cachedClass; } private static String resolveClassName(String signature) throws CompilerException { Logger.debug("Resolving class name for signature %s", signature); List<String> packages = Splitter.on('.').splitToList(signature); if (packages.size() > 1) { char[] cName = packages.get(packages.size() - 1).toCharArray(); StringBuilder sb = new StringBuilder(); for (char c : cName) { sb.append(c == '$' ? '.' : c); } String result = sb.toString(); if (isRegisteredGlobal(result)) { String globalClass = result; for (int i = packages.size() - 2; i >= 0 && isRegisteredGlobal(result); i--) { result = packages.get(i) + '_' + result; } Logger.debug("Resolved class name as %s to avoid conflict with global class %s", result, globalClass); if (isRegisteredGlobal(result)) { String msg = "Unexpected class name (%s) duplicate detected!"; throw new CompilerException(String.format(msg, result)); } } return result; } // class does not reside in a package else return signature; } private static boolean isRegisteredGlobal(String name) { return GLOBAL_CLASSES.containsKey(name); } public static @UnmodifiableView Set<LuaClass> getGlobalTypes() { Set<LuaClass> result = new HashSet<>(); /* * filter out types that are already defined as global classes, * they have their own declaration in dedicated files */ for (Map.Entry<String, LuaClass> entry : GLOBAL_TYPES.entrySet()) { if (!GLOBAL_CLASSES.containsKey(entry.getKey())) { result.add(entry.getValue()); } } /* represents ? parameter type * since EmmyLua does not have a good format for notating parameterized types * this is the best way we can note an unknown parameter type */ result.add(new LuaClass("Unknown")); return Collections.unmodifiableSet(result); } @Override public Set<ZomboidLuaDoc> compile() throws CompilerException { Logger.info("Start compiling lua classes..."); Set<ZomboidLuaDoc> result = PredicatedSet.predicatedSet( new HashSet<>(), PredicateUtils.notNullPredicate() ); for (ZomboidJavaDoc javaDoc : javaDocs) { LuaClass luaClass = resolveLuaClass(javaDoc.getName()); Logger.debug("Compiling lua class %s...", luaClass.getName()); List<LuaField> luaFields = new ArrayList<>(); for (IField field : javaDoc.getFields()) { LuaType fieldType = resolveLuaType(field.getType()); luaFields.add(new LuaField(fieldType, field.getName(), field.getModifier(), field.getComment())); Logger.debug("Compiled field %s", field.getName()); } Set<LuaMethod> luaMethods = new HashSet<>(); for (JavaMethod method : javaDoc.getMethods()) { List<LuaParameter> parameters = new ArrayList<>(); for (IParameter param : method.getParams()) { LuaType paramClass = resolveLuaType(param.getType()); parameters.add(new LuaParameter(paramClass, param.getName(), param.getComment())); } JavaMethod.ReturnType returnType = method.getReturnType(); luaMethods.add(LuaMethod.Builder.create(method.getName()) .withOwner(luaClass).withModifier(method.getModifier()) .withReturnType(resolveLuaType(returnType), returnType.getComment()) .withParams(parameters).withVarArg(method.hasVarArg()) .withComment(method.getComment()).build()); Logger.debug("Compiled method %s", method.getName()); } result.add(new ZomboidLuaDoc(luaClass, luaFields, luaMethods)); Logger.detail("Compiled lua class %s with %d fields and %d methods", luaClass.getName(), luaFields.size(), luaMethods.size()); } Logger.info("Finished compiling %d/%d lua classes", result.size(), javaDocs.size()); return result; } }
8,799
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
CompilerException.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/compile/CompilerException.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.compile; public class CompilerException extends Exception { CompilerException(String message, Throwable cause) { super(message, cause); } CompilerException(String message) { super(message); } }
984
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
LoggerType.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/logger/LoggerType.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.logger; import java.util.Arrays; public enum LoggerType { INFO("info", "StandardLogger"), DEBUG("debug", "DebugLogger"); final String key, name; LoggerType(String key, String name) { this.key = key; this.name = name; } public static LoggerType get(String key, LoggerType defaultType) { return Arrays.stream(LoggerType.values()).filter(l -> l.key.equals(key)).findFirst().orElse(defaultType); } }
1,198
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
Logger.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/logger/Logger.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.logger; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.core.config.Configurator; @SuppressWarnings("unused") public class Logger { public static final Level VERBOSE = Level.forName("VERBOSE", 450); private static final String JVM_PROPERTY = "zdoc.logger"; private static final org.apache.logging.log4j.Logger logger; static { String loggerName = System.getProperty(JVM_PROPERTY); if (loggerName == null || loggerName.isEmpty()) { logger = LogManager.getLogger(LoggerType.INFO.name); } else if (!loggerName.equals("dev")) { logger = LogManager.getLogger(LoggerType.get(loggerName, LoggerType.INFO).name); } else logger = Configurator.initialize(null, "log4j2-dev.xml").getRootLogger(); logger.debug("Initialize logger: " + (!logger.getName().isEmpty() ? logger.getName() : loggerName)); } /* Make the constructor private to disable instantiation */ private Logger() { throw new UnsupportedOperationException(); } public static org.apache.logging.log4j.Logger get() { return logger; } /* * Short-hand methods to print logs to console. For more methods * use the static getter method to get a hold of a Logger instance. */ public static void info(String log) { logger.info(log); } public static void info(String log, Object... params) { logger.printf(Level.INFO, log, params); } public static void detail(String log) { logger.log(VERBOSE, log); } public static void detail(String log, Object... params) { logger.printf(VERBOSE, log, params); } public static void error(String log) { logger.error(log); } public static void error(String log, Object... args) { logger.printf(Level.ERROR, log, args); } public static void error(String log, Throwable t) { logger.error(log, t); } public static void warn(String log) { logger.warn(log); } public static void warn(String format, Object... params) { logger.printf(Level.WARN, format, params); } public static void debug(String log) { logger.debug(log); } public static void debug(String format, Object... args) { logger.printf(Level.DEBUG, format, args); } public static void debug(String log, Throwable t) { logger.debug(log, t); } public static void printf(Level level, String format, Object... params) { logger.printf(level, format, params); } }
3,149
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
ParseUtils.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/util/ParseUtils.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.util; import java.util.regex.MatchResult; import org.jetbrains.annotations.NotNull; public class ParseUtils { /** * Returns optional group captured by {@code Matcher}. * * @param match {@code MatchResult} that holds the captured group. * @param group the index of a capturing group in this matcher's pattern * @return input subsequence captured by {@code Matcher} for the given group * or an empty string if the group failed to match part of the input. * * @throws IllegalStateException if the given {@code Matcher} has * not attempted a match, or if the previous match operation failed * @throws IndexOutOfBoundsException if no capturing group with the * given index could be found by {@code Matcher}. */ public static @NotNull String getOptionalMatchedGroup(MatchResult match, int group) { String result = match.group(group); return result != null ? result : ""; } public static String flushStringBuilder(StringBuilder sb) { String result = sb.toString(); sb.setLength(0); return result; } }
1,825
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
Utils.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/util/Utils.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.util; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.nio.file.InvalidPathException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.Properties; import org.apache.commons.io.FilenameUtils; import org.jetbrains.annotations.Nullable; import org.springframework.util.ClassUtils; import io.cocolabs.pz.zdoc.Main; @SuppressWarnings("WeakerAccess") public class Utils { /** * Returns {@code true} if file denoted by given filename is a Lua file. * * @throws IllegalArgumentException <b>Windows only:</b> filename parameter is, in fact, the identifier * of an Alternate Data Stream, for example "foo.exe:bar.txt". */ public static boolean isLuaFile(String filename) { return FilenameUtils.getExtension(filename).equals("lua"); } /** * Returns {@code true} if file denoted by given path is a Lua file. * * @throws NullPointerException if given path has no elements. */ public static boolean isLuaFile(Path path) { return isLuaFile(path.getFileName().toString()); } public static @Nullable Path getPathOrNull(String path) { try { return Paths.get(path); } catch (InvalidPathException e) { return null; } } public static URL getURL(String link) { try { return new URL(link); } catch (MalformedURLException e) { throw new RuntimeException(e); } } public static @Nullable URL getURLOrNull(String link) { try { return new URL(link); } catch (MalformedURLException e) { return null; } } public static URL getURL(URL root, String... link) { try { StringBuilder sb = new StringBuilder(); Arrays.stream(link).forEach(l -> sb.append(l).append('/')); return new URL(root, sb.substring(0, sb.length() - 1)); } catch (MalformedURLException e) { throw new RuntimeException(e); } } public static URL getURLBase(URL url) { return getURL(url.getProtocol() + "://" + url.getHost()); } public static Class<?> getClassForName(String name) throws ClassNotFoundException { return ClassUtils.forName(name, null); } public static Properties getProperties(String path) throws IOException { Properties properties = new Properties(); try (InputStream iStream = Main.CLASS_LOADER.getResourceAsStream(path)) { if (iStream == null) { throw new IllegalStateException("Unable to find resource for path " + path); } properties.load(iStream); } return properties; } }
3,281
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
EmmyLuaReturn.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/lang/lua/EmmyLuaReturn.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.lang.lua; import java.util.regex.Pattern; import io.cocolabs.pz.zdoc.element.lua.LuaMethod; /** * Use {@code @return} to specify the return type of a function * <ul> * <li>Full format: * <pre> * ---@return MY_TYPE[|OTHER_TYPE] [@comment] * </pre></li> * <li>Target: * <ul style="list-style-type:circle"> * <li>functions<pre> * ---@return Car|Ship * local function create() * ... * end * ---Here car_or_ship doesn't need @type annotation, * ---EmmyLua has already inferred the type via "create" function * local car_or_ship = create() * </pre> * <pre> * ---@return Car * function factory:create() * ... * end * </pre></li> * </ul></li> * </ul> * * @see <a href="https://git.io/JLPlm">EmmyLua Documentation</a> */ public class EmmyLuaReturn extends EmmyLua { private static final Pattern REGEX = Pattern.compile( "^---\\s*@return\\s+(\\w+)(?:\\s*\\|\\s*(\\w+))?(?:\\s*@\\s*(.*))?\\s*$" ); public EmmyLuaReturn(LuaMethod.ReturnType type) { super("return", formatType(type), type.getComment()); } public static boolean isAnnotation(String text) { return REGEX.matcher(text).find(); } }
1,916
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
EmmyLuaField.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/lang/lua/EmmyLuaField.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.lang.lua; import java.util.regex.Pattern; import io.cocolabs.pz.zdoc.element.lua.LuaType; /** * Use {@code @field} to add extra fields to an existing class * (even if it doesn't appear in your code). * <ul> * <li>Full format:<pre> * ---@field [public|protected|private] field_name FIELD_TYPE[|OTHER_TYPE] [@comment] * </pre></li> * <li>Target: * <ul style="list-style-type:circle"> * <li>After {@code @class} annotations<pre> * ---@class Car * ---@field public name string @add name field to class Car, you'll see it in code completion * local cls = class() * </pre></li> * </ul></li> * </ul> * * @see <a href="https://git.io/JLP7D">EmmyLua Documentation</a> */ public class EmmyLuaField extends EmmyLua { private static final Pattern REGEX = Pattern.compile( "^---\\s*@field(?:\\s+(public|protected|private))?" + "\\s+(\\w+)(?:\\s*\\|\\s*(\\w+))?(?:\\s*@\\s*(.*))?\\s*$" ); public EmmyLuaField(String name, String access, LuaType type, String comment) { super("field", String.format("%s %s %s", access, name, formatType(type)), comment); } public EmmyLuaField(String name, LuaType type, String comment) { super("field", String.format("%s %s", name, formatType(type)), comment); } public EmmyLuaField(String name, String access, LuaType type) { this(name, access, type, ""); } public EmmyLuaField(String name, LuaType type) { this(name, type, ""); } public static boolean isAnnotation(String text) { return REGEX.matcher(text).find(); } }
2,275
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
EmmyLua.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/lang/lua/EmmyLua.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.lang.lua; import java.util.List; import java.util.Set; import org.apache.commons.lang3.Validate; import org.jetbrains.annotations.Nullable; import com.google.common.base.Strings; import com.google.common.collect.Sets; import io.cocolabs.pz.zdoc.Main; import io.cocolabs.pz.zdoc.element.lua.LuaType; /** * This class represents an EmmyLua annotation * * @see <a href="https://emmylua.github.io/">EmmyLua for IntelliJ IDEA</a> */ public abstract class EmmyLua { /** * Set of keywords reserved by EmmyLua plugin. * * @see <a href="https://git.io/JLPWh">IntelliJ-EmmyLua - builtin.lua</a> */ static final Set<String> BUILT_IN_TYPES = Sets.newHashSet( "boolean", "string", "number", "userdata", "thread", "table", "any", "void", "self" ); /** * Set of keywords reserved by Lua language. * * @see <a href="https://www.lua.org/manual/5.1/manual.html#2.1"> * Lexical Conventions - Lua 5.1 Reference Manual</a> */ static final Set<String> RESERVED_KEYWORDS = Sets.newHashSet( "and", "break", "do", "else", "elseif", "end", "false", "for", "function", "goto", "if", "in", "local", "nil", "not", "or", "repeat", "return", "then", "true", "until", "while" ); private final String annotation; EmmyLua(String keyword, String annotation, String comment) { if (Strings.nullToEmpty(comment).trim().isEmpty()) { this.annotation = String.format("---@%s %s", keyword, annotation); } else this.annotation = String.format("---@%s %s @%s", keyword, annotation, comment); } EmmyLua(String keyword) { Validate.notEmpty(keyword); this.annotation = "---@" + keyword; } /** * Returns {@code true} if given {@code String} is a keyword reserved by EmmyLua. */ public static boolean isBuiltInType(String type) { return BUILT_IN_TYPES.contains(type); } /** * Returns {@code true} if given {@code String} is a keyword reserved by Lua. */ public static boolean isReservedKeyword(String keyword) { return RESERVED_KEYWORDS.contains(keyword); } /** * Returns safe to use Lua member {@code String}. * * @return {@code String} that is safe to use as member name in Lua. * If the given string matches (non-case-sensitive) a reserved or built-in Lua keyword, * the result will be prepended with {@code '_'} character to avoid keyword clashing. */ public static String getSafeLuaName(String name) { return isReservedKeyword(name) || isBuiltInType(name) ? '_' + name : name; } static String formatType(LuaType type) { String typeName = readLuaTypeName(type); List<LuaType> typeParameters = type.getTypeParameters(); if (!typeParameters.isEmpty()) { StringBuilder sb = new StringBuilder(); sb.append(typeName).append('|').append(readLuaTypeName(typeParameters.get(0))); for (int i = 1; i < typeParameters.size(); i++) { sb.append('|').append(readLuaTypeName(typeParameters.get(i))); } return sb.toString(); } else return typeName; } private static String readLuaTypeName(@Nullable LuaType luaType) { return luaType != null ? Main.getSafeLuaClassName(luaType.getName()) : "any"; } /** Returns textual representation of this annotation. */ @Override public String toString() { return annotation; } }
3,999
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
EmmyLuaParam.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/lang/lua/EmmyLuaParam.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.lang.lua; import java.util.regex.Pattern; import io.cocolabs.pz.zdoc.element.lua.LuaType; /** * Use {@code @param} to specify the types of function parameters, * to improve completions and other functionality. * <ul> * <li>Full format: * <pre> * ---{@code @param} param_name MY_TYPE[|other_type] [@comment] * </pre> * </li> * <li>Target: * <ul style="list-style-type:circle"> * <li>function parameters<pre> * ---{@code @param} car Car * local function setCar(car) * ... * end * </pre> * <pre> * ---{@code @param} car Car * setCallback(function(car) * ... * end) * </pre></li> * <li>for loop variables<pre> * ---{@code @param} car Car * for k, car in ipairs(list) do * end * </pre></li> * </ul></li> * </ul> * * @see <a href="https://git.io/JLPlL">EmmyLua Documentation</a> */ public class EmmyLuaParam extends EmmyLua { private static final Pattern REGEX = Pattern.compile( "^---\\s*@param\\s+(\\w+)\\s+(\\w+)(?:\\s*\\|\\s*(\\w+))?(?:\\s*@\\s*(.*))?\\s*$" ); public EmmyLuaParam(String name, LuaType type, String comment) { super("param", String.format("%s %s", name, formatType(type)), comment); } public EmmyLuaParam(String name, LuaType type) { this(name, type, ""); } public static boolean isAnnotation(String text) { return REGEX.matcher(text).find(); } }
2,105
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
EmmyLuaAccess.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/lang/lua/EmmyLuaAccess.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.lang.lua; import io.cocolabs.pz.zdoc.element.mod.AccessModifierKey; public class EmmyLuaAccess extends EmmyLua { public EmmyLuaAccess(AccessModifierKey access) { super(access.name); } }
972
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
EmmyLuaVarArg.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/lang/lua/EmmyLuaVarArg.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.lang.lua; import io.cocolabs.pz.zdoc.Main; import io.cocolabs.pz.zdoc.element.lua.LuaType; /** * Used to denote a variadic argument. * <ul> * <li>Full format: * <pre> * ---@vararg TYPE * </pre></li> * <li>Example: * <pre> * ---@vararg string * ---@return string * local function format(...) * local tbl = { ... } -- inferred as string[] * end * </pre> * </li> * </ul> * * @see <a href="https://git.io/JLPlm">EmmyLua Documentation</a> */ public class EmmyLuaVarArg extends EmmyLua { public EmmyLuaVarArg(LuaType type, String comment) { super("vararg", Main.getSafeLuaClassName(type.getName()), comment); } public EmmyLuaVarArg(LuaType type) { this(type, ""); } }
1,476
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
EmmyLuaOverload.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/lang/lua/EmmyLuaOverload.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.lang.lua; import java.util.List; import io.cocolabs.pz.zdoc.element.lua.LuaParameter; /** * Use {@code @overload} to specify overloaded methods. * <ul> * <li>Full format: * <pre> * ---{@code @overloaded} fun(param_name:MY_TYPE[|other_type]...) [@comment] * </pre> * </li> * </ul> * * @see <a href="https://git.io/JqhaG">EmmyLua Documentation</a> */ public class EmmyLuaOverload extends EmmyLua { public EmmyLuaOverload(List<LuaParameter> params) { super("overload", formatAnnotation(params), ""); } private static String formatAnnotation(List<LuaParameter> params) { StringBuilder sb = new StringBuilder(); if (!params.isEmpty()) { LuaParameter param = params.get(0); sb.append(param.getName()).append(':').append(formatType(param.getType())); } for (int i = 1; i < params.size(); i++) { LuaParameter param = params.get(i); sb.append(", ").append(param.getName()).append(':').append(formatType(param.getType())); } return String.format("fun(%s)", sb.toString()); } }
1,798
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
EmmyLuaClass.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/lang/lua/EmmyLuaClass.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.lang.lua; import java.util.regex.Pattern; import org.jetbrains.annotations.Nullable; /** * EmmyLua use {@code @class} to simulate classes in OOP, supporting inheritance and fields. * <ul> * <li>Full format:<pre> * --@class MY_TYPE[:PARENT_TYPE] [@comment] * </pre></li> * <li>Target:</li> * <li><ul style="list-style-type:circle"> * <li>local variables</li> * <li>global variables</li> * </ul></li> * <li>Examples:<pre> * ---@class Car : Transport @define class Car extends Transport * local cls = class() * function cls:test() * end * </pre></li> * </ul> * * @see <a href="https://git.io/JLPlJ">EmmyLua Documentation</a> */ public class EmmyLuaClass extends EmmyLua { private static final Pattern REGEX = Pattern.compile( "^---\\s*@class\\s+(\\w+)(?:\\s*:\\s*(\\w+))?(?:\\s*@\\s*(.*))?\\s*$?" ); public EmmyLuaClass(String type, @Nullable String parentType, String comment) { super("class", formatType(type, parentType), comment); } public EmmyLuaClass(String type, @Nullable String parentType) { this(type, parentType, ""); } public static boolean isAnnotation(String text) { return REGEX.matcher(text).find(); } private static String formatType(String type, @Nullable String parentType) { return parentType != null ? type + " : " + parentType : type; } }
2,086
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
Color.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/zombie/java/zombie/core/Color.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package zombie.core; import org.jetbrains.annotations.TestOnly; @TestOnly public class Color { }
850
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
IsoPlayer.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/zombie/java/zombie/characters/IsoPlayer.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package zombie.characters; import org.jetbrains.annotations.TestOnly; @TestOnly public class IsoPlayer { }
860
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
MainTest.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/intTest/java/io/cocolabs/pz/zdoc/MainTest.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc; import java.util.List; import org.jetbrains.annotations.TestOnly; import io.cocolabs.pz.zdoc.cmd.Command; class MainTest extends TestWorkspace implements IntegrationTest { // MainTest() { // super("sampleLua.lua"); // } // // private static Executable runMain(@Nullable Command command, String input, String output) { // return () -> Main.main(formatAppArgs(command != null ? command.getName() : "", input, output)); // } // // @Test // void shouldThrowExceptionWhenApplicationRunWithMissingCommand() { // // // Missing or unknown command argument // Assertions.assertThrows(ParseException.class, // runMain(null, "input/path", "output/path")); // } // // @Test // void shouldThrowExceptionWhenApplicationRunWithMissingArgs() { // // Arrays.stream(Command.values()).filter(c -> c != Command.HELP) // .forEach(c -> Assertions.assertThrows(ParseException.class, // runMain(c, "", "output/path"))); // } // // @Test // void shouldThrowExceptionWhenApplicationRunWithNonDirectoryOutput() throws IOException { // // File notDirFile = dir.toPath().resolve("not_dir.file").toFile(); // Assertions.assertTrue(notDirFile.createNewFile()); // // Assertions.assertThrows(IllegalArgumentException.class, // runMain(Command.COMPILE, "input/path", notDirFile.getPath())); // } // // @Test // void shouldDocumentLuaFileWithSpecifiedExistingOutputDir() throws IOException { // // createSampleLuaFile(); // File outputDir = dir.toPath().resolve("output").toFile(); // Assertions.assertTrue(outputDir.mkdir()); // Assertions.assertDoesNotThrow(runMain(Command.ANNOTATE, file.getPath(), outputDir.getPath())); // } // // @Test // void shouldDocumentLuaFileWithSpecifiedNonExistingOutputDir() throws IOException { // // createSampleLuaFile(); // File outputDir = dir.toPath().resolve("output").toFile(); // Assertions.assertDoesNotThrow(runMain(Command.ANNOTATE, file.getPath(), outputDir.getPath())); // } // //// @Test //// void whenApplicationRunShouldDocumentLuaClasses() throws Throwable { //// //// String[] write = { //// "--- This is a sample comment", //// "---@class otherSampleLua", //// "sampleLua = luaClass:new()" //// }; //// FileUtils.writeLines(file, Arrays.asList(write)); //// //// runMain(Command.ANNOTATE, dir.getPath(), "").execute(); //// //// List<String> read = FileUtils.readLines(file, Charset.defaultCharset()); //// Assertions.assertEquals(EmmyLua.CLASS.create(new String[]{ "sampleLua" }), read.get(1)); //// } //// //// @Test //// void shouldKeepDirectoryHierarchyWhenDocumentingLuaFile() throws Throwable { //// //// Path rootPath = dir.toPath(); //// Path outputDir = rootPath.resolve("output"); //// File sampleDir = rootPath.resolve("sample").toFile(); //// Assertions.assertTrue(sampleDir.mkdir()); //// //// createSampleLuaFile(); //// FileUtils.moveFileToDirectory(file, sampleDir, false); //// File sampleFile = sampleDir.toPath().resolve(file.getName()).toFile(); //// Assertions.assertTrue(sampleFile.exists()); //// //// runMain(Command.ANNOTATE, rootPath.toString(), outputDir.toString()).execute(); //// //// File outputFile = outputDir.resolve("sample").resolve(file.getName()).toFile(); //// Assertions.assertTrue(outputFile.exists()); //// //// List<String> lines = FileUtils.readLines(outputFile, Charset.defaultCharset()); //// Assertions.assertEquals(7, lines.size()); //// Assertions.assertEquals(EmmyLua.CLASS.create(new String[]{ "sampleLua" }), lines.get(5)); //// } // // @Test // void whenApplicationRunShouldConvertJavaToLuaDoc() throws Throwable { // // File outputDir = dir.toPath().resolve("output").toFile(); // Assertions.assertTrue(outputDir.mkdir()); // // String input = "src/test/resources/Test.html"; // runMain(Command.COMPILE, input, outputDir.getPath()).execute(); // // String[] expected = { // "---@return void", // "function begin()", // "", // "---@return boolean", // "function DoesInstantly()", // "", // "---@param object String", // "---@param params String[]", // "---@return void", // "function init(object, params)", // "", // "---@return boolean", // "function IsFinished()", // "", // "---@return void", // "function update()", // }; // List<String> actual = FileUtils.readLines(file, Charset.defaultCharset()); // for (int i = 0; i < actual.size(); i++) { // Assertions.assertEquals(expected[i], actual.get(i)); // } // } // @TestOnly static String[] formatAppArgs(String command, String input, String output) { List<String> args = new java.util.ArrayList<>(); args.add(command); if (!input.isEmpty()) { args.add("-i"); args.add(input); } if (!output.isEmpty()) { args.add("-o"); args.add(output); } return args.toArray(new String[]{}); } @TestOnly static String[] formatAppArgs(Command command, String input, String output) { return formatAppArgs(command.getName(), input, output); } }
5,694
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
IntegrationTest.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/intTest/java/io/cocolabs/pz/zdoc/IntegrationTest.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc; import java.io.File; import java.io.IOException; import java.io.InputStream; import org.apache.commons.io.FileUtils; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Tag; @Tag("integration") public interface IntegrationTest { @BeforeAll static void initializeIntegrationTest() throws IOException { File targetFile = new File("serialize.lua"); if (!targetFile.exists()) { try (InputStream iStream = Main.CLASS_LOADER.getResourceAsStream("serialize.lua")) { if (iStream == null) { throw new IllegalStateException("Unable to find serialize.lua resource file"); } FileUtils.copyToFile(iStream, targetFile); } } } @AfterAll static void finalizeIntegrationTest() { File targetFile = new File("serialize.lua"); if (!targetFile.delete()) { targetFile.deleteOnExit(); } } }
1,660
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
JavaCompilerIntTest.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/intTest/java/io/cocolabs/pz/zdoc/compile/JavaCompilerIntTest.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.compile; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.util.HashSet; import java.util.List; import java.util.Objects; import org.apache.commons.io.FileUtils; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.opentest4j.AssertionFailedError; import io.cocolabs.pz.zdoc.IntegrationTest; class JavaCompilerIntTest implements IntegrationTest { private static final File EXPOSED_JAVA; static { try { ClassLoader cl = JavaCompilerIntTest.class.getClassLoader(); EXPOSED_JAVA = new File( Objects.requireNonNull(cl.getResource("exposed.txt")).toURI() ); } catch (URISyntaxException e) { throw new RuntimeException(e); } } @Test void shouldGetAllExposedJavaClasses() throws ReflectiveOperationException, IOException { List<String> expectedExposedElements = FileUtils.readLines(EXPOSED_JAVA, Charset.defaultCharset()); HashSet<Class<?>> actualExposedElements = JavaCompiler.getExposedJava(); for (Class<?> actualExposedElement : actualExposedElements) { if (!expectedExposedElements.contains(actualExposedElement.getName())) { String message = "Did not find exposed Java class"; throw new AssertionFailedError(message, null, actualExposedElement); } } } /** * Ensure that {@link NoClassDefFoundError} and {@link ClassNotFoundException} * exceptions are not thrown, which happens when JDK classes are not found. */ @Test void shouldNotThrowClassNotFoundExceptionWhenReadingExposedJavaClasses() throws ReflectiveOperationException { for (Class<?> exposedClass : JavaCompiler.getExposedJava()) { Assertions.assertDoesNotThrow(exposedClass::getDeclaredConstructors); Assertions.assertDoesNotThrow(exposedClass::getDeclaredFields); Assertions.assertDoesNotThrow(exposedClass::getDeclaredMethods); } } }
2,683
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
ZDocJar.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/buildSrc/src/main/java/ZDocJar.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import java.util.NoSuchElementException; import java.util.Objects; import javax.annotation.Nullable; import org.gradle.api.NonNullApi; import org.gradle.api.Project; import org.gradle.api.Task; import org.gradle.api.plugins.ExtraPropertiesExtension; import org.gradle.jvm.tasks.Jar; import org.gradle.util.GUtil; import groovy.lang.Closure; @NonNullApi public class ZDocJar extends Jar { private static final String GAME_VERSION_PROPERTY = "gameVersion"; private static final String TASK_GROUP = "zomboid"; private static final String[] DEPENDANT_TASKS = new String[]{ "jar" }; private static final Object[] DEPENDENCY_TASKS = new String[]{ "zomboidVersion" }; private final Project project = this.getProject(); public ZDocJar() { getArchiveFileName().set(project.provider(() -> { ExtraPropertiesExtension ext = project.getExtensions().getExtraProperties(); if (ext.has(GAME_VERSION_PROPERTY)) { String name = GUtil.elvis(getArchiveBaseName().getOrNull(), ""); name = name + maybe(name, getArchiveAppendix().getOrNull()); Object pGameVersion = Objects.requireNonNull(ext.get(GAME_VERSION_PROPERTY)); name = name + maybe(name, pGameVersion.toString().trim()); name = name + maybe(name, getArchiveClassifier().getOrNull()); String extension = this.getArchiveExtension().getOrNull(); return name + (GUtil.isTrue(extension) ? "." + extension : ""); } return getArchiveFileName().get(); })); } private static String maybe(@Nullable String prefix, @Nullable String value) { return GUtil.isTrue(value) ? GUtil.isTrue(prefix) ? "-".concat(value) : value : ""; } @Override public Task configure(Closure closure) { Task configure = super.configure(closure); /* * additional configuration actions */ setGroup(TASK_GROUP); dependsOn(DEPENDENCY_TASKS); for (String taskName : DEPENDANT_TASKS) { getTaskByName(taskName).dependsOn(this); } return configure; } /** * Returns single {@code Task} with the given name * * @throws NoSuchElementException when the requested task was not found */ private Task getTaskByName(String name) { try { return project.getTasksByName(name, false).iterator().next(); } catch (NoSuchElementException e) { throw new NoSuchElementException("Unable to find " + name + " gradle task"); } } }
3,074
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
ZUnixStartScriptGenerator.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/buildSrc/src/main/java/ZUnixStartScriptGenerator.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import java.io.IOException; import java.io.InputStream; import java.io.Writer; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.IOUtils; import org.gradle.api.NonNullApi; import org.gradle.api.Transformer; import org.gradle.api.UncheckedIOException; import org.gradle.api.internal.plugins.StartScriptTemplateBindingFactory; import org.gradle.jvm.application.scripts.JavaAppStartScriptGenerationDetails; import org.gradle.jvm.application.scripts.ScriptGenerator; import org.gradle.util.TextUtil; @NonNullApi public class ZUnixStartScriptGenerator implements ScriptGenerator { private static final Charset CHARSET = StandardCharsets.UTF_8; private static final ClassLoader CL = ZUnixStartScriptGenerator.class.getClassLoader(); private static final String[] CLASSPATH_ADDENDUM = new String[]{ "$PZ_DIR_PATH", // Project Zomboid game classes "$PZ_DIR_PATH/*" // Project Zomboid libraries }; private static final Pattern REGEX_TOKEN = Pattern.compile("%!(.*)!%"); private final String scriptTemplate, lineSeparator; private final Transformer<Map<String, String>, JavaAppStartScriptGenerationDetails> bindingFactory; public ZUnixStartScriptGenerator() { this.lineSeparator = TextUtil.getUnixLineSeparator(); this.scriptTemplate = readScriptResourceFile(); this.bindingFactory = StartScriptTemplateBindingFactory.unix(); } private static String readScriptResourceFile() { String filename = "unixScriptTemplate.sh"; try (InputStream iStream = CL.getResourceAsStream(filename)) { if (iStream == null) { throw new IllegalStateException("Unable to find file \"" + filename + "\""); } return IOUtils.toString(iStream, CHARSET); } catch (IOException e) { throw new ExceptionInInitializerError(e); } } @Override public void generateScript(JavaAppStartScriptGenerationDetails details, Writer destination) { try { Map<String, String> binding = this.bindingFactory.transform(details); StringBuilder sb = new StringBuilder(); sb.append(binding.get("classpath")); for (String entry : CLASSPATH_ADDENDUM) { sb.append(':').append(entry); } binding.put("classpath", sb.toString()); destination.write(generateStartScriptContentFromTemplate(binding)); } catch (IOException var5) { throw new UncheckedIOException(var5); } } private String generateStartScriptContentFromTemplate(final Map<String, String> binding) { Matcher matcher = REGEX_TOKEN.matcher(scriptTemplate); StringBuffer sb = new StringBuffer(); /* * all matched tokens will be replaced with binding params that match token name * see: StartScriptTemplateBindingFactory#ScriptBindingParameter */ while (matcher.find()) { String bindingParam = binding.get(matcher.group(1)); matcher.appendReplacement(sb, Matcher.quoteReplacement(bindingParam)); } matcher.appendTail(sb); return Objects.requireNonNull(TextUtil.convertLineSeparators(sb.toString(), lineSeparator)); } }
3,883
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
ZWindowsStartScriptGenerator.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/buildSrc/src/main/java/ZWindowsStartScriptGenerator.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2021 Matthew Cain * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import java.io.IOException; import java.io.InputStream; import java.io.Writer; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.IOUtils; import org.gradle.api.NonNullApi; import org.gradle.api.Transformer; import org.gradle.api.UncheckedIOException; import org.gradle.api.internal.plugins.StartScriptTemplateBindingFactory; import org.gradle.jvm.application.scripts.JavaAppStartScriptGenerationDetails; import org.gradle.jvm.application.scripts.ScriptGenerator; import org.gradle.util.TextUtil; @NonNullApi public class ZWindowsStartScriptGenerator implements ScriptGenerator { private static final Charset CHARSET = StandardCharsets.UTF_8; private static final ClassLoader CL = ZWindowsStartScriptGenerator.class.getClassLoader(); private static final String[] CLASSPATH_ADDENDUM = new String[]{ "%PZ_DIR_PATH%", // Project Zomboid game classes "%PZ_DIR_PATH%\\*" // Project Zomboid libraries }; private static final Pattern REGEX_TOKEN = Pattern.compile("%!(.*)!%"); private final String scriptTemplate, lineSeparator; private final Transformer<Map<String, String>, JavaAppStartScriptGenerationDetails> bindingFactory; public ZWindowsStartScriptGenerator() { this.lineSeparator = TextUtil.getWindowsLineSeparator(); this.scriptTemplate = readScriptResourceFile(); this.bindingFactory = StartScriptTemplateBindingFactory.windows(); } private static String readScriptResourceFile() { String filename = "winScriptTemplate.bat"; try (InputStream iStream = CL.getResourceAsStream(filename)) { if (iStream == null) { throw new IllegalStateException("Unable to find file \"" + filename + "\""); } return IOUtils.toString(iStream, CHARSET); } catch (IOException e) { throw new ExceptionInInitializerError(e); } } @Override public void generateScript(JavaAppStartScriptGenerationDetails details, Writer destination) { try { Map<String, String> binding = this.bindingFactory.transform(details); StringBuilder sb = new StringBuilder(); sb.append(binding.get("classpath")); for (String entry : CLASSPATH_ADDENDUM) { sb.append(';').append(entry); } binding.put("classpath", sb.toString()); destination.write(generateStartScriptContentFromTemplate(binding)); } catch (IOException var5) { throw new UncheckedIOException(var5); } } private String generateStartScriptContentFromTemplate(final Map<String, String> binding) { Matcher matcher = REGEX_TOKEN.matcher(scriptTemplate); StringBuffer sb = new StringBuffer(); /* * all matched tokens will be replaced with binding params that match token name * see: StartScriptTemplateBindingFactory#ScriptBindingParameter */ while (matcher.find()) { String bindingParam = binding.get(matcher.group(1)); matcher.appendReplacement(sb, Matcher.quoteReplacement(bindingParam)); } matcher.appendTail(sb); return Objects.requireNonNull(TextUtil.convertLineSeparators(sb.toString(), lineSeparator)); } }
3,900
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
AudioPlayer.java
/FileExtraction/Java_unseen/martinmimigames_tiny-music-player/app/src/main/java/com/martinmimigames/tinymusicplayer/AudioPlayer.java
package com.martinmimigames.tinymusicplayer; import android.media.AudioAttributes; import android.media.AudioManager; import android.media.MediaPlayer; import android.net.Uri; import android.os.Build; import java.io.IOException; class AudioPlayer extends Thread implements MediaPlayer.OnCompletionListener { private final Service service; private final MediaPlayer mediaPlayer; /** * Initiate an audio player, throws exceptions if failed. * * @param service the service initialising this. * @param audioLocation the Uri containing the location of the audio. * @throws IllegalArgumentException when the media player need cookies, but we do not supply it. * @throws IllegalStateException when the media player is not in the correct state. * @throws SecurityException when the audio file is protected and cannot be played. * @throws IOException when the audio file cannot be read. */ public AudioPlayer(Service service, Uri audioLocation) throws IllegalArgumentException, IllegalStateException, SecurityException, IOException { this.service = service; /* initiate new audio player */ mediaPlayer = new MediaPlayer(); /* setup player variables */ mediaPlayer.setDataSource(service, audioLocation); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); } else { mediaPlayer.setAudioAttributes( new AudioAttributes.Builder() .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC) .setUsage(AudioAttributes.USAGE_MEDIA) .build() ); } mediaPlayer.setLooping(false); /* setup listeners for further logics */ mediaPlayer.setOnCompletionListener(this); } @Override public void run() { /* get ready for playback */ try { mediaPlayer.prepare(); service.setState(true, false); } catch (IllegalStateException e) { Exceptions.throwError(service, Exceptions.IllegalState); } catch (IOException e) { Exceptions.throwError(service, Exceptions.IO); } } /** * check if audio is playing */ public boolean isPlaying() { return mediaPlayer.isPlaying(); } /** * check if audio is looping, always false on < android cupcake (sdk 3) */ public boolean isLooping() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CUPCAKE) { return mediaPlayer.isLooping(); } else { return false; } } /** * set player state * * @param playing is audio playing * @param looping is audio looping */ void setState(boolean playing, boolean looping) { if (playing) { mediaPlayer.start(); } else { mediaPlayer.pause(); } mediaPlayer.setLooping(looping); } /** * release resource when playback finished */ @Override public void onCompletion(MediaPlayer mp) { service.stopSelf(); } /** * release and kill service */ @Override public void interrupt() { mediaPlayer.release(); super.interrupt(); } }
3,080
Java
.java
martinmimigames/tiny-music-player
58
9
4
2022-12-10T13:10:17Z
2024-01-31T16:47:27Z
Launcher.java
/FileExtraction/Java_unseen/martinmimigames_tiny-music-player/app/src/main/java/com/martinmimigames/tinymusicplayer/Launcher.java
package com.martinmimigames.tinymusicplayer; import android.Manifest; import android.app.Activity; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.provider.Settings; /** * activity for controlling the playback by invoking different logics based on incoming intents */ public class Launcher extends Activity { static final String TYPE = "type"; static final byte NULL = 0; static final byte PLAY_PAUSE = 1; static final byte KILL = 2; static final byte PLAY = 3; static final byte PAUSE = 4; static final byte LOOP = 5; private static final int REQUEST_CODE = 3216487; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (!Intent.ACTION_VIEW.equals(getIntent().getAction()) && !Intent.ACTION_SEND.equals(getIntent().getAction())) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && this.getPackageManager() .checkPermission( Manifest.permission.POST_NOTIFICATIONS, this.getPackageName()) != PackageManager.PERMISSION_GRANTED) { final var intent = new Intent(); intent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS); intent.putExtra(Settings.EXTRA_APP_PACKAGE, this.getPackageName()); this.startActivity(intent); finish(); return; } /* request a file from the system */ var intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("audio/*"); // intent type to filter application based on your requirement startActivityForResult(intent, REQUEST_CODE); return; } onIntent(getIntent()); } /** * redirect call to actual logic */ @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); onIntent(intent); } /** * restarts service */ private void onIntent(Intent intent) { intent.setClass(this, Service.class); stopService(intent); startService(intent); /* does not need to keep this activity */ finish(); } /** * call service control on receiving file */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { /* if result unusable, discard */ if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) { /* redirect to service */ intent.setAction(Intent.ACTION_VIEW); onIntent(intent); return; } finish(); } }
2,535
Java
.java
martinmimigames/tiny-music-player
58
9
4
2022-12-10T13:10:17Z
2024-01-31T16:47:27Z
Service.java
/FileExtraction/Java_unseen/martinmimigames_tiny-music-player/app/src/main/java/com/martinmimigames/tinymusicplayer/Service.java
package com.martinmimigames.tinymusicplayer; import android.annotation.TargetApi; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.IBinder; import java.io.IOException; /** * service for playing music */ public class Service extends android.app.Service { final HWListener hwListener; final Notifications notifications; /** * audio playing logic class */ private AudioPlayer audioPlayer; public Service() { hwListener = new HWListener(this); notifications = new Notifications(this); } /** * unused */ @Override public IBinder onBind(Intent intent) { return null; } /** * setup */ @Override public void onCreate() { hwListener.create(); notifications.create(); super.onCreate(); } /** * startup logic */ @Override public void onStart(final Intent intent, final int startId) { /* check if called from self */ if (intent.getAction() == null) { var isPLaying = audioPlayer.isPlaying(); var isLooping = audioPlayer.isLooping(); switch (intent.getByteExtra(Launcher.TYPE, Launcher.NULL)) { /* start or pause audio playback */ case Launcher.PLAY_PAUSE -> setState(!isPLaying, isLooping); case Launcher.PLAY -> setState(true, isLooping); case Launcher.PAUSE -> setState(false, isLooping); case Launcher.LOOP -> setState(isPLaying, !isLooping); /* cancel audio playback and kill service */ case Launcher.KILL -> stopSelf(); } } else { switch (intent.getAction()) { case Intent.ACTION_VIEW -> setAudio(intent.getData()); case Intent.ACTION_SEND -> setAudio(intent.getParcelableExtra(Intent.EXTRA_STREAM)); } } } void setAudio(final Uri audioLocation) { try { /* get audio playback logic and start async */ audioPlayer = new AudioPlayer(this, audioLocation); audioPlayer.start(); /* create notification for playback control */ notifications.getNotification(audioLocation); /* start service as foreground */ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) startForeground(Notifications.NOTIFICATION_ID, notifications.notification); } catch (IllegalArgumentException e) { Exceptions.throwError(this, Exceptions.IllegalArgument); } catch (SecurityException e) { Exceptions.throwError(this, Exceptions.Security); } catch (IllegalStateException e) { Exceptions.throwError(this, Exceptions.IllegalState); } catch (IOException e) { Exceptions.throwError(this, Exceptions.IO); } } /** * Switch to player component state */ void setState(boolean playing, boolean looping) { audioPlayer.setState(playing, looping); hwListener.setState(playing, looping); notifications.setState(playing, looping); } /** * forward to startup logic for newer androids */ @TargetApi(Build.VERSION_CODES.ECLAIR) @Override public int onStartCommand(final Intent intent, final int flags, final int startId) { onStart(intent, startId); return START_STICKY; } /** * service killing logic */ @Override public void onDestroy() { notifications.destroy(); hwListener.destroy(); /* interrupt audio playback logic */ if (!audioPlayer.isInterrupted()) audioPlayer.interrupt(); super.onDestroy(); } }
3,413
Java
.java
martinmimigames/tiny-music-player
58
9
4
2022-12-10T13:10:17Z
2024-01-31T16:47:27Z
Exceptions.java
/FileExtraction/Java_unseen/martinmimigames_tiny-music-player/app/src/main/java/com/martinmimigames/tinymusicplayer/Exceptions.java
package com.martinmimigames.tinymusicplayer; import android.content.Context; import mg.utils.notify.ToastHelper; final class Exceptions { static final String IllegalArgument = "Requires cookies, which the app does not support."; static final String IllegalState = "Unusable player state, close app and try again."; static final String IO = "Read error, try again later."; static final String Security = "File location protected, cannot be accessed."; /** * create and display error toast to report errors */ static void throwError(Context context, String msg) { ToastHelper.showLong(context, msg); } }
630
Java
.java
martinmimigames/tiny-music-player
58
9
4
2022-12-10T13:10:17Z
2024-01-31T16:47:27Z
Notifications.java
/FileExtraction/Java_unseen/martinmimigames_tiny-music-player/app/src/main/java/com/martinmimigames/tinymusicplayer/Notifications.java
package com.martinmimigames.tinymusicplayer; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Intent; import android.media.AudioManager; import android.net.Uri; import android.os.Build; import android.widget.RemoteViews; import java.io.File; import mg.utils.notify.NotificationHelper; class Notifications { /** * notification channel id */ public static final String NOTIFICATION_CHANNEL = "nc"; /** * notification id */ public static final int NOTIFICATION_ID = 1; private static final String TAP_TO_CLOSE = "Tap to close"; private final Service service; /** * notification for playback control */ Notification notification; Notification.Builder builder; public Notifications(Service service) { this.service = service; } public void create() { if (Build.VERSION.SDK_INT >= 26) { /* create a notification channel */ var name = "Playback Control"; var description = "Notification audio controls"; var importance = NotificationManager.IMPORTANCE_LOW; var notificationChannel = NotificationHelper.setupNotificationChannel(service, NOTIFICATION_CHANNEL, name, description, importance); notificationChannel.setSound(null, null); notificationChannel.setVibrationPattern(null); } } /** * setup notification properties * * @param title title of notification (title of file) * @param playPauseIntent pending intent for pause/play audio * @param killIntent pending intent for closing the service */ void setupNotificationBuilder(String title, PendingIntent playPauseIntent, PendingIntent killIntent, PendingIntent loopIntent) { if (Build.VERSION.SDK_INT < 11) return; // create builder instance if (Build.VERSION.SDK_INT >= 26) { builder = new Notification.Builder(service, NOTIFICATION_CHANNEL); } else { builder = new Notification.Builder(service); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { builder.setCategory(Notification.CATEGORY_SERVICE); } builder.setSmallIcon(R.drawable.ic_notif); builder.setContentTitle(title); builder.setSound(null); builder.setVibrate(null); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { builder.setContentIntent(playPauseIntent); builder.addAction(0, "loop", loopIntent); builder.addAction(0, TAP_TO_CLOSE, killIntent); } else { builder.setContentText(TAP_TO_CLOSE); builder.setContentIntent(killIntent); } } /** * Switch playback state */ void setState(boolean playing, boolean looping) { // no notification controls < Jelly bean if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { var playbackText = "Tap to "; playbackText += (playing) ? "pause" : "play"; if (looping) { playbackText += " | looping"; } builder.setContentText(playbackText); buildNotification(); update(); } } /** * Generate pending intents for service control * * @param id the id for the intent * @param action the control action * @return the pending intent generated */ PendingIntent genIntent(int id, byte action) { /* flags for control logics on notification */ var pendingIntentFlag = PendingIntent.FLAG_IMMUTABLE; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CUPCAKE) pendingIntentFlag |= PendingIntent.FLAG_UPDATE_CURRENT; var intentFlag = Intent.FLAG_ACTIVITY_NO_HISTORY; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) intentFlag |= Intent.FLAG_ACTIVITY_NO_ANIMATION; return PendingIntent .getService(service, id, new Intent(service, Service.class) .addFlags(intentFlag) .putExtra(Launcher.TYPE, action) , pendingIntentFlag); } /** * generate new notification */ void genNotification() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { buildNotification(); } else { notification = new Notification(); } } /** * build notification from notification builder */ void buildNotification() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { notification = builder.build(); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { notification = builder.getNotification(); } } /** * setup notification properties * * @param title title of notification (title of file) * @param killIntent pending intent for closing the service */ void setupNotification(String title, PendingIntent killIntent) { if (Build.VERSION.SDK_INT < 11) { notification.contentView = new RemoteViews("com.martinmimigames.tinymusicplayer", R.layout.notif); notification.icon = R.drawable.ic_notif; // icon display notification.audioStreamType = AudioManager.STREAM_MUSIC; notification.sound = null; notification.contentIntent = killIntent; notification.contentView.setTextViewText(R.id.notif_title, title); notification.vibrate = null; } } /** * create and start playback control notification */ void getNotification(final Uri uri) { /* setup notification variable */ var title = new File(uri.getPath()).getName(); /* calls for control logic by starting activity with flags */ var killIntent = genIntent(1, Launcher.KILL); var playPauseIntent = genIntent(2, Launcher.PLAY_PAUSE); var loopIntent = genIntent(3, Launcher.LOOP); setupNotificationBuilder(title, playPauseIntent, killIntent, loopIntent); genNotification(); setupNotification(title, killIntent); update(); } /** * update notification content and place on stack */ private void update() { NotificationHelper.send(service, NOTIFICATION_ID, notification); } void destroy() { /* remove notification from stack */ NotificationHelper.unsend(service, NOTIFICATION_ID); } }
6,041
Java
.java
martinmimigames/tiny-music-player
58
9
4
2022-12-10T13:10:17Z
2024-01-31T16:47:27Z
HWListener.java
/FileExtraction/Java_unseen/martinmimigames_tiny-music-player/app/src/main/java/com/martinmimigames/tinymusicplayer/HWListener.java
package com.martinmimigames.tinymusicplayer; import static android.content.Intent.EXTRA_KEY_EVENT; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.media.AudioManager; import android.media.session.MediaSession; import android.media.session.PlaybackState; import android.os.Build; import android.view.KeyEvent; /** * Hardware Listener for button controls */ public class HWListener extends BroadcastReceiver { private Service service; private MediaSession mediaSession; private PlaybackState.Builder playbackStateBuilder; private ComponentName cn; /** * Required for older android versions, * initialized by the system */ public HWListener() { super(); } /** * Returns an instance, only useful when SDK_INT >= LOLLIPOP * * @param service the music service */ public HWListener(Service service) { this.service = service; } /** * Initializer, only useful when SDK_INT >= LOLLIPOP */ void create() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { mediaSession = new MediaSession(service, HWListener.class.toString()); mediaSession.setCallback(new MediaSession.Callback() { @Override public boolean onMediaButtonEvent(Intent mediaButtonIntent) { onReceive(service, mediaButtonIntent); return super.onMediaButtonEvent(mediaButtonIntent); } }); playbackStateBuilder = new PlaybackState.Builder(); playbackStateBuilder.setActions(PlaybackState.ACTION_PLAY | PlaybackState.ACTION_PAUSE | PlaybackState.ACTION_PLAY_PAUSE); mediaSession.setPlaybackState(playbackStateBuilder.build()); mediaSession.setActive(true); } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) { cn = new ComponentName(service, HWListener.class); ((AudioManager) service.getSystemService(Context.AUDIO_SERVICE)).registerMediaButtonEventReceiver(cn); } service.registerReceiver(this, new IntentFilter(Intent.ACTION_MEDIA_BUTTON)); } } /** * Switch playback state, only useful when SDK_INT >= LOLLIPOP */ void setState(boolean playing, boolean looping) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { if (playing) playbackStateBuilder.setState(PlaybackState.STATE_PLAYING, PlaybackState.PLAYBACK_POSITION_UNKNOWN, 1); else playbackStateBuilder.setState(PlaybackState.STATE_PAUSED, PlaybackState.PLAYBACK_POSITION_UNKNOWN, 1); mediaSession.setPlaybackState(playbackStateBuilder.build()); } } /** * Get ready to be destroyed, only useful when SDK_INT >= LOLLIPOP */ void destroy() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { mediaSession.setActive(false); mediaSession.release(); } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) { ((AudioManager) service.getSystemService(Context.AUDIO_SERVICE)).unregisterMediaButtonEventReceiver(cn); } service.unregisterReceiver(this); } } /** * Responds to media keycodes (ie. from bluetooth ear phones, etc.). * Does not connect directly to service variable because service may not be initialized. */ @Override public void onReceive(Context context, Intent intent) { var event = (KeyEvent) intent.getParcelableExtra(EXTRA_KEY_EVENT); if (event.getAction() == KeyEvent.ACTION_DOWN) { intent = new Intent(context, Service.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_HISTORY); switch (event.getKeyCode()) { case KeyEvent.KEYCODE_MEDIA_PLAY: intent.putExtra(Launcher.TYPE, Launcher.PLAY); break; case KeyEvent.KEYCODE_MEDIA_PAUSE: intent.putExtra(Launcher.TYPE, Launcher.PAUSE); break; case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE: intent.putExtra(Launcher.TYPE, Launcher.PLAY_PAUSE); break; case KeyEvent.KEYCODE_MEDIA_STOP: intent.putExtra(Launcher.TYPE, Launcher.KILL); break; default: return; } context.startService(intent); } } }
4,293
Java
.java
martinmimigames/tiny-music-player
58
9
4
2022-12-10T13:10:17Z
2024-01-31T16:47:27Z
Tools.java
/FileExtraction/Java_unseen/scleriot_yaam-application/src/com/pixellostudio/newyaam/Tools.java
package com.pixellostudio.newyaam; import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLConnection; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.http.util.ByteArrayBuffer; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.util.Log; public class Tools { public static void queryWeb(final String url, final Handler handler) { class LoadURL extends AsyncTask<Object, Object, Integer> { private final int NETWORK_ERROR = -1, ERROR = 0, SUCCESS = 1; String txt=""; private int number; @Override protected Integer doInBackground(Object... params) { number=0; txt=""; try { URL updateURL = new URL(url); URLConnection conn = updateURL.openConnection(); InputStream is = conn.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); ByteArrayBuffer baf = new ByteArrayBuffer(50); int current = 0; while((current = bis.read()) != -1){ baf.append((byte)current); } /* Convert the Bytes read to a String. */ txt = new String(baf.toByteArray()); } catch (IOException e) { return NETWORK_ERROR; } catch (Exception e) { e.printStackTrace(); return ERROR; } return SUCCESS; } @Override protected void onCancelled() { this.execute(); } @Override protected void onPostExecute(Integer result) { switch (result) { case NETWORK_ERROR: if(number<10) { Log.i("YAAM", "Network unavailable"); this.cancel(true); } number++; break; case ERROR: break; case SUCCESS: Message msg=new Message(); Bundle data=new Bundle(); data.putString("content", txt); msg.setData(data); handler.sendMessage(msg); break; } } } new LoadURL().execute(); } public static String queryWeb(final String url) { String txt=""; try { URL updateURL = new URL(url); URLConnection conn = updateURL.openConnection(); InputStream is = conn.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); ByteArrayBuffer baf = new ByteArrayBuffer(50); int current = 0; while((current = bis.read()) != -1){ baf.append((byte)current); } /* Convert the Bytes read to a String. */ txt = new String(baf.toByteArray()); return txt; } catch (Exception e) { e.printStackTrace(); return ""; } } public static AlertDialog.Builder dialog(Context context,String title,String txt,String buttonOk) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setMessage(txt) .setCancelable(false) .setPositiveButton(buttonOk, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { }; }); builder.setTitle(title); return builder; } public static AlertDialog.Builder dialog(Context context,String title,int txt,String buttonOk) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setMessage(context.getResources().getString(txt)) .setCancelable(false) .setPositiveButton(buttonOk, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { }; }); builder.setTitle(title); return builder; } public static Bitmap loadImageFromUrl(String url) { URL aURL; try { aURL = new URL(url); URLConnection conn = aURL.openConnection(); conn.connect(); InputStream is = conn.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); Bitmap bm = BitmapFactory.decodeStream(bis); bis.close(); is.close(); return bm; } catch (Exception e) { e.printStackTrace(); } return null; } public static String md5(String s) { try { // Create MD5 Hash MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(s.getBytes()); byte messageDigest[] = digest.digest(); // Create Hex String StringBuffer hexString = new StringBuffer(); for (int i=0; i<messageDigest.length; i++) hexString.append(Integer.toHexString(0xFF & messageDigest[i])); return "0"+hexString.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; } private static String convertToHex(byte[] data) { StringBuffer buf = new StringBuffer(); for (int i = 0; i < data.length; i++) { int halfbyte = (data[i] >>> 4) & 0x0F; int two_halfs = 0; do { if ((0 <= halfbyte) && (halfbyte <= 9)) buf.append((char) ('0' + halfbyte)); else buf.append((char) ('a' + (halfbyte - 10))); halfbyte = data[i] & 0x0F; } while(two_halfs++ < 1); } return buf.toString(); } public static String sha1(String s){ MessageDigest md; try { md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(s.getBytes("iso-8859-1"), 0, s.length()); sha1hash = md.digest(); return convertToHex(sha1hash); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ""; } public static class HTMLEntities { private static Map<String, Character> HTML_ENTITIES; private static Map<Character, String> UTF8_CHARS; private static void initEntities() { HTML_ENTITIES = new HashMap<String, Character>(); HTML_ENTITIES.put("&acute;", '\u00B4'); HTML_ENTITIES.put("&quot;", '\"'); HTML_ENTITIES.put("&amp;", '\u0026'); HTML_ENTITIES.put("&lt;", '\u003C'); HTML_ENTITIES.put("&gt;", '\u003E'); HTML_ENTITIES.put("&nbsp;", '\u00A0'); HTML_ENTITIES.put("&iexcl;", '\u00A1'); HTML_ENTITIES.put("&cent;", '\u00A2'); HTML_ENTITIES.put("&pound;", '\u00A3'); HTML_ENTITIES.put("&curren;", '\u00A4'); HTML_ENTITIES.put("&yen;", '\u00A5'); HTML_ENTITIES.put("&brvbar;", '\u00A6'); HTML_ENTITIES.put("&sect;", '\u00A7'); HTML_ENTITIES.put("&uml;", '\u00A8'); HTML_ENTITIES.put("&copy;", '\u00A9'); HTML_ENTITIES.put("&ordf;", '\u00AA'); HTML_ENTITIES.put("&laquo;", '\u00AB'); HTML_ENTITIES.put("&not;", '\u00AC'); HTML_ENTITIES.put("&shy;", '\u00AD'); HTML_ENTITIES.put("&reg;", '\u00AE'); HTML_ENTITIES.put("&macr;", '\u00AF'); HTML_ENTITIES.put("&deg;", '\u00B0'); HTML_ENTITIES.put("&plusmn;", '\u00B1'); HTML_ENTITIES.put("&sup2;", '\u00B2'); HTML_ENTITIES.put("&sup3;", '\u00B3'); HTML_ENTITIES.put("&acute;", '\u00B4'); HTML_ENTITIES.put("&micro;", '\u00B5'); HTML_ENTITIES.put("&para;", '\u00B6'); HTML_ENTITIES.put("&middot;", '\u00B7'); HTML_ENTITIES.put("&cedil;", '\u00B8'); HTML_ENTITIES.put("&sup1;", '\u00B9'); HTML_ENTITIES.put("&ordm;", '\u00BA'); HTML_ENTITIES.put("&raquo;", '\u00BB'); HTML_ENTITIES.put("&frac14;", '\u00BC'); HTML_ENTITIES.put("&frac12;", '\u00BD'); HTML_ENTITIES.put("&frac34;", '\u00BE'); HTML_ENTITIES.put("&iquest;", '\u00BF'); HTML_ENTITIES.put("&Agrave;", '\u00C0'); HTML_ENTITIES.put("&Aacute;", '\u00C1'); HTML_ENTITIES.put("&Acirc;", '\u00C2'); HTML_ENTITIES.put("&Atilde;", '\u00C3'); HTML_ENTITIES.put("&Auml;", '\u00C4'); HTML_ENTITIES.put("&Aring;", '\u00C5'); HTML_ENTITIES.put("&AElig;", '\u00C6'); HTML_ENTITIES.put("&Ccedil;", '\u00C7'); HTML_ENTITIES.put("&Egrave;", '\u00C8'); HTML_ENTITIES.put("&Eacute;", '\u00C9'); HTML_ENTITIES.put("&Ecirc;", '\u00CA'); HTML_ENTITIES.put("&Euml;", '\u00CB'); HTML_ENTITIES.put("&Igrave;", '\u00CC'); HTML_ENTITIES.put("&Iacute;", '\u00CD'); HTML_ENTITIES.put("&Icirc;", '\u00CE'); HTML_ENTITIES.put("&Iuml;", '\u00CF'); HTML_ENTITIES.put("&ETH;", '\u00D0'); HTML_ENTITIES.put("&Ntilde;", '\u00D1'); HTML_ENTITIES.put("&Ograve;", '\u00D2'); HTML_ENTITIES.put("&Oacute;", '\u00D3'); HTML_ENTITIES.put("&Ocirc;", '\u00D4'); HTML_ENTITIES.put("&Otilde;", '\u00D5'); HTML_ENTITIES.put("&Ouml;", '\u00D6'); HTML_ENTITIES.put("&times;", '\u00D7'); HTML_ENTITIES.put("&Oslash;", '\u00D8'); HTML_ENTITIES.put("&Ugrave;", '\u00D9'); HTML_ENTITIES.put("&Uacute;", '\u00DA'); HTML_ENTITIES.put("&Ucirc;", '\u00DB'); HTML_ENTITIES.put("&Uuml;", '\u00DC'); HTML_ENTITIES.put("&Yacute;", '\u00DD'); HTML_ENTITIES.put("&THORN;", '\u00DE'); HTML_ENTITIES.put("&szlig;", '\u00DF'); HTML_ENTITIES.put("&agrave;", '\u00E0'); HTML_ENTITIES.put("&aacute;", '\u00E1'); HTML_ENTITIES.put("&acirc;", '\u00E2'); HTML_ENTITIES.put("&atilde;", '\u00E3'); HTML_ENTITIES.put("&auml;", '\u00E4'); HTML_ENTITIES.put("&aring;", '\u00E5'); HTML_ENTITIES.put("&aelig;", '\u00E6'); HTML_ENTITIES.put("&ccedil;", '\u00E7'); HTML_ENTITIES.put("&egrave;", '\u00E8'); HTML_ENTITIES.put("&eacute;", '\u00E9'); HTML_ENTITIES.put("&ecirc;", '\u00EA'); HTML_ENTITIES.put("&euml;", '\u00EB'); HTML_ENTITIES.put("&igrave;", '\u00EC'); HTML_ENTITIES.put("&iacute;", '\u00ED'); HTML_ENTITIES.put("&icirc;", '\u00EE'); HTML_ENTITIES.put("&iuml;", '\u00EF'); HTML_ENTITIES.put("&eth;", '\u00F0'); HTML_ENTITIES.put("&ntilde;", '\u00F1'); HTML_ENTITIES.put("&ograve;", '\u00F2'); HTML_ENTITIES.put("&oacute;", '\u00F3'); HTML_ENTITIES.put("&ocirc;", '\u00F4'); HTML_ENTITIES.put("&otilde;", '\u00F5'); HTML_ENTITIES.put("&ouml;", '\u00F6'); HTML_ENTITIES.put("&divide;", '\u00F7'); HTML_ENTITIES.put("&oslash;", '\u00F8'); HTML_ENTITIES.put("&ugrave;", '\u00F9'); HTML_ENTITIES.put("&uacute;", '\u00FA'); HTML_ENTITIES.put("&ucirc;", '\u00FB'); HTML_ENTITIES.put("&uuml;", '\u00FC'); HTML_ENTITIES.put("&yacute;", '\u00FD'); HTML_ENTITIES.put("&thorn;", '\u00FE'); HTML_ENTITIES.put("&yuml;", '\u00FF'); HTML_ENTITIES.put("&OElig;", '\u008C'); HTML_ENTITIES.put("&oelig;", '\u009C'); HTML_ENTITIES.put("&euro;", '\u20AC'); UTF8_CHARS = new HashMap<Character, String>(); for (String key : HTML_ENTITIES.keySet()) { UTF8_CHARS.put(HTML_ENTITIES.get(key), key); } } public static String encode(String s) { if ((UTF8_CHARS == null) && (HTML_ENTITIES == null)) { HTMLEntities.initEntities(); } StringBuffer result = new StringBuffer(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); String htmlEntity = UTF8_CHARS.get(c); if (htmlEntity != null) { result.append(htmlEntity); } else { result.append(c); } } return (result.toString()); } public static String decode(String s) { if ((UTF8_CHARS == null) && (HTML_ENTITIES == null)) { HTMLEntities.initEntities(); } StringBuffer result = new StringBuffer(); int start = 0; Pattern p = Pattern.compile("&[a-zA-Z]+;"); Matcher m = p.matcher(s); while (m.find(start)) { Character utf8Char = HTML_ENTITIES.get(s.substring(m.start(), m.end())); result.append(s.substring(start, m.start())); if (utf8Char != null) { result.append(utf8Char); } else { result.append(s.substring(m.start(), m.end())); } start = m.end(); } String txt = (result.append(s.substring(start)).toString()); txt=txt.replaceAll("<br />", "\n"); txt=txt.replaceAll("<br/>", "\n"); txt=txt.replaceAll("&#039;", "'"); txt=txt.replaceAll("&#39;", "\'"); txt=txt.replaceAll("&#37;","%"); txt=txt.replaceAll("&#36;","$"); txt=txt.replaceAll("&#167;","§"); txt=txt.replace("&#339;","oe"); txt=txt.replace("&#338;","OE"); return txt; } } static public void createYAAMDir() { File yaamDir = new File(Environment.getExternalStorageDirectory().toString() + "/.yaam"); yaamDir.mkdir(); } }
14,298
Java
.java
scleriot/yaam-application
20
4
0
2011-04-16T16:31:15Z
2011-06-20T06:55:23Z
WatchScreensActivity.java
/FileExtraction/Java_unseen/scleriot_yaam-application/src/com/pixellostudio/newyaam/WatchScreensActivity.java
/******************************************************************************* * Copyright (c) 2011 Cleriot Simon <[email protected]>. * * This file is part of YAAM. * * YAAM is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * YAAM is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with YAAM. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ /* This file is part of YAAM. Copyright (C) 2010 Cleriot Simon <[email protected]> YAAM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. YAAM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with YAAM. If not, see <http://www.gnu.org/licenses/>. */ package com.pixellostudio.newyaam; import android.app.Activity; import android.os.Bundle; import android.view.Window; import android.view.WindowManager; import android.widget.ImageView; public class WatchScreensActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.watchscreens); String url=this.getIntent().getExtras().getString("url"); ImageView imageView = (ImageView)this.findViewById(R.id.ImageViewScreen); imageView.setImageBitmap(Tools.loadImageFromUrl(url)); } }
2,583
Java
.java
scleriot/yaam-application
20
4
0
2011-04-16T16:31:15Z
2011-06-20T06:55:23Z
HomeActivity.java
/FileExtraction/Java_unseen/scleriot_yaam-application/src/com/pixellostudio/newyaam/HomeActivity.java
/******************************************************************************* * Copyright (c) 2011 Cleriot Simon <[email protected]>. * * This file is part of YAAM. * * YAAM is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * YAAM is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with YAAM. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.pixellostudio.newyaam; import java.io.ByteArrayInputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.util.DisplayMetrics; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.ListView; public class HomeActivity extends BaseActivity{ List<Integer> appIds=new ArrayList<Integer>(); private ProgressDialog mProgress; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.homescreen); DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); int width = dm.widthPixels; Button buttonApps = (Button) findViewById(R.id.ButtonApps); buttonApps.setWidth(width/3); buttonApps.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent i = new Intent(HomeActivity.this, CategoriesActivity.class); Bundle objetbunble = new Bundle(); objetbunble.putInt("game",0); i.putExtras(objetbunble ); startActivity(i); } }); Button buttonGames = (Button) findViewById(R.id.ButtonGames); buttonGames.setWidth(width/3); buttonGames.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent i = new Intent(HomeActivity.this, CategoriesActivity.class); Bundle objetbunble = new Bundle(); objetbunble.putInt("game",1); i.putExtras(objetbunble ); startActivity(i); } }); Button buttonUpdates = (Button) findViewById(R.id.ButtonUpdates); buttonUpdates.setWidth(width/3); buttonUpdates.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent i = new Intent(HomeActivity.this, UpdatesActivity.class); startActivity(i); } }); //Tools.queryWeb(Functions.getHost(getApplicationContext())+"/yaamUpdate.php", yaamUpdateHandler); mProgress = ProgressDialog.show(this, this.getText(R.string.loading), this.getText(R.string.loadingtext), true, false); SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(this); String terminal=pref.getString("terminal", "phone"); String sdk=Build.VERSION.SDK; String lang=getApplicationContext().getResources().getConfiguration().locale.getISO3Language(); try { Tools.queryWeb(Functions.getHost(getApplicationContext())+"/apps/getAppsRecommended.php?lang="+lang+"&sdk="+URLEncoder.encode(sdk,"UTF-8")+"&terminal="+URLEncoder.encode(terminal,"UTF-8")+"&ypass="+Functions.getPassword(getApplicationContext()), parser); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } ///WELCOME DIALOG/// if(pref.getBoolean("welcome", true)) { AlertDialog.Builder build = new AlertDialog.Builder(this); build.setMessage(R.string.welcome) .setCancelable(false) .setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); AlertDialog dialog = build.create(); dialog.show(); Editor editor=pref.edit(); editor.putBoolean("welcome", false); editor.commit(); } } public Handler parser=new Handler() { public void handleMessage(Message msg) { String content=msg.getData().getString("content"); try { DocumentBuilderFactory builder = DocumentBuilderFactory.newInstance(); DocumentBuilder constructeur = builder.newDocumentBuilder(); Document document = constructeur.parse(new ByteArrayInputStream( content.getBytes())); Element racine = document.getDocumentElement(); NodeList liste = racine.getElementsByTagName("app"); List<String> names=new ArrayList<String>(); List<String> icons=new ArrayList<String>(); List<Float> ratings=new ArrayList<Float>(); List<Float> prices=new ArrayList<Float>(); for(int i=0; i<liste.getLength(); i++){ Element E1= (Element) liste.item(i); String name="",id="",rating="",icon="",price=""; name=Functions.getDataFromXML(E1,"name"); icon=Functions.getDataFromXML(E1,"icon"); id=Functions.getDataFromXML(E1,"id"); rating=Functions.getDataFromXML(E1,"rating"); price=Functions.getDataFromXML(E1,"price"); names.add(name); appIds.add(Integer.valueOf(id)); icons.add(icon); ratings.add(Float.valueOf(rating)); prices.add(Float.valueOf(price)); } ListView listRecommended = (ListView) findViewById(R.id.ListViewRecommended); listRecommended.setAdapter(new AppsListAdapter(HomeActivity.this,names,icons,ratings,prices)); listRecommended.setOnItemClickListener(new OnItemClickListener() { @SuppressWarnings("rawtypes") public void onItemClick(AdapterView parent, View v, int position, long id) { Intent i = new Intent(HomeActivity.this, ShowAppActivity.class); Bundle objetbunble = new Bundle(); objetbunble.putInt("id",appIds.get(position)); i.putExtras(objetbunble ); startActivity(i); } }); //handlerRecommended.sendEmptyMessage(0); } catch (Exception e) { e.printStackTrace(); //handlerError.sendEmptyMessage(0); } mProgress.dismiss(); } }; }
7,254
Java
.java
scleriot/yaam-application
20
4
0
2011-04-16T16:31:15Z
2011-06-20T06:55:23Z
Functions.java
/FileExtraction/Java_unseen/scleriot_yaam-application/src/com/pixellostudio/newyaam/Functions.java
/******************************************************************************* * Copyright (c) 2011 Cleriot Simon <[email protected]>. * * This file is part of YAAM. * * YAAM is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * YAAM is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with YAAM. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.pixellostudio.newyaam; import java.io.File; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import android.app.Activity; import android.app.ProgressDialog; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.os.Message; import android.preference.PreferenceManager; import android.widget.Toast; public class Functions implements Runnable { public static String getPassword(Context context) { return context.getText(R.string.ypass).toString(); } public static String getHost(Context context) { return context.getText(R.string.yhost).toString(); } public static String getDataFromXML(Element E1, String tag) { NodeList liste=E1.getElementsByTagName(tag); Element E2= (Element)liste.item(0); return E2.getAttribute("data"); } private DownloadProcessor mThread; private ProgressDialog mProgress; Configuration config; Activity activity; Service service; Context context; String idApp; public void run() { SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(context); String name=pref.getString("username", ""); String phone=Build.MODEL; String sdk=Build.VERSION.SDK; String lang=config.locale.getISO3Language(); String country=config.locale.getISO3Country(); try { Tools.queryWeb(Functions.getHost(activity.getApplicationContext())+"/apps/addApplicationDL.php?ypass="+Functions.getPassword(activity.getApplicationContext())+"&appid="+idApp+"&username="+URLEncoder.encode(name,"UTF-8")+"&phone="+URLEncoder.encode(phone,"UTF-8")+"&lang="+URLEncoder.encode(lang,"UTF-8")+"&country="+URLEncoder.encode(country,"UTF-8")+"&sdk="+URLEncoder.encode(sdk,"UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } private final DownloadHandler mHandler = new DownloadHandler() { @Override public void handleMessage(Message msg) { DownloadProcessor.Download dl = mThread.getDownload(); switch (msg.what) { case MSG_FINISHED: mProgress.dismiss(); mProgress = null; mThread = null; Thread addAppDl=new Thread(Functions.this); addAppDl.start(); Intent intent=new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.parse("file://"+Environment.getExternalStorageDirectory().toString()+"/.yaam/"+idApp+".apk"), "application/vnd.android.package-archive"); activity.startActivityForResult(intent,1); break; case MSG_SET_LENGTH: mProgress.setIndeterminate(false); mProgress.setProgress(0); dl.length = (Long)msg.obj; break; case MSG_ON_RECV: if (dl.length >= 0) { float prog = ((float)((Long)msg.obj) / (float)dl.length) * 100f; mProgress.setProgress((int)(prog * 100f)); mProgress.setMessage("Received " + (int)prog + "%"); } else { mProgress.setMessage("Received " + (Long)msg.obj + " bytes"); } break; case MSG_ERROR: mProgress.dismiss(); mProgress = null; mThread = null; Toast.makeText(context, "Error: " + msg.obj, Toast.LENGTH_LONG).show(); break; default: super.handleMessage(msg); } } }; public final void install(final String _idApp,final Activity _activity,final Configuration _config) { context=_activity.getApplicationContext(); idApp=_idApp; config=_config; activity=_activity; SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(_activity.getApplicationContext()); String name=pref.getString("username", ""); String src=""; try { src = Functions.getHost(activity.getApplicationContext())+"/apps/downloadApk.php?ypass="+Functions.getPassword(activity.getApplicationContext())+"&username="+URLEncoder.encode(name,"UTF-8")+"&id="+idApp; } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } String dst = Environment.getExternalStorageDirectory().toString()+"/.yaam/"+idApp+".apk"; URL srcUrl; try { srcUrl = new URL(src); } catch (MalformedURLException e) { Toast.makeText(activity, "Invalid source URL", Toast.LENGTH_SHORT).show(); return; } mProgress = ProgressDialog.show(activity, "Downloading...", "Connecting to server...", true, false); DownloadProcessor.Download dl = new DownloadProcessor.Download(srcUrl, new File(dst)); mThread = new DownloadProcessor(dl, mHandler); mThread.start(); } public final void updateYAAM(final Activity _activity,final Configuration _config) { context=_activity.getApplicationContext(); config=_config; activity=_activity; String src= Functions.getHost(activity.getApplicationContext())+"/yaam.apk"; String dst = Environment.getExternalStorageDirectory().toString()+"/.yaam/yaam.apk"; idApp="yaam"; URL srcUrl; try { srcUrl = new URL(src); } catch (MalformedURLException e) { Toast.makeText(activity, "Invalid source URL", Toast.LENGTH_SHORT).show(); return; } mProgress = ProgressDialog.show(activity, "Downloading...", "Connecting to server...", true, false); DownloadProcessor.Download dl = new DownloadProcessor.Download(srcUrl, new File(dst)); mThread = new DownloadProcessor(dl, mHandler); mThread.start(); } }
7,955
Java
.java
scleriot/yaam-application
20
4
0
2011-04-16T16:31:15Z
2011-06-20T06:55:23Z
CheckUpdatesBroadcast.java
/FileExtraction/Java_unseen/scleriot_yaam-application/src/com/pixellostudio/newyaam/CheckUpdatesBroadcast.java
/******************************************************************************* * Copyright (c) 2011 Cleriot Simon <[email protected]>. * * This file is part of YAAM. * * YAAM is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * YAAM is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with YAAM. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.pixellostudio.newyaam; import java.io.ByteArrayInputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Build; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; public class CheckUpdatesBroadcast extends BroadcastReceiver { List<Integer> appIds=new ArrayList<Integer>(); Context _Context; @Override public void onReceive(Context context, Intent intent) { _Context=context; LoadInfos(); } public void LoadInfos() { SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(_Context); String terminal=pref.getString("terminal", "phone"); String username=pref.getString("username", ""); String sdk=Build.VERSION.SDK; String lang=_Context.getResources().getConfiguration().locale.getISO3Language(); try { Tools.queryWeb(Functions.getHost(_Context)+"/apps/getUpdates.php?order=top&username="+URLEncoder.encode(username,"UTF-8")+"&lang="+lang+"&sdk="+URLEncoder.encode(sdk,"UTF-8")+"&terminal="+URLEncoder.encode(terminal,"UTF-8")+"&ypass="+Functions.getPassword(_Context), parser); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } public Handler parser=new Handler() { public void handleMessage(Message msg) { appIds.clear(); String content=msg.getData().getString("content"); try { DocumentBuilderFactory builder = DocumentBuilderFactory.newInstance(); DocumentBuilder constructeur = builder.newDocumentBuilder(); Document document = constructeur.parse(new ByteArrayInputStream( content.getBytes())); Element racine = document.getDocumentElement(); NodeList liste = racine.getElementsByTagName("app"); for(int i=0; i<liste.getLength(); i++){ Element E1= (Element) liste.item(i); String id; id=Functions.getDataFromXML(E1,"id"); if(isAppInstalled(Functions.getDataFromXML(E1,"package"))) { appIds.add(Integer.valueOf(id)); } } if(appIds.size()>0) { int notificationID = 10; NotificationManager notificationManager = (NotificationManager) _Context.getSystemService(Context.NOTIFICATION_SERVICE); Notification notification = new Notification(R.drawable.icon, _Context.getText(R.string.updatesavailable), System.currentTimeMillis()); notification.flags |= Notification.FLAG_AUTO_CANCEL; Intent intent = new Intent(_Context, UpdatesActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pendingIntent = PendingIntent.getActivity(_Context, 0, intent, 0); notification.setLatestEventInfo(_Context, _Context.getText(R.string.newupdate), _Context.getText(R.string.updatesavailable), pendingIntent); notificationManager.notify(notificationID, notification); } } catch (Exception e) { e.printStackTrace(); } } }; public boolean isAppInstalled(String packagename) { PackageManager pm=CheckUpdatesBroadcast.this._Context.getPackageManager(); try { pm.getPackageInfo(packagename, PackageManager.GET_ACTIVITIES); } catch (NameNotFoundException e) { return false; } return true; } }
4,724
Java
.java
scleriot/yaam-application
20
4
0
2011-04-16T16:31:15Z
2011-06-20T06:55:23Z
DownloadProcessor.java
/FileExtraction/Java_unseen/scleriot_yaam-application/src/com/pixellostudio/newyaam/DownloadProcessor.java
package com.pixellostudio.newyaam; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.SingleClientConnManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpParams; import android.util.Log; public class DownloadProcessor extends Thread { public static final String TAG = "DownloadProcessor"; private Download mDownload; private HttpGet mMethod = null; private DownloadHandler mHandler; protected volatile boolean mStopped = false; private Object lock = new Object(); public DownloadProcessor(Download dl, DownloadHandler handler) { mDownload = dl; mHandler = handler; } public Download getDownload() { return mDownload; } private HttpClient getClient() { /* Set the connection timeout to 10s for our test. */ HttpParams params = new BasicHttpParams(); /* Avoid registering the https scheme, and thus initializing * SSLSocketFactory on Android. Seems to be very heavy for some * reason. */ SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); SingleClientConnManager cm = new SingleClientConnManager(params, schemeRegistry); return new DefaultHttpClient(cm, params); } public void run() { Log.d(TAG, "Connecting..."); HttpClient cli = getClient(); HttpGet method; method = new HttpGet(mDownload.url.toString()); /* It's important that we pause here to check if we've been stopped * already. Otherwise, we would happily progress, seemingly ignoring * the stop request. */ if (mStopped == true) return; synchronized(lock) { mMethod = method; } HttpEntity ent = null; InputStream in = null; OutputStream out = null; try { HttpResponse resp = cli.execute(mMethod); if (mStopped == true) return; StatusLine status = resp.getStatusLine(); if (status.getStatusCode() != HttpStatus.SC_OK) throw new Exception("HTTP GET failed: " + status); if ((ent = resp.getEntity()) != null) { long len; if ((len = ent.getContentLength()) >= 0) mHandler.sendSetLength(len); in = ent.getContent(); out = new FileOutputStream(mDownload.getDestination()); byte[] b = new byte[2048]; int n; long bytes = 0; /* Note that for most applications, sending a handler message * after each read() would be unnecessary. Instead, a timed * approach should be utilized to send a message at most every * x seconds. */ while ((n = in.read(b)) >= 0) { bytes += n; mHandler.sendOnRecv(bytes); out.write(b, 0, n); } } if (mStopped == false) mHandler.sendFinished(); } catch (Exception e) { /* We expect a SocketException on cancellation. Any other type of * exception that occurs during cancellation is ignored regardless * as there would be no need to handle it. */ if (mStopped == false) { mHandler.sendError(e.toString()); Log.e(TAG, "Unexpected error", e); } } finally { if (in != null) try { in.close(); } catch (IOException e) {} synchronized(lock) { mMethod = null; } /* Close the socket (if it's still open) and cleanup. */ cli.getConnectionManager().shutdown(); if (out != null) { try { out.close(); } catch (IOException e) { mHandler.sendError("Error writing output: " + e.toString()); return; } finally { if (mStopped == true) mDownload.abortCleanup(); } } } } /** * This method is to be called from a separate thread. That is, not the * one executing run(). When it exits, the download thread should be on * its way out (failing a connect or read call and cleaning up). */ public void stopDownload() { /* As we've written this method, calling it from multiple threads would * be problematic. */ if (mStopped == true) return; /* Too late! */ if (isAlive() == false) return; Log.d(TAG, "Stopping download..."); /* Flag to instruct the downloading thread to halt at the next * opportunity. */ mStopped = true; /* Interrupt the blocking thread. This won't break out of a blocking * I/O request, but will break out of a wait or sleep call. While in * this case we know that no such condition is possible, it is always a * good idea to include an interrupt to avoid assumptions about the * thread in question. */ interrupt(); /* A synchronized lock is necessary to avoid catching mMethod in * an uncommitted state from the download thread. */ synchronized(lock) { /* This closes the socket handling our blocking I/O, which will * interrupt the request immediately. This is not the same as * closing the InputStream yieled by HttpEntity#getContent, as the * stream is synchronized in such a way that would starve our main * thread. */ if (mMethod != null) mMethod.abort(); } mHandler.sendAborted(); Log.d(TAG, "Download stopped."); } public void stopDownloadThenJoin() { stopDownload(); while (true) { try { join(); break; } catch (InterruptedException e) {} } } public static class Download { public URL url; public boolean directory; public File dst; public String name; public long length; public Download(URL url, File dst) { this.url = url; this.dst = dst; /* Figure out the filename to save to from the URL. Note that * it would be better to override once the HTTP server responds, * since a better name will have been provided, possibly after * redirect. But I don't care right now. */ if ((directory = dst.isDirectory()) == true) { String[] paths = url.getPath().split("/"); int n = paths.length; if (n > 0) n--; if (paths[n].length() > 0) name = paths[n]; else name = "index.html"; } } public File getDestination() { File f; if (directory == true) f = new File(dst.getAbsolutePath() + File.separator + name); else f = dst; return f; } /** * Delete the destination file, if it exists. */ public void abortCleanup() { getDestination().delete(); } } }
10,190
Java
.java
scleriot/yaam-application
20
4
0
2011-04-16T16:31:15Z
2011-06-20T06:55:23Z
YAAMUpdate.java
/FileExtraction/Java_unseen/scleriot_yaam-application/src/com/pixellostudio/newyaam/YAAMUpdate.java
/******************************************************************************* * Copyright (c) 2011 Cleriot Simon <[email protected]>. * * This file is part of YAAM. * * YAAM is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * YAAM is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with YAAM. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.pixellostudio.newyaam; import android.app.Activity; import android.content.Intent; import android.os.Bundle; public class YAAMUpdate extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Functions functions=new Functions(); functions.updateYAAM(this, getApplicationContext().getResources().getConfiguration()); } protected void onActivityResult(int requestCode, int resultCode, Intent data) { this.finish(); } }
1,451
Java
.java
scleriot/yaam-application
20
4
0
2011-04-16T16:31:15Z
2011-06-20T06:55:23Z
ShowAppActivity.java
/FileExtraction/Java_unseen/scleriot_yaam-application/src/com/pixellostudio/newyaam/ShowAppActivity.java
/******************************************************************************* * Copyright (c) 2011 Cleriot Simon <[email protected]>. * * This file is part of YAAM. * * YAAM is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * YAAM is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with YAAM. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.pixellostudio.newyaam; import java.io.ByteArrayInputStream; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.math.MathContext; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.ResolveInfo; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.util.Log; import android.view.Display; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.Window; import android.view.WindowManager; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RatingBar; import android.widget.SimpleAdapter; import android.widget.TabHost; import android.widget.TabHost.TabSpec; import android.widget.TextView; import com.paypal.android.MEP.CheckoutButton; import com.paypal.android.MEP.PayPal; import com.paypal.android.MEP.PayPalAdvancedPayment; import com.paypal.android.MEP.PayPalInvoiceData; import com.paypal.android.MEP.PayPalInvoiceItem; import com.paypal.android.MEP.PayPalReceiverDetails; public class ShowAppActivity extends BaseActivity { private String idApp="",name="",size="",packagename="",versionName="",widget="",price="",screens="",rating="",icon="",description="", devname="", devpaypal="", dlCount=""; private String url; private String isUpdate; private float fees=0f; private String discount="0"; private ProgressDialog progressDialog, mProgress; private Dialog paymentDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.showappscreen); /*if (PayPal.getInstance().isLibraryInitialized()) ppObj = PayPal.initWithAppID(this.getBaseContext(), "APP-9VH00888N66449701", PayPal.ENV_LIVE); else ppObj=PayPal.getInstance(); ppObj.setShippingEnabled(false);*/ //ppObj = PayPal.initWithAppID(this.getBaseContext(), "APP-80W284485P519543T", PayPal.ENV_NONE); TabHost mTabHost = (TabHost) this.findViewById(R.id.tabhost); mTabHost.setup(); TabSpec tab1=mTabHost.newTabSpec("tab_infos").setIndicator(getText(R.string.app_infos).toString()).setContent(R.id.LinearLayoutInfos); mTabHost.addTab(tab1); TabSpec tab2=mTabHost.newTabSpec("tab_comments").setIndicator(getText(R.string.app_comments).toString()).setContent(R.id.LinearLayoutComments); mTabHost.addTab(tab2); mTabHost.getTabWidget().getChildAt(0).getLayoutParams().height = 40; mTabHost.getTabWidget().getChildAt(1).getLayoutParams().height = 40; Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay(); int width = display.getWidth(); Button buttonBuy = (Button) findViewById(R.id.ButtonBuy); buttonBuy.setWidth(width); buttonBuy.setVisibility(View.GONE); buttonBuy.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if(isAppBought()) { Functions functions=new Functions(); functions.install(idApp, ShowAppActivity.this, getApplicationContext().getResources().getConfiguration()); } else { ShowChoosePaymentDial(); } } }); Button buttonDL = (Button) findViewById(R.id.ButtonDownload); buttonDL.setWidth(width); buttonDL.setVisibility(View.GONE); buttonDL.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Functions functions=new Functions(); functions.install(idApp, ShowAppActivity.this, getApplicationContext().getResources().getConfiguration()); } }); Button buttonUninstall = (Button) findViewById(R.id.ButtonUninstall); buttonUninstall.setWidth(width/2); buttonUninstall.setVisibility(View.GONE); buttonUninstall.setCompoundDrawablesWithIntrinsicBounds(android.R.drawable.ic_menu_delete, 0, 0, 0); buttonUninstall.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Uri uninstallUri = Uri.fromParts("package", packagename, null); Intent intent = new Intent(Intent.ACTION_DELETE, uninstallUri); startActivityForResult(intent,2); } }); Button buttonOpen = (Button) findViewById(R.id.ButtonOpen); buttonOpen.setWidth(width/2); buttonOpen.setVisibility(View.GONE); buttonOpen.setCompoundDrawablesWithIntrinsicBounds(android.R.drawable.ic_menu_more, 0, 0, 0); buttonOpen.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent i = new Intent(Intent.ACTION_MAIN); PackageManager pm=getPackageManager(); List<ResolveInfo> launchables=pm.queryIntentActivities(i, 0); for(int j=0;j<launchables.size();j++) { ActivityInfo activity=launchables.get(j).activityInfo; if(activity.applicationInfo.packageName.equals(packagename)) { ComponentName name=new ComponentName(activity.applicationInfo.packageName, activity.name); Intent intent=new Intent(Intent.ACTION_MAIN); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); intent.setComponent(name); startActivity(intent); j=launchables.size(); } } } }); Button buttonCommentAndRate = (Button) findViewById(R.id.ButtonComment); buttonCommentAndRate.setWidth(width); buttonCommentAndRate.setCompoundDrawablesWithIntrinsicBounds(android.R.drawable.ic_menu_edit, 0, 0, 0); buttonCommentAndRate.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent intent = new Intent(ShowAppActivity.this,CommentActivity.class); Bundle objetbunble = new Bundle(); objetbunble.putInt("id",Integer.valueOf(idApp)); intent.putExtras(objetbunble ); startActivityForResult(intent,3); } }); if(this.getIntent().getExtras().getInt("id")!=0) { String lang=getApplicationContext().getResources().getConfiguration().locale.getISO3Language(); idApp=String.valueOf(getIntent().getExtras().getInt("id")); SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(ShowAppActivity.this); String username=pref.getString("username", ""); try { url = Functions.getHost(getApplicationContext())+"/apps/application.php?username="+URLEncoder.encode(username,"UTF-8")+"&appid="+idApp+"&lang="+lang+"&ypass="+Functions.getPassword(getApplicationContext()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } //LoadInfos(); } else if(this.getIntent().getExtras().getString("package")!=null) { try { String packagename2=this.getIntent().getExtras().getString("package"); Tools.queryWeb(Functions.getHost(getApplicationContext())+"/apps/idFromPackage.php?package="+URLEncoder.encode(packagename2,"UTF-8")+"&ypass="+Functions.getPassword(getApplicationContext()),gotId); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } @Override protected void onResume() { LoadInfos(); super.onResume(); } public void LoadInfos() { mProgress = ProgressDialog.show(this, this.getText(R.string.loading), this.getText(R.string.loadingtext), true, false); try { Tools.queryWeb(url, parser); } catch (Exception e) { e.printStackTrace(); } } public Handler gotId=new Handler() { public void handleMessage(Message msg) { SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(ShowAppActivity.this); String lang=getApplicationContext().getResources().getConfiguration().locale.getISO3Language(); idApp=msg.getData().getString("content"); String username=pref.getString("username", ""); try { url = Functions.getHost(getApplicationContext())+"/apps/application.php?username="+URLEncoder.encode(username,"UTF-8")+"&appid="+idApp+"&lang="+lang+"&ypass="+Functions.getPassword(getApplicationContext()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } //LoadInfos(); } }; public Handler parser=new Handler() { public void handleMessage(Message msg) { String content=msg.getData().getString("content"); try { DocumentBuilderFactory builder = DocumentBuilderFactory.newInstance(); DocumentBuilder constructeur = builder.newDocumentBuilder(); Document document = constructeur.parse(new ByteArrayInputStream( content.getBytes())); Element racine = document.getDocumentElement(); NodeList liste = racine.getElementsByTagName("app"); for(int i=0; i<liste.getLength(); i++){ Element E1= (Element) liste.item(i); name=Functions.getDataFromXML(E1,"name"); description=Functions.getDataFromXML(E1,"description"); size=Functions.getDataFromXML(E1,"size"); price=Functions.getDataFromXML(E1,"price"); versionName=Functions.getDataFromXML(E1,"version"); dlCount=Functions.getDataFromXML(E1,"dlCount"); screens=Functions.getDataFromXML(E1,"screens"); icon=Functions.getDataFromXML(E1,"icon"); idApp=Functions.getDataFromXML(E1,"id"); rating=Functions.getDataFromXML(E1,"rating"); //TODO : youtube=Functions.getDataFromXML(E1,"youtube"); packagename=Functions.getDataFromXML(E1,"packagename"); devname=Functions.getDataFromXML(E1,"devname"); widget=Functions.getDataFromXML(E1,"widget"); devpaypal=Functions.getDataFromXML(E1,"devpaypal"); isUpdate=Functions.getDataFromXML(E1,"update"); fees=Float.valueOf(Functions.getDataFromXML(E1,"fees")); } description+="<br /><br /><i>"+dlCount+" "+getBaseContext().getText(R.string.downloads)+". Version "+versionName+"</i><br />" + "Size : "+size; description+="<br /><br />"; String[] screensList=screens.split(";"); for(int y=0;y<screensList.length;y++) { if(!screensList[y].equals("")) description+="<a href='screens://"+screensList[y]+"'><img src='"+screensList[y]+"' width='100px' /></a> "; } if(widget.equals("1")) { description+="<br /><br /><b>"+getBaseContext().getText(R.string.applicationcontainswidget)+"</b>"; } TextView nameApp=(TextView) findViewById(R.id.nameApp); TextView authorApp=(TextView) findViewById(R.id.authorApp); WebView descriptionApp=(WebView) findViewById(R.id.descriptionApp); ImageView iconApp=(ImageView) findViewById(R.id.IconApp); Button buttonDL=(Button) findViewById(R.id.ButtonDownload); Button buttonUninstall=(Button) findViewById(R.id.ButtonUninstall); Button buttonBuy=(Button) findViewById(R.id.ButtonBuy); Button buttonOpen=(Button) findViewById(R.id.ButtonOpen); buttonDL.setCompoundDrawablesWithIntrinsicBounds(android.R.drawable.ic_menu_add, 0, 0, 0); buttonBuy.setCompoundDrawablesWithIntrinsicBounds(android.R.drawable.ic_menu_add, 0, 0, 0); nameApp.setText(name); authorApp.setText(getBaseContext().getText(R.string.by)+" "+devname); descriptionApp.loadDataWithBaseURL(null,description,"text/html", "UTF-8","about:blank"); descriptionApp.getSettings().setPluginsEnabled(true); descriptionApp.setWebViewClient(new WebViewClientScreens()); if(icon!="") { iconApp.setImageBitmap(Tools.loadImageFromUrl(icon)); } float rate=Float.valueOf(rating); if(rate==0) ((RatingBar) findViewById(R.id.ratingbar)).setVisibility(View.INVISIBLE); else ((RatingBar) findViewById(R.id.ratingbar)).setRating(rate); NodeList nodeComments = racine.getElementsByTagName("comments"); ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>(); for(int i1=0; i1<nodeComments.getLength(); i1++){ Element E1= (Element) nodeComments.item(i1); String name="",comment="",phone=""; name=Functions.getDataFromXML(E1,"username"); comment=Functions.getDataFromXML(E1,"comment"); phone=Functions.getDataFromXML(E1,"phone"); HashMap<String, String> map = new HashMap<String, String>(); map.put("name", name+" ("+phone+")"); map.put("comment", comment); mylist.add(map); } ListCommentsAdapter adapterComments = new ListCommentsAdapter(getBaseContext(), mylist, R.layout.commentslistlayout, new String[] {"name", "comment"},new int[] {R.id.nameCommentsList, R.id.commentCommentsList}); ListView listComments=(ListView) findViewById(R.id.listViewComments); listComments.setAdapter(adapterComments); Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay(); int width = display.getWidth(); Button buttonCommentAndRate = (Button) findViewById(R.id.ButtonComment); buttonDL.setWidth(width); if(isAppInstalled()) { if(isUpdate.equals("1")) { buttonOpen.setVisibility(View.GONE); buttonUninstall.setVisibility(View.VISIBLE); buttonBuy.setVisibility(View.GONE); buttonDL.setVisibility(View.VISIBLE); buttonDL.setText(R.string.update); buttonDL.setWidth(width/2); } else { buttonOpen.setVisibility(View.VISIBLE); buttonUninstall.setVisibility(View.VISIBLE); buttonBuy.setVisibility(View.GONE); buttonDL.setVisibility(View.GONE); } buttonCommentAndRate.setVisibility(View.VISIBLE); } else { if(Float.valueOf(price)>0) { if(isAppBought()) { buttonOpen.setVisibility(View.GONE); buttonUninstall.setVisibility(View.GONE); buttonBuy.setVisibility(View.GONE); buttonDL.setVisibility(View.VISIBLE); buttonDL.setText(R.string.download); } else { buttonOpen.setVisibility(View.GONE); buttonUninstall.setVisibility(View.GONE); buttonBuy.setVisibility(View.VISIBLE); buttonBuy.setText(R.string.buy); buttonDL.setVisibility(View.GONE); } } else { buttonOpen.setVisibility(View.GONE); buttonUninstall.setVisibility(View.GONE); buttonBuy.setVisibility(View.GONE); buttonDL.setVisibility(View.VISIBLE); buttonDL.setText(R.string.download); } buttonCommentAndRate.setVisibility(View.GONE); } } catch (Exception e) { e.printStackTrace(); } mProgress.dismiss(); } }; /*boolean isUpdate() { PackageManager pm=this.getApplicationContext().getPackageManager(); try { PackageInfo infos=pm.getPackageInfo(packagename, PackageManager.GET_ACTIVITIES); if(infos!=null) { if(versionName.equals(infos.versionName)) { return false; } else { return true; } } else return false; } catch (NameNotFoundException e) { return false; } }*/ public boolean isAppInstalled() { PackageManager pm=this.getApplicationContext().getPackageManager(); try { pm.getPackageInfo(packagename, PackageManager.GET_ACTIVITIES); } catch (NameNotFoundException e) { return false; } return true; } public boolean isAppBought() { SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); String name=pref.getString("username", ""); String txt=""; try { txt = Tools.queryWeb(Functions.getHost(getApplicationContext())+"/apps/isAppBought.php?username="+URLEncoder.encode(name,"UTF-8")+"&appid="+idApp+"&ypass="+Functions.getPassword(getApplicationContext())); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if(txt.equals("bought")) { return true; } else return false; } //Load screens private class WebViewClientScreens extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if(url.startsWith("screens://")) { Intent i = new Intent(ShowAppActivity.this, WatchScreensActivity.class); Bundle objetbunble = new Bundle(); objetbunble.putString("url",url.replace("screens://", "")); i.putExtras(objetbunble ); startActivity(i); } else { Intent viewIntent = new Intent("android.intent.action.VIEW",Uri.parse(url)); startActivity(viewIntent); } return true; } } public Handler boughtHandler=new Handler() { public void handleMessage(Message msg) { progressDialog.dismiss(); AlertDialog.Builder builder = new AlertDialog.Builder(ShowAppActivity.this); if(isAppBought()) { builder.setMessage(R.string.successbought) .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { //LoadInfos(); } }); } else { builder.setMessage(R.string.errorbought) .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { //LoadInfos(); } }); } AlertDialog alertDialog = builder.create(); alertDialog.show(); } }; protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(requestCode==5) //Paypal Payment { progressDialog.dismiss(); paymentDialog.dismiss(); switch(resultCode) { case Activity.RESULT_OK: /* try { int iDiscount=Integer.valueOf(discount); float toPay=(float) (Float.valueOf(price)-(Float.valueOf(price)*iDiscount/100)); SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); String name=pref.getString("username", ""); String url2 = Functions.getHost(getApplicationContext())+"/apps/buy.php?price="+(toPay*(100-fees)/100)+"&ypass="+Functions.getPassword(getApplicationContext())+"&username="+URLEncoder.encode(name,"UTF-8")+"&id="+idApp; Tools.queryWeb(url2); } catch (Exception e) { e.printStackTrace(); } //LoadInfos(); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.successbought) .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // put your code here } }); AlertDialog alertDialog = builder.create(); alertDialog.show();*/ progressDialog = ProgressDialog.show(ShowAppActivity.this,"", "Buying Application on YAAM...", true); progressDialog.show(); try { int iDiscount=Integer.valueOf(discount); float toPay=(float) (Float.valueOf(price)-(Float.valueOf(price)*iDiscount/100)); SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); String name=pref.getString("username", ""); String url2 = Functions.getHost(getApplicationContext())+"/apps/buy.php?price="+(toPay*(100-fees)/100)+"&ypass="+Functions.getPassword(getApplicationContext())+"&username="+URLEncoder.encode(name,"UTF-8")+"&id="+idApp; Tools.queryWeb(url2,boughtHandler); } catch (Exception e) { e.printStackTrace(); } break; } } else if(requestCode==2) //Uninstalled App { if(isAppInstalled()==false) { SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); String name=pref.getString("username", ""); try { Tools.queryWeb(Functions.getHost(getApplicationContext())+"/apps/uninstall.php?ypass="+Functions.getPassword(getApplicationContext())+"&username="+URLEncoder.encode(name,"UTF-8")+"&appid="+idApp); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } else if(requestCode==3) //Comment App { } //LoadInfos(); } public void ShowChoosePaymentDial() { paymentDialog = new Dialog(this); paymentDialog.setContentView(R.layout.choosepaymentdialog); paymentDialog.setTitle(""); paymentDialog.setCancelable(true); progressDialog = ProgressDialog.show(this,"", "Initializing Paypal...", true); progressDialog.show(); Thread libraryPaypalInitializationThread = new Thread() { public void run() { initPaypalLibrary(); } }; libraryPaypalInitializationThread.start(); Button refundButton = (Button) paymentDialog.findViewById(R.id.ButtonDiscount); refundButton.setVisibility(View.GONE); refundButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //TODO : ShowRefundDial(); } }); } private void initPaypalLibrary() { PayPal pp = PayPal.getInstance(); if(pp == null) { Log.d("YAAM","Initializing Paypal..."); pp = PayPal.initWithAppID(this, "APP-9VH00888N66449701", PayPal.ENV_LIVE); //TODO: //pp.setLanguage("en_US"); // Sets the language for the library. pp.setFeesPayer(PayPal.FEEPAYER_EACHRECEIVER); pp.setShippingEnabled(false); } if (PayPal.getInstance().isLibraryInitialized()) { LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); params.bottomMargin = 10; LinearLayout paypalButton = pp.getCheckoutButton(this, PayPal.BUTTON_278x43, CheckoutButton.TEXT_PAY); paypalButton.setLayoutParams(params); ((LinearLayout)paymentDialog.findViewById(R.id.layout_root)).addView(paypalButton); paypalButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { progressDialog = ProgressDialog.show(ShowAppActivity.this,"", "Loading Paypal...", true); progressDialog.show(); Thread thread = new Thread() { public void run() { int iDiscount=Integer.valueOf(discount); float toPay=(float) (Float.valueOf(price)-(Float.valueOf(price)*iDiscount/100)); /*PayPalPayment newPayment = new PayPalPayment(); newPayment.setSubtotal((new BigDecimal(toPay)).round(MathContext.DECIMAL32)); newPayment.setCurrencyType("EUR"); newPayment.setRecipient("[email protected]"); newPayment.setDescription("YAAM application : "+name+" ("+price+"€)"); newPayment.setMerchantName("YAAM Market"); newPayment.setPaymentType(PayPal.PAYMENT_TYPE_SERVICE); Intent checkoutIntent = PayPal.getInstance().checkout(newPayment, ShowAppActivity.this); startActivityForResult(checkoutIntent, 5);*/ SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); String name=pref.getString("username", ""); PayPalAdvancedPayment payment = new PayPalAdvancedPayment(); payment.setCurrencyType("EUR"); //payment.setMerchantName("YAAM Market"); try { payment.setIpnUrl(Functions.getHost(getApplicationContext())+"/apps/buy_ipn.php"); } catch (Exception e) { e.printStackTrace(); } payment.setMemo("YAAM application : "+name+" ("+price+"€)"); /*PayPalReceiverDetails receiverYAAM = new PayPalReceiverDetails(); receiverYAAM.setRecipient("[email protected]"); receiverYAAM.setSubtotal((new BigDecimal(toPay*fees/100)).round(MathContext.DECIMAL32)); //receiverYAAM.setSubtotal((new BigDecimal("10.0")).round(MathContext.DECIMAL32)); receiverYAAM.setIsPrimary(false); receiverYAAM.setPaymentType(PayPal.PAYMENT_TYPE_SERVICE); receiverYAAM.setMerchantName("YAAM Market"); receiverYAAM.setDescription("YAAM fees ("+fees+"%)"); receiverYAAM.setPaymentSubtype(PayPal.PAYMENT_SUBTYPE_NONE); PayPalInvoiceData invoice1 = new PayPalInvoiceData(); PayPalInvoiceItem item1 = new PayPalInvoiceItem(); item1.setName("YAAM fees (15%)"); item1.setTotalPrice((new BigDecimal(toPay*fees/100)).round(MathContext.DECIMAL32)); invoice1.getInvoiceItems().add(item1); receiverYAAM.setInvoiceData(invoice1); payment.getReceivers().add(receiverYAAM);*/ PayPalReceiverDetails receiverDev = new PayPalReceiverDetails(); receiverDev.setRecipient(devpaypal); receiverDev.setSubtotal((new BigDecimal(String.valueOf(toPay*(100-fees)/100))).round(MathContext.DECIMAL32)); receiverDev.setIsPrimary(false); receiverDev.setPaymentType(PayPal.PAYMENT_TYPE_SERVICE); receiverDev.setMerchantName("Developer "+devname); receiverDev.setDescription("Developer benefits ("+(100-fees)+"%)"); receiverDev.setPaymentSubtype(PayPal.PAYMENT_SUBTYPE_NONE); PayPalInvoiceData invoice2 = new PayPalInvoiceData(); PayPalInvoiceItem item2 = new PayPalInvoiceItem(); item2.setName("Developer benefits ("+(100-fees)+"%)"); item2.setTotalPrice((new BigDecimal(String.valueOf(toPay*(100-fees)/100))).round(MathContext.DECIMAL32)); invoice2.getInvoiceItems().add(item2); receiverDev.setInvoiceData(invoice2); payment.getReceivers().add(receiverDev); Intent paypalIntent = PayPal.getInstance().checkout(payment, ShowAppActivity.this); startActivityForResult(paypalIntent, 5); } }; thread.run(); } }); } else { Log.d("YAAM", "Error while initializing paypal!"); } progressDialog.dismiss(); showPaymentDial.sendEmptyMessage(0); } public Handler showPaymentDial=new Handler() { public void handleMessage(Message msg) { paymentDialog.show(); } }; public class ListCommentsAdapter extends SimpleAdapter{ //le constructeur public ListCommentsAdapter (Context context, ArrayList<HashMap<String, String>> data, int resource, String[] from, int[] to) { super(context, data, resource, from, to); } public View getView(int position, View convertView, ViewGroup parent) { View v = super.getView(position, convertView, parent); return v; } } }
30,678
Java
.java
scleriot/yaam-application
20
4
0
2011-04-16T16:31:15Z
2011-06-20T06:55:23Z
CommentActivity.java
/FileExtraction/Java_unseen/scleriot_yaam-application/src/com/pixellostudio/newyaam/CommentActivity.java
/******************************************************************************* * Copyright (c) 2011 Cleriot Simon <[email protected]>. * * This file is part of YAAM. * * YAAM is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * YAAM is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with YAAM. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.pixellostudio.newyaam; import java.net.URLEncoder; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.SharedPreferences; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.EditText; import android.widget.RatingBar; import android.widget.RatingBar.OnRatingBarChangeListener; public class CommentActivity extends BaseActivity implements OnRatingBarChangeListener{ ProgressDialog progressDialog; String terminal="phone"; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.commentscreen); Button commentButton = (Button) findViewById(R.id.ButtonComment); commentButton.setOnClickListener(new OnClickListener(){ public void onClick(View v) { progressDialog = ProgressDialog.show(CommentActivity.this,"", getText(R.string.contactingserver).toString(), true); String idApp=String.valueOf(getIntent().getExtras().getInt("id")); SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(CommentActivity.this); String username=pref.getString("username", ""); EditText editComment = (EditText) findViewById(R.id.EditTextComment); String comment=editComment.getText().toString(); int rating=((RatingBar) findViewById(R.id.ratingbar)).getNumStars(); String phone=Build.MODEL; String sdk=Build.VERSION.SDK; String lang=getApplicationContext().getResources().getConfiguration().locale.getISO3Language(); try { Tools.queryWeb(Functions.getHost(getApplicationContext())+"/comments/add.php?rating="+rating+"&phone="+URLEncoder.encode(phone)+"&sdk="+URLEncoder.encode(sdk)+"&lang="+URLEncoder.encode(lang)+"&appid="+idApp+"&comment="+URLEncoder.encode(comment)+"&username="+URLEncoder.encode(username)+"&ypass="+Functions.getPassword(getApplicationContext()),commentHandler); } catch (Exception e) { e.printStackTrace(); } } }); ((RatingBar)findViewById(R.id.ratingbar)).setOnRatingBarChangeListener(this); } public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromTouch) { ((EditText) findViewById(R.id.EditTextComment)).setVisibility(View.VISIBLE); } private Handler commentHandler=new Handler(){ public void handleMessage(Message msg) { progressDialog.dismiss(); String content=msg.getData().getString("content"); if(content.equals("ok")) { finish(); } else { AlertDialog.Builder builder = new AlertDialog.Builder(CommentActivity.this); builder.setMessage(R.string.erroroccured) .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); } } }; }
4,436
Java
.java
scleriot/yaam-application
20
4
0
2011-04-16T16:31:15Z
2011-06-20T06:55:23Z
CategoriesActivity.java
/FileExtraction/Java_unseen/scleriot_yaam-application/src/com/pixellostudio/newyaam/CategoriesActivity.java
/******************************************************************************* * Copyright (c) 2011 Cleriot Simon <[email protected]>. * * This file is part of YAAM. * * YAAM is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * YAAM is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with YAAM. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.pixellostudio.newyaam; import java.io.ByteArrayInputStream; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; public class CategoriesActivity extends BaseActivity{ List<String> categoriesId=new ArrayList<String>(); List<String> categoriesName=new ArrayList<String>(); private ProgressDialog mProgress; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.categoriesscreen); int game=getIntent().getExtras().getInt("game"); String lang=getApplicationContext().getResources().getConfiguration().locale.getISO3Language(); mProgress = ProgressDialog.show(this, this.getText(R.string.loading), this.getText(R.string.loadingtext), true, false); try { Tools.queryWeb(Functions.getHost(getApplicationContext())+"/categories/get.php?lang="+lang+"&game="+game+"&ypass="+Functions.getPassword(getApplicationContext()), parser); } catch (Exception e) { e.printStackTrace(); } } public Handler parser=new Handler() { public void handleMessage(Message msg) { String content=msg.getData().getString("content"); try { DocumentBuilderFactory builder = DocumentBuilderFactory.newInstance(); DocumentBuilder constructeur = builder.newDocumentBuilder(); Document document = constructeur.parse(new ByteArrayInputStream( content.getBytes())); Element racine = document.getDocumentElement(); NodeList liste = racine.getElementsByTagName("cat"); ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1); int game=getIntent().getExtras().getInt("game"); if(game==0) { adapter.add(getBaseContext().getText(R.string.allapplications).toString()); categoriesId.add("-1"); categoriesName.add(getBaseContext().getText(R.string.allapplications).toString()); } else { adapter.add(getBaseContext().getText(R.string.allgames).toString()); categoriesId.add("-2"); categoriesName.add(getBaseContext().getText(R.string.allgames).toString()); } for(int i=0; i<liste.getLength(); i++){ Element E1= (Element) liste.item(i); String name="",id=""; name=Functions.getDataFromXML(E1,"name"); id=Functions.getDataFromXML(E1,"id"); adapter.add(name); categoriesId.add(id); categoriesName.add(name); } ListView listRecommended = (ListView) findViewById(R.id.ListViewCategories); listRecommended.setAdapter(adapter); listRecommended.setOnItemClickListener(new OnItemClickListener() { @SuppressWarnings("rawtypes") public void onItemClick(AdapterView parent, View v, int position, long id) { Intent i = new Intent(CategoriesActivity.this, CategoryActivity.class); Bundle objetbunble = new Bundle(); objetbunble.putInt("id",Integer.valueOf(categoriesId.get(position))); objetbunble.putString("name",categoriesName.get(position)); i.putExtras(objetbunble ); startActivity(i); } }); //handlerRecommended.sendEmptyMessage(0); } catch (Exception e) { e.printStackTrace(); //handlerError.sendEmptyMessage(0); } mProgress.dismiss(); } }; }
4,823
Java
.java
scleriot/yaam-application
20
4
0
2011-04-16T16:31:15Z
2011-06-20T06:55:23Z
CategoryActivity.java
/FileExtraction/Java_unseen/scleriot_yaam-application/src/com/pixellostudio/newyaam/CategoryActivity.java
/******************************************************************************* * Copyright (c) 2011 Cleriot Simon <[email protected]>. * * This file is part of YAAM. * * YAAM is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * YAAM is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with YAAM. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.pixellostudio.newyaam; import java.io.ByteArrayInputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import android.app.ProgressDialog; import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.view.Display; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.ListView; import android.widget.TabHost; import android.widget.TabHost.TabSpec; import android.widget.TextView; public class CategoryActivity extends BaseActivity { int PAID=0; int FREE=1; List<Integer> appIdsFree=new ArrayList<Integer>(); List<Integer> appIdsPaid=new ArrayList<Integer>(); String order="top"; int pageFree=0; int pagePaid=0; TabHost mTabHost; private ProgressDialog mProgress; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.categoryscreen); mTabHost = (TabHost) this.findViewById(R.id.tabhost); mTabHost.setup(); TabSpec tab1=mTabHost.newTabSpec("tab_free").setIndicator(getText(R.string.categories_paid).toString()).setContent(R.id.LinearLayoutPaid); mTabHost.addTab(tab1); TabSpec tab2=mTabHost.newTabSpec("tab_paid").setIndicator(getText(R.string.categories_free).toString()).setContent(R.id.LinearLayoutFree); mTabHost.addTab(tab2); mTabHost.getTabWidget().getChildAt(PAID).getLayoutParams().height = 40; mTabHost.getTabWidget().getChildAt(FREE).getLayoutParams().height = 40; TextView textCatName = (TextView) findViewById(R.id.TextViewCategoryName); textCatName.setText(getIntent().getExtras().getString("name")+" ("+getText(R.string.top)+")".toString()); Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay(); int width = display.getWidth(); /////FREE BUTTONS////// Button buttonPrevFree = (Button) findViewById(R.id.ButtonPrevFree); //buttonPrevFree.setBackgroundDrawable(this.getResources().getDrawable(android.R.drawable.)); buttonPrevFree.setWidth(width/2); buttonPrevFree.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { pageFree--; updateButtons(); LoadInfos(); } }); Button buttonNextFree = (Button) findViewById(R.id.ButtonNextFree); buttonNextFree.setWidth(width/2); buttonNextFree.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { pageFree++; updateButtons(); LoadInfos(); } }); /////PAID BUTTONS////// Button buttonPrevPaid = (Button) findViewById(R.id.ButtonPrevPaid); buttonPrevPaid.setWidth(width/2); buttonPrevPaid.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { pagePaid--; updateButtons(); LoadInfos(); } }); Button buttonNextPaid = (Button) findViewById(R.id.ButtonNextPaid); buttonNextPaid.setWidth(width/2); buttonNextPaid.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { pagePaid++; updateButtons(); LoadInfos(); } }); updateButtons(); LoadInfos(); } public void updateButtons() { ///FREE BUTTONS/// Button buttonPrevFree = (Button) findViewById(R.id.ButtonPrevFree); if(pageFree<=0) buttonPrevFree.setEnabled(false); else buttonPrevFree.setEnabled(true); ///PAID BUTTONS/// Button buttonPrevPaid = (Button) findViewById(R.id.ButtonPrevPaid); if(pagePaid<=0) buttonPrevPaid.setEnabled(false); else buttonPrevPaid.setEnabled(true); } public void LoadInfos() { mProgress = ProgressDialog.show(this, this.getText(R.string.loading), this.getText(R.string.loadingtext), true, false); int catid=getIntent().getExtras().getInt("id"); SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(this); String terminal=pref.getString("terminal", "phone"); String sdk=Build.VERSION.SDK; String lang=getApplicationContext().getResources().getConfiguration().locale.getISO3Language(); try { Tools.queryWeb(Functions.getHost(getApplicationContext())+"/categories/applications.php?page="+pageFree+"&order="+order+"&catid="+catid+"&lang="+lang+"&sdk="+URLEncoder.encode(sdk,"UTF-8")+"&paid=0&terminal="+URLEncoder.encode(terminal,"UTF-8")+"&ypass="+Functions.getPassword(getApplicationContext()), parserFree); Tools.queryWeb(Functions.getHost(getApplicationContext())+"/categories/applications.php?page="+pagePaid+"&order="+order+"&catid="+catid+"&lang="+lang+"&sdk="+URLEncoder.encode(sdk,"UTF-8")+"&paid=1&terminal="+URLEncoder.encode(terminal,"UTF-8")+"&ypass="+Functions.getPassword(getApplicationContext()), parserPaid); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } public Handler parserFree=new Handler() { public void handleMessage(Message msg) { appIdsFree.clear(); String content=msg.getData().getString("content"); try { DocumentBuilderFactory builder = DocumentBuilderFactory.newInstance(); DocumentBuilder constructeur = builder.newDocumentBuilder(); Document document = constructeur.parse(new ByteArrayInputStream( content.getBytes())); Element racine = document.getDocumentElement(); NodeList liste = racine.getElementsByTagName("app"); List<String> names=new ArrayList<String>(); List<String> icons=new ArrayList<String>(); List<Float> ratings=new ArrayList<Float>(); List<Float> prices=new ArrayList<Float>(); for(int i=0; i<liste.getLength(); i++){ Element E1= (Element) liste.item(i); String name="",id="",rating="",icon="",price=""; name=Functions.getDataFromXML(E1,"name"); icon=Functions.getDataFromXML(E1,"icon"); id=Functions.getDataFromXML(E1,"id"); rating=Functions.getDataFromXML(E1,"rating"); price=Functions.getDataFromXML(E1,"price"); names.add(name); appIdsFree.add(Integer.valueOf(id)); icons.add(icon); prices.add(Float.valueOf(price)); ratings.add(Float.valueOf(rating)); } ListView listRecommended = (ListView) findViewById(R.id.ListViewAppsFree); listRecommended.setAdapter(new AppsListAdapter(CategoryActivity.this,names,icons,ratings,prices)); listRecommended.setOnItemClickListener(new OnItemClickListener() { @SuppressWarnings("rawtypes") public void onItemClick(AdapterView parent, View v, int position, long id) { Intent i = new Intent(CategoryActivity.this, ShowAppActivity.class); Bundle objetbunble = new Bundle(); objetbunble.putInt("id",appIdsFree.get(position)); i.putExtras(objetbunble ); startActivity(i); } }); } catch (Exception e) { e.printStackTrace(); } TextView title = (TextView) mTabHost.getTabWidget().getChildAt(FREE).findViewById(android.R.id.title); if(appIdsFree.size()<10) title.setText(CategoryActivity.this.getText(R.string.categories_free)+" ("+appIdsFree.size()+")"); else title.setText(CategoryActivity.this.getText(R.string.categories_free)+" ("+appIdsFree.size()+"+)"); mProgress.dismiss(); } }; public Handler parserPaid=new Handler() { public void handleMessage(Message msg) { appIdsPaid.clear(); String content=msg.getData().getString("content"); try { DocumentBuilderFactory builder = DocumentBuilderFactory.newInstance(); DocumentBuilder constructeur = builder.newDocumentBuilder(); Document document = constructeur.parse(new ByteArrayInputStream( content.getBytes())); Element racine = document.getDocumentElement(); NodeList liste = racine.getElementsByTagName("app"); List<String> names=new ArrayList<String>(); List<String> icons=new ArrayList<String>(); List<Float> ratings=new ArrayList<Float>(); List<Float> prices=new ArrayList<Float>(); for(int i=0; i<liste.getLength(); i++){ Element E1= (Element) liste.item(i); String name="",id="",rating="",icon="",price=""; name=Functions.getDataFromXML(E1,"name"); icon=Functions.getDataFromXML(E1,"icon"); id=Functions.getDataFromXML(E1,"id"); rating=Functions.getDataFromXML(E1,"rating"); price=Functions.getDataFromXML(E1,"price"); names.add(name); appIdsPaid.add(Integer.valueOf(id)); icons.add(icon); prices.add(Float.valueOf(price)); ratings.add(Float.valueOf(rating)); } ListView listRecommended = (ListView) findViewById(R.id.ListViewAppsPaid); listRecommended.setAdapter(new AppsListAdapter(CategoryActivity.this,names,icons,ratings,prices)); listRecommended.setOnItemClickListener(new OnItemClickListener() { @SuppressWarnings("rawtypes") public void onItemClick(AdapterView parent, View v, int position, long id) { Intent i = new Intent(CategoryActivity.this, ShowAppActivity.class); Bundle objetbunble = new Bundle(); objetbunble.putInt("id",appIdsPaid.get(position)); i.putExtras(objetbunble ); startActivity(i); } }); } catch (Exception e) { e.printStackTrace(); } TextView title = (TextView) mTabHost.getTabWidget().getChildAt(PAID).findViewById(android.R.id.title); if(appIdsPaid.size()<10) title.setText(CategoryActivity.this.getText(R.string.categories_paid)+" ("+appIdsPaid.size()+")"); else title.setText(CategoryActivity.this.getText(R.string.categories_paid)+" ("+appIdsPaid.size()+"+)"); mProgress.dismiss(); } }; public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, 1, 0, R.string.top); menu.add(0, 2, 0, R.string.last); menu.add(0, 3, 0, R.string.search_menu).setIcon(android.R.drawable.ic_menu_search); return true; } public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case 1: //Top order="top"; TextView textCatName = (TextView) findViewById(R.id.TextViewCategoryName); textCatName.setText(getIntent().getExtras().getString("name")+" ("+getText(R.string.top)+")".toString()); pageFree=0; pagePaid=0; updateButtons(); LoadInfos(); return true; case 2: //Last order="last"; TextView textCatName2 = (TextView) findViewById(R.id.TextViewCategoryName); textCatName2.setText(getIntent().getExtras().getString("name")+" ("+getText(R.string.last).toString()+")"); pageFree=0; pagePaid=0; updateButtons(); LoadInfos(); return true; case 3: //Search this.startSearch("", false, null, false); return true; } return false; } }
12,780
Java
.java
scleriot/yaam-application
20
4
0
2011-04-16T16:31:15Z
2011-06-20T06:55:23Z
LoginActivity.java
/FileExtraction/Java_unseen/scleriot_yaam-application/src/com/pixellostudio/newyaam/LoginActivity.java
/******************************************************************************* * Copyright (c) 2011 Cleriot Simon <[email protected]>. * * This file is part of YAAM. * * YAAM is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * YAAM is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with YAAM. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.pixellostudio.newyaam; import java.io.File; import java.io.FileWriter; import java.net.URLEncoder; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.EditText; import android.widget.RadioButton; public class LoginActivity extends Activity{ ProgressDialog progressDialog; String terminal="phone"; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.loginscreen); // Ensure /sdcard/.yaam directory is present Tools.createYAAMDir(); SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(this); if(pref.getBoolean("connected2", false)) { Intent intent = new Intent(LoginActivity.this, HomeActivity.class); startActivity(intent); this.finish(); } RadioButton radio1=(RadioButton) findViewById(R.id.RadioPhone); radio1.setOnClickListener(new OnClickListener(){ public void onClick(View v) { terminal="phone"; } }); RadioButton radio2=(RadioButton) findViewById(R.id.RadioTablet); radio2.setOnClickListener(new OnClickListener(){ public void onClick(View v) { terminal="tablet"; } }); RadioButton radio3=(RadioButton) findViewById(R.id.RadioGoogleTV); radio3.setOnClickListener(new OnClickListener(){ public void onClick(View v) { terminal="gtv"; } }); Button loginButton = (Button) findViewById(R.id.ButtonLogin); loginButton.setOnClickListener(new OnClickListener(){ public void onClick(View v) { progressDialog = ProgressDialog.show(LoginActivity.this,getText(R.string.logging).toString(), getText(R.string.contactingserver).toString(), true); String username, password; EditText editUsername = (EditText) findViewById(R.id.EditTextUsername); EditText editPassword = (EditText) findViewById(R.id.EditTextPassword); username=editUsername.getText().toString(); password=editPassword.getText().toString(); try { Tools.queryWeb(Functions.getHost(getApplicationContext())+"/account/login.php?password="+URLEncoder.encode(Tools.sha1("yaamprotection"+password+"echoyaamemee"),"UTF-8")+"&username="+URLEncoder.encode(username)+"&ypass="+Functions.getPassword(getApplicationContext()),connectedHandler); } catch (Exception e) { e.printStackTrace(); } } }); Button registerButton = (Button) findViewById(R.id.ButtonRegister); registerButton.setOnClickListener(new OnClickListener(){ public void onClick(View v) { Intent intent = new Intent(LoginActivity.this, RegisterActivity.class); startActivity(intent); } }); } private Handler connectedHandler=new Handler(){ public void handleMessage(Message msg) { progressDialog.dismiss(); String content=msg.getData().getString("content"); if(content.equals("ok")) { EditText editUsername = (EditText) findViewById(R.id.EditTextUsername); EditText editPassword = (EditText) findViewById(R.id.EditTextPassword); SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(LoginActivity.this.getApplicationContext()); Editor editor=pref.edit(); editor.putBoolean("connected2", true); editor.putString("username", editUsername.getText().toString()); editor.putString("password", Tools.sha1("yaamprotection"+editPassword.getText().toString()+"echoyaamemee")); editor.putString("terminal", terminal); editor.commit(); File file=new File(Environment.getExternalStorageDirectory().toString()+"/.yaam/user"); file.delete(); try { String username=Tools.sha1(pref.getString("username", "").toUpperCase()+"YAAMISTHEBEST"); FileWriter writer = new FileWriter(file); writer.append(username); writer.flush(); writer.close(); } catch (Exception e) { e.printStackTrace(); } file=new File(Environment.getExternalStorageDirectory().toString()+"/.yaam/password"); file.delete(); try { String pass=Tools.sha1("yaamprotection"+editPassword.getText().toString()+"echoyaamemee"); FileWriter writer = new FileWriter(file); writer.append(pass); writer.flush(); writer.close(); } catch (Exception e) { e.printStackTrace(); } Intent intent = new Intent(LoginActivity.this, HomeActivity.class); startActivity(intent); finish(); } else { AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this); builder.setMessage(R.string.errorconnection) .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); } } }; }
7,076
Java
.java
scleriot/yaam-application
20
4
0
2011-04-16T16:31:15Z
2011-06-20T06:55:23Z
RegisterActivity.java
/FileExtraction/Java_unseen/scleriot_yaam-application/src/com/pixellostudio/newyaam/RegisterActivity.java
/******************************************************************************* * Copyright (c) 2011 Cleriot Simon <[email protected]>. * * This file is part of YAAM. * * YAAM is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * YAAM is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with YAAM. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.pixellostudio.newyaam; import java.net.URLEncoder; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.EditText; public class RegisterActivity extends Activity{ ProgressDialog progressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.registerscreen); Button registerButton = (Button) findViewById(R.id.ButtonRegister); registerButton.setOnClickListener(new OnClickListener(){ public void onClick(View v) { String username, password,password2,email; EditText editUsername = (EditText) findViewById(R.id.EditTextUsername); EditText editMail = (EditText) findViewById(R.id.EditTextEmail); EditText editPassword = (EditText) findViewById(R.id.EditTextPassword1); EditText editPassword2 = (EditText) findViewById(R.id.EditTextPassword2); username=editUsername.getText().toString(); email=editMail.getText().toString(); password=editPassword.getText().toString(); password2=editPassword2.getText().toString(); if(password.equals(password2)) { progressDialog = ProgressDialog.show(RegisterActivity.this,getText(R.string.registering).toString(), getText(R.string.contactingserver).toString(), true); try { Tools.queryWeb(Functions.getHost(getApplicationContext())+"/account/register.php?password="+URLEncoder.encode(Tools.sha1("yaamprotection"+password+"echoyaamemee"),"UTF-8")+"&username="+URLEncoder.encode(username)+"&email="+URLEncoder.encode(email)+"&ypass="+Functions.getPassword(getApplicationContext()),registeredHandler); } catch (Exception e) { e.printStackTrace(); } } else { AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this); builder.setMessage(R.string.passworddontmatch) .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); } } }); } private Handler registeredHandler=new Handler(){ public void handleMessage(Message msg) { String content=msg.getData().getString("content"); progressDialog.dismiss(); if(content.equals("ok")) { AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this); builder.setMessage(R.string.needactivate) .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { RegisterActivity.this.finish(); } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); } else { AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this); builder.setMessage(R.string.erroroccured) .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); } } }; }
4,673
Java
.java
scleriot/yaam-application
20
4
0
2011-04-16T16:31:15Z
2011-06-20T06:55:23Z
HandleIntent.java
/FileExtraction/Java_unseen/scleriot_yaam-application/src/com/pixellostudio/newyaam/HandleIntent.java
/******************************************************************************* * Copyright (c) 2011 Cleriot Simon <[email protected]>. * * This file is part of YAAM. * * YAAM is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * YAAM is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with YAAM. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.pixellostudio.newyaam; import android.app.Activity; import android.content.Intent; import android.os.Bundle; public class HandleIntent extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent i = this.getIntent(); if(i.getDataString().contains("yaam://details?id=") || i.getDataString().contains("market://details?id=")) { String packagename=""; if(i.getDataString().contains("yaam://details?id=")) packagename=i.getDataString().replace("yaam://details?id=",""); else if(i.getDataString().contains("market://details?id=")) packagename=i.getDataString().replace("market://details?id=",""); Intent j = new Intent(HandleIntent.this, ShowAppActivity.class); Bundle objetbunble = new Bundle(); objetbunble.putString("package",packagename); j.putExtras(objetbunble ); startActivity(j); this.finish(); } } }
2,060
Java
.java
scleriot/yaam-application
20
4
0
2011-04-16T16:31:15Z
2011-06-20T06:55:23Z
SearchActivity.java
/FileExtraction/Java_unseen/scleriot_yaam-application/src/com/pixellostudio/newyaam/SearchActivity.java
/******************************************************************************* * Copyright (c) 2011 Cleriot Simon <[email protected]>. * * This file is part of YAAM. * * YAAM is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * YAAM is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with YAAM. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.pixellostudio.newyaam; import java.io.ByteArrayInputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import android.app.ProgressDialog; import android.app.SearchManager; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.view.Display; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.ListView; import android.widget.TabHost; import android.widget.TabHost.TabSpec; import android.widget.TextView; public class SearchActivity extends BaseActivity { int PAID=0; int FREE=1; List<Integer> appIdsFree=new ArrayList<Integer>(); List<Integer> appIdsPaid=new ArrayList<Integer>(); String order="top"; String query; TabHost mTabHost; private ProgressDialog mProgress; int pageFree=0; int pagePaid=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.categoryscreen); mTabHost = (TabHost) this.findViewById(R.id.tabhost); mTabHost.setup(); TabSpec tab1=mTabHost.newTabSpec("tab_paid").setIndicator(getText(R.string.categories_paid).toString()).setContent(R.id.LinearLayoutPaid); mTabHost.addTab(tab1); TabSpec tab2=mTabHost.newTabSpec("tab_free").setIndicator(getText(R.string.categories_free).toString()).setContent(R.id.LinearLayoutFree); mTabHost.addTab(tab2); mTabHost.getTabWidget().getChildAt(PAID).getLayoutParams().height = 40; mTabHost.getTabWidget().getChildAt(FREE).getLayoutParams().height = 40; TextView textCatName = (TextView) findViewById(R.id.TextViewCategoryName); textCatName.setText(getBaseContext().getText(R.string.search_results)+" ("+getText(R.string.top)+")".toString()); Intent intent = getIntent(); if (Intent.ACTION_SEARCH.equals(intent.getAction())) { query = intent.getStringExtra(SearchManager.QUERY); //Log.d("YAAM", query); LoadInfos(); } Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay(); int width = display.getWidth(); /////FREE BUTTONS////// Button buttonPrevFree = (Button) findViewById(R.id.ButtonPrevFree); //buttonPrevFree.setBackgroundDrawable(this.getResources().getDrawable(android.R.drawable.)); buttonPrevFree.setWidth(width/2); buttonPrevFree.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { pageFree--; updateButtons(); LoadInfos(); } }); Button buttonNextFree = (Button) findViewById(R.id.ButtonNextFree); buttonNextFree.setWidth(width/2); buttonNextFree.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { pageFree++; updateButtons(); LoadInfos(); } }); /////PAID BUTTONS////// Button buttonPrevPaid = (Button) findViewById(R.id.ButtonPrevPaid); buttonPrevPaid.setWidth(width/2); buttonPrevPaid.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { pagePaid--; updateButtons(); LoadInfos(); } }); Button buttonNextPaid = (Button) findViewById(R.id.ButtonNextPaid); buttonNextPaid.setWidth(width/2); buttonNextPaid.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { pagePaid++; updateButtons(); LoadInfos(); } }); updateButtons(); } public void updateButtons() { ///FREE BUTTONS/// Button buttonPrevFree = (Button) findViewById(R.id.ButtonPrevFree); if(pageFree<=0) buttonPrevFree.setEnabled(false); else buttonPrevFree.setEnabled(true); ///PAID BUTTONS/// Button buttonPrevPaid = (Button) findViewById(R.id.ButtonPrevPaid); if(pagePaid<=0) buttonPrevPaid.setEnabled(false); else buttonPrevPaid.setEnabled(true); } public void LoadInfos() { mProgress = ProgressDialog.show(this, this.getText(R.string.loading), this.getText(R.string.loadingtext), true, false); SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(this); String terminal=pref.getString("terminal", "phone"); String sdk=Build.VERSION.SDK; String lang=getApplicationContext().getResources().getConfiguration().locale.getISO3Language(); try { Tools.queryWeb(Functions.getHost(getApplicationContext())+"/apps/search.php?page="+pageFree+"&order="+order+"&query="+URLEncoder.encode(query,"UTF-8")+"&lang="+lang+"&sdk="+URLEncoder.encode(sdk,"UTF-8")+"&paid=0&terminal="+URLEncoder.encode(terminal,"UTF-8")+"&ypass="+Functions.getPassword(getApplicationContext()), parserFree); Tools.queryWeb(Functions.getHost(getApplicationContext())+"/apps/search.php?page="+pagePaid+"&order="+order+"&query="+URLEncoder.encode(query,"UTF-8")+"&lang="+lang+"&sdk="+URLEncoder.encode(sdk,"UTF-8")+"&paid=1&terminal="+URLEncoder.encode(terminal,"UTF-8")+"&ypass="+Functions.getPassword(getApplicationContext()), parserPaid); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } public Handler parserFree=new Handler() { public void handleMessage(Message msg) { appIdsFree.clear(); String content=msg.getData().getString("content"); try { DocumentBuilderFactory builder = DocumentBuilderFactory.newInstance(); DocumentBuilder constructeur = builder.newDocumentBuilder(); Document document = constructeur.parse(new ByteArrayInputStream( content.getBytes())); Element racine = document.getDocumentElement(); NodeList liste = racine.getElementsByTagName("app"); List<String> names=new ArrayList<String>(); List<String> icons=new ArrayList<String>(); List<Float> ratings=new ArrayList<Float>(); List<Float> prices=new ArrayList<Float>(); for(int i=0; i<liste.getLength(); i++){ Element E1= (Element) liste.item(i); String name="",id="",rating="",icon="",price=""; name=Functions.getDataFromXML(E1,"name"); icon=Functions.getDataFromXML(E1,"icon"); id=Functions.getDataFromXML(E1,"id"); rating=Functions.getDataFromXML(E1,"rating"); price=Functions.getDataFromXML(E1,"price"); names.add(name); appIdsFree.add(Integer.valueOf(id)); icons.add(icon); prices.add(Float.valueOf(price)); ratings.add(Float.valueOf(rating)); } ListView listRecommended = (ListView) findViewById(R.id.ListViewAppsFree); listRecommended.setAdapter(new AppsListAdapter(SearchActivity.this,names,icons,ratings,prices)); listRecommended.setOnItemClickListener(new OnItemClickListener() { @SuppressWarnings("rawtypes") public void onItemClick(AdapterView parent, View v, int position, long id) { Intent i = new Intent(SearchActivity.this, ShowAppActivity.class); Bundle objetbunble = new Bundle(); objetbunble.putInt("id",appIdsFree.get(position)); i.putExtras(objetbunble ); startActivity(i); } }); } catch (Exception e) { e.printStackTrace(); } TextView title = (TextView) mTabHost.getTabWidget().getChildAt(FREE).findViewById(android.R.id.title); if(appIdsFree.size()<10) title.setText(SearchActivity.this.getText(R.string.categories_free)+" ("+appIdsFree.size()+")"); else title.setText(SearchActivity.this.getText(R.string.categories_free)+" ("+appIdsFree.size()+"+)"); mProgress.dismiss(); } }; public Handler parserPaid=new Handler() { public void handleMessage(Message msg) { appIdsPaid.clear(); String content=msg.getData().getString("content"); try { DocumentBuilderFactory builder = DocumentBuilderFactory.newInstance(); DocumentBuilder constructeur = builder.newDocumentBuilder(); Document document = constructeur.parse(new ByteArrayInputStream( content.getBytes())); Element racine = document.getDocumentElement(); NodeList liste = racine.getElementsByTagName("app"); List<String> names=new ArrayList<String>(); List<String> icons=new ArrayList<String>(); List<Float> ratings=new ArrayList<Float>(); List<Float> prices=new ArrayList<Float>(); for(int i=0; i<liste.getLength(); i++){ Element E1= (Element) liste.item(i); String name="",id="",rating="",icon="",price=""; name=Functions.getDataFromXML(E1,"name"); icon=Functions.getDataFromXML(E1,"icon"); id=Functions.getDataFromXML(E1,"id"); rating=Functions.getDataFromXML(E1,"rating"); price=Functions.getDataFromXML(E1,"price"); names.add(name); appIdsPaid.add(Integer.valueOf(id)); icons.add(icon); prices.add(Float.valueOf(price)); ratings.add(Float.valueOf(rating)); } ListView listRecommended = (ListView) findViewById(R.id.ListViewAppsPaid); listRecommended.setAdapter(new AppsListAdapter(SearchActivity.this,names,icons,ratings,prices)); listRecommended.setOnItemClickListener(new OnItemClickListener() { @SuppressWarnings("rawtypes") public void onItemClick(AdapterView parent, View v, int position, long id) { Intent i = new Intent(SearchActivity.this, ShowAppActivity.class); Bundle objetbunble = new Bundle(); objetbunble.putInt("id",appIdsPaid.get(position)); i.putExtras(objetbunble ); startActivity(i); } }); } catch (Exception e) { e.printStackTrace(); } TextView title = (TextView) mTabHost.getTabWidget().getChildAt(PAID).findViewById(android.R.id.title); if(appIdsPaid.size()<10) title.setText(SearchActivity.this.getText(R.string.categories_paid)+" ("+appIdsPaid.size()+")"); else title.setText(SearchActivity.this.getText(R.string.categories_paid)+" ("+appIdsPaid.size()+"+)"); mProgress.dismiss(); } }; public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, 1, 0, R.string.top); menu.add(0, 2, 0, R.string.last); menu.add(0, 3, 0, R.string.search_menu).setIcon(android.R.drawable.ic_menu_search); menu.add(0, 4, 0, R.string.disconnect_menu).setIcon(android.R.drawable.ic_menu_close_clear_cancel); return true; } public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case 1: //Top order="top"; TextView textCatName = (TextView) findViewById(R.id.TextViewCategoryName); textCatName.setText(getBaseContext().getText(R.string.search_results)+" ("+getText(R.string.top)+")".toString()); pageFree=0; pagePaid=0; updateButtons(); LoadInfos(); return true; case 2: //Last order="last"; TextView textCatName2 = (TextView) findViewById(R.id.TextViewCategoryName); textCatName2.setText(getBaseContext().getText(R.string.search_results)+" ("+getText(R.string.last).toString()+")"); pageFree=0; pagePaid=0; updateButtons(); LoadInfos(); return true; case 3: //Search this.startSearch("", false, null, false); return true; case 4: //disconnect SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(SearchActivity.this.getApplicationContext()); Editor editor=pref.edit(); editor.putBoolean("connected", false); editor.putString("username", ""); editor.putString("terminal", ""); editor.commit(); Intent i = new Intent(SearchActivity.this, LoginActivity.class); startActivity(i); this.finish(); return true; } return false; } }
13,628
Java
.java
scleriot/yaam-application
20
4
0
2011-04-16T16:31:15Z
2011-06-20T06:55:23Z
DownloadHandler.java
/FileExtraction/Java_unseen/scleriot_yaam-application/src/com/pixellostudio/newyaam/DownloadHandler.java
package com.pixellostudio.newyaam; import android.os.Handler; public class DownloadHandler extends Handler { public static final int MSG_SET_LENGTH = 0; public static final int MSG_ON_RECV = 1; public static final int MSG_FINISHED = 2; public static final int MSG_ERROR = 3; public static final int MSG_ABORTED = 4; public void sendSetLength(long length) { sendMessage(obtainMessage(MSG_SET_LENGTH, (Long)length)); } public void sendOnRecv(long recvd) { sendMessage(obtainMessage(MSG_ON_RECV, (Long)recvd)); } public void sendFinished() { sendMessage(obtainMessage(MSG_FINISHED)); } public void sendError(String errmsg) { sendMessage(obtainMessage(MSG_ERROR, errmsg)); } public void sendAborted() { sendMessage(obtainMessage(MSG_ABORTED)); } public void removeMyMessages() { removeMessages(MSG_SET_LENGTH); removeMessages(MSG_ON_RECV); removeMessages(MSG_FINISHED); removeMessages(MSG_ERROR); removeMessages(MSG_ABORTED); } }
1,293
Java
.java
scleriot/yaam-application
20
4
0
2011-04-16T16:31:15Z
2011-06-20T06:55:23Z
UpdatesActivity.java
/FileExtraction/Java_unseen/scleriot_yaam-application/src/com/pixellostudio/newyaam/UpdatesActivity.java
/******************************************************************************* * Copyright (c) 2011 Cleriot Simon <[email protected]>. * * This file is part of YAAM. * * YAAM is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * YAAM is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with YAAM. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.pixellostudio.newyaam; import java.io.ByteArrayInputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import android.app.AlarmManager; import android.app.PendingIntent; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.ListView; import android.widget.TabHost; import android.widget.TabHost.TabSpec; import android.widget.TextView; public class UpdatesActivity extends BaseActivity { List<Integer> appIds=new ArrayList<Integer>(); String order="top"; String query; private ProgressDialog mProgress; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.categoryscreen); TabHost mTabHost = (TabHost) this.findViewById(R.id.tabhost); mTabHost.setup(); TabSpec tab1=mTabHost.newTabSpec("tab_free").setIndicator("").setContent(R.id.LinearLayoutPaid); mTabHost.addTab(tab1); TabSpec tab2=mTabHost.newTabSpec("tab_paid").setIndicator("").setContent(R.id.LinearLayoutFree); mTabHost.addTab(tab2); mTabHost.getTabWidget().getChildAt(0).getLayoutParams().height = 0; mTabHost.getTabWidget().getChildAt(1).getLayoutParams().height = 0; TextView textCatName = (TextView) findViewById(R.id.TextViewCategoryName); textCatName.setText(getBaseContext().getText(R.string.updates_menu)+" ("+getText(R.string.top)+")".toString()); Button buttonPrev = (Button) findViewById(R.id.ButtonPrevPaid); Button buttonNext = (Button) findViewById(R.id.ButtonNextPaid); Button buttonPrev2 = (Button) findViewById(R.id.ButtonPrevFree); Button buttonNext2 = (Button) findViewById(R.id.ButtonNextFree); buttonPrev.setVisibility(View.GONE); buttonNext.setVisibility(View.GONE); buttonPrev2.setVisibility(View.GONE); buttonNext2.setVisibility(View.GONE); //LoadInfos(); } @Override protected void onResume() { super.onResume(); Calendar cal = Calendar.getInstance(); cal.add(Calendar.HOUR,1); Intent intent = new Intent(this, CheckUpdatesBroadcast.class); PendingIntent sender = PendingIntent.getBroadcast(this, 192837, intent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE); am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender); LoadInfos(); } public void LoadInfos() { mProgress = ProgressDialog.show(this, this.getText(R.string.loading), this.getText(R.string.loadingtext), true, false); SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(this); String terminal=pref.getString("terminal", "phone"); String username=pref.getString("username", ""); String sdk=Build.VERSION.SDK; String lang=getApplicationContext().getResources().getConfiguration().locale.getISO3Language(); try { Tools.queryWeb(Functions.getHost(getApplicationContext())+"/apps/getUpdates.php?order="+order+"&username="+URLEncoder.encode(username,"UTF-8")+"&lang="+lang+"&sdk="+URLEncoder.encode(sdk,"UTF-8")+"&terminal="+URLEncoder.encode(terminal,"UTF-8")+"&ypass="+Functions.getPassword(getApplicationContext()), parser); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } public Handler parser=new Handler() { public void handleMessage(Message msg) { appIds.clear(); String content=msg.getData().getString("content"); try { DocumentBuilderFactory builder = DocumentBuilderFactory.newInstance(); DocumentBuilder constructeur = builder.newDocumentBuilder(); Document document = constructeur.parse(new ByteArrayInputStream( content.getBytes())); Element racine = document.getDocumentElement(); NodeList liste = racine.getElementsByTagName("app"); List<String> names=new ArrayList<String>(); List<String> icons=new ArrayList<String>(); List<Float> ratings=new ArrayList<Float>(); List<Float> prices=new ArrayList<Float>(); for(int i=0; i<liste.getLength(); i++){ Element E1= (Element) liste.item(i); String name="",id="",rating="",icon="",price=""; name=Functions.getDataFromXML(E1,"name"); icon=Functions.getDataFromXML(E1,"icon"); id=Functions.getDataFromXML(E1,"id"); rating=Functions.getDataFromXML(E1,"rating"); price=Functions.getDataFromXML(E1,"price"); if(isAppInstalled(Functions.getDataFromXML(E1,"package"))) { names.add(name); appIds.add(Integer.valueOf(id)); icons.add(icon); prices.add(Float.valueOf(price)); ratings.add(Float.valueOf(rating)); } } ListView listRecommended = (ListView) findViewById(R.id.ListViewAppsPaid); listRecommended.setAdapter(new AppsListAdapter(UpdatesActivity.this,names,icons,ratings,prices)); listRecommended.setOnItemClickListener(new OnItemClickListener() { @SuppressWarnings("rawtypes") public void onItemClick(AdapterView parent, View v, int position, long id) { Intent i = new Intent(UpdatesActivity.this, ShowAppActivity.class); Bundle objetbunble = new Bundle(); objetbunble.putInt("id",appIds.get(position)); i.putExtras(objetbunble ); startActivity(i); } }); } catch (Exception e) { e.printStackTrace(); } mProgress.dismiss(); } }; public boolean isAppInstalled(String packagename) { PackageManager pm=this.getApplicationContext().getPackageManager(); try { pm.getPackageInfo(packagename, PackageManager.GET_ACTIVITIES); } catch (NameNotFoundException e) { return false; } return true; } public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, 1, 0, R.string.top); menu.add(0, 2, 0, R.string.last); menu.add(0, 3, 0, R.string.search_menu).setIcon(android.R.drawable.ic_menu_search); menu.add(0, 4, 0, R.string.disconnect_menu).setIcon(android.R.drawable.ic_menu_close_clear_cancel); return true; } public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case 1: //Top order="top"; TextView textCatName = (TextView) findViewById(R.id.TextViewCategoryName); textCatName.setText(getBaseContext().getText(R.string.updates_button)+" ("+getText(R.string.top)+")".toString()); LoadInfos(); return true; case 2: //Last order="last"; TextView textCatName2 = (TextView) findViewById(R.id.TextViewCategoryName); textCatName2.setText(getBaseContext().getText(R.string.updates_button)+" ("+getText(R.string.last).toString()+")"); LoadInfos(); return true; case 3: //Search this.startSearch("", false, null, false); return true; case 4: //disconnect SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(UpdatesActivity.this.getApplicationContext()); Editor editor=pref.edit(); editor.putBoolean("connected", false); editor.putString("username", ""); editor.putString("terminal", ""); editor.commit(); Intent i = new Intent(UpdatesActivity.this, LoginActivity.class); startActivity(i); this.finish(); return true; } return false; } }
9,260
Java
.java
scleriot/yaam-application
20
4
0
2011-04-16T16:31:15Z
2011-06-20T06:55:23Z
BaseActivity.java
/FileExtraction/Java_unseen/scleriot_yaam-application/src/com/pixellostudio/newyaam/BaseActivity.java
/******************************************************************************* * Copyright (c) 2011 Cleriot Simon <[email protected]>. * * This file is part of YAAM. * * YAAM is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * YAAM is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with YAAM. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.pixellostudio.newyaam; import java.util.Calendar; import android.app.Activity; import android.app.AlarmManager; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.view.Menu; import android.view.MenuItem; import android.view.Window; public class BaseActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Tools.createYAAMDir(); SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(this); if(!pref.getBoolean("connected2", false)) { Intent intent = new Intent(this, LoginActivity.class); startActivity(intent); this.finish(); } Calendar cal = Calendar.getInstance(); cal.add(Calendar.MINUTE,1); Intent intent = new Intent(this, CheckUpdatesBroadcast.class); PendingIntent sender = PendingIntent.getBroadcast(this, 192837, intent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender); Tools.queryWeb(Functions.getHost(getApplicationContext())+"/yaamupdate.php", yaamUpdateHandler); requestWindowFeature(Window.FEATURE_NO_TITLE); } public Handler yaamUpdateHandler=new Handler() { public void handleMessage(Message msg) { String content=msg.getData().getString("content"); String updateId=content.split("/")[0]; //TODO:String changelog=content.split("/")[1]; try { if(Integer.valueOf(updateId)>getPackageManager().getPackageInfo("com.pixellostudio.newyaam",PackageManager.GET_ACTIVITIES|PackageManager.GET_GIDS|PackageManager.GET_CONFIGURATIONS|PackageManager.GET_INSTRUMENTATION|PackageManager.GET_PERMISSIONS|PackageManager.GET_PROVIDERS|PackageManager.GET_RECEIVERS|PackageManager.GET_SERVICES|PackageManager.GET_SIGNATURES).versionCode) { int notificationID = 11; NotificationManager notificationManager = (NotificationManager) BaseActivity.this.getSystemService(Context.NOTIFICATION_SERVICE); Notification notification = new Notification(R.drawable.icon, BaseActivity.this.getText(R.string.yaamupdate), System.currentTimeMillis()); notification.flags |= Notification.FLAG_AUTO_CANCEL; Intent intent = new Intent(BaseActivity.this, YAAMUpdate.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pendingIntent = PendingIntent.getActivity(BaseActivity.this, 0, intent, 0); notification.setLatestEventInfo(BaseActivity.this, BaseActivity.this.getText(R.string.newyaamupdate), BaseActivity.this.getText(R.string.yaamupdate), pendingIntent); notificationManager.notify(notificationID, notification); } } catch (Exception e) { e.printStackTrace(); } } }; public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, 3, 0, R.string.search_menu).setIcon(android.R.drawable.ic_menu_search); menu.add(0, 1, 0, R.string.updates_menu).setIcon(android.R.drawable.ic_menu_rotate); //TODO : menu.add(0, 2, 0, R.string.settings_menu).setIcon(android.R.drawable.ic_menu_preferences); menu.add(0, 4, 0, R.string.disconnect_menu).setIcon(android.R.drawable.ic_menu_close_clear_cancel); return true; } public boolean onOptionsItemSelected(MenuItem item) { Intent i; switch (item.getItemId()) { case 1: //Updates i = new Intent(this, UpdatesActivity.class); startActivity(i); return true; case 3: //Search this.startSearch("", false, null, false); return true; case 2: //Settings //i = new Intent(BaseActivity.this, Settings.class); //startActivity(i); return true; case 4: //disconnect SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(BaseActivity.this.getApplicationContext()); Editor editor=pref.edit(); editor.putBoolean("connected1", false); editor.putString("username", ""); editor.putString("terminal", ""); editor.commit(); i = new Intent(BaseActivity.this, LoginActivity.class); startActivity(i); this.finish(); return true; } return false; } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); } }
5,830
Java
.java
scleriot/yaam-application
20
4
0
2011-04-16T16:31:15Z
2011-06-20T06:55:23Z
LegacyCameraConnectionFragment.java
/FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/org/tensorflow/lite/examples/detection/LegacyCameraConnectionFragment.java
package org.tensorflow.lite.examples.detection; /* * Copyright 2019 The TensorFlow Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import android.annotation.SuppressLint; import android.app.Fragment; import android.graphics.SurfaceTexture; import android.hardware.Camera; import android.hardware.Camera.CameraInfo; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.util.Size; import android.util.SparseIntArray; import android.view.LayoutInflater; import android.view.Surface; import android.view.TextureView; import android.view.View; import android.view.ViewGroup; import java.io.IOException; import java.util.List; import com.example.glass.arshopping.R; import org.tensorflow.lite.examples.detection.customview.AutoFitTextureView; import org.tensorflow.lite.examples.detection.env.ImageUtils; import org.tensorflow.lite.examples.detection.env.Logger; @SuppressLint("ValidFragment") public class LegacyCameraConnectionFragment extends Fragment { private static final Logger LOGGER = new Logger(); /** Conversion from screen rotation to JPEG orientation. */ private static final SparseIntArray ORIENTATIONS = new SparseIntArray(); static { ORIENTATIONS.append(Surface.ROTATION_0, 90); ORIENTATIONS.append(Surface.ROTATION_90, 0); ORIENTATIONS.append(Surface.ROTATION_180, 270); ORIENTATIONS.append(Surface.ROTATION_270, 180); } private Camera camera; private Camera.PreviewCallback imageListener; private Size desiredSize; /** The layout identifier to inflate for this Fragment. */ private int layout; /** An {@link AutoFitTextureView} for camera preview. */ private AutoFitTextureView textureView; /** * {@link TextureView.SurfaceTextureListener} handles several lifecycle events on a {@link * TextureView}. */ private final TextureView.SurfaceTextureListener surfaceTextureListener = new TextureView.SurfaceTextureListener() { @Override public void onSurfaceTextureAvailable( final SurfaceTexture texture, final int width, final int height) { int index = getCameraId(); camera = Camera.open(index); try { Camera.Parameters parameters = camera.getParameters(); List<String> focusModes = parameters.getSupportedFocusModes(); if (focusModes != null && focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) { parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE); } List<Camera.Size> cameraSizes = parameters.getSupportedPreviewSizes(); Size[] sizes = new Size[cameraSizes.size()]; int i = 0; for (Camera.Size size : cameraSizes) { sizes[i++] = new Size(size.width, size.height); } Size previewSize = CameraConnectionFragment.chooseOptimalSize( sizes, desiredSize.getWidth(), desiredSize.getHeight()); parameters.setPreviewSize(previewSize.getWidth(), previewSize.getHeight()); camera.setDisplayOrientation(90); camera.setParameters(parameters); camera.setPreviewTexture(texture); } catch (IOException exception) { camera.release(); } camera.setPreviewCallbackWithBuffer(imageListener); Camera.Size s = camera.getParameters().getPreviewSize(); camera.addCallbackBuffer(new byte[ImageUtils.getYUVByteSize(s.height, s.width)]); textureView.setAspectRatio(s.height, s.width); camera.startPreview(); } @Override public void onSurfaceTextureSizeChanged( final SurfaceTexture texture, final int width, final int height) {} @Override public boolean onSurfaceTextureDestroyed(final SurfaceTexture texture) { return true; } @Override public void onSurfaceTextureUpdated(final SurfaceTexture texture) {} }; /** An additional thread for running tasks that shouldn't block the UI. */ private HandlerThread backgroundThread; public LegacyCameraConnectionFragment( final Camera.PreviewCallback imageListener, final int layout, final Size desiredSize) { this.imageListener = imageListener; this.layout = layout; this.desiredSize = desiredSize; } @Override public View onCreateView( final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { return inflater.inflate(layout, container, false); } @Override public void onViewCreated(final View view, final Bundle savedInstanceState) { textureView = (AutoFitTextureView) view.findViewById(R.id.texture); } @Override public void onActivityCreated(final Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public void onResume() { super.onResume(); startBackgroundThread(); // When the screen is turned off and turned back on, the SurfaceTexture is already // available, and "onSurfaceTextureAvailable" will not be called. In that case, we can open // a camera and start preview from here (otherwise, we wait until the surface is ready in // the SurfaceTextureListener). if (textureView.isAvailable()) { camera.startPreview(); } else { textureView.setSurfaceTextureListener(surfaceTextureListener); } } @Override public void onPause() { stopCamera(); stopBackgroundThread(); super.onPause(); } /** Starts a background thread and its {@link Handler}. */ private void startBackgroundThread() { backgroundThread = new HandlerThread("CameraBackground"); backgroundThread.start(); } /** Stops the background thread and its {@link Handler}. */ private void stopBackgroundThread() { backgroundThread.quitSafely(); try { backgroundThread.join(); backgroundThread = null; } catch (final InterruptedException e) { LOGGER.e(e, "Exception!"); } } protected void stopCamera() { if (camera != null) { camera.stopPreview(); camera.setPreviewCallback(null); camera.release(); camera = null; } } private int getCameraId() { CameraInfo ci = new CameraInfo(); for (int i = 0; i < Camera.getNumberOfCameras(); i++) { Camera.getCameraInfo(i, ci); if (ci.facing == CameraInfo.CAMERA_FACING_BACK) return i; } return -1; // No camera found } }
7,069
Java
.java
7people/AR-Shopping
9
2
0
2023-06-12T14:01:53Z
2023-07-26T07:06:06Z
CameraActivity.java
/FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/org/tensorflow/lite/examples/detection/CameraActivity.java
/* * Copyright 2019 The TensorFlow Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may 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.tensorflow.lite.examples.detection; import android.Manifest; import android.app.Fragment; import android.content.Context; import android.content.pm.PackageManager; import android.hardware.Camera; import android.hardware.camera2.CameraAccessException; import android.hardware.camera2.CameraCharacteristics; import android.hardware.camera2.CameraManager; import android.hardware.camera2.params.StreamConfigurationMap; import android.media.Image; import android.media.Image.Plane; import android.media.ImageReader; import android.media.ImageReader.OnImageAvailableListener; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.os.Trace; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.SwitchCompat; import android.speech.tts.TextToSpeech; import android.util.Log; import android.util.Size; import android.view.Surface; import android.view.View; import android.view.ViewTreeObserver; import android.view.WindowManager; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.example.glass.arshopping.R; import com.google.android.material.bottomsheet.BottomSheetBehavior; import java.nio.ByteBuffer; import java.util.Locale; import org.tensorflow.lite.examples.detection.env.ImageUtils; import org.tensorflow.lite.examples.detection.env.Logger; public abstract class CameraActivity extends AppCompatActivity implements OnImageAvailableListener, Camera.PreviewCallback, CompoundButton.OnCheckedChangeListener, View.OnClickListener { private static final Logger LOGGER = new Logger(); private static final int PERMISSIONS_REQUEST = 1; private static final String PERMISSION_CAMERA = Manifest.permission.CAMERA; protected int previewWidth = 0; protected int previewHeight = 0; private boolean debug = false; private Handler handler; private HandlerThread handlerThread; private boolean useCamera2API; private boolean isProcessingFrame = false; private byte[][] yuvBytes = new byte[3][]; private int[] rgbBytes = null; private int yRowStride; private Runnable postInferenceCallback; private Runnable imageConverter; private LinearLayout bottomSheetLayout; private LinearLayout gestureLayout; private BottomSheetBehavior<LinearLayout> sheetBehavior; protected TextView frameValueTextView, cropValueTextView, inferenceTimeTextView; protected ImageView bottomSheetArrowImageView; private ImageView plusImageView, minusImageView; private SwitchCompat apiSwitchCompat; private TextView threadsTextView; public TextToSpeech textToSpeech; @Override protected void onCreate(final Bundle savedInstanceState) { LOGGER.d("onCreate " + this); super.onCreate(null); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); setContentView(R.layout.tfe_od_activity_camera); if (hasPermission()) { setFragment(); } else { requestPermission(); } threadsTextView = findViewById(R.id.threads); plusImageView = findViewById(R.id.plus); minusImageView = findViewById(R.id.minus); apiSwitchCompat = findViewById(R.id.api_info_switch); bottomSheetLayout = findViewById(R.id.bottom_sheet_layout); gestureLayout = findViewById(R.id.gesture_layout); sheetBehavior = BottomSheetBehavior.from(bottomSheetLayout); bottomSheetArrowImageView = findViewById(R.id.bottom_sheet_arrow); ViewTreeObserver vto = gestureLayout.getViewTreeObserver(); vto.addOnGlobalLayoutListener( new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { gestureLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this); } else { gestureLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this); } // int width = bottomSheetLayout.getMeasuredWidth(); int height = gestureLayout.getMeasuredHeight(); sheetBehavior.setPeekHeight(height); } }); sheetBehavior.setHideable(false); sheetBehavior.setBottomSheetCallback( new BottomSheetBehavior.BottomSheetCallback() { @Override public void onStateChanged(@NonNull View bottomSheet, int newState) { switch (newState) { case BottomSheetBehavior.STATE_HIDDEN: break; case BottomSheetBehavior.STATE_EXPANDED: { bottomSheetArrowImageView.setImageResource(R.drawable.icn_chevron_down); } break; case BottomSheetBehavior.STATE_COLLAPSED: { bottomSheetArrowImageView.setImageResource(R.drawable.icn_chevron_up); } break; case BottomSheetBehavior.STATE_DRAGGING: break; case BottomSheetBehavior.STATE_SETTLING: bottomSheetArrowImageView.setImageResource(R.drawable.icn_chevron_up); break; } } @Override public void onSlide(@NonNull View bottomSheet, float slideOffset) {} }); frameValueTextView = findViewById(R.id.frame_info); cropValueTextView = findViewById(R.id.crop_info); inferenceTimeTextView = findViewById(R.id.inference_info); apiSwitchCompat.setOnCheckedChangeListener(this); plusImageView.setOnClickListener(this); minusImageView.setOnClickListener(this); } protected int[] getRgbBytes() { imageConverter.run(); return rgbBytes; } protected int getLuminanceStride() { return yRowStride; } protected byte[] getLuminance() { return yuvBytes[0]; } public void setTextToSpeech(String data){ textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() { @Override public void onInit(int status) { Log.d("init","texttospeech"); if (status == TextToSpeech.SUCCESS) { int ttsLang = textToSpeech.setLanguage(Locale.US); if (ttsLang == TextToSpeech.LANG_MISSING_DATA || ttsLang == TextToSpeech.LANG_NOT_SUPPORTED) { Log.e("TTS", "The Language is not supported!"); } else { Log.i("TTS", "Language Supported."); } int speechStatus = textToSpeech.speak(data, TextToSpeech.QUEUE_FLUSH, null); if (speechStatus == TextToSpeech.ERROR) { Log.e("TTS", "Error in converting Text to Speech!"); } Log.i("TTS", "Initialization success."); } } }); } /** Callback for android.hardware.Camera API */ @Override public void onPreviewFrame(final byte[] bytes, final Camera camera) { if (isProcessingFrame) { LOGGER.w("Dropping frame!"); return; } try { // Initialize the storage bitmaps once when the resolution is known. if (rgbBytes == null) { Camera.Size previewSize = camera.getParameters().getPreviewSize(); previewHeight = previewSize.height; previewWidth = previewSize.width; rgbBytes = new int[previewWidth * previewHeight]; onPreviewSizeChosen(new Size(previewSize.width, previewSize.height), 90); } } catch (final Exception e) { LOGGER.e(e, "Exception!"); return; } isProcessingFrame = true; yuvBytes[0] = bytes; yRowStride = previewWidth; imageConverter = new Runnable() { @Override public void run() { ImageUtils.convertYUV420SPToARGB8888(bytes, previewWidth, previewHeight, rgbBytes); } }; postInferenceCallback = new Runnable() { @Override public void run() { camera.addCallbackBuffer(bytes); isProcessingFrame = false; } }; processImage(); } /** Callback for Camera2 API */ @Override public void onImageAvailable(final ImageReader reader) { // We need wait until we have some size from onPreviewSizeChosen if (previewWidth == 0 || previewHeight == 0) { return; } if (rgbBytes == null) { rgbBytes = new int[previewWidth * previewHeight]; } try { final Image image = reader.acquireLatestImage(); if (image == null) { return; } if (isProcessingFrame) { image.close(); return; } isProcessingFrame = true; Trace.beginSection("imageAvailable"); final Plane[] planes = image.getPlanes(); fillBytes(planes, yuvBytes); yRowStride = planes[0].getRowStride(); final int uvRowStride = planes[1].getRowStride(); final int uvPixelStride = planes[1].getPixelStride(); imageConverter = new Runnable() { @Override public void run() { ImageUtils.convertYUV420ToARGB8888( yuvBytes[0], yuvBytes[1], yuvBytes[2], previewWidth, previewHeight, yRowStride, uvRowStride, uvPixelStride, rgbBytes); } }; postInferenceCallback = new Runnable() { @Override public void run() { image.close(); isProcessingFrame = false; } }; processImage(); } catch (final Exception e) { LOGGER.e(e, "Exception!"); Trace.endSection(); return; } Trace.endSection(); } @Override public synchronized void onStart() { LOGGER.d("onStart " + this); super.onStart(); } @Override public synchronized void onResume() { LOGGER.d("onResume " + this); super.onResume(); handlerThread = new HandlerThread("inference"); handlerThread.start(); handler = new Handler(handlerThread.getLooper()); } @Override public synchronized void onPause() { LOGGER.d("onPause " + this); handlerThread.quitSafely(); try { handlerThread.join(); handlerThread = null; handler = null; } catch (final InterruptedException e) { LOGGER.e(e, "Exception!"); } super.onPause(); } @Override public synchronized void onStop() { LOGGER.d("onStop " + this); super.onStop(); } @Override public synchronized void onDestroy() { LOGGER.d("onDestroy " + this); super.onDestroy(); } protected synchronized void runInBackground(final Runnable r) { if (handler != null) { handler.post(r); } } @Override public void onRequestPermissionsResult( final int requestCode, final String[] permissions, final int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == PERMISSIONS_REQUEST) { if (allPermissionsGranted(grantResults)) { setFragment(); } else { requestPermission(); } } } private static boolean allPermissionsGranted(final int[] grantResults) { for (int result : grantResults) { if (result != PackageManager.PERMISSION_GRANTED) { return false; } } return true; } private boolean hasPermission() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return checkSelfPermission(PERMISSION_CAMERA) == PackageManager.PERMISSION_GRANTED; } else { return true; } } private void requestPermission() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (shouldShowRequestPermissionRationale(PERMISSION_CAMERA)) { Toast.makeText( CameraActivity.this, "Camera permission is required for this demo", Toast.LENGTH_LONG) .show(); } requestPermissions(new String[] {PERMISSION_CAMERA}, PERMISSIONS_REQUEST); } } // Returns true if the device supports the required hardware level, or better. private boolean isHardwareLevelSupported( CameraCharacteristics characteristics, int requiredLevel) { int deviceLevel = characteristics.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL); if (deviceLevel == CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY) { return requiredLevel == deviceLevel; } // deviceLevel is not LEGACY, can use numerical sort return requiredLevel <= deviceLevel; } private String chooseCamera() { final CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE); try { for (final String cameraId : manager.getCameraIdList()) { final CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId); // We don't use a front facing camera in this sample. final Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING); if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) { continue; } final StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); if (map == null) { continue; } // Fallback to camera1 API for internal cameras that don't have full support. // This should help with legacy situations where using the camera2 API causes // distorted or otherwise broken previews. useCamera2API = (facing == CameraCharacteristics.LENS_FACING_EXTERNAL) || isHardwareLevelSupported( characteristics, CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_FULL); LOGGER.i("Camera API lv2?: %s", useCamera2API); return cameraId; } } catch (CameraAccessException e) { LOGGER.e(e, "Not allowed to access camera"); } return null; } protected void setFragment() { String cameraId = chooseCamera(); Fragment fragment; if (useCamera2API) { CameraConnectionFragment camera2Fragment = CameraConnectionFragment.newInstance( new CameraConnectionFragment.ConnectionCallback() { @Override public void onPreviewSizeChosen(final Size size, final int rotation) { previewHeight = size.getHeight(); previewWidth = size.getWidth(); CameraActivity.this.onPreviewSizeChosen(size, rotation); } }, this, getLayoutId(), getDesiredPreviewFrameSize()); camera2Fragment.setCamera(cameraId); fragment = camera2Fragment; } else { fragment = new LegacyCameraConnectionFragment(this, getLayoutId(), getDesiredPreviewFrameSize()); } getFragmentManager().beginTransaction().replace(R.id.container, fragment).commit(); } protected void fillBytes(final Plane[] planes, final byte[][] yuvBytes) { // Because of the variable row stride it's not possible to know in // advance the actual necessary dimensions of the yuv planes. for (int i = 0; i < planes.length; ++i) { final ByteBuffer buffer = planes[i].getBuffer(); if (yuvBytes[i] == null) { LOGGER.d("Initializing buffer %d at size %d", i, buffer.capacity()); yuvBytes[i] = new byte[buffer.capacity()]; } buffer.get(yuvBytes[i]); } } public boolean isDebug() { return debug; } protected void readyForNextImage() { if (postInferenceCallback != null) { postInferenceCallback.run(); } } protected int getScreenOrientation() { switch (getWindowManager().getDefaultDisplay().getRotation()) { case Surface.ROTATION_270: return 270; case Surface.ROTATION_180: return 180; case Surface.ROTATION_90: return 90; default: return 0; } } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { setUseNNAPI(isChecked); if (isChecked) apiSwitchCompat.setText("NNAPI"); else apiSwitchCompat.setText("TFLITE"); } @Override public void onClick(View v) { if (v.getId() == R.id.plus) { String threads = threadsTextView.getText().toString().trim(); int numThreads = Integer.parseInt(threads); if (numThreads >= 9) return; numThreads++; threadsTextView.setText(String.valueOf(numThreads)); setNumThreads(numThreads); } else if (v.getId() == R.id.minus) { String threads = threadsTextView.getText().toString().trim(); int numThreads = Integer.parseInt(threads); if (numThreads == 1) { return; } numThreads--; threadsTextView.setText(String.valueOf(numThreads)); setNumThreads(numThreads); } } protected void showFrameInfo(String frameInfo) { frameValueTextView.setText(frameInfo); } protected void showCropInfo(String cropInfo) { cropValueTextView.setText(cropInfo); } protected void showInference(String inferenceTime) { inferenceTimeTextView.setText(inferenceTime); } protected abstract void processImage(); protected abstract void onPreviewSizeChosen(final Size size, final int rotation); protected abstract int getLayoutId(); protected abstract Size getDesiredPreviewFrameSize(); protected abstract void setNumThreads(int numThreads); protected abstract void setUseNNAPI(boolean isChecked); }
18,290
Java
.java
7people/AR-Shopping
9
2
0
2023-06-12T14:01:53Z
2023-07-26T07:06:06Z
DetectorActivity.java
/FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/org/tensorflow/lite/examples/detection/DetectorActivity.java
/* * Copyright 2019 The TensorFlow Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may 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.tensorflow.lite.examples.detection; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.RectF; import android.graphics.Typeface; import android.media.ImageReader.OnImageAvailableListener; import android.os.SystemClock; import android.speech.tts.TextToSpeech; import android.util.Log; import android.util.Size; import android.util.TypedValue; import android.view.View; import android.widget.CheckBox; import android.widget.Toast; import com.example.glass.arshopping.ProductsActivity; import com.example.glass.arshopping.R; import org.tensorflow.lite.examples.detection.customview.OverlayView; import org.tensorflow.lite.examples.detection.customview.OverlayView.DrawCallback; import org.tensorflow.lite.examples.detection.env.BorderedText; import org.tensorflow.lite.examples.detection.env.ImageUtils; import org.tensorflow.lite.examples.detection.env.Logger; import org.tensorflow.lite.examples.detection.tflite.Classifier; import org.tensorflow.lite.examples.detection.tflite.TFLiteObjectDetectionAPIModel; import org.tensorflow.lite.examples.detection.tracking.MultiBoxTracker; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Set; /** * An activity that uses a TensorFlowMultiBoxDetector and ObjectTracker to detect and then track * objects. */ public class DetectorActivity extends CameraActivity implements OnImageAvailableListener { String username=""; private static final Logger LOGGER = new Logger(); // Configuration values for the prepackaged SSD model. private static final int TF_OD_API_INPUT_SIZE = 300; private static final boolean TF_OD_API_IS_QUANTIZED = true; private static final String TF_OD_API_MODEL_FILE = "detect.tflite"; private static final String TF_OD_API_LABELS_FILE = "file:///android_asset/labelmap.txt"; private static final DetectorMode MODE = DetectorMode.TF_OD_API; // Minimum detection confidence to track a detection. private static final float MINIMUM_CONFIDENCE_TF_OD_API = 0.5f; private static final boolean MAINTAIN_ASPECT = false; private static final Size DESIRED_PREVIEW_SIZE = new Size(640, 480); private static final boolean SAVE_PREVIEW_BITMAP = false; private static final float TEXT_SIZE_DIP = 10; public TextToSpeech textToSpeech; OverlayView trackingOverlay; private Integer sensorOrientation; CheckBox speak; private Classifier detector; private long lastProcessingTimeMs; private Bitmap rgbFrameBitmap = null; private Bitmap croppedBitmap = null; private Bitmap cropCopyBitmap = null; private boolean computingDetection = false; private long timestamp = 0; private Matrix frameToCropTransform; private Matrix cropToFrameTransform; private MultiBoxTracker tracker; private BorderedText borderedText; String myResult = ""; @Override public void onPreviewSizeChosen(final Size size, final int rotation) { Intent intent = getIntent(); username = intent.getStringExtra("username"); Log.d("DetectorActivity", "Username: " + username); final float textSizePx = TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, TEXT_SIZE_DIP, getResources().getDisplayMetrics()); borderedText = new BorderedText(textSizePx); borderedText.setTypeface(Typeface.MONOSPACE); tracker = new MultiBoxTracker(this); int cropSize = TF_OD_API_INPUT_SIZE; try { detector = TFLiteObjectDetectionAPIModel.create( getAssets(), TF_OD_API_MODEL_FILE, TF_OD_API_LABELS_FILE, TF_OD_API_INPUT_SIZE, TF_OD_API_IS_QUANTIZED); cropSize = TF_OD_API_INPUT_SIZE; } catch (final IOException e) { e.printStackTrace(); LOGGER.e(e, "Exception initializing classifier!"); Toast toast = Toast.makeText( getApplicationContext(), "Classifier could not be initialized", Toast.LENGTH_SHORT); toast.show(); finish(); } previewWidth = size.getWidth(); previewHeight = size.getHeight(); sensorOrientation = rotation - getScreenOrientation(); LOGGER.i("Camera orientation relative to screen canvas: %d", sensorOrientation); LOGGER.i("Initializing at size %dx%d", previewWidth, previewHeight); rgbFrameBitmap = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888); croppedBitmap = Bitmap.createBitmap(cropSize, cropSize, Config.ARGB_8888); frameToCropTransform = ImageUtils.getTransformationMatrix( previewWidth, previewHeight, cropSize, cropSize, sensorOrientation, MAINTAIN_ASPECT); cropToFrameTransform = new Matrix(); frameToCropTransform.invert(cropToFrameTransform); trackingOverlay = (OverlayView) findViewById(R.id.tracking_overlay); trackingOverlay.addCallback( new DrawCallback() { @Override public void drawCallback(final Canvas canvas) { tracker.draw(canvas); if (isDebug()) { tracker.drawDebug(canvas); } } }); tracker.setFrameConfiguration(previewWidth, previewHeight, sensorOrientation); } @Override protected void processImage() { ++timestamp; final long currTimestamp = timestamp; trackingOverlay.postInvalidate(); // No mutex needed as this method is not reentrant. if (computingDetection) { readyForNextImage(); return; } computingDetection = true; LOGGER.i("Preparing image " + currTimestamp + " for detection in bg thread."); rgbFrameBitmap.setPixels(getRgbBytes(), 0, previewWidth, 0, 0, previewWidth, previewHeight); readyForNextImage(); final Canvas canvas = new Canvas(croppedBitmap); canvas.drawBitmap(rgbFrameBitmap, frameToCropTransform, null); // For examining the actual TF input. if (SAVE_PREVIEW_BITMAP) { ImageUtils.saveBitmap(croppedBitmap); } runInBackground( new Runnable() { @Override public void run() { LOGGER.i("Running detection on image " + currTimestamp); final long startTime = SystemClock.uptimeMillis(); final List<Classifier.Recognition> results = detector.recognizeImage(croppedBitmap); lastProcessingTimeMs = SystemClock.uptimeMillis() - startTime; cropCopyBitmap = Bitmap.createBitmap(croppedBitmap); final Canvas canvas = new Canvas(cropCopyBitmap); final Paint paint = new Paint(); paint.setColor(Color.RED); paint.setStyle(Style.STROKE); paint.setStrokeWidth(2.0f); float minimumConfidence = MINIMUM_CONFIDENCE_TF_OD_API; switch (MODE) { case TF_OD_API: minimumConfidence = MINIMUM_CONFIDENCE_TF_OD_API; break; } ArrayList<String> speech ; textToSpeech = new TextToSpeech(getApplicationContext(), status -> { if (status == TextToSpeech.SUCCESS) { int ttsLang = textToSpeech.setLanguage(Locale.US); if (ttsLang == TextToSpeech.LANG_MISSING_DATA || ttsLang == TextToSpeech.LANG_NOT_SUPPORTED) { Log.e("TTS", "The Language is not supported!"); } else { Log.i("TTS", "Language Supported."); } Log.i("TTS", "Initialization success."); } else { Toast.makeText(getApplicationContext(), "TTS Initialization failed!", Toast.LENGTH_SHORT).show(); } }); final List<Classifier.Recognition> mappedRecognitions = new LinkedList<Classifier.Recognition>(); speech = new ArrayList<>(); for (final Classifier.Recognition result : results) { final RectF location = result.getLocation(); if (location != null && result.getConfidence() >= minimumConfidence) { canvas.drawRect(location, paint); cropToFrameTransform.mapRect(location); speech.add(result.getTitle()); myResult = result.getTitle(); result.setLocation(location); mappedRecognitions.add(result); } } Set<String> hashSet = new LinkedHashSet(speech); ArrayList<String> removedDuplicates = new ArrayList(hashSet); /*speak=findViewById(R.id.btn); for(int j = 0; j < removedDuplicates.size(); j++){ if (speak.isChecked()){ String data=removedDuplicates.get(j); int speechStatus = textToSpeech.speak(data, TextToSpeech.QUEUE_FLUSH, null); if (speechStatus == TextToSpeech.ERROR) { Log.e("TTS", "Error in converting Text to Speech!"); } } if (!speak.isChecked()){ if (textToSpeech != null) { textToSpeech.stop(); } } } */ tracker.trackResults(mappedRecognitions, currTimestamp); trackingOverlay.postInvalidate(); computingDetection = false; runOnUiThread( new Runnable() { @Override public void run() { showFrameInfo(previewWidth + "x" + previewHeight); showCropInfo(cropCopyBitmap.getWidth() + "x" + cropCopyBitmap.getHeight()); showInference(lastProcessingTimeMs + "ms"); } }); } }); } @Override public void onStop() { super.onStop(); if (textToSpeech != null) { textToSpeech.stop(); textToSpeech.shutdown(); } } @Override public synchronized void onPause() { super.onPause(); if (textToSpeech != null) { textToSpeech.stop(); textToSpeech.shutdown(); } } @Override public synchronized void onDestroy() { super.onDestroy(); if (textToSpeech != null) { textToSpeech.stop(); textToSpeech.shutdown(); } } @Override protected int getLayoutId() { return R.layout.tfe_od_camera_connection_fragment_tracking; } @Override protected Size getDesiredPreviewFrameSize() { return DESIRED_PREVIEW_SIZE; } public void searchObjectDetection(View view) { Intent intent = new Intent(getBaseContext(), ProductsActivity.class); intent.putExtra("search", myResult); intent.putExtra("username", username); startActivity(intent); } public void backObjectDetection(View view) { Intent intent = new Intent(getBaseContext(), ProductsActivity.class); intent.putExtra("username", username); startActivity(intent); } // Which detection model to use: by default uses Tensorflow Object Detection API frozen // checkpoints. private enum DetectorMode { TF_OD_API; } @Override protected void setUseNNAPI(final boolean isChecked) { runInBackground(() -> detector.setUseNNAPI(isChecked)); } @Override protected void setNumThreads(final int numThreads) { runInBackground(() -> detector.setNumThreads(numThreads)); } }
12,477
Java
.java
7people/AR-Shopping
9
2
0
2023-06-12T14:01:53Z
2023-07-26T07:06:06Z
CameraConnectionFragment.java
/FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/org/tensorflow/lite/examples/detection/CameraConnectionFragment.java
/* * Copyright 2019 The TensorFlow Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may 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.tensorflow.lite.examples.detection; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.app.Fragment; import android.content.Context; import android.content.DialogInterface; import android.content.res.Configuration; import android.graphics.ImageFormat; import android.graphics.Matrix; import android.graphics.RectF; import android.graphics.SurfaceTexture; import android.hardware.camera2.CameraAccessException; import android.hardware.camera2.CameraCaptureSession; import android.hardware.camera2.CameraCharacteristics; import android.hardware.camera2.CameraDevice; import android.hardware.camera2.CameraManager; import android.hardware.camera2.CaptureRequest; import android.hardware.camera2.CaptureResult; import android.hardware.camera2.TotalCaptureResult; import android.hardware.camera2.params.StreamConfigurationMap; import android.media.ImageReader; import android.media.ImageReader.OnImageAvailableListener; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.text.TextUtils; import android.util.Size; import android.util.SparseIntArray; import android.view.LayoutInflater; import android.view.Surface; import android.view.TextureView; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import com.example.glass.arshopping.R; import org.tensorflow.lite.examples.detection.customview.AutoFitTextureView; import org.tensorflow.lite.examples.detection.env.Logger; @SuppressLint("ValidFragment") public class CameraConnectionFragment extends Fragment { private static final Logger LOGGER = new Logger(); /** * The camera preview size will be chosen to be the smallest frame by pixel size capable of * containing a DESIRED_SIZE x DESIRED_SIZE square. */ private static final int MINIMUM_PREVIEW_SIZE = 320; /** Conversion from screen rotation to JPEG orientation. */ private static final SparseIntArray ORIENTATIONS = new SparseIntArray(); private static final String FRAGMENT_DIALOG = "dialog"; static { ORIENTATIONS.append(Surface.ROTATION_0, 90); ORIENTATIONS.append(Surface.ROTATION_90, 0); ORIENTATIONS.append(Surface.ROTATION_180, 270); ORIENTATIONS.append(Surface.ROTATION_270, 180); } /** A {@link Semaphore} to prevent the app from exiting before closing the camera. */ private final Semaphore cameraOpenCloseLock = new Semaphore(1); /** A {@link OnImageAvailableListener} to receive frames as they are available. */ private final OnImageAvailableListener imageListener; /** The input size in pixels desired by TensorFlow (width and height of a square bitmap). */ private final Size inputSize; /** The layout identifier to inflate for this Fragment. */ private final int layout; private final ConnectionCallback cameraConnectionCallback; private final CameraCaptureSession.CaptureCallback captureCallback = new CameraCaptureSession.CaptureCallback() { @Override public void onCaptureProgressed( final CameraCaptureSession session, final CaptureRequest request, final CaptureResult partialResult) {} @Override public void onCaptureCompleted( final CameraCaptureSession session, final CaptureRequest request, final TotalCaptureResult result) {} }; /** ID of the current {@link CameraDevice}. */ private String cameraId; /** An {@link AutoFitTextureView} for camera preview. */ private AutoFitTextureView textureView; /** A {@link CameraCaptureSession } for camera preview. */ private CameraCaptureSession captureSession; /** A reference to the opened {@link CameraDevice}. */ private CameraDevice cameraDevice; /** The rotation in degrees of the camera sensor from the display. */ private Integer sensorOrientation; /** The {@link Size} of camera preview. */ private Size previewSize; /** An additional thread for running tasks that shouldn't block the UI. */ private HandlerThread backgroundThread; /** A {@link Handler} for running tasks in the background. */ private Handler backgroundHandler; /** An {@link ImageReader} that handles preview frame capture. */ private ImageReader previewReader; /** {@link CaptureRequest.Builder} for the camera preview */ private CaptureRequest.Builder previewRequestBuilder; /** {@link CaptureRequest} generated by {@link #previewRequestBuilder} */ private CaptureRequest previewRequest; /** {@link CameraDevice.StateCallback} is called when {@link CameraDevice} changes its state. */ private final CameraDevice.StateCallback stateCallback = new CameraDevice.StateCallback() { @Override public void onOpened(final CameraDevice cd) { // This method is called when the camera is opened. We start camera preview here. cameraOpenCloseLock.release(); cameraDevice = cd; createCameraPreviewSession(); } @Override public void onDisconnected(final CameraDevice cd) { cameraOpenCloseLock.release(); cd.close(); cameraDevice = null; } @Override public void onError(final CameraDevice cd, final int error) { cameraOpenCloseLock.release(); cd.close(); cameraDevice = null; final Activity activity = getActivity(); if (null != activity) { activity.finish(); } } }; /** * {@link TextureView.SurfaceTextureListener} handles several lifecycle events on a {@link * TextureView}. */ private final TextureView.SurfaceTextureListener surfaceTextureListener = new TextureView.SurfaceTextureListener() { @Override public void onSurfaceTextureAvailable( final SurfaceTexture texture, final int width, final int height) { openCamera(width, height); } @Override public void onSurfaceTextureSizeChanged( final SurfaceTexture texture, final int width, final int height) { configureTransform(width, height); } @Override public boolean onSurfaceTextureDestroyed(final SurfaceTexture texture) { return true; } @Override public void onSurfaceTextureUpdated(final SurfaceTexture texture) {} }; private CameraConnectionFragment( final ConnectionCallback connectionCallback, final OnImageAvailableListener imageListener, final int layout, final Size inputSize) { this.cameraConnectionCallback = connectionCallback; this.imageListener = imageListener; this.layout = layout; this.inputSize = inputSize; } /** * Given {@code choices} of {@code Size}s supported by a camera, chooses the smallest one whose * width and height are at least as large as the minimum of both, or an exact match if possible. * * @param choices The list of sizes that the camera supports for the intended output class * @param width The minimum desired width * @param height The minimum desired height * @return The optimal {@code Size}, or an arbitrary one if none were big enough */ protected static Size chooseOptimalSize(final Size[] choices, final int width, final int height) { final int minSize = Math.max(Math.min(width, height), MINIMUM_PREVIEW_SIZE); final Size desiredSize = new Size(width, height); // Collect the supported resolutions that are at least as big as the preview Surface boolean exactSizeFound = false; final List<Size> bigEnough = new ArrayList<Size>(); final List<Size> tooSmall = new ArrayList<Size>(); for (final Size option : choices) { if (option.equals(desiredSize)) { // Set the size but don't return yet so that remaining sizes will still be logged. exactSizeFound = true; } if (option.getHeight() >= minSize && option.getWidth() >= minSize) { bigEnough.add(option); } else { tooSmall.add(option); } } LOGGER.i("Desired size: " + desiredSize + ", min size: " + minSize + "x" + minSize); LOGGER.i("Valid preview sizes: [" + TextUtils.join(", ", bigEnough) + "]"); LOGGER.i("Rejected preview sizes: [" + TextUtils.join(", ", tooSmall) + "]"); if (exactSizeFound) { LOGGER.i("Exact size match found."); return desiredSize; } // Pick the smallest of those, assuming we found any if (bigEnough.size() > 0) { final Size chosenSize = Collections.min(bigEnough, new CompareSizesByArea()); LOGGER.i("Chosen size: " + chosenSize.getWidth() + "x" + chosenSize.getHeight()); return chosenSize; } else { LOGGER.e("Couldn't find any suitable preview size"); return choices[0]; } } public static CameraConnectionFragment newInstance( final ConnectionCallback callback, final OnImageAvailableListener imageListener, final int layout, final Size inputSize) { return new CameraConnectionFragment(callback, imageListener, layout, inputSize); } /** * Shows a {@link Toast} on the UI thread. * * @param text The message to show */ private void showToast(final String text) { final Activity activity = getActivity(); if (activity != null) { activity.runOnUiThread( new Runnable() { @Override public void run() { Toast.makeText(activity, text, Toast.LENGTH_SHORT).show(); } }); } } @Override public View onCreateView( final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { return inflater.inflate(layout, container, false); } @Override public void onViewCreated(final View view, final Bundle savedInstanceState) { textureView = (AutoFitTextureView) view.findViewById(R.id.texture); } @Override public void onActivityCreated(final Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public void onResume() { super.onResume(); startBackgroundThread(); // When the screen is turned off and turned back on, the SurfaceTexture is already // available, and "onSurfaceTextureAvailable" will not be called. In that case, we can open // a camera and start preview from here (otherwise, we wait until the surface is ready in // the SurfaceTextureListener). if (textureView.isAvailable()) { openCamera(textureView.getWidth(), textureView.getHeight()); } else { textureView.setSurfaceTextureListener(surfaceTextureListener); } } @Override public void onPause() { closeCamera(); stopBackgroundThread(); super.onPause(); } public void setCamera(String cameraId) { this.cameraId = cameraId; } /** Sets up member variables related to camera. */ private void setUpCameraOutputs() { final Activity activity = getActivity(); final CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE); try { final CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId); final StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); sensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION); // Danger, W.R.! Attempting to use too large a preview size could exceed the camera // bus' bandwidth limitation, resulting in gorgeous previews but the storage of // garbage capture data. previewSize = chooseOptimalSize( map.getOutputSizes(SurfaceTexture.class), inputSize.getWidth(), inputSize.getHeight()); // We fit the aspect ratio of TextureView to the size of preview we picked. final int orientation = getResources().getConfiguration().orientation; if (orientation == Configuration.ORIENTATION_LANDSCAPE) { textureView.setAspectRatio(previewSize.getWidth(), previewSize.getHeight()); } else { textureView.setAspectRatio(previewSize.getHeight(), previewSize.getWidth()); } } catch (final CameraAccessException e) { LOGGER.e(e, "Exception!"); } catch (final NullPointerException e) { // Currently an NPE is thrown when the Camera2API is used but not supported on the // device this code runs. ErrorDialog.newInstance(getString(R.string.tfe_od_camera_error)) .show(getChildFragmentManager(), FRAGMENT_DIALOG); throw new IllegalStateException(getString(R.string.tfe_od_camera_error)); } cameraConnectionCallback.onPreviewSizeChosen(previewSize, sensorOrientation); } /** Opens the camera specified by {@link CameraConnectionFragment#cameraId}. */ private void openCamera(final int width, final int height) { setUpCameraOutputs(); configureTransform(width, height); final Activity activity = getActivity(); final CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE); try { if (!cameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) { throw new RuntimeException("Time out waiting to lock camera opening."); } manager.openCamera(cameraId, stateCallback, backgroundHandler); } catch (final CameraAccessException e) { LOGGER.e(e, "Exception!"); } catch (final InterruptedException e) { throw new RuntimeException("Interrupted while trying to lock camera opening.", e); } } /** Closes the current {@link CameraDevice}. */ private void closeCamera() { try { cameraOpenCloseLock.acquire(); if (null != captureSession) { captureSession.close(); captureSession = null; } if (null != cameraDevice) { cameraDevice.close(); cameraDevice = null; } if (null != previewReader) { previewReader.close(); previewReader = null; } } catch (final InterruptedException e) { throw new RuntimeException("Interrupted while trying to lock camera closing.", e); } finally { cameraOpenCloseLock.release(); } } /** Starts a background thread and its {@link Handler}. */ private void startBackgroundThread() { backgroundThread = new HandlerThread("ImageListener"); backgroundThread.start(); backgroundHandler = new Handler(backgroundThread.getLooper()); } /** Stops the background thread and its {@link Handler}. */ private void stopBackgroundThread() { backgroundThread.quitSafely(); try { backgroundThread.join(); backgroundThread = null; backgroundHandler = null; } catch (final InterruptedException e) { LOGGER.e(e, "Exception!"); } } /** Creates a new {@link CameraCaptureSession} for camera preview. */ private void createCameraPreviewSession() { try { final SurfaceTexture texture = textureView.getSurfaceTexture(); assert texture != null; // We configure the size of default buffer to be the size of camera preview we want. texture.setDefaultBufferSize(previewSize.getWidth(), previewSize.getHeight()); // This is the output Surface we need to start preview. final Surface surface = new Surface(texture); // We set up a CaptureRequest.Builder with the output Surface. previewRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW); previewRequestBuilder.addTarget(surface); LOGGER.i("Opening camera preview: " + previewSize.getWidth() + "x" + previewSize.getHeight()); // Create the reader for the preview frames. previewReader = ImageReader.newInstance( previewSize.getWidth(), previewSize.getHeight(), ImageFormat.YUV_420_888, 2); previewReader.setOnImageAvailableListener(imageListener, backgroundHandler); previewRequestBuilder.addTarget(previewReader.getSurface()); // Here, we create a CameraCaptureSession for camera preview. cameraDevice.createCaptureSession( Arrays.asList(surface, previewReader.getSurface()), new CameraCaptureSession.StateCallback() { @Override public void onConfigured(final CameraCaptureSession cameraCaptureSession) { // The camera is already closed if (null == cameraDevice) { return; } // When the session is ready, we start displaying the preview. captureSession = cameraCaptureSession; try { // Auto focus should be continuous for camera preview. previewRequestBuilder.set( CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE); // Flash is automatically enabled when necessary. previewRequestBuilder.set( CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH); // Finally, we start displaying the camera preview. previewRequest = previewRequestBuilder.build(); captureSession.setRepeatingRequest( previewRequest, captureCallback, backgroundHandler); } catch (final CameraAccessException e) { LOGGER.e(e, "Exception!"); } } @Override public void onConfigureFailed(final CameraCaptureSession cameraCaptureSession) { showToast("Failed"); } }, null); } catch (final CameraAccessException e) { LOGGER.e(e, "Exception!"); } } /** * Configures the necessary {@link Matrix} transformation to `mTextureView`. This method should be * called after the camera preview size is determined in setUpCameraOutputs and also the size of * `mTextureView` is fixed. * * @param viewWidth The width of `mTextureView` * @param viewHeight The height of `mTextureView` */ private void configureTransform(final int viewWidth, final int viewHeight) { final Activity activity = getActivity(); if (null == textureView || null == previewSize || null == activity) { return; } final int rotation = activity.getWindowManager().getDefaultDisplay().getRotation(); final Matrix matrix = new Matrix(); final RectF viewRect = new RectF(0, 0, viewWidth, viewHeight); final RectF bufferRect = new RectF(0, 0, previewSize.getHeight(), previewSize.getWidth()); final float centerX = viewRect.centerX(); final float centerY = viewRect.centerY(); if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) { bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY()); matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL); final float scale = Math.max( (float) viewHeight / previewSize.getHeight(), (float) viewWidth / previewSize.getWidth()); matrix.postScale(scale, scale, centerX, centerY); matrix.postRotate(90 * (rotation - 2), centerX, centerY); } else if (Surface.ROTATION_180 == rotation) { matrix.postRotate(180, centerX, centerY); } textureView.setTransform(matrix); } /** * Callback for Activities to use to initialize their data once the selected preview size is * known. */ public interface ConnectionCallback { void onPreviewSizeChosen(Size size, int cameraRotation); } /** Compares two {@code Size}s based on their areas. */ static class CompareSizesByArea implements Comparator<Size> { @Override public int compare(final Size lhs, final Size rhs) { // We cast here to ensure the multiplications won't overflow return Long.signum( (long) lhs.getWidth() * lhs.getHeight() - (long) rhs.getWidth() * rhs.getHeight()); } } /** Shows an error message dialog. */ public static class ErrorDialog extends DialogFragment { private static final String ARG_MESSAGE = "message"; public static ErrorDialog newInstance(final String message) { final ErrorDialog dialog = new ErrorDialog(); final Bundle args = new Bundle(); args.putString(ARG_MESSAGE, message); dialog.setArguments(args); return dialog; } @Override public Dialog onCreateDialog(final Bundle savedInstanceState) { final Activity activity = getActivity(); return new AlertDialog.Builder(activity) .setMessage(getArguments().getString(ARG_MESSAGE)) .setPositiveButton( android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialogInterface, final int i) { activity.finish(); } }) .create(); } } }
21,891
Java
.java
7people/AR-Shopping
9
2
0
2023-06-12T14:01:53Z
2023-07-26T07:06:06Z
RecognitionScoreView.java
/FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/org/tensorflow/lite/examples/detection/customview/RecognitionScoreView.java
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may 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.tensorflow.lite.examples.detection.customview; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.util.AttributeSet; import android.util.TypedValue; import android.view.View; import java.util.List; import org.tensorflow.lite.examples.detection.tflite.Classifier.Recognition; public class RecognitionScoreView extends View implements ResultsView { private static final float TEXT_SIZE_DIP = 14; private float textSizePx = 0; private Paint fgPaint; private Paint bgPaint; private List<Recognition> results; public RecognitionScoreView(final Context context, final AttributeSet set) { super(context, set); textSizePx = TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, TEXT_SIZE_DIP, getResources().getDisplayMetrics()); fgPaint = new Paint(); fgPaint.setTextSize(textSizePx); bgPaint = new Paint(); bgPaint.setColor(0xcc4285f4); } @Override public void setResults(final List<Recognition> results) { this.results = results; postInvalidate(); } @Override public void onDraw(final Canvas canvas) { final int x = 10; int y = (int) (fgPaint.getTextSize() * 1.5f); canvas.drawPaint(bgPaint); if (results != null) { for (final Recognition recog : results) { canvas.drawText(recog.getTitle() + ": " + recog.getConfidence(), x, y, fgPaint); y += (int) (fgPaint.getTextSize() * 1.5f); } } } }
2,169
Java
.java
7people/AR-Shopping
9
2
0
2023-06-12T14:01:53Z
2023-07-26T07:06:06Z
OverlayView.java
/FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/org/tensorflow/lite/examples/detection/customview/OverlayView.java
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may 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.tensorflow.lite.examples.detection.customview; import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import android.view.View; import java.util.LinkedList; import java.util.List; /** A simple View providing a render callback to other classes. */ public class OverlayView extends View { private final List<DrawCallback> callbacks = new LinkedList<DrawCallback>(); public OverlayView(final Context context, final AttributeSet attrs) { super(context, attrs); } public void addCallback(final DrawCallback callback) { callbacks.add(callback); } @Override public synchronized void draw(final Canvas canvas) { for (final DrawCallback callback : callbacks) { callback.drawCallback(canvas); } } /** Interface defining the callback for client classes. */ public interface DrawCallback { public void drawCallback(final Canvas canvas); } }
1,608
Java
.java
7people/AR-Shopping
9
2
0
2023-06-12T14:01:53Z
2023-07-26T07:06:06Z
AutoFitTextureView.java
/FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/org/tensorflow/lite/examples/detection/customview/AutoFitTextureView.java
/* * Copyright 2019 The TensorFlow Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may 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.tensorflow.lite.examples.detection.customview; import android.content.Context; import android.util.AttributeSet; import android.view.TextureView; /** A {@link TextureView} that can be adjusted to a specified aspect ratio. */ public class AutoFitTextureView extends TextureView { private int ratioWidth = 0; private int ratioHeight = 0; public AutoFitTextureView(final Context context) { this(context, null); } public AutoFitTextureView(final Context context, final AttributeSet attrs) { this(context, attrs, 0); } public AutoFitTextureView(final Context context, final AttributeSet attrs, final int defStyle) { super(context, attrs, defStyle); } /** * Sets the aspect ratio for this view. The size of the view will be measured based on the ratio * calculated from the parameters. Note that the actual sizes of parameters don't matter, that is, * calling setAspectRatio(2, 3) and setAspectRatio(4, 6) make the same result. * * @param width Relative horizontal size * @param height Relative vertical size */ public void setAspectRatio(final int width, final int height) { if (width < 0 || height < 0) { throw new IllegalArgumentException("Size cannot be negative."); } ratioWidth = width; ratioHeight = height; requestLayout(); } @Override protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); final int width = MeasureSpec.getSize(widthMeasureSpec); final int height = MeasureSpec.getSize(heightMeasureSpec); if (0 == ratioWidth || 0 == ratioHeight) { setMeasuredDimension(width, height); } else { if (width < height * ratioWidth / ratioHeight) { setMeasuredDimension(width, width * ratioHeight / ratioWidth); } else { setMeasuredDimension(height * ratioWidth / ratioHeight, height); } } } }
2,576
Java
.java
7people/AR-Shopping
9
2
0
2023-06-12T14:01:53Z
2023-07-26T07:06:06Z
ResultsView.java
/FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/org/tensorflow/lite/examples/detection/customview/ResultsView.java
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may 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.tensorflow.lite.examples.detection.customview; import java.util.List; import org.tensorflow.lite.examples.detection.tflite.Classifier.Recognition; public interface ResultsView { public void setResults(final List<Recognition> results); }
923
Java
.java
7people/AR-Shopping
9
2
0
2023-06-12T14:01:53Z
2023-07-26T07:06:06Z
Size.java
/FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/org/tensorflow/lite/examples/detection/env/Size.java
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may 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.tensorflow.lite.examples.detection.env; import android.graphics.Bitmap; import android.text.TextUtils; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** Size class independent of a Camera object. */ public class Size implements Comparable<Size>, Serializable { // 1.4 went out with this UID so we'll need to maintain it to preserve pending queries when // upgrading. public static final long serialVersionUID = 7689808733290872361L; public final int width; public final int height; public Size(final int width, final int height) { this.width = width; this.height = height; } public Size(final Bitmap bmp) { this.width = bmp.getWidth(); this.height = bmp.getHeight(); } /** * Rotate a size by the given number of degrees. * * @param size Size to rotate. * @param rotation Degrees {0, 90, 180, 270} to rotate the size. * @return Rotated size. */ public static Size getRotatedSize(final Size size, final int rotation) { if (rotation % 180 != 0) { // The phone is portrait, therefore the camera is sideways and frame should be rotated. return new Size(size.height, size.width); } return size; } public static Size parseFromString(String sizeString) { if (TextUtils.isEmpty(sizeString)) { return null; } sizeString = sizeString.trim(); // The expected format is "<width>x<height>". final String[] components = sizeString.split("x"); if (components.length == 2) { try { final int width = Integer.parseInt(components[0]); final int height = Integer.parseInt(components[1]); return new Size(width, height); } catch (final NumberFormatException e) { return null; } } else { return null; } } public static List<Size> sizeStringToList(final String sizes) { final List<Size> sizeList = new ArrayList<Size>(); if (sizes != null) { final String[] pairs = sizes.split(","); for (final String pair : pairs) { final Size size = Size.parseFromString(pair); if (size != null) { sizeList.add(size); } } } return sizeList; } public static String sizeListToString(final List<Size> sizes) { String sizesString = ""; if (sizes != null && sizes.size() > 0) { sizesString = sizes.get(0).toString(); for (int i = 1; i < sizes.size(); i++) { sizesString += "," + sizes.get(i).toString(); } } return sizesString; } public static final String dimensionsAsString(final int width, final int height) { return width + "x" + height; } public final float aspectRatio() { return (float) width / (float) height; } @Override public int compareTo(final Size other) { return width * height - other.width * other.height; } @Override public boolean equals(final Object other) { if (other == null) { return false; } if (!(other instanceof Size)) { return false; } final Size otherSize = (Size) other; return (width == otherSize.width && height == otherSize.height); } @Override public int hashCode() { return width * 32713 + height; } @Override public String toString() { return dimensionsAsString(width, height); } }
3,996
Java
.java
7people/AR-Shopping
9
2
0
2023-06-12T14:01:53Z
2023-07-26T07:06:06Z
BorderedText.java
/FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/org/tensorflow/lite/examples/detection/env/BorderedText.java
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may 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.tensorflow.lite.examples.detection.env; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.Paint.Style; import android.graphics.Rect; import android.graphics.Typeface; import java.util.Vector; /** A class that encapsulates the tedious bits of rendering legible, bordered text onto a canvas. */ public class BorderedText { private final Paint interiorPaint; private final Paint exteriorPaint; private final float textSize; /** * Creates a left-aligned bordered text object with a white interior, and a black exterior with * the specified text size. * * @param textSize text size in pixels */ public BorderedText(final float textSize) { this(Color.WHITE, Color.BLACK, textSize); } /** * Create a bordered text object with the specified interior and exterior colors, text size and * alignment. * * @param interiorColor the interior text color * @param exteriorColor the exterior text color * @param textSize text size in pixels */ public BorderedText(final int interiorColor, final int exteriorColor, final float textSize) { interiorPaint = new Paint(); interiorPaint.setTextSize(textSize); interiorPaint.setColor(interiorColor); interiorPaint.setStyle(Style.FILL); interiorPaint.setAntiAlias(false); interiorPaint.setAlpha(255); exteriorPaint = new Paint(); exteriorPaint.setTextSize(textSize); exteriorPaint.setColor(exteriorColor); exteriorPaint.setStyle(Style.FILL_AND_STROKE); exteriorPaint.setStrokeWidth(textSize / 8); exteriorPaint.setAntiAlias(false); exteriorPaint.setAlpha(255); this.textSize = textSize; } public void setTypeface(Typeface typeface) { interiorPaint.setTypeface(typeface); exteriorPaint.setTypeface(typeface); } public void drawText(final Canvas canvas, final float posX, final float posY, final String text) { canvas.drawText(text, posX, posY, exteriorPaint); canvas.drawText(text, posX, posY, interiorPaint); } public void drawText( final Canvas canvas, final float posX, final float posY, final String text, Paint bgPaint) { float width = exteriorPaint.measureText(text); float textSize = exteriorPaint.getTextSize(); Paint paint = new Paint(bgPaint); paint.setStyle(Paint.Style.FILL); paint.setAlpha(160); canvas.drawRect(posX, (posY + (int) (textSize)), (posX + (int) (width)), posY, paint); canvas.drawText(text, posX, (posY + textSize), interiorPaint); } public void drawLines(Canvas canvas, final float posX, final float posY, Vector<String> lines) { int lineNum = 0; for (final String line : lines) { drawText(canvas, posX, posY - getTextSize() * (lines.size() - lineNum - 1), line); ++lineNum; } } public void setInteriorColor(final int color) { interiorPaint.setColor(color); } public void setExteriorColor(final int color) { exteriorPaint.setColor(color); } public float getTextSize() { return textSize; } public void setAlpha(final int alpha) { interiorPaint.setAlpha(alpha); exteriorPaint.setAlpha(alpha); } public void getTextBounds( final String line, final int index, final int count, final Rect lineBounds) { interiorPaint.getTextBounds(line, index, count, lineBounds); } public void setTextAlign(final Align align) { interiorPaint.setTextAlign(align); exteriorPaint.setTextAlign(align); } }
4,205
Java
.java
7people/AR-Shopping
9
2
0
2023-06-12T14:01:53Z
2023-07-26T07:06:06Z
Logger.java
/FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/org/tensorflow/lite/examples/detection/env/Logger.java
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may 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.tensorflow.lite.examples.detection.env; import android.annotation.SuppressLint; import android.util.Log; import java.util.HashSet; import java.util.Set; /** Wrapper for the platform log function, allows convenient message prefixing and log disabling. */ public final class Logger { private static final String DEFAULT_TAG = "tensorflow"; private static final int DEFAULT_MIN_LOG_LEVEL = Log.DEBUG; // Classes to be ignored when examining the stack trace private static final Set<String> IGNORED_CLASS_NAMES; static { IGNORED_CLASS_NAMES = new HashSet<String>(3); IGNORED_CLASS_NAMES.add("dalvik.system.VMStack"); IGNORED_CLASS_NAMES.add("java.lang.Thread"); IGNORED_CLASS_NAMES.add(Logger.class.getCanonicalName()); } private final String tag; private final String messagePrefix; private int minLogLevel = DEFAULT_MIN_LOG_LEVEL; /** * Creates a Logger using the class name as the message prefix. * * @param clazz the simple name of this class is used as the message prefix. */ public Logger(final Class<?> clazz) { this(clazz.getSimpleName()); } /** * Creates a Logger using the specified message prefix. * * @param messagePrefix is prepended to the text of every message. */ public Logger(final String messagePrefix) { this(DEFAULT_TAG, messagePrefix); } /** * Creates a Logger with a custom tag and a custom message prefix. If the message prefix is set to * * <pre>null</pre> * * , the caller's class name is used as the prefix. * * @param tag identifies the source of a log message. * @param messagePrefix prepended to every message if non-null. If null, the name of the caller is * being used */ public Logger(final String tag, final String messagePrefix) { this.tag = tag; final String prefix = messagePrefix == null ? getCallerSimpleName() : messagePrefix; this.messagePrefix = (prefix.length() > 0) ? prefix + ": " : prefix; } /** Creates a Logger using the caller's class name as the message prefix. */ public Logger() { this(DEFAULT_TAG, null); } /** Creates a Logger using the caller's class name as the message prefix. */ public Logger(final int minLogLevel) { this(DEFAULT_TAG, null); this.minLogLevel = minLogLevel; } /** * Return caller's simple name. * * <p>Android getStackTrace() returns an array that looks like this: stackTrace[0]: * dalvik.system.VMStack stackTrace[1]: java.lang.Thread stackTrace[2]: * com.google.android.apps.unveil.env.UnveilLogger stackTrace[3]: * com.google.android.apps.unveil.BaseApplication * * <p>This function returns the simple version of the first non-filtered name. * * @return caller's simple name */ private static String getCallerSimpleName() { // Get the current callstack so we can pull the class of the caller off of it. final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); for (final StackTraceElement elem : stackTrace) { final String className = elem.getClassName(); if (!IGNORED_CLASS_NAMES.contains(className)) { // We're only interested in the simple name of the class, not the complete package. final String[] classParts = className.split("\\."); return classParts[classParts.length - 1]; } } return Logger.class.getSimpleName(); } public void setMinLogLevel(final int minLogLevel) { this.minLogLevel = minLogLevel; } public boolean isLoggable(final int logLevel) { return logLevel >= minLogLevel || Log.isLoggable(tag, logLevel); } private String toMessage(final String format, final Object... args) { return messagePrefix + (args.length > 0 ? String.format(format, args) : format); } @SuppressLint("LogTagMismatch") public void v(final String format, final Object... args) { if (isLoggable(Log.VERBOSE)) { Log.v(tag, toMessage(format, args)); } } @SuppressLint("LogTagMismatch") public void v(final Throwable t, final String format, final Object... args) { if (isLoggable(Log.VERBOSE)) { Log.v(tag, toMessage(format, args), t); } } @SuppressLint("LogTagMismatch") public void d(final String format, final Object... args) { if (isLoggable(Log.DEBUG)) { Log.d(tag, toMessage(format, args)); } } @SuppressLint("LogTagMismatch") public void d(final Throwable t, final String format, final Object... args) { if (isLoggable(Log.DEBUG)) { Log.d(tag, toMessage(format, args), t); } } @SuppressLint("LogTagMismatch") public void i(final String format, final Object... args) { if (isLoggable(Log.INFO)) { Log.i(tag, toMessage(format, args)); } } @SuppressLint("LogTagMismatch") public void i(final Throwable t, final String format, final Object... args) { if (isLoggable(Log.INFO)) { Log.i(tag, toMessage(format, args), t); } } @SuppressLint("LogTagMismatch") public void w(final String format, final Object... args) { if (isLoggable(Log.WARN)) { Log.w(tag, toMessage(format, args)); } } @SuppressLint("LogTagMismatch") public void w(final Throwable t, final String format, final Object... args) { if (isLoggable(Log.WARN)) { Log.w(tag, toMessage(format, args), t); } } @SuppressLint("LogTagMismatch") public void e(final String format, final Object... args) { if (isLoggable(Log.ERROR)) { Log.e(tag, toMessage(format, args)); } } @SuppressLint("LogTagMismatch") public void e(final Throwable t, final String format, final Object... args) { if (isLoggable(Log.ERROR)) { Log.e(tag, toMessage(format, args), t); } } }
6,384
Java
.java
7people/AR-Shopping
9
2
0
2023-06-12T14:01:53Z
2023-07-26T07:06:06Z
ImageUtils.java
/FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/org/tensorflow/lite/examples/detection/env/ImageUtils.java
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may 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.tensorflow.lite.examples.detection.env; import android.graphics.Bitmap; import android.graphics.Matrix; import android.os.Environment; import java.io.File; import java.io.FileOutputStream; /** Utility class for manipulating images. */ public class ImageUtils { // This value is 2 ^ 18 - 1, and is used to clamp the RGB values before their ranges // are normalized to eight bits. static final int kMaxChannelValue = 262143; @SuppressWarnings("unused") private static final Logger LOGGER = new Logger(); /** * Utility method to compute the allocated size in bytes of a YUV420SP image of the given * dimensions. */ public static int getYUVByteSize(final int width, final int height) { // The luminance plane requires 1 byte per pixel. final int ySize = width * height; // The UV plane works on 2x2 blocks, so dimensions with odd size must be rounded up. // Each 2x2 block takes 2 bytes to encode, one each for U and V. final int uvSize = ((width + 1) / 2) * ((height + 1) / 2) * 2; return ySize + uvSize; } /** * Saves a Bitmap object to disk for analysis. * * @param bitmap The bitmap to save. */ public static void saveBitmap(final Bitmap bitmap) { saveBitmap(bitmap, "preview.png"); } /** * Saves a Bitmap object to disk for analysis. * * @param bitmap The bitmap to save. * @param filename The location to save the bitmap to. */ public static void saveBitmap(final Bitmap bitmap, final String filename) { final String root = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "tensorflow"; LOGGER.i("Saving %dx%d bitmap to %s.", bitmap.getWidth(), bitmap.getHeight(), root); final File myDir = new File(root); if (!myDir.mkdirs()) { LOGGER.i("Make dir failed"); } final String fname = filename; final File file = new File(myDir, fname); if (file.exists()) { file.delete(); } try { final FileOutputStream out = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.PNG, 99, out); out.flush(); out.close(); } catch (final Exception e) { LOGGER.e(e, "Exception!"); } } public static void convertYUV420SPToARGB8888(byte[] input, int width, int height, int[] output) { final int frameSize = width * height; for (int j = 0, yp = 0; j < height; j++) { int uvp = frameSize + (j >> 1) * width; int u = 0; int v = 0; for (int i = 0; i < width; i++, yp++) { int y = 0xff & input[yp]; if ((i & 1) == 0) { v = 0xff & input[uvp++]; u = 0xff & input[uvp++]; } output[yp] = YUV2RGB(y, u, v); } } } private static int YUV2RGB(int y, int u, int v) { // Adjust and check YUV values y = (y - 16) < 0 ? 0 : (y - 16); u -= 128; v -= 128; // This is the floating point equivalent. We do the conversion in integer // because some Android devices do not have floating point in hardware. // nR = (int)(1.164 * nY + 2.018 * nU); // nG = (int)(1.164 * nY - 0.813 * nV - 0.391 * nU); // nB = (int)(1.164 * nY + 1.596 * nV); int y1192 = 1192 * y; int r = (y1192 + 1634 * v); int g = (y1192 - 833 * v - 400 * u); int b = (y1192 + 2066 * u); // Clipping RGB values to be inside boundaries [ 0 , kMaxChannelValue ] r = r > kMaxChannelValue ? kMaxChannelValue : (r < 0 ? 0 : r); g = g > kMaxChannelValue ? kMaxChannelValue : (g < 0 ? 0 : g); b = b > kMaxChannelValue ? kMaxChannelValue : (b < 0 ? 0 : b); return 0xff000000 | ((r << 6) & 0xff0000) | ((g >> 2) & 0xff00) | ((b >> 10) & 0xff); } public static void convertYUV420ToARGB8888( byte[] yData, byte[] uData, byte[] vData, int width, int height, int yRowStride, int uvRowStride, int uvPixelStride, int[] out) { int yp = 0; for (int j = 0; j < height; j++) { int pY = yRowStride * j; int pUV = uvRowStride * (j >> 1); for (int i = 0; i < width; i++) { int uv_offset = pUV + (i >> 1) * uvPixelStride; out[yp++] = YUV2RGB(0xff & yData[pY + i], 0xff & uData[uv_offset], 0xff & vData[uv_offset]); } } } /** * Returns a transformation matrix from one reference frame into another. Handles cropping (if * maintaining aspect ratio is desired) and rotation. * * @param srcWidth Width of source frame. * @param srcHeight Height of source frame. * @param dstWidth Width of destination frame. * @param dstHeight Height of destination frame. * @param applyRotation Amount of rotation to apply from one frame to another. Must be a multiple * of 90. * @param maintainAspectRatio If true, will ensure that scaling in x and y remains constant, * cropping the image if necessary. * @return The transformation fulfilling the desired requirements. */ public static Matrix getTransformationMatrix( final int srcWidth, final int srcHeight, final int dstWidth, final int dstHeight, final int applyRotation, final boolean maintainAspectRatio) { final Matrix matrix = new Matrix(); if (applyRotation != 0) { if (applyRotation % 90 != 0) { LOGGER.w("Rotation of %d % 90 != 0", applyRotation); } // Translate so center of image is at origin. matrix.postTranslate(-srcWidth / 2.0f, -srcHeight / 2.0f); // Rotate around origin. matrix.postRotate(applyRotation); } // Account for the already applied rotation, if any, and then determine how // much scaling is needed for each axis. final boolean transpose = (Math.abs(applyRotation) + 90) % 180 == 0; final int inWidth = transpose ? srcHeight : srcWidth; final int inHeight = transpose ? srcWidth : srcHeight; // Apply scaling if necessary. if (inWidth != dstWidth || inHeight != dstHeight) { final float scaleFactorX = dstWidth / (float) inWidth; final float scaleFactorY = dstHeight / (float) inHeight; if (maintainAspectRatio) { // Scale by minimum factor so that dst is filled completely while // maintaining the aspect ratio. Some image may fall off the edge. final float scaleFactor = Math.max(scaleFactorX, scaleFactorY); matrix.postScale(scaleFactor, scaleFactor); } else { // Scale exactly to fill dst from src. matrix.postScale(scaleFactorX, scaleFactorY); } } if (applyRotation != 0) { // Translate back from origin centered reference to destination frame. matrix.postTranslate(dstWidth / 2.0f, dstHeight / 2.0f); } return matrix; } }
7,394
Java
.java
7people/AR-Shopping
9
2
0
2023-06-12T14:01:53Z
2023-07-26T07:06:06Z
MultiBoxTracker.java
/FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/org/tensorflow/lite/examples/detection/tracking/MultiBoxTracker.java
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may 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.tensorflow.lite.examples.detection.tracking; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Paint.Cap; import android.graphics.Paint.Join; import android.graphics.Paint.Style; import android.graphics.RectF; import android.text.TextUtils; import android.util.Pair; import android.util.TypedValue; import java.util.LinkedList; import java.util.List; import java.util.Queue; import org.tensorflow.lite.examples.detection.env.BorderedText; import org.tensorflow.lite.examples.detection.env.ImageUtils; import org.tensorflow.lite.examples.detection.env.Logger; import org.tensorflow.lite.examples.detection.tflite.Classifier.Recognition; /** A tracker that handles non-max suppression and matches existing objects to new detections. */ public class MultiBoxTracker { private static final float TEXT_SIZE_DIP = 18; private static final float MIN_SIZE = 16.0f; private static final int[] COLORS = { Color.BLUE, Color.RED, Color.GREEN, Color.YELLOW, Color.CYAN, Color.MAGENTA, Color.WHITE, Color.parseColor("#55FF55"), Color.parseColor("#FFA500"), Color.parseColor("#FF8888"), Color.parseColor("#AAAAFF"), Color.parseColor("#FFFFAA"), Color.parseColor("#55AAAA"), Color.parseColor("#AA33AA"), Color.parseColor("#0D0068") }; final List<Pair<Float, RectF>> screenRects = new LinkedList<Pair<Float, RectF>>(); private final Logger logger = new Logger(); private final Queue<Integer> availableColors = new LinkedList<Integer>(); private final List<TrackedRecognition> trackedObjects = new LinkedList<TrackedRecognition>(); private final Paint boxPaint = new Paint(); private final float textSizePx; private final BorderedText borderedText; private Matrix frameToCanvasMatrix; private int frameWidth; private int frameHeight; private int sensorOrientation; public MultiBoxTracker(final Context context) { for (final int color : COLORS) { availableColors.add(color); } boxPaint.setColor(Color.RED); boxPaint.setStyle(Style.STROKE); boxPaint.setStrokeWidth(10.0f); boxPaint.setStrokeCap(Cap.ROUND); boxPaint.setStrokeJoin(Join.ROUND); boxPaint.setStrokeMiter(100); textSizePx = TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, TEXT_SIZE_DIP, context.getResources().getDisplayMetrics()); borderedText = new BorderedText(textSizePx); } public synchronized void setFrameConfiguration( final int width, final int height, final int sensorOrientation) { frameWidth = width; frameHeight = height; this.sensorOrientation = sensorOrientation; } public synchronized void drawDebug(final Canvas canvas) { final Paint textPaint = new Paint(); textPaint.setColor(Color.WHITE); textPaint.setTextSize(60.0f); final Paint boxPaint = new Paint(); boxPaint.setColor(Color.RED); boxPaint.setAlpha(200); boxPaint.setStyle(Style.STROKE); for (final Pair<Float, RectF> detection : screenRects) { final RectF rect = detection.second; canvas.drawRect(rect, boxPaint); canvas.drawText("" + detection.first, rect.left, rect.top, textPaint); borderedText.drawText(canvas, rect.centerX(), rect.centerY(), "" + detection.first); } } public synchronized void trackResults(final List<Recognition> results, final long timestamp) { logger.i("Processing %d results from %d", results.size(), timestamp); processResults(results); } private Matrix getFrameToCanvasMatrix() { return frameToCanvasMatrix; } public synchronized void draw(final Canvas canvas) { final boolean rotated = sensorOrientation % 180 == 90; final float multiplier = Math.min( canvas.getHeight() / (float) (rotated ? frameWidth : frameHeight), canvas.getWidth() / (float) (rotated ? frameHeight : frameWidth)); frameToCanvasMatrix = ImageUtils.getTransformationMatrix( frameWidth, frameHeight, (int) (multiplier * (rotated ? frameHeight : frameWidth)), (int) (multiplier * (rotated ? frameWidth : frameHeight)), sensorOrientation, false); for (final TrackedRecognition recognition : trackedObjects) { final RectF trackedPos = new RectF(recognition.location); getFrameToCanvasMatrix().mapRect(trackedPos); boxPaint.setColor(recognition.color); float cornerSize = Math.min(trackedPos.width(), trackedPos.height()) / 8.0f; canvas.drawRoundRect(trackedPos, cornerSize, cornerSize, boxPaint); final String labelString = !TextUtils.isEmpty(recognition.title) ? String.format("%s %.2f", recognition.title, (100 * recognition.detectionConfidence)) : String.format("%.2f", (100 * recognition.detectionConfidence)); // borderedText.drawText(canvas, trackedPos.left + cornerSize, trackedPos.top, // labelString); borderedText.drawText( canvas, trackedPos.left + cornerSize, trackedPos.top, labelString + "%", boxPaint); } } private void processResults(final List<Recognition> results) { final List<Pair<Float, Recognition>> rectsToTrack = new LinkedList<Pair<Float, Recognition>>(); screenRects.clear(); final Matrix rgbFrameToScreen = new Matrix(getFrameToCanvasMatrix()); for (final Recognition result : results) { if (result.getLocation() == null) { continue; } final RectF detectionFrameRect = new RectF(result.getLocation()); final RectF detectionScreenRect = new RectF(); rgbFrameToScreen.mapRect(detectionScreenRect, detectionFrameRect); logger.v( "Result! Frame: " + result.getLocation() + " mapped to screen:" + detectionScreenRect); screenRects.add(new Pair<Float, RectF>(result.getConfidence(), detectionScreenRect)); if (detectionFrameRect.width() < MIN_SIZE || detectionFrameRect.height() < MIN_SIZE) { logger.w("Degenerate rectangle! " + detectionFrameRect); continue; } rectsToTrack.add(new Pair<Float, Recognition>(result.getConfidence(), result)); } trackedObjects.clear(); if (rectsToTrack.isEmpty()) { logger.v("Nothing to track, aborting."); return; } for (final Pair<Float, Recognition> potential : rectsToTrack) { final TrackedRecognition trackedRecognition = new TrackedRecognition(); trackedRecognition.detectionConfidence = potential.first; trackedRecognition.location = new RectF(potential.second.getLocation()); trackedRecognition.title = potential.second.getTitle(); trackedRecognition.color = COLORS[trackedObjects.size()]; trackedObjects.add(trackedRecognition); if (trackedObjects.size() >= COLORS.length) { break; } } } private static class TrackedRecognition { RectF location; float detectionConfidence; int color; String title; } }
7,766
Java
.java
7people/AR-Shopping
9
2
0
2023-06-12T14:01:53Z
2023-07-26T07:06:06Z
Classifier.java
/FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/org/tensorflow/lite/examples/detection/tflite/Classifier.java
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may 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.tensorflow.lite.examples.detection.tflite; import android.graphics.Bitmap; import android.graphics.RectF; import java.util.List; /** Generic interface for interacting with different recognition engines. */ public interface Classifier { List<Recognition> recognizeImage(Bitmap bitmap); void enableStatLogging(final boolean debug); String getStatString(); void close(); void setNumThreads(int num_threads); void setUseNNAPI(boolean isChecked); /** An immutable result returned by a Classifier describing what was recognized. */ public class Recognition { /** * A unique identifier for what has been recognized. Specific to the class, not the instance of * the object. */ private final String id; /** Display name for the recognition. */ private final String title; /** * A sortable score for how good the recognition is relative to others. Higher should be better. */ private final Float confidence; /** Optional location within the source image for the location of the recognized object. */ private RectF location; public Recognition( final String id, final String title, final Float confidence, final RectF location) { this.id = id; this.title = title; this.confidence = confidence; this.location = location; } public String getId() { return id; } public String getTitle() { return title; } public Float getConfidence() { return confidence; } public RectF getLocation() { return new RectF(location); } public void setLocation(RectF location) { this.location = location; } @Override public String toString() { String resultString = ""; if (id != null) { resultString += "[" + id + "] "; } if (title != null) { resultString += title + " "; } if (confidence != null) { resultString += String.format("(%.1f%%) ", confidence * 100.0f); } if (location != null) { resultString += location + " "; } return resultString.trim(); } } }
2,818
Java
.java
7people/AR-Shopping
9
2
0
2023-06-12T14:01:53Z
2023-07-26T07:06:06Z
TFLiteObjectDetectionAPIModel.java
/FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/org/tensorflow/lite/examples/detection/tflite/TFLiteObjectDetectionAPIModel.java
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may 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.tensorflow.lite.examples.detection.tflite; import android.content.res.AssetFileDescriptor; import android.content.res.AssetManager; import android.graphics.Bitmap; import android.graphics.RectF; import android.os.Trace; import org.tensorflow.lite.Interpreter; import org.tensorflow.lite.examples.detection.env.Logger; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Vector; /** * Wrapper for frozen detection models trained using the Tensorflow Object Detection API: * github.com/tensorflow/models/tree/master/research/object_detection */ public class TFLiteObjectDetectionAPIModel implements Classifier { private static final Logger LOGGER = new Logger(); // Only return this many results. private static final int NUM_DETECTIONS = 10; // Float model private static final float IMAGE_MEAN = 128.0f; private static final float IMAGE_STD = 128.0f; // Number of threads in the java app private static final int NUM_THREADS = 4; private boolean isModelQuantized; // Config values. private int inputSize; // Pre-allocated buffers. private Vector<String> labels = new Vector<String>(); private int[] intValues; // outputLocations: array of shape [Batchsize, NUM_DETECTIONS,4] // contains the location of detected boxes private float[][][] outputLocations; // outputClasses: array of shape [Batchsize, NUM_DETECTIONS] // contains the classes of detected boxes private float[][] outputClasses; // outputScores: array of shape [Batchsize, NUM_DETECTIONS] // contains the scores of detected boxes private float[][] outputScores; // numDetections: array of shape [Batchsize] // contains the number of detected boxes private float[] numDetections; private ByteBuffer imgData; private Interpreter tfLite; private TFLiteObjectDetectionAPIModel() {} /** Memory-map the model file in Assets. */ private static MappedByteBuffer loadModelFile(AssetManager assets, String modelFilename) throws IOException { AssetFileDescriptor fileDescriptor = assets.openFd(modelFilename); FileInputStream inputStream = new FileInputStream(fileDescriptor.getFileDescriptor()); FileChannel fileChannel = inputStream.getChannel(); long startOffset = fileDescriptor.getStartOffset(); long declaredLength = fileDescriptor.getDeclaredLength(); return fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength); } /** * Initializes a native TensorFlow session for classifying images. * * @param assetManager The asset manager to be used to load assets. * @param modelFilename The filepath of the model GraphDef protocol buffer. * @param labelFilename The filepath of label file for classes. * @param inputSize The size of image input * @param isQuantized Boolean representing model is quantized or not */ public static Classifier create( final AssetManager assetManager, final String modelFilename, final String labelFilename, final int inputSize, final boolean isQuantized) throws IOException { final TFLiteObjectDetectionAPIModel d = new TFLiteObjectDetectionAPIModel(); InputStream labelsInput = null; String actualFilename = labelFilename.split("file:///android_asset/")[1]; labelsInput = assetManager.open(actualFilename); BufferedReader br = null; br = new BufferedReader(new InputStreamReader(labelsInput)); String line; while ((line = br.readLine()) != null) { LOGGER.w(line); d.labels.add(line); } br.close(); d.inputSize = inputSize; try { d.tfLite = new Interpreter(loadModelFile(assetManager, modelFilename)); } catch (Exception e) { throw new RuntimeException(e); } d.isModelQuantized = isQuantized; // Pre-allocate buffers. int numBytesPerChannel; if (isQuantized) { numBytesPerChannel = 1; // Quantized } else { numBytesPerChannel = 4; // Floating point } d.imgData = ByteBuffer.allocateDirect(1 * d.inputSize * d.inputSize * 3 * numBytesPerChannel); d.imgData.order(ByteOrder.nativeOrder()); d.intValues = new int[d.inputSize * d.inputSize]; d.tfLite.setNumThreads(NUM_THREADS); d.outputLocations = new float[1][NUM_DETECTIONS][4]; d.outputClasses = new float[1][NUM_DETECTIONS]; d.outputScores = new float[1][NUM_DETECTIONS]; d.numDetections = new float[1]; return d; } @Override public List<Recognition> recognizeImage(final Bitmap bitmap) { // Log this method so that it can be analyzed with systrace. Trace.beginSection("recognizeImage"); Trace.beginSection("preprocessBitmap"); // Preprocess the image data from 0-255 int to normalized float based // on the provided parameters. bitmap.getPixels(intValues, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight()); imgData.rewind(); for (int i = 0; i < inputSize; ++i) { for (int j = 0; j < inputSize; ++j) { int pixelValue = intValues[i * inputSize + j]; if (isModelQuantized) { // Quantized model imgData.put((byte) ((pixelValue >> 16) & 0xFF)); imgData.put((byte) ((pixelValue >> 8) & 0xFF)); imgData.put((byte) (pixelValue & 0xFF)); } else { // Float model imgData.putFloat((((pixelValue >> 16) & 0xFF) - IMAGE_MEAN) / IMAGE_STD); imgData.putFloat((((pixelValue >> 8) & 0xFF) - IMAGE_MEAN) / IMAGE_STD); imgData.putFloat(((pixelValue & 0xFF) - IMAGE_MEAN) / IMAGE_STD); } } } Trace.endSection(); // preprocessBitmap // Copy the input data into TensorFlow. Trace.beginSection("feed"); outputLocations = new float[1][NUM_DETECTIONS][4]; outputClasses = new float[1][NUM_DETECTIONS]; outputScores = new float[1][NUM_DETECTIONS]; numDetections = new float[1]; Object[] inputArray = {imgData}; Map<Integer, Object> outputMap = new HashMap<>(); outputMap.put(0, outputLocations); outputMap.put(1, outputClasses); outputMap.put(2, outputScores); outputMap.put(3, numDetections); Trace.endSection(); // Run the inference call. Trace.beginSection("run"); tfLite.runForMultipleInputsOutputs(inputArray, outputMap); Trace.endSection(); // Show the best detections. // after scaling them back to the input size. final ArrayList<Recognition> recognitions = new ArrayList<>(NUM_DETECTIONS); for (int i = 0; i < NUM_DETECTIONS; ++i) { final RectF detection = new RectF( outputLocations[0][i][1] * inputSize, outputLocations[0][i][0] * inputSize, outputLocations[0][i][3] * inputSize, outputLocations[0][i][2] * inputSize); // SSD Mobilenet V1 Model assumes class 0 is background class // in label file and class labels start from 1 to number_of_classes+1, // while outputClasses correspond to class index from 0 to number_of_classes int labelOffset = 1; recognitions.add( new Recognition( "" + i, labels.get((int) outputClasses[0][i] + labelOffset), outputScores[0][i], detection)); } Trace.endSection(); // "recognizeImage" return recognitions; } @Override public void enableStatLogging(final boolean logStats) {} @Override public String getStatString() { return ""; } @Override public void close() {} public void setNumThreads(int num_threads) { if (tfLite != null) tfLite.setNumThreads(num_threads); } @Override public void setUseNNAPI(boolean isChecked) { if (tfLite != null) tfLite.setUseNNAPI(isChecked); } }
8,695
Java
.java
7people/AR-Shopping
9
2
0
2023-06-12T14:01:53Z
2023-07-26T07:06:06Z
QRCodeImageAnalysis.java
/FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/com/example/glass/arshopping/QRCodeImageAnalysis.java
package com.example.glass.arshopping; import android.util.Log; import androidx.camera.core.ImageAnalysis; import androidx.camera.core.ImageAnalysis.Analyzer; import androidx.camera.core.ImageAnalysisConfig; import androidx.camera.core.ImageProxy; import androidx.camera.core.UseCase; import com.google.zxing.BinaryBitmap; import com.google.zxing.ChecksumException; import com.google.zxing.FormatException; import com.google.zxing.NotFoundException; import com.google.zxing.PlanarYUVLuminanceSource; import com.google.zxing.Result; import com.google.zxing.common.HybridBinarizer; import com.google.zxing.qrcode.QRCodeReader; import java.nio.ByteBuffer; import java.util.concurrent.Executor; public class QRCodeImageAnalysis implements Analyzer { private static final String TAG = QRCodeImageAnalysis.class.getSimpleName(); private final ImageAnalysisConfig imageAnalysisConfig; private final Executor executor; private final QrCodeAnalysisCallback qrCodeAnalysisCallback; public QRCodeImageAnalysis(ImageAnalysisConfig imageAnalysisConfig, Executor executor, QrCodeAnalysisCallback qrCodeAnalysisCallback) { this.imageAnalysisConfig = imageAnalysisConfig; this.executor = executor; this.qrCodeAnalysisCallback = qrCodeAnalysisCallback; } public UseCase getUseCase() { final ImageAnalysis imageAnalysis = new ImageAnalysis(imageAnalysisConfig); imageAnalysis.setAnalyzer(executor, this); return imageAnalysis; } @Override public void analyze(ImageProxy image, int rotationDegrees) { final ByteBuffer buffer = image.getPlanes()[0].getBuffer(); final byte[] imageBytes = new byte[buffer.remaining()]; buffer.get(imageBytes); final int width = image.getWidth(); final int height = image.getHeight(); final PlanarYUVLuminanceSource source = new PlanarYUVLuminanceSource(imageBytes, width, height, 0, 0, width, height, false); final BinaryBitmap zxingBinaryBitmap = new BinaryBitmap(new HybridBinarizer(source)); try { final Result decodedBarcode = new QRCodeReader().decode(zxingBinaryBitmap); qrCodeAnalysisCallback.onQrCodeDetected(decodedBarcode.getText()); } catch (NotFoundException | ChecksumException | FormatException e) { Log.e(TAG, "QR Code decoding error", e); } } interface QrCodeAnalysisCallback { void onQrCodeDetected(String result); } }
2,370
Java
.java
7people/AR-Shopping
9
2
0
2023-06-12T14:01:53Z
2023-07-26T07:06:06Z
CameraConfigProvider.java
/FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/com/example/glass/arshopping/CameraConfigProvider.java
package com.example.glass.arshopping; import android.util.Size; import androidx.camera.core.ImageAnalysis.ImageReaderMode; import androidx.camera.core.ImageAnalysisConfig; import androidx.camera.core.PreviewConfig; public class CameraConfigProvider { public static PreviewConfig getPreviewConfig(Size displaySize) { return new PreviewConfig.Builder() .setTargetResolution(displaySize) .build(); } public static ImageAnalysisConfig getImageAnalysisConfig() { return new ImageAnalysisConfig.Builder() .setImageReaderMode(ImageReaderMode.ACQUIRE_LATEST_IMAGE) .build(); } }
621
Java
.java
7people/AR-Shopping
9
2
0
2023-06-12T14:01:53Z
2023-07-26T07:06:06Z
SignUp.java
/FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/com/example/glass/arshopping/SignUp.java
package com.example.glass.arshopping; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.android.volley.RequestQueue; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import com.example.glass.arshopping.utils.Global; import com.example.glass.ui.GlassGestureDetector.Gesture; import org.json.JSONObject; import java.util.HashMap; public class SignUp extends BaseActivity { RequestQueue mRequestQueue; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sign_up); mRequestQueue = Volley.newRequestQueue((Context) this); EditText passwordField1 = findViewById(R.id.password); EditText passwordField2 = findViewById(R.id.RePassword); EditText emailField = findViewById(R.id.email); EditText username = findViewById(R.id.username); Button regbtn = findViewById(R.id.SignUpButton); regbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String username1 = username.getText().toString(); String password1 = passwordField1.getText().toString(); String password2 = passwordField2.getText().toString(); String email1= emailField.getText().toString(); final EditText emailValidate = findViewById(R.id.email); final TextView textView = findViewById(R.id.email); String email = emailValidate.getText().toString().trim(); String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+"; if (TextUtils.isEmpty(username1) || TextUtils.isEmpty(password1) || TextUtils.isEmpty(password2) || TextUtils.isEmpty(email1)) { Toast.makeText(getApplicationContext(), "Please fill all the blanks", Toast.LENGTH_SHORT).show(); } else { if (password1.equals(password2)) { if (email.matches(emailPattern)) { if (username1.length() >= 5 && password1.length() >= 5) { HashMap<String, String> hm = new HashMap<String, String>(); hm.put("user_name", username1); hm.put("user_email", email1); hm.put("user_password", password1); JsonObjectRequest mRequest; mRequest = new JsonObjectRequest(Global.url+"/signup", new JSONObject(hm), response -> { try { boolean success = response.optBoolean("Success"); String message = response.optString("Message"); if(success){ Toast.makeText(SignUp.this, username1 + " registered", Toast.LENGTH_SHORT).show(); username.setText(""); emailField.setText(""); passwordField1.setText(""); passwordField2.setText(""); String usernameValue = username1; Intent intent = new Intent(getBaseContext(),Login.class); intent.putExtra("username", usernameValue); startActivity(intent); } else { Toast.makeText(SignUp.this, "Error: " + message, Toast.LENGTH_LONG).show(); } } catch (Exception e) {} }, error -> { }); mRequestQueue.add(mRequest); } else { Toast.makeText(getApplicationContext(), "Username and password must have at least 5 digits", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(getApplicationContext(), "Invalid email address", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(SignUp.this, "Your passwords are not matching", Toast.LENGTH_SHORT).show(); } } } }); findViewById(R.id.back).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(SignUp.this, MainActivity.class); startActivity(intent); } }); } @Override public boolean onGesture(Gesture gesture) { switch (gesture) { case SWIPE_DOWN: finish(); return true; default: return false; } } }
5,493
Java
.java
7people/AR-Shopping
9
2
0
2023-06-12T14:01:53Z
2023-07-26T07:06:06Z
QRCodePreview.java
/FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/com/example/glass/arshopping/QRCodePreview.java
package com.example.glass.arshopping; import android.view.TextureView; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.camera.core.Preview; import androidx.camera.core.Preview.OnPreviewOutputUpdateListener; import androidx.camera.core.Preview.PreviewOutput; import androidx.camera.core.PreviewConfig; import androidx.camera.core.UseCase; public class QRCodePreview implements OnPreviewOutputUpdateListener { private final PreviewConfig previewConfig; private final TextureView textureView; public QRCodePreview(PreviewConfig previewConfig, TextureView textureView) { this.previewConfig = previewConfig; this.textureView = textureView; } public UseCase getUseCase() { final Preview preview = new Preview(previewConfig); preview.setOnPreviewOutputUpdateListener(this); return preview; } @Override public void onUpdated(@NonNull PreviewOutput output) { final ViewGroup viewGroup = (ViewGroup) textureView.getParent(); viewGroup.removeView(textureView); viewGroup.addView(textureView, 0); textureView.setSurfaceTexture(output.getSurfaceTexture()); } }
1,142
Java
.java
7people/AR-Shopping
9
2
0
2023-06-12T14:01:53Z
2023-07-26T07:06:06Z
otpCheck.java
/FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/com/example/glass/arshopping/otpCheck.java
package com.example.glass.arshopping; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.android.volley.RequestQueue; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import com.example.glass.arshopping.utils.Global; import org.json.JSONObject; import java.util.HashMap; public class otpCheck extends AppCompatActivity { String email_ = ""; RequestQueue mRequestQueue; @Override protected void onCreate(Bundle savedInstanceState) { mRequestQueue = Volley.newRequestQueue((Context) this); super.onCreate(savedInstanceState); setContentView(R.layout.activity_otp_check); email_ = getIntent().getStringExtra("email"); EditText cod2e = findViewById(R.id.code); Button btn = findViewById(R.id.checkbtn); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String code = cod2e.getText().toString(); HashMap<String, String> hm = new HashMap<String, String>(); hm.put("otp", code); hm.put("email", email_); if (code != null && email_ != null) { JsonObjectRequest mRequest; mRequest = new JsonObjectRequest(Global.url + "/chcotp", new JSONObject(hm), response -> { try { boolean success = response.optBoolean("Success"); String message = response.optString("Message"); if (success) { Toast.makeText(otpCheck.this, "OTP Code Affirmed", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(getBaseContext(), resetPassword.class); intent.putExtra("email", email_); startActivity(intent); } else { Toast.makeText(otpCheck.this, "Error: " + message, Toast.LENGTH_LONG).show(); } } catch (Exception e) { } }, error -> { }); mRequestQueue.add(mRequest); } else { Toast.makeText(getApplicationContext(), "Invalid email address", Toast.LENGTH_SHORT).show(); } } }); } public void BackButton(View view) { Intent intent = new Intent(getBaseContext(),Forgotpassword.class); startActivity(intent); } }
2,860
Java
.java
7people/AR-Shopping
9
2
0
2023-06-12T14:01:53Z
2023-07-26T07:06:06Z
Forgotpassword.java
/FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/com/example/glass/arshopping/Forgotpassword.java
package com.example.glass.arshopping; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.android.volley.RequestQueue; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import com.example.glass.arshopping.utils.Global; import com.example.glass.ui.GlassGestureDetector; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.Collections; import java.util.HashMap; import papaya.in.sendmail.SendMail; public class Forgotpassword extends BaseActivity { RequestQueue mRequestQueue; String OTPCode = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_forgotpassword); TextView email =(TextView) findViewById(R.id.email); Button reset= (Button) findViewById(R.id.reset); mRequestQueue = Volley.newRequestQueue((Context) this); findViewById(R.id.reset).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(Forgotpassword.this,otpCheck.class); startActivity(intent); } }); findViewById(R.id.back).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getBaseContext(),Login.class); startActivity(intent); } }); EditText emailEditText = (EditText) findViewById(R.id.email); Button regbtn = (Button) findViewById(R.id.reset); EditText emailField = findViewById(R.id.email); regbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String email1= emailField.getText().toString(); final EditText emailValidate = (EditText)findViewById(R.id.email); final TextView textView = (TextView)findViewById(R.id.email); String email = emailValidate.getText().toString().trim(); String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+"; HashMap<String, String> hm = new HashMap<String, String>(); hm.put("email", email); if(email.matches(emailPattern)) { Toast.makeText(Forgotpassword.this, "Password reset code sent", Toast.LENGTH_SHORT).show(); JsonObjectRequest mRequest; mRequest = new JsonObjectRequest(Global.url + "/resetpsw", new JSONObject(Collections.singletonMap("email", email)), response -> { try { boolean success = response.optBoolean("Success"); String message = response.optString("Message"); if (success) { getgeneratedOTP(email, new OTPCallback() { @Override public void onOTPReceived(String OTP) { if (OTP != null) { SendMail mail = new SendMail("CHANGE HERE WITH YOUR EMAIL ADDRESS", "CHANGE HERE WITH WITH PASSWORD", email, "One Time Password - AR Shopping App", "Your One Time Password Code:" + OTP ); mail.execute(); Intent intent = new Intent(getBaseContext(), otpCheck.class); intent.putExtra("email", email); startActivity(intent); } else { Toast.makeText(Forgotpassword.this, "Error: Unable to generate OTP", Toast.LENGTH_LONG).show(); } } }); } else { Toast.makeText(Forgotpassword.this, "Error: " + message, Toast.LENGTH_LONG).show(); } } catch (Exception e) { e.printStackTrace(); } }, error -> { Toast.makeText(Forgotpassword.this, "Error: " + error.getMessage(), Toast.LENGTH_LONG).show(); }); mRequestQueue.add(mRequest); } else { Toast.makeText(getApplicationContext(), "Invalid email address", Toast.LENGTH_SHORT).show(); } } }); } private void getgeneratedOTP(String userEmail, OTPCallback callback) { JsonObjectRequest mRequest = new JsonObjectRequest(Global.url + "/getlatestpasswordreset/" + userEmail, null, response -> { try { boolean success = response.optBoolean("Success"); String message = response.optString("Message"); if (success) { JSONArray data = response.optJSONArray("Data"); try { String generatedOTP = data.getJSONObject(0).optString("otp"); callback.onOTPReceived(generatedOTP); } catch (JSONException e) { callback.onOTPReceived(null); } } else { Toast.makeText(getBaseContext(), "Error: " + message, Toast.LENGTH_LONG).show(); callback.onOTPReceived(null); } } catch (Exception e) { callback.onOTPReceived(null); } }, error -> { callback.onOTPReceived(null); }); mRequestQueue.add(mRequest); } interface OTPCallback { void onOTPReceived(String OTP); } @Override public boolean onGesture(GlassGestureDetector.Gesture gesture) { switch (gesture) { case SWIPE_DOWN: finish(); return true; default: return false; } } }
6,658
Java
.java
7people/AR-Shopping
9
2
0
2023-06-12T14:01:53Z
2023-07-26T07:06:06Z